SQL Basics
Create tables and write queries — SELECT, WHERE, ORDER BY, LIMIT, aggregates and GROUP BY/HAVING, INSERT/UPDATE/DELETE, NULL semantics and logical query order.
SQL (Structured Query Language) is how you talk to relational databases: PostgreSQL, MySQL, SQLite, SQL Server, Oracle, and analytical engines like BigQuery, Snowflake and DuckDB. It's declarative: you describe the result and the database figures out how to compute it.
We'll use this schema throughout the SQL lessons:
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT,
salary NUMERIC(10, 2),
manager_id INT REFERENCES employees(id),
hired_on DATE
);SELECT: reading data
SELECT name, salary
FROM employees
WHERE dept = 'Engineering' AND salary > 100000
ORDER BY salary DESC
LIMIT 10;| Clause | Does |
|---|---|
SELECT | Which columns (or expressions) to return; * for all |
FROM | Which table(s) |
WHERE | Filter rows |
ORDER BY | Sort (ASC default, DESC) |
LIMIT / OFFSET | Return only some rows (FETCH FIRST n ROWS in standard SQL, TOP in SQL Server) |
DISTINCT | Remove duplicate rows |
Useful operators in WHERE:
WHERE salary BETWEEN 50000 AND 80000
WHERE dept IN ('Sales', 'Marketing')
WHERE name LIKE 'A%' -- starts with A (ILIKE: case-insensitive in Postgres)
WHERE manager_id IS NULL -- never "= NULL"!
WHERE hired_on >= DATE '2024-01-01'NULL: the unknown value
NULL means "unknown" or "missing", and it follows three-valued logic: comparisons with NULL yield UNKNOWN, which WHERE treats as false.
| Expression | Result |
|---|---|
NULL = NULL | UNKNOWN (not true!) |
NULL <> 5 | UNKNOWN |
NULL AND FALSE | FALSE |
NULL OR TRUE | TRUE |
salary + NULL | NULL |
SELECT * FROM employees WHERE dept <> 'Sales';
-- Rows with dept = NULL are NOT returned! Add: OR dept IS NULL
SELECT COALESCE(dept, 'Unassigned') FROM employees; -- first non-null valueAggregates and GROUP BY
SELECT dept,
COUNT(*) AS headcount,
AVG(salary) AS avg_salary,
MAX(salary) AS top_salary
FROM employees
WHERE hired_on >= '2020-01-01'
GROUP BY dept
HAVING COUNT(*) >= 5
ORDER BY avg_salary DESC;COUNT(*)counts rows;COUNT(col)counts non-null values;COUNT(DISTINCT col)counts distinct ones.- Aggregates (
SUM,AVG,MIN,MAX) ignore NULLs. - Every non-aggregated column in
SELECTmust appear inGROUP BY. WHEREfilters rows before grouping;HAVINGfilters groups after aggregation.
Logical order of evaluation
SQL is written in one order but evaluated (logically) in another, which explains many errors such as "column alias doesn't exist in WHERE":
FROM/JOIN— build the working set of rowsWHERE— filter rowsGROUP BY— form groupsHAVING— filter groupsSELECT— compute output columns and aliasesDISTINCTORDER BY— can use aliasesLIMIT/OFFSET
Modifying data
INSERT INTO employees (name, dept, salary, hired_on)
VALUES ('Ada', 'Engineering', 150000, '2024-03-01'),
('Alan', 'Research', 140000, '2024-04-15')
RETURNING id; -- Postgres: get generated ids back
UPDATE employees
SET salary = salary * 1.05
WHERE dept = 'Engineering';
DELETE FROM employees WHERE hired_on < '2000-01-01';
-- Upsert: insert or update on conflict
INSERT INTO employees (id, name, salary) VALUES (7, 'Grace', 160000)
ON CONFLICT (id) DO UPDATE SET salary = EXCLUDED.salary; -- MySQL: ON DUPLICATE KEY UPDATEFrom application code: always parameterise
String sql = "SELECT id, name FROM employees WHERE dept = ? AND salary > ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, dept);
ps.setBigDecimal(2, minSalary);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) System.out.println(rs.getLong("id") + " " + rs.getString("name"));
}
}import psycopg
with psycopg.connect(dsn) as conn:
rows = conn.execute(
"SELECT id, name FROM employees WHERE dept = %s AND salary > %s",
(dept, min_salary),
).fetchall()import pg from "pg";
const pool = new pg.Pool();
const { rows } = await pool.query(
"SELECT id, name FROM employees WHERE dept = $1 AND salary > $2",
[dept, minSalary],
);DDL: changing structure
ALTER TABLE employees ADD COLUMN email TEXT;
ALTER TABLE employees ALTER COLUMN dept SET NOT NULL;
CREATE INDEX idx_employees_dept ON employees (dept);
DROP TABLE IF EXISTS temp_import;In production, schema changes go through migration tools (Flyway, Liquibase, Alembic, Prisma Migrate) so every environment changes in the same versioned way. Large tables need care: some ALTERs lock or rewrite the whole table.
- SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT.
- NULL is unknown: use IS NULL, COALESCE, and avoid NOT IN with nullable columns.
- WHERE filters rows; HAVING filters groups.
- Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
- Always use parameterised queries; test UPDATE/DELETE predicates first.
QWhat's the difference between WHERE and HAVING?easy
WHERE filters individual rows before grouping and can't use aggregates. HAVING filters groups after GROUP BY and can use aggregates, e.g. HAVING COUNT(*) > 5.
QFind the second-highest salary.medium
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); or, generally for the nth: SELECT DISTINCT salary FROM employees ORDER BY salary DESC OFFSET 1 LIMIT 1; or DENSE_RANK() in a window function.