Skip to content
Commitwise
Menu
Databases

SQL basics: reading and changing data

SELECT, WHERE, ORDER BY and LIMIT, the order SQL really runs in, why = NULL never matches and NOT IN can return nothing, and INSERT, UPDATE, DELETE and upserts without lost updates or a missing WHERE. The everyday SQL every developer interview assumes.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“Find the customers who haven’t set a country” returns nobody, though there are hundreds. A one-line price fix updates all 4,000 products. Two people buy the last item in stock and both get a confirmation. Each of these is one line of SQL, and each is a classic.

This lesson covers the statements you’ll write every day: reading rows with SELECT, the special value NULL, and changing data with INSERT, UPDATE and DELETE. It uses the shop tables from How relational databases work: customers, products, orders and order_items.

New to some of these? Open what you need, or skip ahead.

Basics:What is SQL?

SQLSQLThe language for defining, querying and changing data in a relational database.Open in glossary → (Structured Query Language, said “S-Q-L” or “sequel”) is the language you use to talk to a relational database. One statement creates a table, another adds a row, another asks a question:

SELECT name FROM customers WHERE country = 'RS';

You describe what you want, not how to find it. The database decides how.

Basics:Tables, rows and keys

A table has named, typed columns, and each row is one thing (one customer, one order). The primary keyPrimary keyThe column (or columns) that uniquely identifies each row of a table; never empty, never repeated.Open in glossary → (usually id) identifies each row, and a foreign keyForeign keyA column that points at a row in another table, and that the database keeps valid.Open in glossary → like orders.customer_id points at a row in another table.

Part Not started

Reading rows: SELECT, WHERE and ORDER BY

A query has a few parts, and you’ll write them in this order:

SELECT name, price          -- which columns
FROM products               -- from which table
WHERE price < 20            -- which rows
ORDER BY price DESC         -- sorted how (DESC = biggest first)
LIMIT 10;                   -- how many

The conditions you can put in WHERE:

ConditionMeaning
price = 10, price <> 10equal, not equal (!= works too)
price < 10, price >= 10comparisons
price BETWEEN 10 AND 2010 to 20, both included
country IN ('RS', 'HR', 'BA')one of a list
name LIKE 'Ana%'a pattern: % is any text, _ is one character
a AND b, a OR b, NOT acombine conditions

Text goes in single quotes: 'Ana'. Double quotes are for names of tables and columns, which you rarely need.

You can compute values and name them with AS:

SELECT name, price * 1.2 AS price_with_tax FROM products;

One rule surprises everyone. SQL doesn’t run in the order you write it. It runs like this:

  1. FROM: take the table.
  2. WHERE: keep the matching rows.
  3. SELECT: compute the columns, including names like price_with_tax.
  4. ORDER BY: sort.
  5. LIMIT: cut.

So WHERE can’t use a name created in SELECT: it doesn’t exist yet. ORDER BY can, because it runs later.

