Core engineeringDatabasesBeginner → Advanced

SQL Complete Guide: Beginner to Advanced

Everything from your first SELECT to window functions, indexes and transactions, with runnable examples, the mistakes interviewers look for, and solved interview queries.

The short answerSQL (Structured Query Language) is the standard language for defining, querying and changing data in relational databases such as PostgreSQL, MySQL, SQL Server and Oracle. You describe what data you want (SELECT … FROM … WHERE …) and the database's optimiser decides how to get it. For interviews, focus on joins, GROUP BY and HAVING, subqueries and EXISTS, CTEs, window functions, indexes, transactions and isolation levels.

SQL handbook
01Fundamentals

Databases, DBMS, RDBMS and keys

Before writing queries, get the vocabulary straight. Interviews often start here.

A database is an organised collection of data that applications can store, search, update and share safely. A DBMS (database management system) is the software that manages it: it parses and optimises queries, runs transactions, controls concurrent access, maintains indexes and recovers after crashes.

An RDBMS stores data in tables of rows and columns and links tables with keys. SQL is the language you use to talk to it.

Inside a DBMS
Client / applicationSends SQL
Parser → optimiser → executorTurns SQL into an efficient plan
Transaction + buffer managerConcurrency, caching, logging
StorageData files, indexes, WAL
A one-to-many relationshipsql
-- users.id  1 ────< many  orders.user_id
CREATE TABLE users  (id BIGINT PRIMARY KEY, name VARCHAR(100) NOT NULL);
CREATE TABLE orders (
  id      BIGINT PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id),
  amount  DECIMAL(10,2) NOT NULL
);

The terms you must know

TermMeaning
SchemaThe logical structure: tables, columns, types, constraints.
Row / tuple / recordOne entry in a table.
Column / attributeOne property of the entity.
Primary keyUniquely identifies each row; never NULL.
Foreign keyReferences a key in another table.
Candidate keyAny minimal column set that could be the primary key.
Super keyAny column set that uniquely identifies rows (may include extras).
Alternate keyA candidate key not chosen as the primary key.
Composite keyA key made of several columns.
Natural vs surrogate keyA real-world value (email) vs an artificial one (auto ID, UUID).
02Structure

Data types, tables and SQL command categories

Pick precise types, define tables with constraints, and know which family each command belongs to.

TypeUse it forNote
INT / BIGINT / SMALLINTWhole numbersBIGINT for IDs that may exceed ~2 billion
DECIMAL(p, s) / NUMERICMoney, exact valuesNever FLOAT for money
FLOAT / DOUBLEScientific, approximate valuesRounding errors are expected
CHAR(n) / VARCHAR(n) / TEXTFixed, variable and long textVARCHAR for most strings
DATE / TIME / TIMESTAMPDates and timesStore in UTC (TIMESTAMPTZ in PostgreSQL)
BOOLEANTrue / falseMySQL maps it to TINYINT(1)
JSON / JSONBSemi-structured dataJSONB is indexable in PostgreSQL
Create a database and a tablesql
CREATE DATABASE targettrek;

