Quick Reference

SQL Glossary

Quickly find what a SQL concept means, what it is for and how to use it.

150 entries to look up

Browse by topic

Browse by topicAll

150 results

Basic queries

10

Filters and conditions

10

Grouping and calculating

11
AVGAVG computes the average of the non-NULL values. It does not count missing values as zero.Function or operator COUNTCOUNT(*) counts rows; COUNT(column) counts non-null values; COUNT(DISTINCT column) counts distinct non-null values.Function or operator FILTER (WHERE ...) in SQL aggregatesFILTER (WHERE ...) limits the rows of one particular aggregate without excluding them from the query's other calculations.Function or operator GROUP BYGROUP BY gathers rows that share the same value to produce one summary per group, such as the number of customers in each city.Concept GROUP BY with multiple columnsGROUP BY with several columns creates one group for each distinct combination of their values.Concept GROUPING SETS, ROLLUP and CUBE: subtotal rows in SQLGROUPING SETS computes the groups you list; ROLLUP adds hierarchical subtotal rows; CUBE computes every combination of the dimensions.Comparison HAVINGHAVING filters groups after the aggregates are calculated. WHERE filters rows before grouping.Concept MAXMAX returns the largest non-null value of an expression. It does not automatically return the row that contains it.Function or operator MINMIN returns the smallest non-null value of an expression. To get the matching row you need a different query and a decision about ties.Function or operator SUMSUM adds up numeric values and ignores NULL. If there is no known value at all, it returns NULL rather than zero.Function or operator WHERE vs HAVINGWHERE filters rows before grouping; HAVING filters groups after the aggregates are calculated.Comparison

Combining tables

9

Modifying data

12
BEGIN / START TRANSACTIONBEGIN or START TRANSACTION opens a transaction: a group of changes that are either committed together with COMMIT or undone with ROLLBACK.Concept COMMITCOMMIT makes the current transaction's changes permanent. A later ROLLBACK no longer undoes them.Concept DELETEDELETE removes rows from a table while preserving its structure. WHERE determines which rows; without WHERE, all rows are candidates.Concept DELETE vs TRUNCATE vs DROPDELETE removes rows and supports WHERE; TRUNCATE empties the whole table; DROP also removes its definition.Comparison INSERT INTOINSERT INTO creates new rows. The column list determines where each value goes.Concept MERGEMERGE compares source data with a target table to decide which rows to update, insert or delete, according to the rules in the statement.Concept Transaction isolation levelsThe isolation level decides what a transaction can see while others are working, and how conflicts between them are resolved.Concept RETURNING with INSERT, UPDATE and DELETERETURNING gives back values from the rows a statement has just inserted, updated or deleted. Its availability and alternatives depend on the engine.Concept ROLLBACKROLLBACK undoes every change in the transaction in progress and ends it without committing them. It cannot undo a transaction that has already ended with COMMIT.Concept SAVEPOINTSAVEPOINT sets a marker inside a transaction. ROLLBACK TO returns to that marker and keeps the changes made before it.Concept TRUNCATE TABLETRUNCATE TABLE empties a whole table and keeps its definition. It does not accept WHERE; check its effect on keys and transactions in your engine.Concept UPDATEUPDATE changes the columns listed in SET for the rows that match WHERE. The other columns keep their values.Concept

Designing databases