The logical processing order answers most “why doesn’t this work” questions: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT (including window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET. Aliases are visible only after SELECT; PostgreSQL also accepts them in GROUP BY, MySQL in HAVING, but WHERE never. The planner may physically reorder anything, as long as results match this logical order.

Details that come up in reviews and interviews:

  • Precedence. NOT > AND > OR. Parenthesize every mixed condition.
  • SELECT * in application code breaks when columns are added, sends unused data, and prevents index-only scans. Name the columns.
  • Patterns. LIKE 'abc%' can use a B-tree index (with the C collation or a text_pattern_ops index); LIKE '%abc' can’t. Use a trigram index (pg_trgm) or full-text search for “contains”. ILIKE is PostgreSQL-only; MySQL’s default collations are already case-insensitive.
  • Determinism. LIMIT without ORDER BY returns arbitrary rows, and ORDER BY created_at with ties returns ties in any order. Add a unique tiebreaker: ORDER BY created_at DESC, id DESC.
  • Paging. OFFSET 100000 still reads and throws away 100,000 rows; use keyset paginationKeyset paginationPaging by continuing after the last row's sort key instead of skipping a number of rows with OFFSET.Open in glossary → for deep pages (see Database performance).
  • Standard vs dialect. LIMIT is PostgreSQL, MySQL and SQLite; the standard is FETCH FIRST 10 ROWS ONLY (PostgreSQL, Oracle, SQL Server 2012+ with OFFSET).

Predict the output

Which orders does this query return?

SELECT id, status, total
FROM orders
WHERE status = 'PAID' OR status = 'SHIPPED' AND total > 100;
-- the 20 cheapest active products, cheapest first
SELECT id, name, price
FROM products
WHERE is_active AND price > 0
ORDER BY price, id
LIMIT 20;

-- customers from three countries who signed up this year
SELECT id, name, email
FROM customers
WHERE country IN ('RS', 'HR', 'BA')
  AND created_at >= date '2026-01-01'
ORDER BY created_at DESC;

-- products whose name starts with "Mug"
SELECT id, name FROM products WHERE name LIKE 'Mug%';

The column that doesn’t exist yet

Spot the bugBig order lines

Tap the line with the bug.

SELECT order_id,
       product_id,
       quantity * unit_price AS line_total
FROM order_items
WHERE line_total > 100
ORDER BY line_total DESC;

Deep diveSQL injection, and the part parameters can't protectInterview favorite

Building SQL by joining strings lets user input become code:

// search?q=x' OR '1'='1
val sql = "SELECT * FROM products WHERE name = '" + q + "'"

The fix is parameters (prepared statements): the SQL text and the values travel separately, so a value can never change the statement’s structure. WHERE name = ? with JdbcTemplate, :name in JPA, $1 in node-postgres, ? in Room’s @Query and in SQLite’s bind. ORMs parameterize for you unless you concatenate into a native query.

The interview follow-up: parameters only replace values. Table names, column names, ASC/DESC and LIMIT in some drivers can’t be bound. A ?sort=price query parameter must go through an allowlist:

var column = Map.of("price", "price", "newest", "created_at").get(sort);
if (column == null) throw new BadRequestException("sort");
var sql = "SELECT id, name FROM products ORDER BY " + column + ", id LIMIT ?";

Defense in depth: the app’s database user has only the privileges it needs (no DROP, no access to other schemas), and errors don’t echo SQL back to the client.

  • Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. No SELECT aliases in WHERE.
  • AND before OR: parenthesize. Name columns instead of SELECT *.
  • LIKE 'x%' can use an index, '%x' can’t (trigram, full-text). LIMIT needs ORDER BY with a unique tiebreaker; deep pages need keyset.
  • Values through parameters; identifiers through an allowlist.
SELECT id, name, price
FROM products
WHERE (name LIKE 'Mug%' OR name LIKE 'Cup%') AND price < $1
ORDER BY price, id
LIMIT 20;

Check this part

  1. Which runs first?

  2. What does name LIKE 'Ana%' match?

  3. A paginated endpoint uses ORDER BY created_at LIMIT 20 OFFSET 40. Users see some rows twice and miss others. Why?

  4. How do you safely let users choose the sort column?

SELECT picks columns, WHERE filters rows, ORDER BY sorts and LIMIT cuts. SQL runs FROM, then WHERE, then SELECT, then ORDER BY, so a column alias works in ORDER BY but not in WHERE. AND binds tighter than OR. Always pass values as parameters, never by gluing strings.

Part Not started

NULL: the value that isn’t there

Some customers haven’t told us their country. That column holds NULL: no value, unknown. It isn’t 0, and it isn’t the empty text ''. It’s like a blank on a form.

NULL has one rule that trips everyone up: any comparison with NULL is “unknown”, not true and not false. Is an unknown country equal to 'RS'? Unknown. Is it different from 'RS'? Also unknown. And WHERE keeps only rows where the condition is true.

So:

  • WHERE country = NULL matches nothing, ever. Use WHERE country IS NULL.
  • WHERE country <> 'RS' skips customers with no country, which is often not what you meant.
  • price * NULL is NULL, and 'Hi ' || NULL is NULL in PostgreSQL.

Tools for NULL:

You wantWrite
rows with no valuecountry IS NULL
rows with a valuecountry IS NOT NULL
a fallback valueCOALESCE(country, 'unknown')
“different, counting NULL as a value”country IS DISTINCT FROM 'RS'

SQL uses three-valued logic: TRUE, FALSE, UNKNOWN. NULL = anything is UNKNOWN; NOT UNKNOWN is UNKNOWN; UNKNOWN AND FALSE is FALSE; UNKNOWN OR TRUE is TRUE. WHERE, JOIN ... ON and HAVING keep only TRUE, while a CHECK constraint passes on UNKNOWN (so CHECK (price > 0) accepts a NULL price unless the column is NOT NULL).

Where NULL changes results:

  • NOT IN with a NULL in the list or subquery returns no rows (see below). Prefer NOT EXISTS.
  • Aggregates skip NULLs: count(country) counts values, count(*) counts rows, avg divides by non-NULL rows, and sum of no rows is NULL, not 0 (COALESCE(sum(x), 0)).
  • UNIQUE allows many NULLs (they aren’t equal to each other); PostgreSQL 15+ has UNIQUE NULLS NOT DISTINCT.
  • Sorting. PostgreSQL and Oracle sort NULLs as the largest value (last in ASC, first in DESC); MySQL, SQLite and SQL Server sort them first in ASC. Be explicit with NULLS LAST where supported.
  • IS [NOT] DISTINCT FROM is the NULL-safe comparison (MySQL: <=>), useful in change detection and joins on nullable columns.
  • Oracle treats '' as NULL; most other databases don’t.

In code, NULL maps to Swift and Kotlin optionals and to Java null. Decide per column whether “unknown” is a real state; if not, make it NOT NULL with a default.

Predict the output

customers has three rows: Ana with country 'RS', Ben with 'DE', and Cleo with NULL. Which names does this return?

SELECT name FROM customers WHERE country <> 'RS';
-- customers who haven't set a country
SELECT id, name FROM customers WHERE country IS NULL;

-- show a label instead of an empty cell
SELECT name, COALESCE(country, 'unknown') AS country FROM customers;

-- everyone outside Serbia, including those with no country
SELECT name FROM customers WHERE country IS DISTINCT FROM 'RS';

-- sorted by country, customers without one at the end
SELECT name, country FROM customers ORDER BY country NULLS LAST, name;

The overdue report that’s always empty

Spot the bugBooks that are still out

Tap the line with the bug.

-- loans: id, book_id, member_id, borrowed_at, returned_at
-- returned_at is NULL while the book is still out

SELECT book_id, member_id, borrowed_at
FROM loans
WHERE returned_at = NULL
  AND borrowed_at < now() - interval '14 days';

Practice: predict each row

For each customer, would WHERE country = 'RS' OR country IS NULL keep the row?

namecountrycountry = 'RS'country IS NULLkept?
AnaRStruefalseyes
BenDEfalsefalseno
CleoNULLunknowntrueyes, because unknown OR true is true
Deep diveNOT IN and the NULL that empties the resultInterview favorite

“Customers who never ordered”:

SELECT id, name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

It works until one order has customer_id = NULL (a guest checkout, a nullable column). Then id NOT IN (1, 2, NULL) means id <> 1 AND id <> 2 AND id <> NULL. The last part is unknown for every customer, so the whole condition is never true and the query returns nothing. No error, just an empty report.

NOT EXISTS doesn’t have this problem, because it asks “is there a matching row?”, which is plainly true or false:

SELECT c.id, c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

It’s also what planners turn into an efficient anti-join, while NOT IN over a nullable subquery often can’t be optimized the same way in PostgreSQL. IN (without NOT) is safe: a NULL in the list just never matches. The Joins lesson covers anti-joins in detail.

  • Three-valued logic: comparisons with NULL are UNKNOWN; WHERE/ON/HAVING keep TRUE only, CHECK passes UNKNOWN.
  • IS NULL, COALESCE, IS DISTINCT FROM (MySQL <=>). <> 'x' drops NULL rows.
  • NOT IN + a NULL = empty result; use NOT EXISTS. Aggregates skip NULLs, sum of nothing is NULL.
  • NULL sort order differs by database; say NULLS FIRST/LAST. UNIQUE allows many NULLs.

Check this part

  1. How do you find customers with no country?

  2. What does COALESCE(country, 'unknown') return for a NULL country?

  3. WHERE id NOT IN (SELECT customer_id FROM orders) returns no rows. What is the likely cause?

  4. A column has CHECK (price > 0) but no NOT NULL. Is a NULL price accepted?

NULL means unknown, not zero or empty. Any comparison with NULL is unknown, and WHERE keeps only true rows, so = NULL and <> 'RS' skip NULL rows. Use IS NULL, COALESCE and IS DISTINCT FROM. A NULL inside NOT IN makes the whole result empty.

Part Not started

Changing data: INSERT, UPDATE and DELETE

Three statements change data:

INSERT INTO customers (email, name, country)
VALUES ('ana@example.com', 'Ana', 'RS');

UPDATE products SET price = 12.90 WHERE id = 7;

DELETE FROM orders WHERE id = 1001;

Always list the columns in INSERT. Columns you leave out get their DEFAULT (or NULL), and the statement keeps working when someone adds a column later.

UPDATE and DELETE change every row that matches WHERE. Forget the WHERE, and they change every row in the table. Two habits that prevent the worst day of your career:

  1. Run a SELECT with the same WHERE first and look at what it returns.
  2. Try it inside a transaction: BEGIN;, run the change, check it, then COMMIT;, or ROLLBACK; to undo it.

Let the database do the math. To sell one mug, don’t read the stock in your app, subtract one and write it back. Two buyers can both read “1” and both write “0”, and you’ve sold one mug twice. Instead, ask the database to do it in one step, only if there’s stock left:

UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0;

The database reports how many rows it changed. 1 means sold; 0 means it was already gone.

In PostgreSQL and SQLite, RETURNING gives you back values the database generated, like the new id:

INSERT INTO orders (customer_id) VALUES (42) RETURNING id, created_at;
  • Atomic updates. SET x = x - 1 WHERE … AND x > 0 is a single row-locking statement; concurrent ones queue on the row lock and re-check the condition (in PostgreSQL’s Read Committed, the second sees the updated row). Check the affected row count: it’s your success signal. App-side read-modify-write needs SELECT … FOR UPDATE or optimistic lockingOptimistic lockingDetecting that someone else changed a record since you read it, and failing your update instead of overwriting theirs.Open in glossary → (a version column), covered in the Transactions lesson.
  • Upsert. PostgreSQL and SQLite (3.24+): INSERT … ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name or DO NOTHING; MySQL: ON DUPLICATE KEY UPDATE; standard MERGE exists in PostgreSQL 15+, SQL Server and Oracle. The conflict target needs a unique index or constraint.
  • RETURNING: PostgreSQL, SQLite 3.35+, MariaDB; not MySQL (use LAST_INSERT_ID()). Also works on UPDATE/DELETE (returns old-and-new in PostgreSQL 18 via OLD/NEW).
  • Joins in writes. PostgreSQL: UPDATE … FROM other WHERE …, DELETE … USING other; MySQL: multi-table UPDATE a JOIN b.
  • Volume. Multi-row VALUES or COPY for bulk loads; big UPDATE/DELETE in batches by key range, so locks, WAL and replica lag stay small. TRUNCATE empties a table instantly but takes an exclusive lock and skips row triggers.
  • Safety in tooling. psql’s \set ON_ERROR_STOP, MySQL’s --safe-updates (rejects UPDATE without a key in WHERE), and reviewing data migrations like code.

Predict the output

Product 7 has stock = 1. Two requests run this statement at the same moment. What happens?

UPDATE products SET stock = stock - 1
WHERE id = 7 AND stock > 0;
-- several rows in one statement, get the generated ids back
INSERT INTO products (name, price) VALUES
    ('Mug', 9.90),
    ('Notebook', 4.50)
RETURNING id, name;

-- check first...
SELECT id, status FROM orders WHERE status = 'NEW' AND created_at < now() - interval '30 days';
-- ...then change exactly those rows
UPDATE orders SET status = 'CANCELLED'
WHERE status = 'NEW' AND created_at < now() - interval '30 days';

-- insert, or update the name if the email already exists
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana Petrović')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;

Practice: write the statements

Exerciseeasy

A day in the shop's database

Write one statement for each:

  1. Add a customer ben@example.com named Ben from Germany (DE) and get back the new id.
  2. All products that cost exactly 0 should become inactive (is_active = false).
  3. Delete cancelled orders created before 2025.
  4. Raise the price of product 12 by 10%.
›

is_active is a boolean: SET is_active = false. For the date, created_at < date '2025-01-01'.

›

Every UPDATE and DELETE here needs a WHERE. Read each one out loud: which rows does it change?

SolutionTry it yourself first
-- 1
INSERT INTO customers (email, name, country)
VALUES ('ben@example.com', 'Ben', 'DE')
RETURNING id;

-- 2
UPDATE products SET is_active = false WHERE price = 0;

-- 3 (order_items go too, because of ON DELETE CASCADE)
DELETE FROM orders
WHERE status = 'CANCELLED' AND created_at < date '2025-01-01';

-- 4
UPDATE products SET price = round(price * 1.10, 2) WHERE id = 12;

In 4, price = price * 1.10 lets the database compute the new value from the current one, so a concurrent change to the price can’t be lost in between. round(…, 2) keeps it at two decimals.

Deep diveUpsert, and the race it removesInterview favorite

“Save the device token if new, otherwise update it” is often written as SELECT, then INSERT or UPDATE in the app. Two requests from the same phone arrive together, both see “not found”, both insert: one fails with a unique violation (or, without a constraint, you get duplicates).

INSERT … ON CONFLICT does it in one statement, using the unique index to detect the conflict atomically:

INSERT INTO device_tokens (user_id, token, updated_at)
VALUES ($1, $2, now())
ON CONFLICT (token) DO UPDATE
    SET user_id = EXCLUDED.user_id, updated_at = EXCLUDED.updated_at
RETURNING id;

Follow-up points interviewers like:

  • EXCLUDED is the row you tried to insert. A WHERE on DO UPDATE skips no-op updates.
  • DO NOTHING … RETURNING returns no row on a conflict; select the existing row afterwards if you need its id.
  • Every attempt consumes a sequence value, so conflicts leave gaps in ids. Ids were never gap-free anyway (rollbacks also burn values); don’t use them as invoice numbers.
  • ON CONFLICT DO UPDATE can’t update the same row twice in one statement: deduplicate the input batch first.
  • MERGE is more general (several match conditions, deletes) but in PostgreSQL it doesn’t take the same conflict-safe path: two concurrent MERGEs can still both try to insert. For “insert or update one key”, ON CONFLICT is the safer tool.
  • UPDATE/DELETE without WHERE hit every row: SELECT first, run inside BEGIN … ROLLBACK/COMMIT, batch big changes.
  • Read-modify-write in one statement (stock = stock - 1 WHERE stock > 0) and check the affected row count.
  • Upsert: ON CONFLICT … DO UPDATE SET … = EXCLUDED.… (PostgreSQL, SQLite), ON DUPLICATE KEY UPDATE (MySQL); needs a unique index.
  • RETURNING for generated values (not in MySQL). Ids have gaps; never rely on them being consecutive.

Check this part

  1. What does UPDATE products SET price = 0; do?

  2. Why use UPDATE ... SET stock = stock - 1 WHERE stock > 0 instead of reading the stock in the app?

  3. What does INSERT ... ON CONFLICT (email) need to work?

  4. INSERT ... ON CONFLICT DO NOTHING RETURNING id hits a conflict. What does it return?

INSERT adds rows, UPDATE and DELETE change the rows WHERE selects, and without WHERE they hit every row. Let the database do read-modify-write in one statement (stock = stock - 1 WHERE stock > 0) and check the row count. RETURNING gives back generated values; ON CONFLICT does an upsert.

Key takeaways

  • A query is SELECT … FROM … WHERE … ORDER BY … LIMIT, but it runs FROM, WHERE, SELECT, ORDER BY, LIMIT.
  • AND binds tighter than OR: use parentheses. Text goes in single quotes.
  • NULL is unknown: use IS NULL, not = NULL, and remember that <> skips NULL rows.
  • UPDATE and DELETE change every row their WHERE matches, all rows without one. Check with SELECT first.
  • Let the database do read-modify-write in one statement and look at how many rows changed.
  • Know the logical processing order; name columns; add a unique tiebreaker to every paginated ORDER BY.
  • Parameters for values, allowlists for identifiers.
  • Three-valued logic: NOT IN with NULLs, aggregates skipping NULLs, CHECK passing on UNKNOWN, dialect differences in NULL sorting.
  • Atomic conditional updates plus row counts, ON CONFLICT upserts on a unique index, batched bulk changes.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.