CREATE TABLE products (
  id          BIGINT PRIMARY KEY,
  name        VARCHAR(200) NOT NULL,
  description TEXT,
  price       DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
  stock       INT DEFAULT 0,
  active      BOOLEAN DEFAULT TRUE,
  created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

SQL command categories

DDL · definition

CREATE, ALTER, DROP, TRUNCATE

DML · manipulation

INSERT, UPDATE, DELETE

DQL · query

SELECT

DCL · control

GRANT, REVOKE

TCL · transactions

BEGIN, COMMIT, ROLLBACK, SAVEPOINT

03Reading and writing

INSERT and SELECT

Add rows, then read back exactly the columns you need.

INSERTsql
INSERT INTO users (id, name, email, age, city)
VALUES (1, 'Rahul', '[email protected]', 25, 'Delhi');

-- several rows in one statement
INSERT INTO users (id, name, email, age, city) VALUES
  (2, 'Priya', '[email protected]', 24, 'Pune'),
  (3, 'Aman',  '[email protected]',  28, 'Noida');
SELECTsql
SELECT * FROM users;                                   -- every column (avoid in production code)
SELECT name, email FROM users;                         -- only what you need
SELECT name AS user_name, email AS user_email FROM users;
SELECT name, age, age + 1 AS age_next_year FROM users; -- expressions
04Filtering

WHERE, precedence, IN, BETWEEN and LIKE

WHERE decides which rows a query reads, updates or deletes.

Comparison and logicsql
SELECT * FROM users WHERE age > 25;
SELECT * FROM users WHERE age >= 18 AND city = 'Delhi';
SELECT * FROM users WHERE city = 'Delhi' OR city = 'Pune';
SELECT * FROM users WHERE NOT city = 'Delhi';          -- also: city <> 'Delhi'
Make the intent explicitsql
SELECT * FROM users
WHERE (city = 'Delhi' OR city = 'Mumbai') AND age > 25;
IN, BETWEEN and LIKEsql
SELECT * FROM users WHERE city IN ('Delhi', 'Pune', 'Mumbai');
SELECT * FROM users WHERE city NOT IN ('Delhi', 'Pune');

SELECT * FROM products WHERE price BETWEEN 500 AND 1000;   -- inclusive on both ends

SELECT * FROM users WHERE name LIKE 'A%';     -- starts with A (can use an index)
SELECT * FROM users WHERE name LIKE '%dev%';  -- contains dev (can't use a normal index)
SELECT * FROM users WHERE name LIKE 'R_hul';  -- _ = exactly one character
05Correctness

NULL, DISTINCT and ORDER BY

NULL is the source of more wrong SQL answers than anything else.

NULL means unknown, not zero and not an empty string. Any comparison with NULL gives UNKNOWN, and WHERE keeps only TRUE rows, so = NULL never matches anything. SQL uses three-valued logic: TRUE, FALSE, UNKNOWN.

Handling NULLsql
SELECT * FROM users WHERE phone = NULL;     -- wrong: always empty
SELECT * FROM users WHERE phone IS NULL;    -- right
SELECT * FROM users WHERE phone IS NOT NULL;

SELECT name, COALESCE(phone, alternate_phone, 'Not provided') AS phone FROM users;
DISTINCT and ORDER BYsql
SELECT DISTINCT city FROM users;
SELECT DISTINCT city, age FROM users;            -- distinct pairs

SELECT * FROM users ORDER BY city ASC, age DESC;
SELECT * FROM orders ORDER BY created_at DESC, id DESC;   -- tie-breaker keeps order stable
06Performance

LIMIT, OFFSET and keyset pagination

OFFSET is fine for page 3. It's a disaster for page 30,000.

OFFSET pagination

  • LIMIT 20 OFFSET 600000 still walks past 600,000 rows
  • Pages shift when new rows arrive
  • Simple, and fine for small tables

Keyset (cursor) pagination

  • WHERE id > :lastSeenId ORDER BY id LIMIT 20
  • Seeks directly through an index
  • Stable even while data changes
Both stylessql
-- OFFSET
SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 40;

-- keyset on one column
SELECT * FROM products WHERE id > 500 ORDER BY id LIMIT 20;

-- keyset on (created_at, id) for a newest-first feed
SELECT * FROM orders
WHERE (created_at, id) < ('2026-11-18 10:00:00', 5000)    -- row-value comparison
ORDER BY created_at DESC, id DESC
LIMIT 20;
07Changing data

UPDATE, DELETE, TRUNCATE, DROP and ALTER

The commands that change data. One missing WHERE can ruin your day.

UPDATE and DELETEsql
UPDATE users SET age = 26 WHERE id = 1;
UPDATE products SET price = 899.00, updated_at = CURRENT_TIMESTAMP WHERE id = 100;

DELETE FROM users WHERE id = 5;
DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;

UPDATE users SET active = FALSE;   -- no WHERE: every row changes
DELETE FROM users;                 -- no WHERE: every row is gone
CommandRemovesWHERE?Typical behaviour
DELETEChosen rowsYesRow by row, logged, can roll back
TRUNCATEAll rowsNoFast, keeps the table, often resets identity
DROPThe whole tableNoStructure, data and indexes are gone
ALTER TABLEsql
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users ADD COLUMN active BOOLEAN DEFAULT TRUE;
ALTER TABLE users DROP COLUMN phone;
ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email);
08Integrity

Constraints and foreign key actions

Let the database enforce the rules, so bad data can't get in no matter which code path writes it.

Constraints in one tablesql
CREATE TABLE employees (
  id            BIGINT PRIMARY KEY,
  email         VARCHAR(255) UNIQUE NOT NULL,
  name          VARCHAR(100) NOT NULL,
  age           INT CHECK (age >= 18),
  status        VARCHAR(20) DEFAULT 'ACTIVE',
  department_id BIGINT,
  CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(id)
);

NOT NULL

A value is required.

UNIQUE

No duplicate values.

PRIMARY KEY

Unique + not null; identifies the row.

FOREIGN KEY

Must match a row in the referenced table.

CHECK

A condition every row must satisfy.

DEFAULT

The value used when none is given.

What happens when the referenced row changes

ActionEffect
ON DELETE CASCADEDeleting the parent deletes its children too.
ON DELETE SET NULLChildren keep existing; their foreign key becomes NULL.
RESTRICT / NO ACTIONThe delete is blocked while children exist.
ON UPDATE CASCADEA changed parent key is copied to its children.
09Analysis

Aggregates, GROUP BY and HAVING

Collapse many rows into summaries, per group, and filter those summaries.

Aggregate functionssql
SELECT COUNT(*)               FROM orders;   -- every row
SELECT COUNT(phone)           FROM users;    -- skips NULLs
SELECT COUNT(DISTINCT user_id) FROM orders;
SELECT SUM(amount), AVG(amount), MIN(amount), MAX(amount) FROM orders;
Per-group summariessql
SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_spent
FROM   orders
WHERE  status = 'PAID'          -- rows, before grouping
GROUP  BY user_id
HAVING SUM(amount) > 10000;     -- groups, after aggregating

The logical order of execution

  1. FROM and JOIN

    Build the working set of rows.

  2. WHERE

    Keep only rows that match.

  3. GROUP BY

    Form groups.

  4. HAVING

    Keep only groups that match.

  5. SELECT

    Compute the output columns and aliases.

  6. DISTINCT

    Remove duplicate output rows.

  7. ORDER BY

    Sort (aliases from SELECT are visible here).

  8. LIMIT / OFFSET

    Return only part of the result.

10Combining tables

Joins and set operations

Joins combine columns from related tables; set operators combine whole result sets.

JoinReturns
INNER JOINOnly rows that match on both sides.
LEFT JOINEvery left row, plus matches (NULLs where none).
RIGHT JOINEvery right row, plus matches.
FULL OUTER JOINEverything from both sides, matched where possible.
CROSS JOINEvery combination (rows × rows).
SELF JOINA table joined to itself, using aliases.
The joins you'll use dailysql
-- matching rows only
SELECT u.name, o.id AS order_id, o.amount
FROM   users u
JOIN   orders o ON o.user_id = u.id;

-- all users, with orders if they have any
SELECT u.name, o.id AS order_id
FROM   users u
LEFT   JOIN orders o ON o.user_id = u.id;

-- users with NO orders (anti-join)
SELECT u.id, u.name
FROM   users u
LEFT   JOIN orders o ON o.user_id = u.id
WHERE  o.id IS NULL;
Self join: employees and their managerssql
SELECT e.name AS employee, m.name AS manager
FROM   employees e
LEFT   JOIN employees m ON e.manager_id = m.id;
Cross join: generate combinationssql
SELECT c.name AS colour, s.name AS size
FROM   colours c
CROSS  JOIN sizes s;        -- 4 colours × 3 sizes = 12 rows

Set operations

UNION, UNION ALL, INTERSECT, EXCEPTsql
SELECT email FROM customers UNION     SELECT email FROM newsletter_users;  -- de-duplicated
SELECT email FROM customers UNION ALL SELECT email FROM newsletter_users;  -- keeps duplicates, faster
SELECT email FROM customers INTERSECT SELECT email FROM newsletter_users;  -- in both
SELECT email FROM customers EXCEPT    SELECT email FROM newsletter_users;  -- first, not second
11Nesting

Subqueries, correlated subqueries and EXISTS

Queries inside queries, and the NULL trap that catches almost everyone.

Scalar and multi-row subqueriessql
-- products pricier than average (scalar: one value)
SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);

