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.
-- 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
| Term | Meaning |
|---|---|
| Schema | The logical structure: tables, columns, types, constraints. |
| Row / tuple / record | One entry in a table. |
| Column / attribute | One property of the entity. |
| Primary key | Uniquely identifies each row; never NULL. |
| Foreign key | References a key in another table. |
| Candidate key | Any minimal column set that could be the primary key. |
| Super key | Any column set that uniquely identifies rows (may include extras). |
| Alternate key | A candidate key not chosen as the primary key. |
| Composite key | A key made of several columns. |
| Natural vs surrogate key | A real-world value (email) vs an artificial one (auto ID, UUID). |
Data types, tables and SQL command categories
Pick precise types, define tables with constraints, and know which family each command belongs to.
| Type | Use it for | Note |
|---|---|---|
| INT / BIGINT / SMALLINT | Whole numbers | BIGINT for IDs that may exceed ~2 billion |
| DECIMAL(p, s) / NUMERIC | Money, exact values | Never FLOAT for money |
| FLOAT / DOUBLE | Scientific, approximate values | Rounding errors are expected |
| CHAR(n) / VARCHAR(n) / TEXT | Fixed, variable and long text | VARCHAR for most strings |
| DATE / TIME / TIMESTAMP | Dates and times | Store in UTC (TIMESTAMPTZ in PostgreSQL) |
| BOOLEAN | True / false | MySQL maps it to TINYINT(1) |
| JSON / JSONB | Semi-structured data | JSONB is indexable in PostgreSQL |
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
INSERT and SELECT
Add rows, then read back exactly the columns you need.
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');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; -- expressionsWHERE, precedence, IN, BETWEEN and LIKE
WHERE decides which rows a query reads, updates or deletes.
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'SELECT * FROM users
WHERE (city = 'Delhi' OR city = 'Mumbai') AND age > 25;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 characterNULL, 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.
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;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 stableLIMIT, 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
-- 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;UPDATE, DELETE, TRUNCATE, DROP and ALTER
The commands that change data. One missing WHERE can ruin your day.
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| Command | Removes | WHERE? | Typical behaviour |
|---|---|---|---|
| DELETE | Chosen rows | Yes | Row by row, logged, can roll back |
| TRUNCATE | All rows | No | Fast, keeps the table, often resets identity |
| DROP | The whole table | No | Structure, data and indexes are gone |
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);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.
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
| Action | Effect |
|---|---|
| ON DELETE CASCADE | Deleting the parent deletes its children too. |
| ON DELETE SET NULL | Children keep existing; their foreign key becomes NULL. |
| RESTRICT / NO ACTION | The delete is blocked while children exist. |
| ON UPDATE CASCADE | A changed parent key is copied to its children. |
Aggregates, GROUP BY and HAVING
Collapse many rows into summaries, per group, and filter those summaries.
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;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 aggregatingThe logical order of execution
FROM and JOIN
Build the working set of rows.
WHERE
Keep only rows that match.
GROUP BY
Form groups.
HAVING
Keep only groups that match.
SELECT
Compute the output columns and aliases.
DISTINCT
Remove duplicate output rows.
ORDER BY
Sort (aliases from SELECT are visible here).
LIMIT / OFFSET
Return only part of the result.
Joins and set operations
Joins combine columns from related tables; set operators combine whole result sets.
| Join | Returns |
|---|---|
| INNER JOIN | Only rows that match on both sides. |
| LEFT JOIN | Every left row, plus matches (NULLs where none). |
| RIGHT JOIN | Every right row, plus matches. |
| FULL OUTER JOIN | Everything from both sides, matched where possible. |
| CROSS JOIN | Every combination (rows × rows). |
| SELF JOIN | A table joined to itself, using aliases. |
-- 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;SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;SELECT c.name AS colour, s.name AS size
FROM colours c
CROSS JOIN sizes s; -- 4 colours × 3 sizes = 12 rowsSet operations
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 secondSubqueries, correlated subqueries and EXISTS
Queries inside queries, and the NULL trap that catches almost everyone.
-- 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);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
);SELECT * FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Common table expressions and recursion
Name your intermediate steps so complex queries read top to bottom, and walk hierarchies with recursion.
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;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;CASE and built-in functions
Conditional logic and value transformations inside a query.
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;| Family | Functions | Watch out |
|---|---|---|
| String | UPPER, LOWER, LENGTH, CONCAT, TRIM, SUBSTRING | Names vary (LEN in SQL Server) |
| Numeric | ROUND, ABS, CEIL, FLOOR, POWER, MOD | Integer division truncates in some engines |
| Date / time | CURRENT_DATE, NOW(), DATE_TRUNC, INTERVAL | Most engine-specific area; agree on UTC |
| NULL handling | COALESCE, NULLIF | COALESCE returns the first non-NULL argument |
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
SELECT employee_id, department_id, salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg_salary
FROM employees;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;| Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
| 80 | 4 | 4 | 3 |
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;Normalisation and relationships
Store each fact once; connect entities with keys.
| Form | Rule | Goal |
|---|---|---|
| 1NF | Atomic values, no repeating groups | No lists inside a column |
| 2NF | 1NF + no partial dependency | Nothing depends on part of a composite key |
| 3NF | 2NF + no transitive dependency | Non-key columns depend only on the key |
| BCNF | Every determinant is a candidate key | Stricter 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.
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
);Views and materialised views
Save a query under a name, or save its result.
| View | Materialised view | |
|---|---|---|
| Stores | The query | The query and its result |
| Freshness | Always current | Stale until refreshed |
| Read speed | Same as the query | Fast (pre-computed) |
| Use for | Abstraction, access control | Expensive reports and dashboards |
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;Indexes and EXPLAIN
Like the index at the back of a book: find the page instead of reading every page.
CREATE INDEX idx_users_email ON users (email);
SELECT * FROM users WHERE email = '[email protected]'; -- index lookup, not a full scan| Index type | Typical use | Notes |
|---|---|---|
| B-tree | Equality, ranges, ORDER BY | The default, general-purpose |
| Hash | Equality only | Support varies by engine |
| Composite | Multi-column filters | Column order matters |
| Unique | Uniqueness + lookup | Rejects duplicates |
| Partial / filtered | A subset of rows | e.g. WHERE status = 'ACTIVE' |
| Full-text | Natural-language text search | Use it, not LIKE '%word%' |
| GIN / GiST | Arrays, JSONB, full-text, geometry | PostgreSQL |
Composite indexes and column order
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
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
Transactions, ACID and isolation
Group statements so they succeed or fail together, and decide how much concurrent work can see.
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 level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible |
| Read committed | Prevented | Possible | Possible |
| Repeatable read | Prevented | Prevented | Engine-dependent |
| Serializable | Prevented | Prevented | Prevented |
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.
Locking, optimistic concurrency and deadlocks
How the database, and your code, keep concurrent updates from corrupting data.
| Optimistic | Pessimistic | |
|---|---|---|
| Assumes | Conflicts are rare | Conflicts are likely |
| Locks early | No | Yes |
| Mechanism | Version column | SELECT … FOR UPDATE |
| Concurrency | High | Lower |
| On conflict | Detect and retry | Wait |
BEGIN;
SELECT * FROM inventory WHERE product_id = 100 FOR UPDATE; -- others wait
UPDATE inventory SET stock = stock - 1 WHERE product_id = 100;
COMMIT;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 retryDeadlocks
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.
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.
SQL injection
When user input becomes part of the SQL text, attackers can rewrite your query.
// email = "' OR '1'='1" → returns every user
const sql = "SELECT * FROM users WHERE email = '" + email + "'";const sql = "SELECT * FROM users WHERE email = ?"; // $1 in PostgreSQL drivers
await db.execute(sql, [email]); // the value is sent separately, as dataParameterise 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.
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
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 productA real e-commerce schema
How the concepts combine in a production-style relational design.
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);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;Solved interview queries
The patterns that come up again and again in backend, data and SDE interviews. Try each one before reading the solution.
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);WITH ranked AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees
)
SELECT DISTINCT salary FROM ranked WHERE rnk = 3;SELECT email, COUNT(*) AS occurrences
FROM users
GROUP BY email
HAVING COUNT(*) > 1;DELETE FROM users u
USING users d
WHERE u.email = d.email AND u.id > d.id; -- PostgreSQL; use a CTE + ROW_NUMBER elsewhereSELECT 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;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;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;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;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" trickPractise 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
SQL cheat sheet
The syntax you'll reach for most often, on one screen.
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;SQL interview questions, with answers
Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.
1What 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.
2Primary 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.
3What 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.
4Candidate, 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).
5DELETE 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.
6WHERE 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).
7In 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.
8UNION 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.
9INNER 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.
10IN 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.
11What 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.
12CTE 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.
13What 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.
14What 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.
15ROW_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”.
16What 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.
17What 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.
18What 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.
19When 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.
20What 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.
21Clustered 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.
22Explain 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).
23What 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.
24View 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.
25What 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.
26Why 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.
27OFFSET 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.
28What 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.
29Partitioning 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.
30SQL 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
Which query finds users with a NULL phone?
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.
Key takeaways
- SQL is declarative: describe the result, and let the optimiser choose the plan. Then check the plan.
- Know the logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
- NULL means unknown: use IS NULL, COALESCE, and NOT EXISTS instead of NOT IN.
- Joins, GROUP BY + HAVING, CTEs and window functions solve most interview problems.
- Design indexes from real queries; respect the leftmost-prefix rule and the write cost.
- Keep transactions short, lock in a consistent order, and know your isolation level.
- Always parameterise queries. Concatenated SQL is an injection waiting to happen.
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.
REST, HTTP, GraphQL, authentication, pagination, idempotency, caching, rate limiting and webhooks: the contract on top of your data.
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
Last reviewed 18 November 2026