SELECT is the most important statement in SQL. It is how you retrieve data from your database. Everything else — inserts, updates, deletes — is just maintenance. SELECT is where you get the answers to your questions.
Selecting All Data
To get every row and every column from a table:
SELECT * FROM students;
The * means "all columns." This is great for exploring a table but not
practical for large tables with millions of rows.
Selecting Specific Columns
Most of the time, you only need certain columns:
SELECT first_name, last_name, email FROM students;
This is faster and cleaner. Only fetch the data you actually need.
Column Aliases
You can rename columns in your results using AS:
SELECT
first_name AS "First Name",
last_name AS "Last Name",
email AS "Email Address"
FROM students;
This is useful when you want friendlier column names in your results, especially when building reports or feeding data to an application.
Filtering with WHERE
Use WHERE to filter rows:
SELECT first_name, last_name
FROM students
WHERE enrollment_date > '2023-01-01';
Only students who enrolled after January 1, 2023 will be returned. We will cover more filtering options in the WHERE lesson.
Sorting with ORDER BY
Sort your results:
SELECT first_name, last_name, date_of_birth
FROM students
ORDER BY date_of_birth DESC;
ASC sorts ascending (smallest first) and DESC sorts descending
(largest first). ASC is the default.
Limiting Results
When working with large tables, you often want just the first few rows:
SELECT first_name, last_name
FROM students
ORDER BY enrollment_date DESC
LIMIT 10;
This gives you the 10 most recently enrolled students. You can also use OFFSET to skip rows:
SELECT first_name, last_name
FROM students
ORDER BY enrollment_date DESC
LIMIT 10 OFFSET 20;
This skips the first 20 and returns the next 10. Useful for pagination.
Removing Duplicates
Use DISTINCT to eliminate duplicate rows:
SELECT DISTINCT last_name
FROM students
ORDER BY last_name;
This returns each unique last name only once, regardless of how many students share it.