-- users who placed a large order (multi-row)
SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE amount > 5000);
Correlated subquery with EXISTSsql
SELECT u.id, u.name
FROM   users u
WHERE  EXISTS (
  SELECT 1 FROM orders o
  WHERE  o.user_id = u.id AND o.amount > 5000   -- references the outer row
);
The safe anti-joinsql
SELECT * FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
12Readability

Common table expressions and recursion

Name your intermediate steps so complex queries read top to bottom, and walk hierarchies with recursion.

A CTEsql
WITH high_value_orders AS (
  SELECT id, user_id, amount FROM orders WHERE amount >= 5000
)
SELECT u.name, h.amount
FROM   high_value_orders h
JOIN   users u ON u.id = h.user_id;
Recursive CTE: an org chartsql
WITH RECURSIVE employee_tree AS (
  SELECT id, name, manager_id, 1 AS level      -- anchor: the CEO
  FROM   employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, t.level + 1   -- recursive step
  FROM   employees e
  JOIN   employee_tree t ON e.manager_id = t.id
)
SELECT * FROM employee_tree ORDER BY level, name;
13Expressions

CASE and built-in functions

Conditional logic and value transformations inside a query.

CASE, and conditional aggregationsql
SELECT name, price,
       CASE WHEN price >= 5000 THEN 'Premium'
            WHEN price >= 1000 THEN 'Mid range'
            ELSE 'Budget' END AS price_category
FROM products;

-- count several categories in one pass
SELECT COUNT(*) FILTER (WHERE status = 'PAID')     AS paid,      -- PostgreSQL
       SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed  -- portable
FROM orders;
FamilyFunctionsWatch out
StringUPPER, LOWER, LENGTH, CONCAT, TRIM, SUBSTRINGNames vary (LEN in SQL Server)
NumericROUND, ABS, CEIL, FLOOR, POWER, MODInteger division truncates in some engines
Date / timeCURRENT_DATE, NOW(), DATE_TRUNC, INTERVALMost engine-specific area; agree on UTC
NULL handlingCOALESCE, NULLIFCOALESCE returns the first non-NULL argument
14Interview favourite

Window functions