27
ADD COLUMN vs changing a columnADD COLUMN creates a new column. ALTER COLUMN or MODIFY COLUMN changes an existing one, with syntax that varies by engine.Comparison ALTER TABLEALTER TABLE changes the definition of an existing table: depending on the engine, it can add columns, rename them or change constraints.Concept ALTER TABLE on large tablesThe cost of ALTER TABLE depends on whether it changes metadata, rewrites data or blocks access. Rehearse the specific operation and version with a realistic data volume.Design and best practice Best practice for SQL aliasesChoose aliases that explain each table's role and what each calculation means. Keep the same convention throughout the query.Design and best practice CHECKCHECK rejects a row that breaks a condition defined in the schema, such as a discount out of range.Concept Composite primary keyA composite primary key identifies each row by the combination of two or more columns.Design and best practice Auto-generated keys: IDENTITY, AUTO_INCREMENT and AUTOINCREMENTAn auto-generated column lets the engine assign an id when a row is inserted. Declare the matching uniqueness rule as well.Design and best practice Generated columns in SQL: GENERATED ALWAYS ASA generated column computes its value from other columns in the same row, using an expression defined in the table.Concept CREATE TABLECREATE TABLE creates a table and defines its columns, types, and constraints.Concept DEFAULTDEFAULT sets the value a column receives when an INSERT does not supply one. It does not automatically replace an explicit NULL.Concept DROP TABLEDROP TABLE removes the table, its data and its definition. After that, the object can no longer be queried.Concept EXPLAINEXPLAIN shows the plan the engine prepares for a query: how it will read tables, use indexes and combine operations.Design and best practice FOREIGN KEYA FOREIGN KEY is a column that points to the PRIMARY KEY or a unique key of another table. It requires every non-null reference to exist, so no child row is left without its parent row.Concept INDEXAn index gives the engine a route to find rows with less work. It can help filters, joins and sorts, but it takes up space and has a maintenance cost.Concept Composite index in SQL: several columns and their orderA composite index includes several columns in a defined order. That order affects which filters and sorts it can help with.Design and best practice Indexing a FOREIGN KEYThe referenced key needs to be unique; the columns in the child table may need an index of their own. Check your engine and the existing indexes before adding it.Design and best practice Partial or filtered indexes in SQL: indexing only some rowsA partial or filtered index contains only the rows that meet a condition, such as the pending tasks in a table.Design and best practice Indexes on expressions, or functional indexesAn index on an expression stores computed values, such as LOWER(email), to help queries that apply that same transformation.Design and best practice Database normalisation: from one table to 3NFNormalising means separating data according to its dependencies, to avoid repeated information and contradictory changes. Each table should represent one clear entity or relationship.Design and best practice NOT NULLNOT NULL stops a NULL value from being stored in a column. On its own it does not block an empty string or check that the value is correct.Concept ON DELETE CASCADE with FOREIGN KEYON DELETE CASCADE deletes the child rows when their parent row is deleted. Use this rule only when both should disappear together.Concept ON UPDATE CASCADE with FOREIGN KEYON UPDATE CASCADE updates child references when the parent row key changes.Concept Planning a structural change with ALTER TABLEPlan a schema change in stages: add the new structure, migrate the data, adapt the queries and remove the old structure once nothing uses it.Design and best practice PRIMARY KEYA PRIMARY KEY is the column or set of columns that uniquely identifies each row in a table. Its values cannot repeat and, in standard SQL, cannot be NULL.Concept Tables in SQLA table organises data into columns and rows. Each row represents an entity or a fact; each column describes a property.Concept SQL data types: how to choose the right oneThe data type defines which values a column expects. Choose by meaning, range and precision; the names and rules vary by engine.Design and best practice UNIQUEUNIQUE prevents a value, or a combination of values, from repeating. A table can have several UNIQUE rules, and how NULL is treated depends on the engine.Concept

Advanced SQL

24
ANY and ALL in SQLANY compares a value with a list and accepts it if any comparison is true; ALL requires every comparison to be true.Function or operator Recursive CTE with WITH RECURSIVEA recursive CTE produces new rows from the previous ones. It lets you walk a hierarchy without knowing all its levels in advance.Concept CTE vs subquery in SQL: when to use eachA subquery is written where its result is needed; a CTE names it up front with WITH. Choose for clarity and check performance.Comparison EXCEPTEXCEPT returns the rows from the first SELECT that do not appear in the second. By default it removes duplicates.Concept EXISTSEXISTS checks whether a subquery returns at least one row. It does not need to fetch any value from that row.Function or operator FIRST_VALUE and LAST_VALUE in SQLFIRST_VALUE and LAST_VALUE return the value from the first and last rows of the window frame. To cover the whole partition, declare the full frame.Function or operator INTERSECTINTERSECT returns the rows that appear in both SELECT statements. The queries must have compatible columns in the same positions.Concept LAGLAG returns a value from an earlier row in the order defined in OVER, while keeping the current row.Function or operator LATERAL in SQL and APPLY in SQL ServerLATERAL lets a subquery in FROM use columns from the rows that come earlier in that FROM. SQL Server expresses the same idea with APPLY.Concept LEADLEAD returns a value from a later row, following the order defined in OVER. PARTITION BY restarts the sequence for each group.Function or operator NTILE in SQL: Split sorted rows into groupsNTILE(N) splits the sorted rows into N groups of similar size. When the rows do not divide evenly, the larger groups come first.Function or operator OVEROVER defines the window of rows a function uses to calculate the value for the current row, without collapsing the result into a single row.Concept PARTITION BYPARTITION BY separates the groups of a window function. Each row keeps its detail and gets a calculation within its group.Concept PERCENT_RANK and CUME_DIST in SQL: relative positionPERCENT_RANK expresses relative position based on RANK; CUME_DIST measures the share of rows that come before or are tied. Ties produce different results.Comparison RANK and DENSE_RANKRANK leaves gaps after a tie; DENSE_RANK carries on without gaps. Both give tied values the same position.Comparison ROW_NUMBERROW_NUMBER numbers the rows from 1 following the window's ORDER BY. PARTITION BY restarts the numbering for each group.Function or operator ROWS BETWEEN and the window frameThe window frame decides which rows of a partition take part in the calculation for the current row. ROWS counts positions; RANGE looks at values and ties.Concept SubqueryA subquery is a SELECT query written in parentheses inside another query. Its result can be a single value, a list or an intermediate table, and it can be used in WHERE, FROM or SELECT.Concept Temporary tables in SQL: CREATE TEMP and TEMPORARY TABLEA temporary table holds working data for the session, or for whatever context the engine defines. You can reuse it across several statements.Concept UNIONUNION combines compatible results and keeps a single copy of each repeated row.Concept UNION ALLUNION ALL combines compatible results and keeps every row, including repeated ones.Concept UNION vs UNION ALLUNION removes repeated rows; UNION ALL keeps every occurrence. Choose based on whether a repeat represents the same item or a separate fact.Comparison VIEWA VIEW stores a named query. A normal view reads the rows from the base tables whenever you query it and does not keep a separate copy.Concept WITH and CTEWITH defines a CTE: a named helper result that exists only while the statement using it runs.Concept

