Skip to content

SQL basics

The core of relational databases: querying, filtering, joining, aggregating and changing data, plus the schema and transaction statements you reach for daily. Standard SQL that works across PostgreSQL, MySQL, SQLite and most engines — minor dialect differences aside.

Print or save this page for offline reference.

Querying

CommandDescription
SELECT * FROM users;Return every column and row of a table.
SELECT name, email FROM users;Return only the named columns.
SELECT DISTINCT country FROM users;Return unique values, dropping duplicates.
SELECT COUNT(*) FROM users;Count the number of rows.

Filtering & ordering

CommandDescription
WHERE age >= 18Keep only rows matching a condition.
WHERE name LIKE 'A%'Pattern match: names starting with A.
WHERE id IN (1,2,3)Match any value in a list.
ORDER BY created_at DESCSort rows, newest first.
LIMIT 10 OFFSET 20Return 10 rows, skipping the first 20 (paging).

Joins

CommandDescription
INNER JOIN orders ON orders.user_id = users.idRows with a match in both tables.
LEFT JOIN orders ON ...All left rows, plus matches (NULLs when none).
COUNT(*) ... GROUP BY user_idAggregate rows into groups.
HAVING COUNT(*) > 5Filter groups after aggregation.

Modifying data

CommandDescription
INSERT INTO users (name) VALUES ('Ada');Add a new row.
UPDATE users SET active = true WHERE id = 1;Change existing rows — always with WHERE.
DELETE FROM users WHERE id = 1;Remove rows matching a condition.
UPSERT / ON CONFLICT DO UPDATEInsert, or update the row if it already exists.

Schema

CommandDescription
CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT);Define a new table and its columns.
ALTER TABLE t ADD COLUMN email TEXT;Add a column to an existing table.
CREATE INDEX idx ON t (email);Speed up lookups on a column.
FOREIGN KEY (user_id) REFERENCES users(id)Enforce a relationship between two tables.

Transactions

CommandDescription
BEGIN;Start a transaction.
COMMIT;Make all changes in the transaction permanent.
ROLLBACK;Undo every change since BEGIN.
SAVEPOINT sp1;Mark a point to partially roll back to.

Put this to work on Android with the Database Manager.