Databases
Query and shape relational data: joins, aggregates, constraints, transactions, window functions and tuning.
A practical path through SQL from the first SELECT to window functions and query plans. It suits developers, analysts and anyone who needs to read and write data in a relational database; examples lean on PostgreSQL, with notes where MySQL or SQL Server differ. Each subject links the official documentation.
The subjects follow the roadmap.sh SQL roadmap.
SQL is the declarative language for asking questions of relational databases: you describe the result you want and the engine works out how to fetch it. Before writing queries, understand the relational model it sits on and where it is a poor fit.
Databases that store data as tables of typed columns and rows, linked through primary and foreign keys. Relationships are expressed at query time with joins rather than baked into the storage layout.
You get transactions, constraints, ad-hoc joins and decades of optimiser work. The price: schema changes need migrations, and write-heavy workloads usually scale up on one primary before sharding becomes an option.
Document, key-value, wide-column and graph stores relax the fixed schema and often the consistency guarantees to make horizontal scaling and flexible records easier. Pick by access pattern, not fashion; many apps are well served by a relational database alone.
A statement is built from keywords, identifiers, literals, operators and a terminating semicolon. Keywords are case-insensitive, string literals use single quotes, and quoted identifiers use double quotes in standard SQL (MySQL uses backticks by default).
Reserved words such as SELECT, FROM, WHERE, JOIN and ORDER that give a statement its shape. Avoid them as table or column names, or you will be quoting those names forever.
Integers, exact NUMERIC/DECIMAL for money, floating point, CHAR/VARCHAR/TEXT, BOOLEAN, dates and timestamps. Each engine adds its own; choosing the right one gives you validation and smaller storage for free.
Arithmetic (+ - * / %), comparison (= <> < >), logical (AND OR NOT) and special predicates like BETWEEN, IN, LIKE and IS NULL. Remember that any comparison with NULL yields unknown, not true or false.
DDL statements create and change the structure that holds data: tables, columns, indexes, views and schemas. In many engines DDL commits implicitly, while PostgreSQL lets you wrap it in a transaction and roll it back.
CREATE TABLE names the table, lists columns with types, defaults and constraints, and declares keys. IF NOT EXISTS makes setup scripts safe to rerun.
Adds, drops or renames columns, changes types and adds or removes constraints on an existing table. On big tables some changes rewrite every row and hold a heavy lock, so check before running them in production.
Removes the table, its data, indexes and triggers for good. Objects that depend on it, such as views or foreign keys, block the drop unless you add CASCADE.
Empties a table in one fast operation instead of deleting row by row. It skips per-row triggers, can reset identity counters with RESTART IDENTITY, and is not allowed on a table referenced by a foreign key without CASCADE.
DML reads and changes the rows inside tables. A SELECT is evaluated logically as FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY, which explains why a column alias cannot be used in WHERE.
Returns a result set: the columns or expressions to output, plus optional DISTINCT, LIMIT/OFFSET (or FETCH FIRST). List columns explicitly rather than SELECT * so schema changes do not silently change your results.
Names the source of rows: tables, views, subqueries or joins between them, each optionally given a short alias. Everything else in the query operates on what this clause produces.
Filters rows before grouping with a boolean condition. Rows where the condition is false or unknown are dropped, so col <> 5 silently excludes rows where col is NULL.
Sorts the final result by one or more expressions, ASC or DESC, with NULLS FIRST/LAST in engines that support it. Without it, row order is undefined even if it looks stable.
Combine rows from two or more tables on a matching condition, usually a foreign key equal to a primary key. The JOIN Queries section below covers each join type in detail.
Adds rows from a VALUES list or from a SELECT. Name the target columns explicitly, use multi-row VALUES for batches, and use RETURNING (Postgres, SQLite) to read back generated keys.
Changes column values in rows that match a WHERE clause. Forgetting the WHERE updates every row, so run the same condition as a SELECT first or work inside a transaction.
Removes rows matching a condition, firing triggers and checking foreign keys row by row. For clearing a whole table, TRUNCATE is much faster.
Aggregate functions collapse many rows into one value, either over the whole result or per group. Except for COUNT(*), they skip NULL inputs, and an aggregate over zero rows returns NULL rather than zero.
Adds up a numeric column across the rows in each group. Wrap it in COALESCE(SUM(x), 0) when an empty group should show zero instead of NULL.
COUNT(*) counts rows, COUNT(col) counts non-null values, and COUNT(DISTINCT col) counts unique ones. Mixing them up is a classic source of off-by-some reports.
Arithmetic mean of non-null values. On integer columns some engines return an integer or a truncated value, so cast to a decimal type when precision matters.
Smallest value in the group; works on numbers, text (by collation) and dates. A plain B-tree index lets the engine answer an ungrouped MIN almost instantly.
Largest value in the group, often used for "latest timestamp per user". To fetch the whole row holding that maximum, reach for a window function or a correlated subquery instead.
Splits rows into groups sharing the same values in the listed columns and computes aggregates per group. Every selected column must be grouped or aggregated; MySQL only enforces this with ONLY_FULL_GROUP_BY enabled.
Filters groups after aggregation, for example HAVING COUNT(*) > 5. Conditions that do not involve aggregates belong in WHERE, where they cut rows earlier and cheaper.
Constraints are rules the database enforces on every write, so bad data is rejected no matter which application or script sends it. They are cheaper and more reliable than the same checks repeated in application code.
One column or a set of columns that uniquely identifies each row and can never be NULL. Use a surrogate key (identity or UUID) when no natural value is truly stable.
Requires a column value to exist in another table's key. ON DELETE CASCADE, SET NULL or RESTRICT decides what happens to children when the parent row goes; index the referencing column yourself.
Forbids duplicate values in a column or combination of columns and creates an index behind the scenes. Most engines still allow several NULLs, since NULL is not equal to NULL.
Makes a value mandatory. Default to NOT NULL and allow nulls only where "unknown" is a real state, which keeps queries free of three-valued-logic surprises.
A boolean expression every row must satisfy, such as price >= 0 or end_date > start_date. MySQL ignored CHECK before 8.0.16, so verify your engine enforces it.
Joins pair rows from two sources on a condition and are how normalised data is put back together. The join type decides what happens to rows that find no partner; write the condition with ON and keep filters on the outer side in mind.
Returns only the row pairs where the condition matches; unmatched rows on either side disappear. Plain JOIN means the same thing.
Keeps every row from the left table and fills the right side with NULL when there is no match. Putting a right-table filter in WHERE quietly turns it back into an inner join; put it in ON instead.
The mirror of a left join: all rows from the right table are kept. Most people rewrite it as a left join with the tables swapped because it reads more naturally.
Keeps unmatched rows from both sides, padding the missing side with NULL. Handy for reconciling two lists; MySQL lacks it, so there you emulate it with a UNION of a left and right join.
A table joined to itself under two aliases, used for hierarchies like employee and manager or for comparing rows within the same table.
The Cartesian product: every row of one side paired with every row of the other. Useful for generating combinations such as dates by products; accidental cross joins explode row counts.
A query nested inside another, used as a value, a list, or a derived table. Modern optimisers often turn subqueries into joins, but readability and correctness with NULLs still differ, especially NOT IN against a list containing NULL.
A subquery that returns exactly one row and one column, usable anywhere a single value is, such as in a select list. If it returns more than one row the statement fails at run time.
Returns one column of many rows, consumed by IN, ANY or ALL. Prefer NOT EXISTS over NOT IN when the column may contain NULL.
Returns a single row with several columns, compared as a tuple: WHERE (a, b) = (SELECT x, y FROM ...). Support for row constructors varies between engines.
A subquery in FROM that acts as a temporary derived table and must be given an alias. Often clearer as a CTE when it grows beyond a few lines.
Subqueries inside subqueries, each evaluated independently of the outer row. Deep nesting gets hard to read quickly; flatten it with joins or CTEs.
A subquery that refers to columns of the outer query and is therefore logically re-run for every outer row, as in EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id). Check the plan to make sure it is not literally executed per row.
Built-in scalar functions transform values inside a query, so formatting, rounding and fallbacks can happen in the database instead of in application loops. Names and argument orders differ between engines more than any other part of SQL, so keep your engine's reference handy.
Rounding, absolute value and remainder functions used for money, bucketing and pagination maths. Results depend on the input type, so integer and decimal arguments can behave differently.
Rounds down to the nearest integer toward negative infinity, so FLOOR(-2.5) is -3. Handy for bucketing values into fixed-size bins.
Returns the magnitude of a number without its sign, for example to compute the size of a difference regardless of direction.
Remainder after integer division, also written % in most engines. MOD(id, 2) = 0 picks even rows; the sign of the result follows the dividend.
ROUND(x, n) rounds to n decimal places. Exact decimal types round half away from zero in most engines, while floating point can surprise you, so keep money in NUMERIC.
Rounds up toward positive infinity (CEIL in many engines). A common use is page counts: CEILING(total / page_size) with a decimal division.
Functions for building, measuring, slicing and normalising text. Watch for collation, multibyte characters and NULL handling, which differ between engines.
Joins strings together. CONCAT() treats NULL as empty, whereas the standard || operator returns NULL if any part is NULL; MySQL uses || as logical OR by default.
Number of characters in a string. SQL Server calls it LEN and trims trailing spaces; MySQL's LENGTH counts bytes, so use CHAR_LENGTH for characters.
Extracts part of a string by a 1-based start position and length: SUBSTRING(code FROM 1 FOR 3) or SUBSTRING(code, 1, 3). Positions count from 1, not 0.
Substitutes every occurrence of one substring with another, as in REPLACE(phone, '-', ''). For pattern-based replacements use the engine's regular-expression function.
Converts text to upper case. Useful for normalised display or comparisons, though for case-insensitive searches an expression index or a case-insensitive collation is faster.
Converts text to lower case, commonly used to compare emails as LOWER(email) = LOWER($1). Back it with an index on LOWER(email) so the lookup stays fast.
Expressions that pick a value based on conditions, letting you bucket, relabel and supply defaults inside a single query. They are portable across almost every engine.
SQL's if/else expression: CASE WHEN score >= 90 THEN 'A' ELSE 'B' END. It works in select lists, ORDER BY and inside aggregates for conditional counts like SUM(CASE WHEN ... THEN 1 ELSE 0 END).
Returns NULL when its two arguments are equal, otherwise the first one. The classic trick is x / NULLIF(y, 0) to avoid division-by-zero errors.
Returns the first non-null argument, so COALESCE(nickname, first_name, 'Guest') supplies a fallback chain. It is the standard replacement for IFNULL, ISNULL and NVL.
Temporal types and the functions that extract parts, add intervals and format output. This is the least portable corner of SQL, so learn your engine's names and always be clear whether a value carries a time zone.
A calendar day with no time part. Casting a timestamp to DATE (or calling DATE() in MySQL) truncates it, a common way to group events by day.
A time of day without a date, suited to opening hours or schedules. Avoid the time-zone-aware variant; time zones only make sense with a date attached.
Date plus time. Store moments in UTC using the zone-aware type (timestamptz in Postgres, DATETIMEOFFSET in SQL Server) and convert only for display.
SQL Server's function for pulling one component, such as year, month or weekday, out of a date. The standard equivalent is EXTRACT(field FROM value), available in Postgres and MySQL.
SQL Server's way to add an interval: DATEADD(day, 7, order_date). Postgres writes order_date + INTERVAL '7 days' and MySQL offers DATE_ADD.
A view is a saved query that behaves like a table, used to hide joins, expose a narrow set of columns or grant access without exposing base tables. A plain view stores no data; a materialized view stores its result and must be refreshed.
CREATE VIEW name AS SELECT ... saves the query under a name. Simple single-table views are often updatable, which lets inserts and updates pass through to the base table.
CREATE OR REPLACE VIEW swaps the definition, but usually only if existing columns keep their names and types. ALTER VIEW handles renames and options; bigger changes mean drop and recreate.
DROP VIEW [IF EXISTS] name removes the definition but never the underlying data. Views built on top of it block the drop unless you add CASCADE.
An index is a separate sorted structure, usually a B-tree, that lets the engine find rows without scanning the whole table. Every index speeds some reads and slows every write, so add them for real query patterns, not speculatively.
Create with CREATE INDEX, choose column order for composite indexes (equality columns first), drop unused ones, and in Postgres build on live tables with CONCURRENTLY to avoid blocking writes.
The optimiser chooses between scans and index lookups using table statistics. Indexes go unused when you wrap the column in a function, compare against a mismatched type or use a leading wildcard in LIKE.
A transaction groups statements into one unit that either fully happens or not at all. Keep transactions short: long ones hold locks and, in MVCC engines, stop old row versions from being cleaned up.
Starts an explicit transaction (START TRANSACTION in standard SQL). Without it, most clients run in autocommit mode where each statement commits on its own.
Makes all changes in the transaction permanent and visible to other sessions. Once it returns, the data is durable even if the server crashes immediately afterwards.
Discards every change made since BEGIN. Application code should roll back on any error so a half-finished unit of work never commits.
A named marker inside a transaction you can return to with ROLLBACK TO SAVEPOINT, undoing part of the work while keeping the rest. ORMs use them to emulate nested transactions.
Atomicity, Consistency, Isolation and Durability: the four guarantees a transactional database makes so concurrent work and crashes cannot corrupt data.
Four standard levels decide how much concurrent transactions can see of each other: the stricter the level, the fewer anomalies (dirty reads, phantoms, write skew) and the more blocking or retries. Postgres defaults to Read Committed, MySQL InnoDB to Repeatable Read.
Keeping data correct and keeping it in the right hands. Integrity comes from constraints and transactions; security comes from least-privilege roles, encrypted connections and never building SQL from raw user input.
Entity integrity (primary keys), referential integrity (foreign keys) and domain integrity (types, NOT NULL, CHECK) together stop invalid states being stored, whatever code path writes the data.
GRANT SELECT, INSERT ON orders TO app_role hands out specific privileges and REVOKE takes them back. Grant to roles, then add users to roles, so permissions stay manageable.
Use parameterised queries everywhere, give the application a role with only the rights it needs, require TLS, keep the database off the public internet, rotate credentials and encrypt backups.
Code that lives and runs inside the database, written in SQL or a procedural dialect such as PL/pgSQL or T-SQL. Functions return a value and can be used in queries; procedures are called with CALL and, in some engines, can control transactions. They cut round trips but are harder to version and test than application code.
Fast SQL comes from reading less data: the right indexes, selective filters, narrow results and plans that avoid repeated work. Measure with the real plan before and after every change rather than guessing.
Match indexes to your WHERE, JOIN and ORDER BY columns and keep predicates sargable, meaning the bare column is compared to a value. A covering index can answer a query without touching the table at all.
Index foreign key columns, join on matching types, and filter early so fewer rows reach the join. Learn the nested loop, hash and merge strategies so plans make sense.
Replace a subquery re-evaluated per row with a join, an EXISTS, or a window function computed once. Check the plan, since some engines already rewrite the subquery for you.
Ask only for the columns you use. Dropping SELECT * cuts network transfer, lets index-only scans kick in and keeps wide text or JSON columns out of memory.
Read execution plans with EXPLAIN and EXPLAIN ANALYZE, compare estimated with actual row counts, and find the heaviest queries with tools such as pg_stat_statements or the slow query log.
Features that let one query do what used to need application loops: CTEs, recursion, window functions, pivots and SQL generated at run time. They are where SQL turns from a lookup language into an analytics tool.
WITH name AS (SELECT ...) defines named, query-local result sets you can reference like tables. They make long queries readable top to bottom; modern Postgres inlines them unless marked MATERIALIZED.
WITH RECURSIVE combines an anchor query with a step that references itself, walking trees and graphs such as category hierarchies or org charts. Guard against cycles or the query never ends.
Turning row values into columns and back. SQL Server and Oracle have PIVOT/UNPIVOT operators; elsewhere you pivot with SUM(CASE WHEN ...) or FILTER, and Postgres offers crosstab in tablefunc.
Compute across a set of related rows without collapsing them: func() OVER (PARTITION BY ... ORDER BY ... ROWS ...). Running totals, rankings and period-over-period comparisons all become single queries.
Assigns 1, 2, 3 ... within each partition, with no ties. The standard way to take the top N rows per group or deduplicate by keeping row number 1.
Ranks rows by the window ordering; ties share a rank and leave gaps afterwards, so two firsts are followed by a third.
Like rank but without gaps: two firsts are followed by a second. Use it when you want the Nth distinct value, such as the second-highest salary.
Reads a value from a following row in the window, such as the next event's timestamp, to compute gaps and durations without a self join. An optional default replaces NULL at the end.
Reads a value from a preceding row, the usual tool for month-over-month change: revenue - LAG(revenue) OVER (ORDER BY month).
Returns the value from the first row of the window frame, for instance each customer's first order date next to every order. Its sibling last_value needs an explicit frame to behave as expected.
SQL text built and executed at run time, via EXECUTE in PL/pgSQL or sp_executesql in SQL Server. Pass values as parameters and quote identifiers with functions like format('%I') to stay safe from injection.