SQL Basics: SELECT, WHERE, JOIN and GROUP BY on One Example
SQL is the language for asking questions of a relational database: data stored in tables of rows and columns, linked by shared values. A handful of statements covers most daily work, and this page builds them up on one small example so you can see how each clause changes the answer.
Every statement here runs unchanged in PostgreSQL and SQLite, and was run in both (PostgreSQL 16 and the SQLite 3 command line shell). Output is shown from SQLite; PostgreSQL prints the same rows in a slightly different table style.
The example database
Two tables: customers, and the orders they placed. Each order points at its customer through customer_id. Money is stored as whole cents in an integer, because floating-point numbers cannot represent most decimal amounts exactly.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id),
ordered_on DATE NOT NULL,
total_cents INTEGER NOT NULL -- money as whole cents, never floats
);
INSERT INTO customers (id, name, country) VALUES
(1, 'Ada', 'UK'),
(2, 'Grace', 'US'),
(3, 'Linus', 'FI'),
(4, 'Margaret', 'US');
INSERT INTO orders (id, customer_id, ordered_on, total_cents) VALUES
(101, 1, '2026-10-02', 4500),
(102, 2, '2026-10-05', 12000),
(103, 1, '2026-10-20', 2500),
(104, 3, '2026-11-01', 9900),
(105, 2, '2026-11-03', 3000),
(106, 2, '2026-11-15', 15000);
To follow along, save that as schema.sql and load it into a new database:
sqlite3 shop.db < schema.sql
sqlite3 -header -column shop.db
or, for PostgreSQL:
createdb shop
psql -d shop -f schema.sql
psql -d shop
Notice that Margaret has no orders. She matters later.
SELECT, WHERE and ORDER BY
SELECT picks columns, FROM picks the table, WHERE keeps only the rows that match, and ORDER BY sorts the result:
SELECT name, country
FROM customers
WHERE country = 'US'
ORDER BY name;
name country
-------- -------
Grace US
Margaret US
Conditions combine with AND, OR and NOT. Dates written as 'YYYY-MM-DD' compare correctly in both databases:
SELECT id, ordered_on, total_cents
FROM orders
WHERE ordered_on >= '2026-11-01'
AND total_cents > 5000
ORDER BY total_cents DESC;
id ordered_on total_cents
--- ---------- -----------
106 2026-11-15 15000
104 2026-11-01 9900
Other conditions you will use often: country IN ('US', 'UK'), total_cents BETWEEN 1000 AND 5000 (inclusive at both ends), name LIKE 'Mar%' (% matches any run of characters, _ exactly one), and LIMIT 10 at the end to return only the first rows. Two rules save a lot of confusion:
- Without
ORDER BY, row order is not guaranteed. It may look stable in testing and change later. - Test for missing values with
IS NULL, never= NULL.NULLmeans "unknown", and any comparison with it is unknown too, soWHERE country = NULLmatches no rows at all.
JOIN: combining tables
A join lines rows up across tables using a condition, here "the order's customer_id equals the customer's id". AS c and AS o are short aliases:
SELECT c.name, o.id AS order_id, o.total_cents
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
ORDER BY o.id;
name order_id total_cents
----- -------- -----------
Ada 101 4500
Grace 102 12000
Ada 103 2500
Linus 104 9900
Grace 105 3000
Grace 106 15000
JOIN (short for INNER JOIN) keeps only rows that have a match on both sides, which is why Margaret is missing. LEFT JOIN keeps every row from the left table and fills the right side with NULL where there is no match:
SELECT c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE c.country = 'US'
ORDER BY c.name, o.id;
name order_id
-------- --------
Grace 102
Grace 105
Grace 106
Margaret
That gives a common pattern for "rows with no match", such as customers who never ordered:
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.id IS NULL;
name
--------
Margaret
Forgetting the ON condition, or writing the wrong one, multiplies rows: every order is paired with every customer. If a join returns far more rows than you expected, check the ON clause first.
GROUP BY and aggregates
Aggregate functions summarize many rows into one value: COUNT, SUM, AVG, MIN, MAX. GROUP BY splits the rows into groups first, giving one result row per group:
SELECT c.name,
COUNT(o.id) AS orders,
SUM(o.total_cents) AS spent_cents
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY spent_cents DESC;
name orders spent_cents
----- ------ -----------
Grace 3 30000
Linus 1 9900
Ada 2 7000
Every column in the SELECT list must either be in the GROUP BY or be inside an aggregate. PostgreSQL rejects anything else with an error (except columns of a table whose primary key is in the GROUP BY); SQLite allows it but returns a value from an arbitrary row of the group, which is a quiet source of wrong answers. Grouping by c.id as well as c.name keeps two customers who share a name apart.
COUNT(*) counts rows; COUNT(column) counts rows where that column is not NULL. With a LEFT JOIN, COUNT(o.id) correctly gives 0 for a customer with no orders, while COUNT(*) would give 1.
WHERE versus HAVING
WHERE filters rows before grouping; HAVING filters groups after the aggregates are computed. Countries whose orders since October total more than 100.00:
SELECT c.country, COUNT(*) AS orders, SUM(o.total_cents) AS spent_cents
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.ordered_on >= '2026-10-01'
GROUP BY c.country
HAVING SUM(o.total_cents) > 10000
ORDER BY c.country;
country orders spent_cents
------- ------ -----------
US 3 30000
The UK (7000) and Finland (9900) were grouped and then removed by HAVING. You cannot put SUM(...) in a WHERE clause, because when WHERE runs, the sums do not exist yet.
The order a query is evaluated
SQL is written in one order and evaluated, logically, in another. Knowing the second order explains most error messages:
FROMandJOIN: build the combined rowsWHERE: filter rowsGROUP BY: form groupsHAVING: filter groupsSELECT: compute the output columns and aliasesORDER BY: sort (it can use theSELECTaliases, as inORDER BY spent_cents)LIMIT: cut the result
Changing data safely: UPDATE and DELETE
UPDATE and DELETE change data in place, and there is no undo once the change is committed. Without a WHERE clause they affect every row in the table. Before changing real data, take a backup:
# SQLite: copy the database file safely, even while it is in use
sqlite3 shop.db ".backup shop-backup.db"
# PostgreSQL: dump the database to a SQL file
pg_dump shop > shop-backup.sql
Then use a transaction, and look at the rows before you change them. Run a SELECT with exactly the WHERE clause you plan to use, make the change, check it, and only then decide:
BEGIN;
-- 1. See exactly which rows the WHERE clause selects
SELECT id, total_cents FROM orders WHERE customer_id = 2 AND ordered_on < '2026-11-01';
-- 2. Run the change with the same WHERE clause
UPDATE orders
SET total_cents = total_cents - 1000
WHERE customer_id = 2 AND ordered_on < '2026-11-01';
-- 3. Check the result
SELECT id, total_cents FROM orders WHERE customer_id = 2 ORDER BY id;
-- 4. Keep it with COMMIT, or throw it away with ROLLBACK
ROLLBACK;
id total_cents
--- -----------
102 12000
id total_cents
--- -----------
102 11000
105 3000
106 15000
The second result shows the discounted total for order 102. Because the script ends with ROLLBACK, nothing was saved; change it to COMMIT once the check looks right. A DELETE follows the same routine: the same WHERE in a SELECT first, then DELETE FROM orders WHERE ... inside a transaction. In application code, give the database user only the permissions it needs, so a bug cannot drop or empty a table.
Running queries from code
When a value comes from a user, pass it as a parameter, never by building the SQL string. With Python's built-in sqlite3 module the placeholder is ?:
import sqlite3
country = "US" # imagine this came from a form or URL
with sqlite3.connect("shop.db") as db:
rows = db.execute(
"""
SELECT c.name, COUNT(o.id), COALESCE(SUM(o.total_cents), 0)
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE c.country = ?
GROUP BY c.id, c.name
ORDER BY c.name
""",
(country,), # the value travels separately from the SQL
).fetchall()
for name, count, cents in rows:
print(f"{name}: {count} orders, {cents / 100:.2f} total")
Grace: 3 orders, 300.00 total
Margaret: 0 orders, 0.00 total
COALESCE(x, 0) returns the first non-NULL value, turning Margaret's missing sum into 0. Why parameters matter, and what they look like in PostgreSQL, Java and Node.js, is the subject of SQL injection and parameterized queries. For the details of any statement, the PostgreSQL SELECT reference is thorough and readable.