Calculate across related rows without collapsing them. The most-asked advanced SQL topic.

GROUP BY

  • One row per group
  • Detail rows disappear
  • SUM(salary) per department

Window function

  • Every row stays
  • Adds a computed column
  • Each employee + their department average
A per-department average beside each rowsql
SELECT employee_id, department_id, salary,
       AVG(salary) OVER (PARTITION BY department_id) AS dept_avg_salary
FROM   employees;
ROW_NUMBER, RANK and DENSE_RANKsql
SELECT employee_id, department_id, salary,
       ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS row_num,
       RANK()       OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk,
       DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dense_rnk
FROM   employees;
SalaryROW_NUMBERRANKDENSE_RANK
100111
100211
90332
80443
LAG, LEAD and a running totalsql
SELECT order_date, revenue,
       LAG(revenue)  OVER (ORDER BY order_date) AS prev_day,
       LEAD(revenue) OVER (ORDER BY order_date) AS next_day,
       revenue - LAG(revenue) OVER (ORDER BY order_date) AS change,
       SUM(revenue)  OVER (ORDER BY order_date
                           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM   daily_revenue;
15Design

Normalisation and relationships

Store each fact once; connect entities with keys.

FormRuleGoal
1NFAtomic values, no repeating groupsNo lists inside a column
2NF1NF + no partial dependencyNothing depends on part of a composite key
3NF2NF + no transitive dependencyNon-key columns depend only on the key
BCNFEvery determinant is a candidate keyStricter 3NF

Before: one wide table

  • orders(order_id, customer_name, customer_phone, products = 'Book, Pen, Bag')
  • A list inside a column
  • Customer data repeated on every order

After: normalised

  • customers(id, name, phone)
  • orders(id, customer_id, created_at)
  • products(id, name, price)
  • order_items(order_id, product_id, quantity, price)

Relationship types

One-to-one

user → user_profile. The foreign key is also unique.

One-to-many

user → orders. The foreign key is on the “many” side.

Many-to-many

students ↔ courses, through a junction table.

A many-to-many junction tablesql
CREATE TABLE student_courses (
  student_id BIGINT REFERENCES students(id),
  course_id  BIGINT REFERENCES courses(id),
  PRIMARY KEY (student_id, course_id)        -- a student enrols once per course
);
16Abstraction

Views and materialised views

Save a query under a name, or save its result.

ViewMaterialised view
StoresThe queryThe query and its result
FreshnessAlways currentStale until refreshed
Read speedSame as the queryFast (pre-computed)
Use forAbstraction, access controlExpensive reports and dashboards
Bothsql
CREATE VIEW active_users AS
SELECT id, name, email FROM users WHERE active = TRUE;

-- PostgreSQL
CREATE MATERIALIZED VIEW monthly_sales AS
SELECT DATE_TRUNC('month', created_at) AS month, SUM(amount) AS revenue
FROM   orders GROUP BY 1;

REFRESH MATERIALIZED VIEW monthly_sales;
17Performance

Indexes and EXPLAIN

Like the index at the back of a book: find the page instead of reading every page.

Create an index, then use itsql
CREATE INDEX idx_users_email ON users (email);
SELECT * FROM users WHERE email = '[email protected]';   -- index lookup, not a full scan
Index typeTypical useNotes
B-treeEquality, ranges, ORDER BYThe default, general-purpose
HashEquality onlySupport varies by engine
CompositeMulti-column filtersColumn order matters
UniqueUniqueness + lookupRejects duplicates
Partial / filteredA subset of rowse.g. WHERE status = 'ACTIVE'
Full-textNatural-language text searchUse it, not LIKE '%word%'
GIN / GiSTArrays, JSONB, full-text, geometryPostgreSQL

Composite indexes and column order

Leftmost-prefix rulesql
CREATE INDEX idx_orders_user_status_created ON orders (user_id, status, created_at);

-- great: equality, equality, then the sort column
SELECT * FROM orders WHERE user_id = 100 AND status = 'SUCCESS' ORDER BY created_at DESC;

-- fine: uses the first column
SELECT * FROM orders WHERE user_id = 100;

-- poor: skips the leading column
SELECT * FROM orders WHERE status = 'SUCCESS';

Put equality columns first and range or sort columns last. A covering index includes every column a query needs, so the database never touches the table.

Read the plan

EXPLAINsql
EXPLAIN SELECT * FROM orders WHERE user_id = 100;           -- the plan
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 100;   -- the plan + real timings (PostgreSQL)

Look out for

  • Seq scan / full table scan on a big table
  • Estimated rows far from actual
  • Sorts that spill to disk
  • Nested loops over large inputs

Typical fixes

  • Add or reorder an index
  • ANALYZE to refresh statistics
  • Rewrite the predicate to be sargable
  • Filter earlier; select fewer columns
18Correctness

Transactions, ACID and isolation

Group statements so they succeed or fail together, and decide how much concurrent work can see.

Commit, roll back, savepointsql
BEGIN;
UPDATE accounts SET balance = balance - 1000 WHERE id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
COMMIT;                                       -- both, or (on error) ROLLBACK for neither

BEGIN;
INSERT INTO orders (id, user_id) VALUES (9, 42);
SAVEPOINT order_created;
INSERT INTO payment_attempts (order_id) VALUES (9);
ROLLBACK TO SAVEPOINT order_created;          -- undo only the payment attempt
COMMIT;

Atomicity

All of it happens, or none of it.

Consistency

Constraints hold before and after.

Isolation

Concurrent transactions don't interfere beyond the chosen level.

Durability

Committed data survives a crash.

Isolation levelDirty readNon-repeatable readPhantom read
Read uncommittedPossiblePossiblePossible
Read committedPreventedPossiblePossible
Repeatable readPreventedPreventedEngine-dependent
SerializablePreventedPreventedPrevented

Dirty read

Seeing another transaction's uncommitted change.

Non-repeatable read

The same row has a different value on a second read.

Phantom read

A repeated range query returns new or missing rows.

19Concurrency

Locking, optimistic concurrency and deadlocks

How the database, and your code, keep concurrent updates from corrupting data.

OptimisticPessimistic
AssumesConflicts are rareConflicts are likely
Locks earlyNoYes
MechanismVersion columnSELECT … FOR UPDATE
ConcurrencyHighLower
On conflictDetect and retryWait
Pessimistic: lock the rowsql
BEGIN;
SELECT * FROM inventory WHERE product_id = 100 FOR UPDATE;   -- others wait
UPDATE inventory SET stock = stock - 1 WHERE product_id = 100;
COMMIT;
Optimistic: check the versionsql
UPDATE products
SET    stock = stock - 1, version = version + 1
WHERE  id = 100 AND version = 7;
-- 0 rows affected → someone else changed it first; re-read and retry

Deadlocks

Transaction AHolds row 1, needs row 2
Transaction BHolds row 2, needs row 1

Each waits for the other. The database detects the cycle and aborts one as the victim.

Lock in a consistent order

e.g. always by ascending id.

Keep transactions short

No user interaction or network calls inside.

Index the WHERE columns

So fewer rows are locked.

Retry the victim

Deadlock errors are expected; retry with backoff.

20In-database logic

Stored procedures, triggers and partitioning

Tools that run inside the database. Powerful, and easy to overuse.

Stored procedures and functions

  • Encapsulate repeated database work
  • Fewer round trips for multi-step operations
  • Can restrict direct table access
  • Syntax is very engine-specific; harder to test

Triggers

  • Run automatically on INSERT / UPDATE / DELETE
  • Good for auditing and invariants
  • Hidden behaviour that surprises developers
  • Hard to debug when there are many

Table partitioning

Range

orders by month or year; old partitions drop cheaply.

List

Rows by region or category.

Hash

Rows spread by a hash of a key.

21Security

SQL injection

When user input becomes part of the SQL text, attackers can rewrite your query.

Unsafe: never build SQL from inputjs
// email = "' OR '1'='1"  →  returns every user
const sql = "SELECT * FROM users WHERE email = '" + email + "'";
Safe: parameterised queryjs
const sql = "SELECT * FROM users WHERE email = ?";   // $1 in PostgreSQL drivers
await db.execute(sql, [email]);                      // the value is sent separately, as data

Parameterise every query

Prepared statements or your driver's placeholders.

Allow-list identifiers

Table and column names can't be parameters, so check them against a fixed list.

Least-privilege accounts

The app user can't DROP tables.

Hide database errors

Never show raw SQL errors to users.

22Performance

Query optimisation

Measure first: read the plan, then fix what it shows.

  • Select only needed columns
  • Filter early
  • Index real access patterns
  • Index foreign keys used in joins
  • Avoid needless DISTINCT and sorts
  • Keep predicates sargable
  • Avoid leading-wildcard LIKE on big tables
  • Use the right data types
  • Kill N+1 queries
  • Batch writes
  • Keep transactions short
  • Keyset pagination
  • Partition or archive huge history
  • Watch the slow-query log
Common performance mistakessql
SELECT * FROM large_orders;                       -- 1. every column
SELECT id, user_id, amount FROM large_orders;     --    better

WHERE LOWER(email) = '[email protected]'           -- 2. function on an indexed column
                                                  --    fix: store normalised, or an expression index

WHERE name LIKE '%developer%'                     -- 3. leading wildcard: no index
                                                  --    fix: full-text search

LIMIT 20 OFFSET 500000                            -- 4. huge offset → keyset pagination

SELECT * FROM users, orders;                      -- 5. accidental cartesian product
23Putting it together

A real e-commerce schema

How the concepts combine in a production-style relational design.

Schemasql
CREATE TABLE users      (id BIGINT PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_at TIMESTAMPTZ DEFAULT now());
CREATE TABLE products   (id BIGINT PRIMARY KEY, name TEXT NOT NULL, price NUMERIC(10,2) NOT NULL, stock INT NOT NULL DEFAULT 0, active BOOLEAN DEFAULT TRUE);
CREATE TABLE orders     (id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(id), status TEXT NOT NULL, total_amount NUMERIC(10,2) NOT NULL, created_at TIMESTAMPTZ DEFAULT now());
CREATE TABLE order_items(id BIGINT PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, product_id BIGINT NOT NULL REFERENCES products(id), quantity INT NOT NULL CHECK (quantity > 0), unit_price NUMERIC(10,2) NOT NULL);
CREATE TABLE payments   (id BIGINT PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders(id), provider TEXT NOT NULL, status TEXT NOT NULL, amount NUMERIC(10,2) NOT NULL, transaction_id TEXT UNIQUE, created_at TIMESTAMPTZ DEFAULT now());
CREATE TABLE reviews    (id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(id), product_id BIGINT NOT NULL REFERENCES products(id), rating INT CHECK (rating BETWEEN 1 AND 5), comment TEXT, UNIQUE (user_id, product_id));

CREATE INDEX idx_orders_user_created ON orders (user_id, created_at DESC);
CREATE INDEX idx_order_items_order    ON order_items (order_id);
Today's orders with item countssql
SELECT o.id AS order_id, u.name AS customer, o.status, o.total_amount, COUNT(oi.id) AS total_items
FROM   orders o
JOIN   users u        ON u.id = o.user_id
JOIN   order_items oi ON oi.order_id = o.id
WHERE  o.created_at >= CURRENT_DATE
GROUP  BY o.id, u.name, o.status, o.total_amount
ORDER  BY o.created_at DESC;
24Interview practice

Solved interview queries

The patterns that come up again and again in backend, data and SDE interviews. Try each one before reading the solution.

Second-highest salarysql
SELECT MAX(salary) AS second_highest
FROM   employees
WHERE  salary < (SELECT MAX(salary) FROM employees);
Nth-highest salary (here N = 3)sql
WITH ranked AS (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees
)
SELECT DISTINCT salary FROM ranked WHERE rnk = 3;
Duplicate emailssql
SELECT email, COUNT(*) AS occurrences
FROM   users
GROUP  BY email
HAVING COUNT(*) > 1;
Delete duplicates, keep the lowest idsql
DELETE FROM users u
USING  users d
WHERE  u.email = d.email AND u.id > d.id;          -- PostgreSQL; use a CTE + ROW_NUMBER elsewhere
Employees who earn more than their managersql
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM   employees e
JOIN   employees m ON e.manager_id = m.id
WHERE  e.salary > m.salary;
Top 3 salaries in every departmentsql
WITH ranked AS (
  SELECT id, name, department_id, salary,
         DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
  FROM   employees
)
SELECT * FROM ranked WHERE rnk <= 3;
Latest order for every usersql
WITH ranked AS (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn
  FROM   orders o
)
SELECT * FROM ranked WHERE rn = 1;
Month-over-month revenue growthsql
WITH monthly AS (
  SELECT DATE_TRUNC('month', created_at) AS month, SUM(amount) AS revenue
  FROM   orders WHERE status = 'SUCCESS'
  GROUP  BY 1
)
SELECT month, revenue,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 2) AS growth_pct
FROM   monthly ORDER BY month;
Users who logged in on 3+ consecutive dayssql
WITH days AS (
  SELECT DISTINCT user_id, login_date::date AS d FROM logins
), grp AS (
  SELECT user_id, d, d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS island
  FROM days
)
SELECT user_id, MIN(d) AS from_day, MAX(d) AS to_day, COUNT(*) AS streak
FROM   grp GROUP BY user_id, island
HAVING COUNT(*) >= 3;     -- the "gaps and islands" trick

