SELECT, WHERE and ORDER BY
Tables, rows and columns, and how to pick and filter them.
A relational database stores data in tables: each row is a record, each column is a field. SQL (Structured Query Language) is how you ask questions. Examples use this table, users:
| id | name | country | age |
|---|---|---|---|
| 1 | Ana | ES | 31 |
| 2 | Bob | US | 45 |
| 3 | Chen | US | 28 |
| 4 | Dara | IE | 39 |
Read data
SELECT name, age FROM users; -- chosen columns
SELECT * FROM users; -- every column
SELECT * FROM users WHERE country = 'US'; -- filter rows
SELECT * FROM users WHERE age >= 30 AND country <> 'ES';
SELECT * FROM users ORDER BY age DESC; -- sort, highest first
SELECT * FROM users ORDER BY age DESC LIMIT 2; -- only the first 2Useful filters
IN ('US','IE')matches any value in a list.BETWEEN 30 AND 40matches an inclusive range.LIKE 'A%'matches text starting with A (%is any characters).IS NULLfinds missing values:= NULLnever matches.
NoteText values use single quotes. Double quotes are for identifiers in standard SQL.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.