SQL Roadmap
SQL is the language for asking questions of relational databases and for changing the data in them. Analysts, back-end developers, data engineers and testers all use it, and almost every technical interview includes at least one query to write. The core ideas have stayed stable for decades, so time spent here pays off for a whole career.
This roadmap takes you from your first SELECT to what interviews test: filtering, joins, grouping, subqueries, window functions, transactions, indexes and reading query plans. Each topic has a short explanation, a runnable example where it helps and an exercise. Core topics are expected of everyone, recommended topics are common in jobs and optional ones can wait. Examples use standard SQL, with notes where PostgreSQL, MySQL and SQL Server differ.
By the end you will be able to design tables, write and tune queries and explain your reasoning. For hands-on problems, use SQL practice, and track your progress in progress page.
- Level
- Beginner to advanced
- Time
- 8–12 weeks at about 8 hours a week
- Scope
- 54 topics in 9 stages
- Before you start
- Comfort using a computer and a text editor; Basic logic: conditions such as and, or, not, and the idea of a function; Helpful: a spreadsheet habit of thinking in rows and columns; Optional: a general language such as Python Roadmap for running queries from code
What you will be able to do
- Write queries that filter, sort, join and aggregate data across several tables.
- Design tables with keys and constraints that protect data quality.
- Use subqueries, CTEs and window functions to solve ranking and comparison problems.
- Explain ACID and choose a transaction isolation level for a given problem.
- Read a query plan and design indexes that speed up slow queries.
- Apply least privilege and parameterised queries to keep a database safe.
The roadmap at a glance
- Stage 1Relational Foundations and Basic SyntaxBeginner · 1 week · 8 topics
- Stage 2Defining and Changing DataBeginner · 1 week · 5 topics
- Stage 3Constraints and KeysBeginner · 1 week · 4 topics
- Stage 4Joining and Aggregating DataIntermediate · 2 weeks · 8 topics
- Stage 5Subqueries and Built-in FunctionsIntermediate · 1–2 weeks · 7 topics
- Stage 6Advanced SQL ConceptsIntermediate · 2 weeks · 9 topics
- Stage 7Transactions and ConcurrencyIntermediate · 1 week · 4 topics
- Stage 8Indexes and PerformanceAdvanced · 2 weeks · 6 topics
- Stage 9Security and Integrity in PracticeAdvanced · 1 week · 3 topics
Stage 1 Relational Foundations and Basic Syntax
Goal. Explain how relational databases store data and write your first queries with the right syntax.
Learn the Basics: Relational Databases Core
A relational database keeps data in tables. Each table describes one kind of thing, such as customers or orders, and tables are linked by shared values. The software that manages them is a relational database management system, or RDBMS. Common ones are PostgreSQL, MySQL, SQL Server, Oracle and SQLite.
SQL, short for Structured Query Language, is the language you use to define tables, change data and ask questions. It is declarative: you describe the result you want, and the database decides how to get it. That is why one query can run well on a small table and badly on a huge one without any change in its text. Learning SQL means learning both the language and what the engine does with it. Practise as you read in SQL practice.
Practice. Pick an app you use and sketch three tables it probably has, with the columns each would need.
Table, Row and Column Core
A Table is a named collection of data with a fixed set of columns. A Column has a name and a data type, and describes one attribute, such as email. A Row is one record, such as one customer, holding one value per column. A single value at the crossing of a row and a column is a Scalar.
Rows in a table have no guaranteed order. If you need an order, you must ask for it. Columns have a position, but good code names them rather than relying on it.
-- customers
id | name | email
1 | Asha | asha@example.com
2 | Bruno | bruno@example.com
Practice. Describe in words what a row, a column and a scalar are for a small books table.
RDBMS Benefits and Limitations, and SQL vs NoSQL Core
RDBMS Benefits and Limitations come from the same design. Benefits: a strict schema, relations between tables, constraints that protect data, transactions with ACID guarantees, and a powerful query language that works on any shape of question. Limitations: changing a schema on a large table takes planning, scaling writes across many machines is harder, and deeply nested or very flexible data fits less naturally.
SQL vs NoSQL is not a contest. Document stores such as MongoDB Roadmap suit flexible, nested records that are read as a whole. Key-value stores such as Redis Roadmap suit caching. Relational databases suit data with many relationships and strong correctness needs, and they are the default choice for most business applications.
Practice. Choose a database type for a blog, a shopping cart cache and a bank ledger, and give one reason for each.
Basic SQL Syntax and SQL Keywords Core
SQL statements end with a semicolon. Keywords such as SELECT, FROM and WHERE are not case sensitive, but writing them in capitals makes queries easier to read. Names of tables and columns may or may not be case sensitive depending on the system, so choose snake_case and stay consistent. Comments start with -- or sit inside /* ... */. Whitespace and line breaks do not matter.
Text values use single quotes: 'Asha'. Double quotes are for identifiers in standard SQL. A clause is one part of a statement, and the clauses have a fixed order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Reserved SQL keywords, like order and user, should not be used as names.
Practice. Format a messy one-line query so that each clause starts on its own line, and add a comment to it.
Data Types Core
Every column has a type that limits and describes its values. The families are numbers (INTEGER, BIGINT, NUMERIC(10,2), REAL), text (CHAR, VARCHAR(n), TEXT), dates and times (DATE, TIME, TIMESTAMP), booleans, binary data, and in many systems JSON and arrays. Exact names vary between products.
Use NUMERIC or DECIMAL for money, never floating point, because 0.1 + 0.2 is not exact in binary. Use a date type rather than text for dates, so you can compare and calculate. Choose the smallest type that is safe, and use BIGINT for ids that may grow large. Type choices affect storage size, index size and speed.
Practice. Pick a type for each column of an invoices table: id, customer email, amount, created time and paid flag.
Select Statement: SELECT, FROM and Selective Projection Core
The SELECT statement reads data. SELECT lists the columns, and the FROM clause in SELECT statements says which table supplies them.
SELECT name, email FROM customers;
SELECT * FROM customers;
SELECT price * quantity AS line_total FROM order_items;Selective Projection means naming only the columns you need rather than *. It reduces data sent, allows index-only reads and keeps code stable if columns are added later. Use AS to give a column or an expression an alias, and DISTINCT to remove duplicate rows from the result. SELECT can also compute values without a table, like SELECT 1 + 1.
Practice. Write a query that returns names and a computed full price with an alias, then add DISTINCT to list unique cities.
WHERE Clause in SELECT Statements and Operators Core
The WHERE Clause filters rows before they are grouped or returned. Operators build the conditions: comparison (=, <>, <, >, <=, >=), logical (AND, OR, NOT), range (BETWEEN), set (IN), pattern (LIKE with % and _) and null checks (IS NULL).
SELECT * FROM orders
WHERE status IN ('paid', 'shipped')
AND total BETWEEN 50 AND 200
AND note IS NOT NULL;NULL means unknown, so NULL = NULL is not true; use IS NULL. Mixed AND and OR follow precedence, with AND first, so add brackets. LIKE '%abc' cannot use a normal index, so be careful on big tables.
Practice. Find orders from the last 30 days that are paid or shipped, and explain why brackets matter in your condition.
ORDER BY and Limiting Results Core
ORDER BY sorts the result. It takes columns or expressions, each with ASC (default) or DESC. You can sort by several columns, and by an alias or position.
SELECT name, score FROM players
ORDER BY score DESC, name ASC
LIMIT 10 OFFSET 20;Without ORDER BY the order is not guaranteed, even if it looks stable today. LIMIT (or FETCH FIRST n ROWS ONLY in the standard, TOP n in SQL Server) takes the first rows. Large OFFSET values are slow because the database must skip those rows; for deep paging use keyset pagination, which filters with WHERE id > last_seen_id. Where nulls sort differs by system; NULLS FIRST and NULLS LAST make it explicit.
Practice. Return the top five most expensive products and then get page three of a ten-per-page listing.
Stage 2 Defining and Changing Data
Goal. Create tables with constraints, change them safely and write data with INSERT, UPDATE and DELETE.
Data Definition Language (DDL) and Create Table Core
Data Definition Language, or DDL, defines structure: CREATE, ALTER, DROP and TRUNCATE. Create Table builds a table with columns, types and constraints.
CREATE TABLE customers (
id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Design a table before you write it: name the thing in the singular or plural consistently, give it a primary key, mark required columns NOT NULL and set defaults. In many systems DDL commits immediately; in PostgreSQL it can run inside a transaction, which makes migrations safer.
Practice. Create tables for authors and books with sensible types, keys and defaults.
Alter Table, Drop Table and Truncate Table Core
Alter Table changes an existing table: add or drop a column, change a type, add a constraint or rename.
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
ALTER TABLE customers DROP COLUMN phone;Drop Table removes the table and its data. Truncate Table removes all rows quickly without logging each one, resets identity counters in some systems and cannot be filtered with WHERE. DELETE without a filter also empties a table but is slower and fires row triggers. On big tables, adding a column with a default or changing a type can lock the table, so learn how your database handles it and use migrations that are safe for production.
Practice. Add a column to a table, back-fill it, make it NOT NULL and then drop the column again, noting which step is risky.
Data Manipulation Language (DML) and the INSERT Statement Core
Data Manipulation Language, or DML, changes rows: INSERT, UPDATE, DELETE and in many systems MERGE. The INSERT Statement adds rows.
INSERT INTO customers (id, email, name)
VALUES (1, 'asha@example.com', 'Asha'),
(2, 'bruno@example.com', 'Bruno');
INSERT INTO archive SELECT * FROM customers WHERE created_at < '2020-01-01';Always name the columns, so the statement still works when the table changes. Insert many rows in one statement, as it is much faster than many single inserts. Use INSERT ... SELECT to copy data. Many systems support an upsert (ON CONFLICT in PostgreSQL, ON DUPLICATE KEY UPDATE in MySQL) when the row may exist.
Practice. Insert three rows with one statement and then copy some of them into a second table with INSERT SELECT.
UPDATE Statement Core
The UPDATE Statement changes values in existing rows.
UPDATE products
SET price = price * 1.1, updated_at = CURRENT_TIMESTAMP
WHERE category = 'books';The WHERE clause chooses the rows. Without it every row changes, which is a classic production accident. Habits that help: write the WHERE first, run a SELECT with the same condition to count the rows, do the update inside a transaction, and check the affected row count before committing. Updates can use values from another table through FROM (PostgreSQL) or JOIN (MySQL and SQL Server).
Practice. Raise prices for one category after first running a SELECT with the same filter to see how many rows will change.
DELETE Statement and DELETE Statement in SQL Safely Core
The DELETE Statement removes rows. The DELETE Statement in SQL follows the same shape as UPDATE.
DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;Again, the WHERE clause is the safety. Deleting a parent row that other rows refer to either fails, or removes the children if the foreign key says ON DELETE CASCADE. For business data, many teams prefer soft deletes, with a deleted_at column, so records can be recovered and audit trails stay intact; the cost is that every query must filter them. Delete huge sets in batches so locks and logs stay small.
Practice. Delete expired rows in batches of 1,000 and describe what you would change to make it a soft delete.
Stage 3 Constraints and Keys
Goal. Protect data quality with keys and constraints and model relationships between tables.
Data Constraints and Data Integrity Constraints Core
Data Constraints are rules the database enforces on every write, no matter which application sends it. This is the strongest form of validation, because application code has bugs and other tools write to the same tables. Data Integrity Constraints fall into groups: entity integrity (every row can be identified, through a primary key), referential integrity (references point to rows that exist, through foreign keys) and domain integrity (values are valid, through types, NOT NULL, CHECK and UNIQUE).
A failing constraint rejects the statement with an error. Put rules in the database when they are about the data itself, and keep rules that depend on changing business logic in the application as well.
Practice. List the constraints you would put on an orders table before writing any SQL.
Primary Key Core
A Primary Key identifies each row uniquely. It cannot be null and the table can have only one, although it may span several columns. The database builds a unique index on it automatically.
CREATE TABLE enrolments (
student_id BIGINT,
course_id BIGINT,
PRIMARY KEY (student_id, course_id)
);Choose between a natural key, such as a country code, and a surrogate key, such as an auto-incrementing number (GENERATED ALWAYS AS IDENTITY, AUTO_INCREMENT) or a UUID. Surrogate keys are stable when business data changes. Random UUIDs spread inserts across the index, which can slow writes, while time-ordered ones are friendlier. Never reuse or change a primary key value.
Practice. Create one table with a surrogate key and one with a composite key, and explain why each fits.
Foreign Key Core
A Foreign Key links a column to the primary key of another table, so the child can only refer to a parent that exists.
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers (id) ON DELETE RESTRICT
);The ON DELETE rule controls what happens to children: RESTRICT or NO ACTION blocks, CASCADE deletes them, SET NULL clears the link. MySQL requires an index on the column and creates one; PostgreSQL does not, so add an index on foreign key columns yourself, since joins and parent deletes use them. One-to-many uses a single foreign key; many-to-many needs a join table with two foreign keys.
Practice. Model students and courses with a join table and test what happens when you delete a course that has enrolments.
Unique Constraint, NOT NULL Constraint and CHECK Core
The Unique Constraint forbids duplicate values in a column or group of columns. Unlike a primary key, it allows nulls (the number of nulls allowed differs between systems) and a table may have several. The NOT NULL Constraint requires a value. CHECK limits values with a condition.
CREATE TABLE products (
sku VARCHAR(30) NOT NULL UNIQUE,
price NUMERIC(10,2) NOT NULL CHECK (price >= 0),
stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0)
);Prefer NOT NULL by default and allow null only when "unknown" has a real meaning. Name your constraints so error messages and migrations are clear. MySQL enforces CHECK from version 8.0.16; older versions parsed it and ignored it.
Practice. Add constraints so that a product cannot have a negative price and an email cannot appear twice in a users table.
Stage 4 Joining and Aggregating Data
Goal. Combine tables with every join type and summarise data with grouping and aggregate functions.
JOINs and JOIN Queries: The Idea Core
Data is split across tables to avoid repetition, and JOIN Queries put it back together. A join pairs rows from two tables whose columns match a condition in the ON clause.
SELECT o.id, c.name, o.total
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id;Use short table aliases and qualify column names. Join on keys, not on names or text. Think of a join as a filtered product of two tables: the result has one row per matching pair, so joining a customer to ten orders gives ten rows. Forgetting the ON condition produces a huge accidental product.
Practice. Write a query that lists each order with the customer name and the number of its items.
INNER JOIN Core
INNER JOIN keeps only rows that have a match on both sides. JOIN alone means inner join. Customers without orders, and orders without customers, disappear from the result.
SELECT c.name, o.id
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;Use it when a missing match means the row is not interesting. The order of tables does not change an inner join's result, though the optimiser may pick its own order. Join several tables by chaining joins, one ON per join, and check that each step does not multiply rows unexpectedly.
Practice. Join customers, orders and order items and confirm the row count equals the number of items.
LEFT JOIN and RIGHT JOIN Core
LEFT JOIN keeps every row from the left table and fills the right side with nulls when nothing matches. It answers questions such as "which customers have never ordered".
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;RIGHT JOIN is the mirror image, and most people rewrite it as a left join by swapping the tables. A common bug: a WHERE condition on the right table, such as o.status = 'paid', removes the null rows and turns the left join into an inner join. Put such conditions in the ON clause instead.
Practice. Find products that were never ordered, then count orders per customer including customers with zero.
FULL OUTER JOIN and CROSS JOIN Recommended
FULL OUTER JOIN keeps unmatched rows from both sides, with nulls on whichever side is missing. It is useful for reconciling two lists, such as finding records in a system A that are missing in B and the other way round. MySQL does not support it; you combine a left and a right join with UNION.
Cross Join pairs every row of one table with every row of another, giving a Cartesian product. It is useful on purpose to generate combinations, such as sizes by colours, or a calendar of dates by stores.
SELECT s.size, c.colour FROM sizes s CROSS JOIN colours c;
Practice. Compare two small tables of ids and list the ones missing from either side with a FULL OUTER JOIN.
Self Join Recommended
A Self Join joins a table to itself, using two aliases. It fits hierarchies and comparisons between rows of the same table, such as employees and their managers.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;It also finds pairs, such as customers in the same city: a.city = b.city AND a.id < b.id avoids pairing a row with itself and counting each pair twice. For an unknown depth of hierarchy, a self join is not enough and you need a recursive query, covered later.
Practice. List each employee with their manager and find all pairs of employees who share a department.
Aggregate Queries and the Basic Aggregates: COUNT, SUM, AVG, MIN and MAX Core
Aggregate Queries collapse many rows into one value. COUNT counts rows, SUM adds values, AVG gives the mean, MIN and MAX give the smallest and largest.
SELECT COUNT(*) AS orders,
SUM(total) AS revenue,
AVG(total) AS average_order,
MIN(created_at), MAX(created_at)
FROM orders;COUNT(*) counts all rows, COUNT(column) skips nulls and COUNT(DISTINCT column) counts unique values. SUM, AVG, MIN and MAX ignore nulls, so an AVG over a column with nulls is the average of the known values. With integer columns, some systems do integer division, so cast to NUMERIC when you need decimals.
Practice. Calculate order count, revenue and average order value for last month and compare COUNT(*) with COUNT(column).
GROUP BY Core
GROUP BY splits rows into groups and applies the aggregates to each group.
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders
GROUP BY customer_id
ORDER BY spent DESC;Every column in SELECT must be either in GROUP BY or inside an aggregate function; otherwise the query is invalid in standard SQL (MySQL used to allow it silently, which gave arbitrary values). You can group by several columns or by expressions, like the month of a date. Remember the logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
Practice. Show revenue per product category per month, sorted by month and then revenue.
HAVING Core
HAVING filters groups after aggregation, where WHERE filters rows before it. Use WHERE for conditions on raw columns, because it reduces the data early, and HAVING for conditions on aggregates.
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING COUNT(*) >= 5;A common interview question is the difference between the two. WHERE cannot use COUNT(*), because the groups do not exist yet. Putting a plain-column filter in HAVING still works but is slower in principle, because the database may group rows it could have dropped.
Practice. Find customers with at least five paid orders and an average order above 100.
Stage 5 Subqueries and Built-in Functions
Goal. Nest queries, reduce them when they are slow and use scalar functions and conditional logic.
Sub Queries, Nested Subqueries and Correlated Subqueries Core
Sub Queries are queries inside another query. A scalar subquery returns one value, a list subquery works with IN, and a table subquery sits in FROM. Nested Subqueries can contain further subqueries.
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);Correlated Subqueries refer to the outer row, so they run once per row, at least logically.
SELECT e.name FROM employees e
WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept);EXISTS checks for any matching row and stops early. Beware NOT IN with a list that contains null: it returns no rows. Use NOT EXISTS instead.
Practice. Find employees paid above their own department average using a correlated subquery, then using a join to a grouped table.
Reducing Subqueries and Rewriting Them Recommended
Reducing Subqueries means rewriting them when they cost too much. A correlated subquery that runs for each row can often become a join to a pre-aggregated result or a window function. An IN subquery can become EXISTS or a join, and modern optimisers often do this for you, so check the plan before changing anything.
Repeated identical subqueries in one statement are better written once as a common table expression, which also makes the query readable. Readability is a good reason on its own: a flat query with named steps is easier to review than three levels of nesting.
Practice. Rewrite a correlated subquery as a join to a grouped result and compare the two query plans.
String Functions: CONCAT, LENGTH, LOWER, UPPER, REPLACE and SUBSTRING Core
CONCAT joins strings (or the || operator in standard SQL and PostgreSQL). LENGTH counts characters (bytes in some systems; CHAR_LENGTH or LEN in others). LOWER and UPPER change case. REPLACE swaps text, and SUBSTRING cuts out part of a string.
SELECT CONCAT(first_name, ' ', last_name) AS full_name,
LOWER(email) AS email,
SUBSTRING(phone, 1, 3) AS area,
REPLACE(phone, '-', '') AS digits,
LENGTH(name) AS name_length
FROM customers;Concatenating with a null gives null in standard SQL (MySQL's CONCAT also returns null; CONCAT_WS skips nulls). Functions applied to a column in WHERE, such as LOWER(email) = 'a@b.com', stop a normal index from being used unless you create an expression index.
Practice. Clean a column of messy emails with LOWER and REPLACE and extract the domain with SUBSTRING.
Numeric Functions: ABS, CEILING, FLOOR, ROUND and MOD Core
ABS returns the absolute value, CEILING rounds up to the next whole number, FLOOR rounds down, ROUND rounds to a number of decimals and MOD gives the remainder.
SELECT ABS(-4.5) AS a, -- 4.5
CEILING(4.2) AS c, -- 5
FLOOR(4.8) AS f, -- 4
ROUND(4.567, 2) AS r, -- 4.57
MOD(17, 5) AS m; -- 2Rounding rules for exact halves differ between databases, and FLOOR of a negative number goes further from zero. Some systems write the remainder as 17 % 5. Round only at the end of a calculation, not between steps, to avoid accumulated error. Use MOD to find even rows or to bucket ids.
Practice. Calculate a price with tax rounded to two decimals and list only rows with an even id using MOD.
Date and Time: DATE, TIME, TIMESTAMP, DATEADD and DATEPART Core
DATE stores a day, TIME a time of day and TIMESTAMP both. Many systems also have a timestamp with time zone; store times in UTC and convert in the application when showing them.
Functions differ by product. SQL Server has DATEADD and DATEPART, PostgreSQL uses interval arithmetic and EXTRACT, and MySQL has DATE_ADD and EXTRACT.
-- SQL Server
SELECT DATEADD(day, 7, order_date) AS due, DATEPART(month, order_date) AS m FROM orders;
-- PostgreSQL
SELECT order_date + INTERVAL '7 days', EXTRACT(MONTH FROM order_date) FROM orders;Filter date ranges with >= start AND < next_day rather than wrapping the column in a function, so an index can be used.
Practice. Count orders per week for the last quarter and list invoices due seven days after their issue date.
CASE, COALESCE and NULLIF Core
CASE adds if-then-else logic inside a query.
SELECT name,
CASE WHEN score >= 90 THEN 'A'
WHEN score >= 75 THEN 'B'
ELSE 'C' END AS grade
FROM results;COALESCE returns the first non-null argument, so COALESCE(nickname, name, 'guest') gives a default. NULLIF returns null when two values are equal, and is a neat way to avoid division by zero: total / NULLIF(count, 0). CASE inside an aggregate gives conditional counts, such as SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END), which is also how you build a pivot by hand.
Practice. Produce a report with one row per month and separate columns for paid, refunded and cancelled order counts.
Advanced Functions and Scalar Functions Overview Recommended
Advanced Functions go beyond the basics: casting with CAST(x AS type), JSON functions for extracting fields, regular expression matching, string aggregation (STRING_AGG, GROUP_CONCAT), array functions in PostgreSQL and date truncation like DATE_TRUNC. A Scalar function returns one value per row, an aggregate function returns one per group and a window function returns one per row while looking at related rows.
The syntax varies by product, so read the manual for the one you use. When you see an unfamiliar function in an interview, say what class it belongs to, think about nulls and say what you would check in the documentation.
Practice. Pick one function per class (scalar, aggregate and window) and write a query using each on the same table.
Stage 6 Advanced SQL Concepts
Goal. Use views, common table expressions, window functions and procedural features to solve harder reporting problems.
Advanced SQL Concepts: Views, Creating Views, Modifying Views and Dropping Views Core
A view is a saved query that you use like a table. Creating Views gives a name to a join or a filter, hides complexity and limits which columns a user sees.
CREATE VIEW active_customers AS
SELECT id, name, email FROM customers WHERE deleted_at IS NULL;Modifying Views uses CREATE OR REPLACE VIEW (PostgreSQL, MySQL) or ALTER VIEW (SQL Server). Dropping Views uses DROP VIEW name. A plain view stores no data and runs its query each time. A materialised view stores the result and must be refreshed, which trades freshness for speed. Simple views can be updated through, but views with joins or aggregates usually cannot. Do not stack many views on views, as plans become hard to understand.
Practice. Create a view that joins orders and customers, grant read access to it, then change and drop it.
CTEs (Common Table Expressions) Core
CTEs (Common Table Expressions) give a name to a subquery with WITH, so a long query reads top to bottom as steps.
WITH monthly AS (
SELECT DATE_TRUNC('month', created_at) AS m, SUM(total) AS revenue
FROM orders GROUP BY 1
)
SELECT m, revenue, revenue - LAG(revenue) OVER (ORDER BY m) AS change
FROM monthly;You can define several, and later ones can use earlier ones. A CTE lives only for one statement. In older PostgreSQL versions a CTE was always computed once and acted as an optimisation barrier; since version 12 the optimiser can inline it unless you write MATERIALIZED. Use them for readability first, then check the plan.
Practice. Rewrite a query with two nested subqueries as a chain of named CTEs.
Recursive Queries Recommended
Recursive Queries walk hierarchies of unknown depth, such as an organisation chart, folder tree or bill of materials. A recursive CTE has an anchor query, which gives the starting rows, and a recursive part that joins the previous results to the table, joined with UNION ALL.
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth FROM employees WHERE id = 7
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e JOIN chain c ON e.id = c.manager_id
)
SELECT * FROM chain;SQL Server omits the word RECURSIVE. Guard against cycles with a depth limit or a visited path, or the query will run until the database stops it.
Practice. List all employees below a given manager with their depth in the hierarchy.
Window Functions Core
Window Functions calculate across a set of related rows without collapsing them, unlike GROUP BY. The OVER clause defines the window with PARTITION BY (groups), ORDER BY (order inside a group) and an optional frame.
SELECT employee, dept, salary,
AVG(salary) OVER (PARTITION BY dept) AS dept_avg,
SUM(salary) OVER (PARTITION BY dept ORDER BY hired_on) AS running_total
FROM employees;They run after WHERE and GROUP BY, so you cannot filter on them in the same WHERE; wrap the query in a CTE and filter outside. Any aggregate can be a window function. Window functions are the standard tool for rankings, running totals, moving averages and comparisons with the previous row.
Practice. Show each sale with its percentage of the total for the same month using a window sum.
Ranking: Row_number, rank and dense_rank Core
Row_number gives each row in the window a unique number. rank gives equal rows the same number and leaves gaps after ties. dense_rank gives ties the same number without gaps.
SELECT name, score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS rn,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS drnk
FROM players;
-- scores 90, 90, 80 -> rn 1,2,3 rank 1,1,3 dense_rank 1,1,2The classic pattern is top N per group: number rows with PARTITION BY group ORDER BY value DESC in a CTE, then keep rn <= 3. Use row_number when you need exactly one row per group, and dense_rank for "second highest salary" questions where ties count as one level.
Practice. Return the three highest-paid employees in each department, then the second highest salary overall with dense_rank.
Offsets: lag and lead Core
lag reads a value from a previous row in the window and lead from a following row. They take the column, an optional offset (default 1) and an optional default for missing rows.
SELECT day, price,
price - LAG(price, 1, price) OVER (ORDER BY day) AS change,
LEAD(price) OVER (ORDER BY day) AS next_price
FROM prices;Use them for day-over-day change, time between events, finding gaps in sequences and spotting when a value changes. Always include a deterministic ORDER BY, and add PARTITION BY when you have several series, such as one per stock, or the previous row may belong to a different one.
Practice. Compute the time between each user event and the next one for the same user.
Pivot / Unpivot Operations Optional
Pivot / Unpivot Operations turn rows into columns and back. Pivot takes values of a column, such as months, and makes each a column of its own with an aggregate in the cells. SQL Server and Oracle have PIVOT and UNPIVOT. Elsewhere you write the same thing with conditional aggregation.
SELECT product,
SUM(CASE WHEN month = 'Jan' THEN sales END) AS jan,
SUM(CASE WHEN month = 'Feb' THEN sales END) AS feb
FROM monthly_sales GROUP BY product;Unpivot can be done with UNION ALL of one select per column, or CROSS JOIN LATERAL with VALUES in PostgreSQL. The set of pivot columns must be known when you write the query. For dynamic columns you need dynamic SQL or to do the shaping in a reporting tool.
Practice. Turn a long table of product, month and sales into a wide table with one column per month.
Stored Procedures and Functions Recommended
Stored Procedures and Functions keep logic in the database. A function returns a value or a table and can be used inside queries. A procedure is called with CALL (or EXEC), can run several statements, and in most systems can control transactions.
CREATE FUNCTION order_total(p_order BIGINT) RETURNS NUMERIC AS $$
SELECT SUM(price * quantity) FROM order_items WHERE order_id = p_order;
$$ LANGUAGE sql;Benefits: fewer round trips, central rules and permission control. Costs: logic outside your normal version control and test tooling unless you manage it with migrations, language differences between systems (PL/pgSQL, T-SQL, PL/SQL) and harder debugging. Use them for data-heavy work that is close to the data, and keep business workflow in the application.
Practice. Write a function that returns an order total and call it inside a SELECT.
Dynamic SQL Optional
Dynamic SQL builds a statement as text and runs it, for cases such as a variable table name or a flexible set of filters. It is powerful and risky. Building a string from user input invites SQL injection.
-- safer: parameters for values, quoted identifiers for names
EXECUTE format('SELECT * FROM %I WHERE id = $1', tbl) USING p_id;Pass values as parameters, never by concatenation, and allow-list identifiers such as table and column names, quoting them with the system's functions. In applications, use the driver's prepared statements. Also remember that each distinct statement text may need its own plan, so heavy dynamic SQL can cost performance.
Practice. Write a procedure that takes a column name from an allow-list and sorts a table by it safely.
Stage 7 Transactions and Concurrency
Goal. Group statements into atomic units and choose isolation levels with an understanding of the anomalies they allow.
Transactions and BEGIN, COMMIT and ROLLBACK Core
Transactions group statements so that they succeed or fail together. BEGIN (or START TRANSACTION) opens one, COMMIT makes its changes permanent and ROLLBACK cancels them.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;If the application crashes before COMMIT, the database rolls back. Many tools use autocommit, where each statement is its own transaction, so transfers like the above need an explicit block. Keep transactions short: long ones hold locks and prevent cleanup of old row versions. In application code use a try, catch and rollback pattern, and never wait for user input inside a transaction.
Practice. Write a transfer between two accounts, force an error in the middle and check that nothing changed after rollback.
ACID Core
ACID describes what a transaction guarantees. Atomicity: all of it happens or none. Consistency: it moves the database from one valid state to another, respecting constraints. Isolation: concurrent transactions do not see each other's half-finished work, to a degree set by the isolation level. Durability: once committed, the data survives a crash, normally through a write-ahead log flushed to disk.
In an interview, give a concrete example for each: a bank transfer for atomicity, a CHECK that stops a negative balance for consistency, two buyers of the last ticket for isolation and a power cut just after commit for durability.
Practice. Explain ACID using an online ticket purchase as the example.
SAVEPOINT Recommended
A SAVEPOINT marks a place inside a transaction that you can return to without cancelling everything.
BEGIN;
INSERT INTO orders (id) VALUES (1);
SAVEPOINT before_items;
INSERT INTO order_items (order_id, sku) VALUES (1, 'bad-sku');
ROLLBACK TO SAVEPOINT before_items;
INSERT INTO order_items (order_id, sku) VALUES (1, 'good-sku');
COMMIT;They are useful in batch imports, where one bad row should not discard the whole load, and are used behind the scenes by frameworks that support nested transactions. In PostgreSQL, a failed statement puts the whole transaction in an error state until you roll back to a savepoint or the whole transaction.
Practice. Import ten rows where one is invalid, keeping the nine good ones in a single transaction.
Transaction Isolation Levels Core
Transaction Isolation Levels trade correctness against concurrency. The standard has four. Read uncommitted allows dirty reads, where you see uncommitted data. Read committed prevents that, but a repeated read can return different values (non-repeatable read). Repeatable read keeps the values you have read stable, though new rows can appear (phantoms) in some systems. Serializable behaves as if transactions ran one after another.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;Defaults differ: read committed in PostgreSQL, SQL Server and Oracle, repeatable read in MySQL's InnoDB. Higher levels can cause serialisation failures or deadlocks, so applications must retry. For a "check then update" race, you can also use SELECT ... FOR UPDATE, atomic updates such as SET stock = stock - 1 WHERE stock > 0, or constraints.
Practice. Run two sessions at once to reproduce a non-repeatable read at read committed and show it disappears at repeatable read.
Stage 8 Indexes and Performance
Goal. Read query plans, design indexes and rewrite slow queries with evidence.
Indexes: What They Are and How They Work Core
Indexes are separate structures that let the database find rows without reading the whole table, like the index of a book. The usual type is a B-tree, which keeps keys sorted and supports equality, ranges and ordering. Other types include hash, GIN and GiST in PostgreSQL, full-text and spatial indexes.
The price: every index uses disk and memory, and slows INSERT, UPDATE and DELETE, because each must be maintained. A table with no index on the filtered column needs a full scan, which is fine for a hundred rows and painful for a hundred million. Primary keys and unique constraints already create an index.
Practice. Create a table with a million generated rows and time a lookup by a column before and after adding an index.
Managing Indexes and Using Indexes Core
Managing Indexes means creating, checking and removing them.
CREATE INDEX idx_orders_customer ON orders (customer_id, created_at);
CREATE UNIQUE INDEX idx_users_email ON users (LOWER(email));
DROP INDEX idx_orders_customer;Using Indexes well starts with the leftmost-prefix rule: an index on (a, b) helps filters on a, and on a and b, but not on b alone. Put equality columns first, then range or sort columns. A covering index includes every column a query needs so the table is never read. Partial indexes cover only some rows. An index is skipped when you wrap the column in a function, compare mismatched types or the query returns a large share of the table. Drop unused and duplicate indexes.
Practice. Design one index for a query that filters on status and sorts by created date, and prove it is used.
Query Analysis Techniques Core
Query Analysis Techniques begin with the plan. EXPLAIN shows what the optimiser intends, and EXPLAIN ANALYZE (PostgreSQL) runs the query and shows real times and row counts.
EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;Read from the innermost step outward. Look for sequential scans on big tables, estimated rows far from actual rows (stale statistics, run ANALYZE), sorts that spill to disk, nested loops over large sets and rows removed by filters after the scan. Slow query logs and pg_stat_statements or the Performance Schema find the queries worth tuning. Change one thing at a time and compare.
Practice. Capture a slow query plan, name its most expensive step and fix it.
Query Optimization Core
Query Optimization is mostly about doing less work. Select only needed columns, filter early, use sargable conditions (created_at >= '2025-01-01' rather than YEAR(created_at) = 2025), avoid SELECT * in hot paths and leading wildcard LIKE, and replace OR chains or functions on indexed columns with forms an index can use.
Other habits: avoid fetching rows only to count them in the application, use EXISTS for presence checks, batch writes, page with keyset pagination, and avoid the N+1 pattern in application code, where one query is followed by one query per row. Fix a bad query before adding hardware.
Practice. Rewrite five slow query patterns from this list into efficient versions and measure each.
Optimizing Joins Recommended
Optimizing Joins starts with indexes on join columns, especially foreign keys on the many side. The optimiser picks a strategy: nested loops (good when one side is small and the other indexed), hash joins (good for large unsorted inputs) or merge joins (good for sorted inputs). You influence it indirectly with indexes, statistics and by reducing rows before the join.
Filter and aggregate before joining when possible, join on columns of the same type, avoid joining on expressions and watch for row multiplication from one-to-many joins before a SUM. Joins across a huge number of tables deserve a look at the schema, not only at the query.
Practice. Compare nested loop and hash join plans for the same query with and without an index on the join column.
Performance Optimization: Beyond the Query Recommended
Performance Optimization also lives outside single queries. Connection pooling avoids paying connection setup for every request. Caching in the application or a store like Redis Roadmap removes repeated reads. Read replicas move reporting off the primary. Partitioning splits a huge table by date or key, so queries and maintenance touch less data. Archiving old rows keeps tables small.
Keep statistics fresh through autovacuum or scheduled analysis, watch locks and long transactions and choose data types carefully. Always measure with real data volumes: a query that is fast on a development database with a thousand rows may not be on production.
Practice. List what you would check, in order, when a report that took one second now takes a minute.
Stage 9 Security and Integrity in Practice
Goal. Control who can do what and prevent the common attacks on SQL databases.
Data Integrity & Security Core
Data Integrity & Security are two sides of trust. Integrity means the data is correct, through constraints, transactions and careful migrations. Security means only the right people can read or change it, through accounts, permissions, encryption and auditing.
Both need layers. Constraints stop bad values that application bugs let through. Permissions limit what a stolen account can do. Backups protect against mistakes and attacks, and are only real once you have tested a restore. Log changes to sensitive tables, using triggers or the database's audit features.
Practice. Choose three tables from a sample app and write the integrity rule and the access rule for each.
GRANT and REVOKE Core
GRANT and REVOKE manage privileges. You give a user or role the least access that lets them work.
CREATE ROLE reporting;
GRANT SELECT ON orders, customers TO reporting;
GRANT reporting TO analyst_anna;
REVOKE DELETE ON orders FROM app_user;Use roles for groups of permissions rather than granting to each person. Give applications their own accounts with only the rights they need, so a web service cannot drop tables. Use views or column-level grants to hide sensitive columns, and in PostgreSQL row-level security for per-user rows. Review privileges regularly and remove those of people who have left.
Practice. Create a read-only role for analysts and test that it cannot update or see the salary column.
DB Security Best Practices Core
DB Security Best Practices include: parameterised queries everywhere to prevent SQL injection, least privilege accounts, no shared admin logins, strong authentication, TLS for connections, encryption at rest, network rules that keep the database off the public internet, regular patching, secrets in a vault rather than code and audit logs.
SQL injection happens when input becomes part of the statement text. The fix is to send values separately as parameters.
-- unsafe: "SELECT * FROM users WHERE name = '" + name + "'"
-- safe: SELECT * FROM users WHERE name = $1Mask or tokenise personal data in non-production copies, and plan for deletion requests under privacy law.
Practice. Find the injection in a short sample login query and rewrite it with parameters.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Library databaseBeginner
Design tables for books, authors, members and loans, with keys and constraints. Load sample data and write queries for overdue loans, popular authors and members with no loans.
DDL · Constraints · Joins · Aggregates
- Online shop reportingIntermediate
Load customers, products, orders and items. Produce monthly revenue, best sellers per category, repeat customer rate and a customer list ranked by spending with window functions.
GROUP BY · Window functions · CTEs · CASE
- Employee hierarchy explorerIntermediate
Store employees with a manager column. Write recursive queries that list a full reporting chain, the size of each team and the depth of each person, and show the data in a view.
Self join · Recursive CTE · Views
- Bank transfer simulatorAdvanced
Build accounts and a transfer procedure with transactions and constraints. Run concurrent transfers from two sessions, show a race at a low isolation level and fix it with locking or atomic updates.
Transactions · Isolation levels · Locking
- Slow query clinicAdvanced
Generate a table with millions of rows and ten slow queries. For each one record the plan, add or change an index or rewrite the query and write down the before and after times.
EXPLAIN · Indexes · Query tuning
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between WHERE and HAVING?Junior
WHERE filters individual rows before grouping, so it cannot use aggregates. HAVING filters groups after aggregation, so it can use COUNT(*) or SUM(x). I put row conditions in WHERE so less data is grouped, and use HAVING only for conditions on aggregates. The logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
Explain the different types of joins.Junior
INNER JOIN returns rows that match on both sides. LEFT JOIN keeps all rows from the left and fills nulls where the right has no match, RIGHT JOIN is the reverse and FULL OUTER JOIN keeps unmatched rows from both. CROSS JOIN returns every combination. A self join joins a table to itself. I use a left join with IS NULL to find rows that have no match.
What is the difference between DELETE, TRUNCATE and DROP?Junior
DELETE removes chosen rows, can use WHERE, fires row triggers and is logged row by row. TRUNCATE removes all rows quickly, cannot filter and may reset identity counters. DROP removes the whole table with its structure. Rollback support for TRUNCATE and DROP depends on the database; PostgreSQL allows it inside a transaction.
How do NULLs behave in SQL?Junior
NULL means unknown. Any comparison with it, including NULL = NULL, is unknown rather than true, so you need IS NULL. Aggregates other than COUNT(*) ignore nulls. NOT IN with a null in the list returns nothing, so I use NOT EXISTS. COALESCE supplies defaults and NULLIF avoids division by zero.
What is the difference between a primary key and a unique constraint?Junior
Both enforce uniqueness and create an index. A table has one primary key, which cannot be null and identifies the row. A table can have many unique constraints, and in most systems they allow null values. Foreign keys normally point to the primary key.
Find the second highest salary.Mid
I would use DENSE_RANK() OVER (ORDER BY salary DESC) in a CTE and select rows where the rank is 2, which handles ties and works for any N. A shorter version is SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). I also say what happens when there is no second value: the query returns null or no row, and I would handle that.
What is the difference between ROW_NUMBER, RANK and DENSE_RANK?Mid
ROW_NUMBER gives every row a unique number even for ties. RANK gives ties the same number and skips the next numbers. DENSE_RANK gives ties the same number and does not skip. For scores 90, 90, 80 the results are 1,2,3 then 1,1,3 then 1,1,2. I use ROW_NUMBER for one row per group and DENSE_RANK for levels.
Explain a correlated subquery and when you would avoid one.Mid
A correlated subquery refers to a column of the outer query, so it is evaluated for each outer row in principle. It reads naturally for "above the average of their own group". On large tables it can be slow, so I rewrite it as a join to a pre-aggregated result or a window function, after checking the plan, because the optimiser sometimes does that itself.
How do you remove duplicate rows from a table?Mid
First decide what makes a row a duplicate. Number rows with ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) in a CTE and delete those with a number above 1. I run the matching SELECT first, do it in a transaction and then add a unique constraint so duplicates cannot return.
What are ACID properties?Mid
Atomicity: a transaction fully happens or not at all. Consistency: constraints hold before and after. Isolation: concurrent transactions do not see each other's partial work, to the degree of the isolation level. Durability: committed data survives a crash, usually through a write-ahead log. A bank transfer shows them all.
What are isolation levels and which anomalies do they prevent?Senior
Read uncommitted allows dirty reads. Read committed prevents them but allows non-repeatable reads. Repeatable read prevents those, and phantoms depending on the engine. Serializable prevents all anomalies, at the cost of retries. Defaults are read committed in PostgreSQL and SQL Server and repeatable read in InnoDB. I pick the lowest level that is correct and design for retries.
How would you speed up a slow query?Senior
I get the real plan with EXPLAIN ANALYZE, find the costly step and compare estimated and actual rows. Typical fixes: an index matching the filter and sort order, a covering index, making the condition sargable, selecting fewer columns, replacing a correlated subquery, updating statistics or reducing the rows earlier. I change one thing at a time and re-measure on realistic data.
How does a composite index work, and how do you order its columns?Senior
A B-tree on (a, b, c) is sorted by a, then b within a, then c. It serves filters on a, on a and b, and so on, but not on b alone. I place equality columns first, then the range or sort column, and choose a more selective column first when queries filter on both. Extra indexes slow writes, so I base the design on real queries.
When would you choose a view, a materialised view or a CTE?Mid
A CTE is local to one statement and improves readability. A view saves a query under a name for reuse and access control, and runs fresh each time. A materialised view stores the result for expensive reports and needs refreshing, so it suits data that can be slightly stale.
How do you prevent SQL injection?Mid
Never build statements by concatenating input. Use parameterised queries or prepared statements so values travel separately from the SQL text, and allow-list identifiers such as column names for dynamic sorting. Give the application account minimal rights, so a flaw cannot drop tables, and avoid showing raw database errors to users.
How would you design a schema for a many-to-many relationship, such as students and courses?Mid
Use a join table, enrolments, with student_id and course_id as foreign keys and a composite primary key so a pair appears once. Extra attributes of the relationship, such as grade or date, go in that table. I add an index on course_id for the reverse lookup and decide on delete rules for each foreign key.
Common mistakes
- Running UPDATE or DELETE without a WHERE clause; write the WHERE first and test with a SELECT.
- Using SELECT * in application queries; name the columns you need.
- Comparing with NULL using equals; use IS NULL and IS NOT NULL.
- Putting a right-table condition in WHERE after a LEFT JOIN, which turns it into an inner join; move it to ON.
- Storing money in floating point columns; use NUMERIC or DECIMAL.
- Wrapping an indexed column in a function in the WHERE clause; compare against a range instead.
- Adding an index for every column; index real query patterns and measure the write cost.
- Building queries by string concatenation; use parameters.
- Relying on row order without ORDER BY; always state the order you need.
Ready-for-interview checklist
- I can write SELECT queries with WHERE, ORDER BY and LIMIT without looking anything up.
- I can explain INNER, LEFT, RIGHT, FULL and CROSS joins with an example of each.
- I can group data and filter groups with HAVING.
- I can explain how NULL behaves in comparisons and aggregates.
- I can design tables with primary keys, foreign keys and constraints.
- I can write CTEs and use window functions for ranking and running totals.
- I can solve top N per group and second highest value questions.
- I can use INSERT, UPDATE and DELETE safely inside a transaction.
- I can explain ACID and the four isolation levels with anomalies.
- I can read EXPLAIN output and name the slow step.
- I can design a composite index for a given query.
- I can explain SQL injection and how to prevent it.
- I can say when a relational database is the right choice compared with a document store.
Related roadmaps
- MongoDB RoadmapDocuments, schema design, aggregation, indexes and replication.
- Redis RoadmapData types, caching patterns, persistence, clustering and streams.
- Python for Data Analysis RoadmapNumPy, pandas, cleaning, visualisation and notebooks.
- System Design RoadmapScalability, caching, queues, consistency and the classic designs.
- Node.js RoadmapEvent loop, modules, HTTP, streams, frameworks and deployment.
- Spring Boot RoadmapDI, Spring MVC, data access, security and microservices.
FAQ
How long does it take to learn SQL?
Basic queries take one to two weeks of regular practice. Reaching interview level, with joins, window functions, transactions and indexing, usually takes two to three months at about eight hours a week. Writing many queries on real data matters more than reading.
Which SQL database should I learn first?
PostgreSQL is a good first choice: it follows the standard closely, is free and is widely used. MySQL, SQL Server and SQLite are also fine. About ninety percent of what you learn transfers; the differences are mostly in date functions, limiting rows and procedural languages.
Is SQL still worth learning with AI tools that write queries?
Yes. You need to check what generated queries do, spot wrong joins and null handling and understand performance. Interviews still test SQL by hand, and the person who understands the data model gets better results from any tool.
What is the difference between SQL and MySQL?
SQL is the language. MySQL is one database product that implements it, alongside PostgreSQL, SQL Server, Oracle and SQLite. Each adds its own functions and small syntax differences.
Do I need to learn NoSQL as well?
Learn SQL first, since most business systems use it. Then learn one document store such as MongoDB Roadmap and one cache such as Redis Roadmap so you can explain when each fits.