Practise these next

  • First order for every customer
  • Customers with more than 5 orders
  • Most frequently purchased product
  • Products above their category average
  • Departments above the company average salary
  • Records repeated 3 times in a row
  • Running total per user
  • Median salary per department
25Revision

SQL cheat sheet

The syntax you'll reach for most often, on one screen.

Quick revisionsql
SELECT col1, col2 FROM t WHERE age >= 18 ORDER BY created_at DESC LIMIT 10;
SELECT city, COUNT(*) FROM users GROUP BY city HAVING COUNT(*) > 10;
SELECT * FROM users u JOIN orders o ON o.user_id = u.id;
SELECT * FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.id IS NULL;
SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);
WITH data AS (SELECT * FROM orders) SELECT * FROM data;
SELECT name, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees;
SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
SELECT * FROM users WHERE phone IS NULL;
SELECT name, CASE WHEN age >= 18 THEN 'Adult' ELSE 'Minor' END FROM users;
CREATE INDEX idx_users_email ON users (email);
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;
Interview prep

SQL interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

What is SQL, and how is it different from MySQL?

SQL is a language. MySQL, PostgreSQL, SQL Server, Oracle and SQLite are database systems that implement it, each with its own extensions and small syntax differences.

2

Primary key vs unique key?

Both enforce uniqueness. A table has exactly one primary key; it can't be NULL and it identifies the row (often the clustered index). A table can have many unique keys, and most databases allow NULLs in them.

