SQL: reference
The query language: selecting, filtering, grouping and joining tables.
Basics
Table and query
Keywords are usually written in capital letters, and every command ends with a semicolon.
-- comment in SQL SELECT name, age FROM users;
Creating a table
PRIMARY KEY uniquely identifies a row, NOT NULL forbids an empty value.
CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, age INTEGER DEFAULT 0 );
Selecting data
SELECT and WHERE
Strings are in single quotes. Checking for an empty value is done with IS NULL, not = NULL.
SELECT * FROM users;
SELECT name FROM users WHERE age >= 18;
SELECT * FROM users WHERE city = 'Dnipro' AND age < 30;
SELECT * FROM users WHERE name LIKE 'A%';
SELECT * FROM users WHERE city IN ('Kyiv', 'Lviv');
SELECT * FROM users WHERE email IS NULL;Sorting and limiting
LIMIT and OFFSET are needed for paged output, DISTINCT removes duplicates.
SELECT name, age FROM users ORDER BY age DESC, name LIMIT 10 OFFSET 20; SELECT DISTINCT city FROM users;
Changing data
INSERT, UPDATE, DELETE
Always write WHERE in UPDATE and DELETE, otherwise the whole table will change.
INSERT INTO users (name, age) VALUES ('Alex', 16);
UPDATE users SET age = 17 WHERE id = 1;
DELETE FROM users WHERE id = 1;Aggregation
Functions
Aggregate functions reduce many rows to a single value.
SELECT COUNT(*), AVG(age), MIN(age), MAX(age), SUM(age) FROM users;
GROUP BY and HAVING
WHERE filters rows before grouping, and HAVING filters the groups after it.
SELECT city, COUNT(*) AS total FROM users GROUP BY city HAVING COUNT(*) > 5 ORDER BY total DESC;
Joining tables
JOIN
JOIN keeps only the matches, LEFT JOIN keeps all rows of the left table (even without a pair).
SELECT u.name, o.total FROM users u JOIN orders o ON o.user_id = u.id; SELECT u.name, o.total FROM users u LEFT JOIN orders o ON o.user_id = u.id;
A relation between tables
The foreign key REFERENCES guarantees that an order belongs to an existing user.
CREATE TABLE orders ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), total REAL );
Subqueries and expressions
Subquery
A subquery in parentheses runs first and returns a value or a list.
SELECT name FROM users WHERE age > (SELECT AVG(age) FROM users);
CASE
CASE works as an if/else condition inside a query.
SELECT name, CASE WHEN age < 18 THEN 'minor' ELSE 'adult' END AS kind FROM users;
Structure and performance
ALTER, DROP, INDEX
An index speeds up search by a column but slows writing down a little.
ALTER TABLE users ADD COLUMN city TEXT; CREATE INDEX idx_users_email ON users(email); DROP TABLE old_users;
Transactions
A transaction is executed completely or not at all.
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- or ROLLBACK, to undo
Learn SQL with practice
- 35 lessons, 30 of them base
- Tasks with in-browser code checking
- Free, nothing to install