Dualo
SQL Essentials

SELECT basics — filter, sort, limit

The bread and butter: SELECT columns FROM table WHERE conditions ORDER BY sort LIMIT n. Learn this well; everything else builds on it.

1 min read

The canonical query: SELECT column_list FROM table WHERE condition ORDER BY sort LIMIT n. Each clause has a specific job.

SELECT chooses what columns you want back. SELECT * gets everything — handy in exploration, anti-pattern in production (fragile to schema changes + wastes bandwidth). Prefer SELECT id, name, created_at.

**FROM** names the source table. **WHERE** filters rows — the column must satisfy the predicate. Classic predicates: `=`, `<>` (or `!=`), `<`, `>`, `IN (...)`, `LIKE 'prefix%'`, `BETWEEN a AND b`, `IS NULL`.

ORDER BY sorts the result. Default ASC (ascending); DESC for reverse. Sort by multiple columns: ORDER BY country ASC, signup_date DESC. LIMIT caps the number of rows returned. Critical: LIMIT without ORDER BY returns arbitrary rows — always order first if order matters.

DISTINCT removes duplicate rows: SELECT DISTINCT country FROM customers — one row per unique country. Cheap-looking, can be expensive on big tables (requires sort or hash).

Aliases rename columns for readability: SELECT COUNT(*) AS total FROM orders. Table aliases shorten joins: SELECT c.name FROM customers c. Use them — queries become readable.

Grounded on https://www.postgresql.org/docs/current/queries-select-lists.html

Next up

Joins — INNER, LEFT, RIGHT, FULL

Combine rows across tables using keys. Pick the right join type or you'll silently lose or duplicate data.