3

What is a foreign key?

A column (or set) that must match a key in another table, enforcing referential integrity: you can't add an order for a user who doesn't exist. ON DELETE and ON UPDATE rules decide what happens when the referenced row changes.

4

Candidate, composite, natural and surrogate keys?

A candidate key is any minimal column set that uniquely identifies rows; one becomes the primary key. A composite key spans several columns. A natural key comes from the real world (an email); a surrogate key is artificial (an auto-increment ID or UUID).

5

DELETE vs TRUNCATE vs DROP?

DELETE removes chosen rows (WHERE) row by row and can be rolled back. TRUNCATE quickly removes all rows and keeps the table, often resetting identity counters. DROP removes the table itself. Locking and transaction behaviour vary by engine.

6

WHERE vs HAVING?

WHERE filters rows before grouping; HAVING filters groups after aggregation. Use WHERE for row conditions (status = 'PAID') and HAVING for aggregate conditions (SUM(amount) > 10000).

7

In what order does SQL logically run a query?

FROM and JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT/OFFSET. That's why a SELECT alias can't be used in WHERE but can be used in ORDER BY.

8

UNION vs UNION ALL?

UNION combines results and removes duplicates, which needs a sort or hash. UNION ALL keeps duplicates and is cheaper. Use UNION ALL unless you actually need de-duplication.