Text, numbers and dates

13
CASTCAST converts a value to another data type within an expression. It does not change the type of the stored column.Function or operator CONCATCONCAT joins text fragments into a single value. The treatment of NULL depends on the engine and the way of concatenating.Function or operator CURRENT_DATECURRENT_DATE returns today's date, with no time, according to the engine's time settings.Function or operator CURRENT_TIMESTAMPCURRENT_TIMESTAMP returns the current date and time according to the engine. Use it to record or compare points in time.Function or operator EXTRACTEXTRACT gets one part of a date, such as the year or the month. SQLite and SQL Server use other functions for this.Function or operator LEAST and GREATEST in SQL: picking the smallest or largest valueLEAST picks the smallest and GREATEST the largest of several values in the same row. MIN and MAX, as aggregates, compare values across several rows.Function or operator LENGTHLENGTH measures the length of a value. In PostgreSQL and SQLite it counts the characters of a string; in MySQL it counts bytes, and CHAR_LENGTH counts characters.Function or operator REPLACEREPLACE returns a string in which every occurrence of one substring is swapped for another. Using it in SELECT does not change the stored text.Function or operator ROUNDROUND rounds a number to the number of decimal places you give. Rounding for display is not the same as keeping precision during a calculation.Function or operator STRING_AGG and GROUP_CONCAT: concatenating rows in SQLSTRING_AGG and GROUP_CONCAT join text from several rows into one string per group. The syntax for ordering depends on the engine.Function or operator SUBSTRINGSUBSTRING extracts part of a string, starting at a given position and, optionally, for a given length. The first position is usually 1.Function or operator TRIMTRIM removes the spaces at both ends of a string. It does not remove spaces in the middle, and using it in SELECT does not change the stored value.Function or operator UPPER and LOWERUPPER converts text to upper case and LOWER to lower case. The rules for languages and special characters depend on the engine.Function or operator

SQL recipes

