SQL is the query language for relational databases. A query is built from blocks: SELECT sets which columns to show, FROM — which table to take, and WHERE filters rows by a condition. Without WHERE all rows of the table are returned.
- Get from a table only the needed columns and rows.
- Sort the result (ORDER BY) and limit its size (LIMIT).
SELECT name, city
FROM usersOutput:
name | city
-------|-----------
Anna | Moscow
Boris | Kazan
Victor | MoscowSELECT lists the columns of the result: here only name and city, the other columns of the table are not returned.
SELECT name, age
FROM users
WHERE age >= 18
ORDER BY age DESCOutput:
name | age
-------|----
Victor | 25
Boris | 18WHERE keeps the adults, and ORDER BY ... DESC sorts them from oldest to youngest.
SELECT DISTINCT city
FROM users
LIMIT 3Output:
city
-----------
Moscow
Kazan
St. PetersburgDISTINCT removes repeated values, LIMIT 3 keeps no more than three result rows.
Key rules:
- ✓SELECT — which columns, FROM — which table, WHERE — a row filter.
- ✓ORDER BY sorts ascending (ASC) by default; DESC — descending.
- ✓LIMIT limits the number of result rows.
Common mistakes:
- !A forgotten WHERE returns all rows of the table.
- !% in LIKE is any set of characters: "A%" means “starts with A”.
Aggregate functions collapse a group of rows into one number: COUNT(*) — the number of rows, SUM — the column sum, AVG — the average, MIN/MAX — the minimum and maximum. GROUP BY splits rows into groups by a column value, and HAVING filters the finished groups.
- Compute statistics over a table or over groups (cities, categories).
- Filter groups by an aggregate value — something WHERE cannot do.
SELECT COUNT(*) AS total
FROM usersOutput:
total
-----
4COUNT(*) counts table rows, ignoring NULL in individual columns.
SELECT SUM(amount) AS total, AVG(amount) AS avg_amount
FROM ordersOutput:
total | avg_amount
------|-----------
5400 | 1800.00SUM adds up amount over all orders, AVG computes their arithmetic mean.
SELECT city, COUNT(*) AS cnt
FROM users
GROUP BY city
HAVING COUNT(*) > 1Output:
city | cnt
-------|----
Moscow | 2GROUP BY creates a group for each city, and HAVING keeps only cities with more than one user.
Key rules:
- ✓COUNT/SUM/AVG/MIN/MAX compute one number over a set of rows.
- ✓GROUP BY joins rows with the same column value into groups.
- ✓HAVING filters groups, WHERE filters individual rows before grouping.
Common mistakes:
- !You cannot filter by an aggregate via WHERE — for that there is HAVING.
- !A column without an aggregate in SELECT must be in GROUP BY.
Tables are linked by keys: PRIMARY KEY — a unique row identifier, FOREIGN KEY — a reference to another primary key. JOIN glues rows of two tables by an ON condition, for example orders.user_id = users.id.
- Bring together data from linked tables (users and their orders).
- Find “orphans” — rows without a pair in another table (LEFT JOIN + IS NULL).
SELECT users.name, orders.amount
FROM users
INNER JOIN orders ON orders.user_id = users.idOutput:
name | amount
-------|-------
Anna | 1200
Victor | 900INNER JOIN keeps only “user + their order” pairs; users without orders do not get into the result.
SELECT users.name, orders.amount
FROM users
LEFT JOIN orders ON orders.user_id = users.idOutput:
name | amount
-------|-------
Anna | 1200
Boris | NULL
Victor | 900LEFT JOIN keeps all rows of users; for Boris without orders the orders fields are filled with NULL.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
amount INTEGER
);Output:
The orders table was createdid is the primary key of an order, and user_id is a foreign key on users(id): an order can reference only an existing user.
Key rules:
- ✓INNER JOIN — only rows with a match in both tables.
- ✓LEFT JOIN — all rows of the left table; where there is no pair, the right fields are NULL.
- ✓The link is built on keys: PRIMARY KEY in the main table, FOREIGN KEY in the child table.
Common mistakes:
- !A forgotten ON turns JOIN into a Cartesian product.
- !INNER and LEFT are easy to confuse: INNER silently drops rows without a pair.
CREATE TABLE describes the table schema: columns, their types and constraints. INTEGER stores integers, TEXT — strings, REAL — fractional numbers. PRIMARY KEY makes a column a unique row identifier, NOT NULL forbids empty values, and REFERENCES links the table to the primary key of another table.
- Define the structure of the data before records get into the table.
- Ensure database integrity: an order cannot be linked to a nonexistent user.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
);Output:
The users table was createdid is the primary key: each row gets a unique number. NOT NULL for name prevents saving a user without a name.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
amount INTEGER
);Output:
The orders table was createduser_id references users(id): you cannot write the id of a nonexistent user into an order.
Key rules:
- ✓INTEGER — integers, TEXT — strings, REAL — fractional numbers.
- ✓PRIMARY KEY — the unique row identifier.
- ✓REFERENCES other_table(column) — a foreign key.
Common mistakes:
- !Without NOT NULL you can insert a row with an empty value.
- !In SQLite VARCHAR(10) does not limit the string: the type stores data, not a length.
INSERT INTO ... VALUES adds a new row, UPDATE ... SET changes existing ones, and DELETE FROM removes them. The main safety rule: UPDATE and DELETE almost always go together with WHERE — otherwise the command affects all rows.
- Fill tables with data and keep them up to date.
- Update and delete exactly the needed rows, not the whole table.
INSERT INTO users (name, age)
VALUES ('Dima', 27);Output:
1 row insertedThe columns name and age get the values “Dima” and 27 — a new user appears in the table.
UPDATE users
SET age = 28
WHERE name = 'Dima';Output:
1 row updatedWHERE narrows UPDATE to the row with the name "Dima". Without WHERE the age would update for all users.
DELETE FROM orders
WHERE amount < 100;Output:
3 rows deletedOnly orders cheaper than 100 are removed. DELETE without WHERE would wipe the whole orders table.
Key rules:
- ✓INSERT INTO ... VALUES — adds a row.
- ✓UPDATE ... SET ... WHERE — changes only the filtered rows.
- ✓DELETE FROM ... WHERE — removes only the filtered rows.
Common mistakes:
- !UPDATE or DELETE without WHERE affects the whole table.
- !A skipped column in INSERT gets NULL if it has no default value.
A query can not just list columns but compute on the fly: arithmetic (+ - * /) works with column names, the result can be named with an alias via AS, and strings can be glued with the || operator. The table does not change: the calculation happens only in the query result.
- Compute derived values (cart total, discount, VAT) without editing the data.
- Make the result readable: give expressions clear names.
SELECT name, price * quantity AS total
FROM carts;Output:
name | total
-----|------
Coffee | 640
Tea | 240price * quantity — column multiplication; the result is output under the name total.
SELECT name,
price * 0.9 AS with_discount
FROM products;Output:
name | with_discount
--------|-------------
Laptop | 49500.0Multiplying by 0.9 takes off 10% of the price — but only in the result, the data in the table does not change.
SELECT name || ' (' || city || ')' AS who
FROM users;Output:
who
----------------
Anna (Moscow)
Boris (Kazan)The || operator joins strings into one; the glued column is also renamed via AS.
Key rules:
- ✓In SELECT the operators +, -, *, / and parentheses work.
- ✓AS gives a name to a column expression.
- ✓|| — string concatenation (SQLite, PostgreSQL).
- ✓Any arithmetic with NULL gives NULL: NULL * 2 = NULL.
Common mistakes:
- !An expression without AS gets a machine column name.
- !NULL “infects” calculations — check or replace it in advance.
SQL is written in one order and executed almost in reverse. The logical order is: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That is why WHERE cannot filter by COUNT(*) (grouping has not happened yet), HAVING can, and ORDER BY freely references aliases from SELECT.
- Understand why WHERE does not see aggregates but HAVING does.
- Know at which step aliases and calculations are available.
SELECT city, COUNT(*) AS cnt
FROM users
WHERE age >= 18
GROUP BY city
HAVING COUNT(*) > 1;Output:
city | cnt
-------|----
Moscow | 2FROM reads rows → WHERE keeps the adults → GROUP BY gathers cities → HAVING takes groups with more than one → SELECT forms columns.
SELECT name, age * 12 AS age_months
FROM users
ORDER BY age_months DESC;Output:
name | age_months
-------|-----------
Victor | 300
Boris | 216ORDER BY runs after SELECT, so the age_months alias already exists in the sort.
Key rules:
- ✓Order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
- ✓WHERE filters rows before grouping, HAVING — groups after.
- ✓ORDER BY and LIMIT work with the already formed result.
Common mistakes:
- !An alias from SELECT is not available in WHERE — it runs earlier.
- !WHERE and HAVING are easy to confuse: the first is about rows, the second about groups.