9

INNER JOIN vs LEFT JOIN?

INNER JOIN returns only rows that match on both sides. LEFT JOIN returns every row from the left table plus matches, with NULLs where there's no match, which is why LEFT JOIN … WHERE right.id IS NULL finds rows with no match.

10

IN vs EXISTS, and why is NOT IN dangerous?

Both test membership; EXISTS stops at the first match and suits correlated checks. NOT IN returns no rows at all if the subquery yields a single NULL, because x NOT IN (1, NULL) is UNKNOWN. NOT EXISTS doesn't have that problem.

11

What is a correlated subquery?

A subquery that references the outer query's current row, so logically it runs once per outer row. EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id) is the classic example. Index the correlation column.

12

CTE vs subquery?

A CTE (WITH …) names a subquery so complex logic reads top to bottom, can be referenced several times, and can be recursive. Performance is usually similar; some engines materialise CTEs, so check the plan.

13

What is a recursive CTE?

A CTE with an anchor query plus a recursive part that references the CTE itself, joined with UNION ALL. It repeats until no new rows appear. It's used for hierarchies such as org charts, category trees and folder paths.

14

What are window functions?

Functions that compute over a set of related rows (the window, defined by OVER (PARTITION BY … ORDER BY …)) without collapsing them like GROUP BY does. Each row keeps its detail and gains a computed column: a rank, a running total, the previous value.

15

ROW_NUMBER vs RANK vs DENSE_RANK?

For salaries 100, 100, 90: ROW_NUMBER gives 1, 2, 3 (always unique); RANK gives 1, 1, 3 (ties share, then a gap); DENSE_RANK gives 1, 1, 2 (ties share, no gap). Use DENSE_RANK for “Nth highest distinct value”.

16

What are LAG and LEAD?

They read a column from the previous (LAG) or next (LEAD) row in the window's order. They're ideal for day-over-day growth, gaps between events and finding consecutive values, without a self-join.

17

What is normalisation? Explain 1NF, 2NF, 3NF and BCNF.

Organising tables to remove redundancy and update anomalies. 1NF: atomic values, no repeating groups. 2NF: no non-key column depends on only part of a composite key. 3NF: no non-key column depends on another non-key column. BCNF: every determinant is a candidate key.

18

What is an index, and how does a B-tree index work?

An extra structure that finds rows without scanning the table. A B-tree keeps keys sorted in a balanced tree of pages, so equality, range and ORDER BY lookups take a few page reads, O(log n), even on huge tables.

19

When should you not add an index?

On small tables, low-selectivity columns (a boolean flag), write-heavy tables where the extra maintenance hurts, or columns no real query filters or sorts on. Each index slows writes and uses storage.

20

What is the leftmost-prefix rule, and what is a covering index?

A composite index on (a, b, c) helps queries filtering on a, on a and b, or on a, b and c, but not on b alone. A covering index contains every column a query needs, so the database answers from the index without touching the table.

21

Clustered vs non-clustered index?

A clustered index defines the physical order of the table's rows (InnoDB clusters on the primary key), so there's only one. Non-clustered (secondary) indexes are separate structures pointing back to the rows.

22

Explain ACID and the isolation anomalies.

Atomicity, consistency, isolation and durability. The anomalies isolation prevents: a dirty read (seeing uncommitted data), a non-repeatable read (a row changes between reads) and a phantom read (new rows appear in a repeated range query).