34
Grouping by month in SQL: dates and GROUP BYTo summarise by month, group by a key that keeps both the year and the month; then apply COUNT or SUM.Recipe Grouping by ranges with CASE in SQLUse CASE to put each row into a band and GROUP BY to summarise the rows in each band.Recipe Aliases with COUNT and SUMGive COUNT and SUM clear names with AS. To filter on the aggregate, use HAVING with the expression itself if you want portability.Recipe Aliases in SELECTWrite AS followed by a clear name to give a calculation in SELECT a heading. You can use it in ORDER BY.Recipe Aliases in subqueriesGive the subquery in FROM an alias and use it to refer to its columns from the outer query.Recipe Anti-join in SQL: finding rows with no matchTo find rows with no match in another table, use NOT EXISTS with a condition linking both tables. How it compares with LEFT JOIN … IS NULL and NOT IN.Recipe Adding constraints with ALTER TABLETo add a constraint, first check that the existing data already satisfies it, then run your engine's ALTER TABLE.Recipe Comparing two tables in SQL and finding the rows that differDefine the key for each row and separate missing rows from changed ones. Use NOT EXISTS for missing rows and a JOIN to compare values, NULLs included.Recipe COUNT(DISTINCT) on multiple columns in SQLTo count distinct combinations, first run SELECT DISTINCT on the columns and then count the rows that subquery returns.Recipe CREATE TABLE AS SELECTCREATE TABLE ... AS SELECT creates a new table with the rows from a query. It does not involve copying all the constraints or the original indexes.Recipe SQL DELETE JOIN: Delete Rows Using Another TableTo delete rows based on another table, use WHERE EXISTS or your engine's JOIN/USING variant. Test the same filter with SELECT first.Recipe Consecutive days in SQL: finding each user's streaksKeep one day per user, compare it with the previous one using LAG and flag every gap. Accumulate those flags to identify and summarise the streaks.Recipe Date differences in SQL: days, hours and monthsDecide whether you need elapsed time or calendar boundaries. Then subtract the dates or use your engine's function for that unit.Recipe Dropping columns with ALTER TABLEALTER TABLE ... DROP COLUMN removes a column along with its data. Check the dependencies and keep anything you need before running it.Recipe Removing duplicates in SQL while keeping one rowDefine what counts as a duplicate and which row to keep. Use ROW_NUMBER to find the others, and delete them by key only after reviewing a preview.Recipe Finding duplicates with GROUP BY and HAVINGGroup by the columns that define a duplicate and use HAVING COUNT(*) > 1 to find the repeated keys.Recipe Common SQL alias mistakesIf an alias fails, check the commas, where it is in scope and the table name. A SELECT alias cannot be used portably in WHERE.Recipe Filtering between two dates in SQL: include the whole last dayTo include whole days in a column that stores a time, use date >= start AND date < the day after the end.Recipe INSERT INTO ... SELECTINSERT INTO ... SELECT inserts the rows returned by a query into an existing table. Match each source column to its target column.Recipe Moving average in SQL: a 7-day average without skipping datesBuild one row per day and entity, then apply AVG OVER with ROWS BETWEEN 6 PRECEDING AND CURRENT ROW. Seven rows only mean seven days if you fill in the calendar.Recipe ORDER BY CASE: building a custom sort orderUse CASE inside ORDER BY to turn categories into priorities, and add a tiebreaker for a stable order.Recipe Keyset pagination in SQL: carrying on from the last rowTo fetch the next page, filter for rows after the last row's key and keep the same ORDER BY. The cursor must include the unique tiebreaker.Recipe PIVOT in SQL: turning rows into columnsTo turn categories into columns, group by the dimension you keep as rows and compute a conditional aggregate for each category.Recipe Percentage of the total in SQL with SUM() OVER()Divide each amount by SUM(amount) OVER () and multiply by 100.0. Use NULLIF on the denominator if the total can be zero.Recipe First and last day of the month in SQLWork out the first day of the month and the first day of the next. Subtracting one day from the latter gives the end of the month; to filter on times, use the exclusive bound.Recipe Renaming columns and tables with ALTER TABLERename using your engine's syntax and update the queries that use the old name. The data stays, but some dependencies may need changes.Recipe SUM with CASE WHENUse CASE to decide what each row contributes and SUM to add those contributions up. With 1 and 0 you can count the rows that meet a condition.Recipe SQL running total: cumulative sums and balances with SUM OVERUse SUM(amount) OVER with PARTITION BY to separate groups, ORDER BY to set the order and ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to accumulate row by row.Recipe Adding and subtracting dates in SQLTo shift a date, state the unit and use your engine's syntax: INTERVAL, DATE_ADD, DATEADD or SQLite's date modifiers.Recipe Top N per group in SQL with ROW_NUMBER()Number each group with ROW_NUMBER and filter rn <= N in an outer query. Define an order and a tiebreaker to choose the rows.Recipe UPDATE with CASE: updating several rows with different valuesUse CASE inside SET to give several rows different values. Limit the scope with WHERE and keep the previous value with ELSE where appropriate.Recipe UPDATE with JOIN: updating one table from anotherUPDATE with JOIN updates the rows of one table using values from a related table. The syntax depends on the database (UPDATE … FROM, UPDATE … JOIN or MERGE), and the source must provide a single match per row.Recipe UPSERT in SQL: ON CONFLICT and ON DUPLICATE KEY UPDATEUPSERT tries to insert and, if it hits a conflict on a unique key, applies the action you defined to the existing row.Recipe Views in SQL ServerIn SQL Server, create a view with CREATE VIEW and query it in FROM. Define explicit columns and follow the rules on batches and ORDER BY.Recipe