23

What is a deadlock, and how do you prevent it?

Two transactions each hold a lock the other needs, so neither can continue; the database kills one as the victim. Prevent it by locking rows in a consistent order, keeping transactions short, indexing so fewer rows lock, and retrying the victim.

24

View vs materialised view?

A view stores a query and runs it every time, so it's always fresh. A materialised view stores the result, so reads are fast, but it must be refreshed and can be stale. Use views for abstraction and access control, materialised views for expensive reports.

25

What does EXPLAIN do?

It shows the plan the optimiser chose: scan types, the indexes used, the join algorithms and order, and estimated rows. EXPLAIN ANALYZE also runs the query and reports actual rows and timings.

26

Why can SELECT * be inefficient?

It reads and sends every column, defeats covering indexes, wastes network and memory, and breaks silently when columns change. Select only the columns you need.

27

OFFSET vs keyset (cursor) pagination?

OFFSET 100000 still makes the database walk past 100,000 rows, and pages shift when data changes. Keyset pagination (WHERE id > :lastId ORDER BY id LIMIT 20) jumps straight to the position through an index and stays stable.

28

What is SQL injection, and how do prepared statements prevent it?

Injection happens when user input is concatenated into SQL and changes its meaning, for example ' OR '1'='1. Prepared statements send the SQL and the values separately, so input is always treated as data, never as code.

29

Partitioning vs sharding?

Partitioning splits one logical table into pieces inside one database, for example by month. Sharding spreads data across separate database servers. Partitioning helps manageability and pruning; sharding scales storage and writes horizontally.

30

SQL vs NoSQL: when do you choose each?

Choose SQL for transactions, constraints, joins and flexible queries: money, orders, inventory. Choose NoSQL when one access pattern dominates at huge scale or the data is naturally schemaless, and accept fewer transactional guarantees.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

Which query finds users with a NULL phone?

Reference

SQL glossary

The terms from this guide, in one line each.

DDL / DML / DQL
Defining structure (CREATE, ALTER) / changing data (INSERT, UPDATE) / querying (SELECT).
Primary key
The column(s) that uniquely identify each row; never NULL.
Foreign key
A column that must match a key in another table.
NULL
An unknown or missing value: not zero, not an empty string.
JOIN
Combining rows from tables using related columns.
Subquery
A query nested inside another; correlated if it uses the outer row.
CTE
A named temporary result set defined with WITH.
Window function
A calculation over related rows using OVER(), keeping each row.
Index
A sorted structure that finds rows without a full scan.
Execution plan
How the database will run a query; shown by EXPLAIN.
Transaction
A group of statements that commit or roll back together.
Deadlock
Two transactions waiting on each other's locks forever.
Summary

Key takeaways

  1. SQL is declarative: describe the result, and let the optimiser choose the plan. Then check the plan.
  2. Know the logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
  3. NULL means unknown: use IS NULL, COALESCE, and NOT EXISTS instead of NOT IN.
  4. Joins, GROUP BY + HAVING, CTEs and window functions solve most interview problems.
  5. Design indexes from real queries; respect the leftmost-prefix rule and the write cost.
  6. Keep transactions short, lock in a consistent order, and know your isolation level.
  7. Always parameterise queries. Concatenated SQL is an injection waiting to happen.
Questions

SQL: frequently asked questions

How long does it take to learn SQL?

Basic querying (SELECT, WHERE, JOIN, GROUP BY) takes one to two weeks of practice. Interview-level SQL (subqueries, CTEs, window functions, indexes and transactions) usually takes four to six weeks of regular problem solving.

Which SQL topics are asked most in interviews?

Joins, GROUP BY with HAVING, subqueries and EXISTS, window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG/LEAD), Nth-highest salary, duplicate detection, indexes, transactions, isolation levels and query optimisation.

Should I learn MySQL or PostgreSQL?

Either. The core SQL is the same. PostgreSQL is stricter and has richer features (CTEs, window functions, JSONB, partial indexes); MySQL is very common in industry. Learn one well and note the differences.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after aggregate functions like COUNT or SUM have been calculated.

What is the best way to find the Nth highest salary?

Use DENSE_RANK() OVER (ORDER BY salary DESC) in a CTE and select the rows where the rank equals N. It handles ties correctly and works for any N.

Are window functions supported in MySQL?

Yes, from MySQL 8.0. PostgreSQL, SQL Server, Oracle and SQLite (3.25+) also support them.

Next topicAPI Engineering

REST, HTTP, GraphQL, authentication, pagination, idempotency, caching, rate limiting and webhooks: the contract on top of your data.

Go deeperSQL Interview Handbook

Hundreds of interview-style problems with step-by-step solutions, from joins and window functions to schema design and query tuning.

  • Joins
  • Window functions
  • CTEs
  • Indexes
  • Transactions
  • Interview problems
Explore the SQL handbook

Last reviewed 18 November 2026