Filter by Database

Query Techniques

ANY / ALL Subquery comparison operators. ANY (or SOME) returns true if the comparison holds for at least one value in the subquery result. ALL returns true only if the comparison holds for every value. Semantically related to EXISTS and IN but more flexible with comparison operators. 4/5 BETWEEN Test whether a value falls within an inclusive range. BETWEEN a AND b is equivalent to val >= a AND val <= b — both endpoints are included. 5/5 CORRELATED SUBQUERY A subquery that references columns from the outer query. The subquery is re-evaluated once per row of the outer query, creating a row-by-row dependency. Powerful but potentially slow on large datasets — often replaceable with a JOIN or window function. 5/5 CUBE An extension of GROUP BY ROLLUP that generates subtotals for every possible combination of the specified columns, not just hierarchical rollups. Produces 2^n grouping combinations for n columns. 3/5 DISTINCT Eliminate duplicate rows in a result set. 5/5 EXISTS Test whether a subquery returns any rows. Returns TRUE if the subquery produces at least one row, FALSE otherwise. Short-circuits on the first match. 5/5 FETCH FIRST / OFFSET-FETCH Standard SQL syntax for skipping a number of rows and limiting the result set size, used for pagination. 5/5 GROUP BY Aggregate rows sharing common values. 5/5 GROUPING SETS An explicit list of grouping combinations to compute in a single pass, giving precise control over which subtotals are produced. More flexible than ROLLUP or CUBE. 3/5 HAVING Filter the results of a GROUP BY aggregation. WHERE filters individual rows before grouping; HAVING filters groups after aggregation. 5/5 IN / NOT IN Test whether a value matches any value in a list or subquery. IN is shorthand for multiple OR equality conditions; NOT IN is the negation. 5/5 IS NULL / IS NOT NULL Test whether a value is NULL (missing/unknown). NULL cannot be compared with = or != — only IS NULL and IS NOT NULL work correctly. 5/5 LATERAL Allows a subquery in the FROM clause to reference columns from tables to its left, enabling advanced row-by-row operations. 4/5 LIKE Pattern matching within strings using % (any sequence of characters) and _ (exactly one character) wildcards. 5/5 LIMIT / TOP / FETCH FIRST Restrict the number of rows returned by a query. Every engine supports this but with different syntax. 5/5 NAMED WINDOW CLAUSE Define a reusable window specification with a name in a WINDOW clause, then reference it by name across multiple window functions in the same query. Eliminates duplicated OVER(...) definitions. 3/5 ORDER BY Sort the result set by one or more columns. 5/5 PIVOT Rotates rows into columns, creating cross-tab reports. 2/5 QUALIFY A post-aggregation filter clause for window functions, analogous to HAVING for aggregate functions, avoiding the need for a subquery. 0/5 QUERY HINTS / OPTIMIZER HINTS Directives embedded in a SQL statement that instruct the query optimizer to use a specific join order, index, or execution strategy. 4/5 RECURSIVE CTE A CTE that references itself for hierarchies or graph traversals. 5/5 REGEX Match strings against regular expression patterns, enabling flexible search beyond simple LIKE wildcards. 3/5 ROLLUP An extension of GROUP BY that generates subtotal and grand-total rows automatically. Produces a result set with multiple levels of aggregation in a single query. 4/5 SET OPERATIONS Combine rows from multiple queries: UNION, INTERSECT, EXCEPT/MINUS. 5/5 SUBQUERY A SELECT statement nested inside another query, used in WHERE, FROM, SELECT, or HAVING clauses. 5/5 TABLESAMPLE Return a random sample of rows from a table efficiently, without scanning and sorting the full table. 3/5 UNPIVOT Transform columns into rows — the inverse of PIVOT. Takes values spread across multiple columns and normalizes them into a key-value row structure. Useful for reshaping wide, denormalized data. 2/5 VALUES CLAUSE Construct an inline table from literal values without referencing a persistent table. Useful for multi-row inserts, testing, and constructing ad-hoc result sets to join against. 4/5 WINDOW FRAME (ROWS/RANGE) Control which rows are included in a window function's calculation relative to the current row. The frame clause (ROWS or RANGE BETWEEN ... AND ...) determines the sliding window boundaries. 5/5 WINDOW FUNCTIONS Perform calculations across a set of rows related to the current row. 5/5 WITH (COMMON TABLE EXPRESSIONS) Common Table Expressions (CTEs) provide a way to write auxiliary statements for use in a larger query. 5/5 WITH TIES An extension to FETCH FIRST / LIMIT that includes additional rows that tie on the last ORDER BY value rather than cutting them off arbitrarily. 3/5

DML

JSON

Indexes & Search

DDL

ALTER TABLE Modify an existing table’s structure. 5/5 CHECK CONSTRAINT A constraint that enforces a boolean condition on column values at the row level — the database rejects any INSERT or UPDATE that would violate it. 5/5 CREATE SCHEMA Create a named namespace within a database that groups related tables, views, and other objects. Schemas provide organizational structure and a layer of access control. 3/5 CREATE TABLE Define a new table and its columns. 5/5 CREATE VIEW Define a named virtual table based on a SELECT query. 5/5 DEFAULT VALUE Specify a value to be used automatically when no value is provided for a column during INSERT. 5/5 DROP TABLE Remove a table and all its data. 5/5 EXCLUSION CONSTRAINTS A generalization of UNIQUE constraints that uses arbitrary operators — most commonly used to prevent overlapping date/time ranges or spatial objects. 1/5 FOREIGN KEY A column or set of columns that references the primary key of another table, enforcing referential integrity between parent and child tables. 5/5 GENERATED COLUMNS Columns whose values are automatically computed from an expression over other columns in the same row. The database maintains the value rather than the application. Also called computed columns or virtual columns. 5/5 IF NOT EXISTS / IF EXISTS (CONDITIONAL DDL) Modifiers on DDL statements that suppress errors when an object already exists (or does not exist), enabling idempotent schema scripts. 5/5 MATERIALIZED VIEW A view whose result set is physically stored on disk and can be refreshed on demand or automatically. Trades storage and staleness for query speed — avoids recomputing expensive aggregations on every query. 3/5 NOT NULL A column constraint that prevents NULL values from being stored, requiring every row to supply a value for that column. 5/5 PRIMARY KEY A column or set of columns that uniquely identifies each row in a table. Enforces uniqueness and NOT NULL, and typically drives the clustered index. 5/5 RENAME TABLE / COLUMN Changing the name of an existing table or column without recreating the object. 5/5 SEQUENCE / AUTOINCREMENT Mechanisms for auto-generating unique sequential integer values, typically used for surrogate primary keys. Syntax and feature names vary significantly across engines. 5/5 TEMPORARY TABLES Tables that exist only for the duration of a session or transaction and are automatically dropped when that session ends. Used to stage intermediate results without polluting the permanent schema. 5/5 UNIQUE CONSTRAINT Enforce that all values in a column or combination of columns are distinct across all rows. Unlike a PRIMARY KEY, a unique constraint allows NULL values (with engine-specific behavior). 5/5

Transactions

Functions

CASE WHEN Conditional expression returning different values based on evaluated conditions. 5/5 CAST Convert a value from one data type to another. 5/5 CHARINDEX / INSTR / POSITION Search for a substring within a string and return the position of the first occurrence. Returns 0 or NULL if not found, depending on the engine. 5/5 COALESCE Returns the first non-NULL value from a list of expressions. 5/5 CONCAT Concatenate two or more strings into a single string. Behavior with NULL values differs significantly between engines. 5/5 COUNT / SUM / AVG / MIN / MAX The five core aggregate functions. COUNT counts rows or non-NULL values. SUM and AVG compute totals and averages. MIN and MAX return the smallest and largest value. All are universally supported. 5/5 CURRENT TIMESTAMP Retrieve the current date and/or time from the database server. Each engine has multiple synonyms with subtle differences around timezone awareness and precision. 5/5 DATE ADD / INTERVAL ARITHMETIC Add or subtract a time interval from a date or timestamp value. Syntax varies more than almost any other operation across SQL engines. 5/5 DATE FORMAT Format a date or timestamp value as a string in a specific display format. Every engine has a different function name and format code system. 5/5 DATE PARSING Functions for parsing strings into dates. 4/5 DATE TRUNC Truncate a date or timestamp to a specified unit of precision (year, month, day, hour, etc.), zeroing out all smaller units. 3/5 DATEDIFF Calculate the difference between two date or timestamp values, returning an integer count of a specified unit (days, months, etc.) or an interval. 5/5 EXTRACT / DATEPART Extract a specific component (year, month, day, hour, etc.) from a date or timestamp as a numeric value. 4/5 FILTER (AGGREGATE) Add a per-aggregate WHERE condition to filter the rows included in that specific aggregate, without a separate subquery. 3/5 FIRST_VALUE / LAST_VALUE Window functions that return the first or last value in the current window frame. Commonly used to carry forward the first value in a group or compare each row to the group's boundary. 5/5 FORMAT / TO_CHAR Formatting a date, number, or other value as a string according to a format pattern. 5/5 GENERATE_SERIES Generate a set of integer, numeric, or timestamp values as a virtual table row source. 3/5 GREATEST / LEAST Return the largest or smallest value from a list of two or more expressions. Evaluate multiple columns or values in a single call without nested CASE expressions. 4/5 IIF / DECODE / CONDITIONAL SHORTHAND Compact conditional expressions that return one of two or more values based on a condition, without the full verbosity of CASE WHEN. Includes IIF (SQL Server, Access), DECODE (Oracle), and IF (MySQL). 3/5 LAG / LEAD Access the value from a row before (LAG) or after (LEAD) the current row within an ordered window partition — without a self-join. 5/5 LENGTH Return the number of characters (or bytes) in a string. 5/5 MATH FUNCTIONS (FLOOR / CEIL / ROUND / ABS) Core numeric functions for rounding, truncating, and taking the absolute value of numeric expressions. 5/5 NTILE Divide rows in a window partition into a specified number of ranked buckets (tiles) as evenly as possible, returning the bucket number for each row. 5/5 NULLIF Returns NULL if two expressions are equal, otherwise returns the first expression. Commonly used to suppress zero-division errors and convert sentinel values to NULL. 5/5 PERCENTILE FUNCTIONS Compute percentile values within a distribution. PERCENTILE_CONT returns an interpolated value; PERCENTILE_DISC returns an actual value from the dataset. Used for medians, quartiles, and statistical analysis. 3/5 RANK / DENSE_RANK Window functions that assign a rank to each row within a partition. RANK skips rank numbers after ties; DENSE_RANK does not skip. 5/5 REGEXP REPLACE A function to replace substrings based on regex patterns. 3/5 REPLACE Replace all occurrences of a substring within a string with a new substring. 5/5 ROW_NUMBER Assign a sequential integer to each row within a result set or partition, starting at 1. Rows with equal values receive different numbers (unlike RANK). 5/5 STRING AGG Concatenates strings separated by a specified separator. In PostgreSQL, this is STRING_AGG; in MySQL and SQLite, use GROUP_CONCAT; in Oracle, use LISTAGG; and in SQL Server, use STRING_AGG (since 2017). Syntax and features may differ between databases. 5/5 STRING PADDING (LPAD / RPAD) Padding a string to a specified length by prepending (LPAD) or appending (RPAD) a fill character. 3/5 STRING SPLIT / STRING TO ROWS Split a delimited string into multiple rows or elements. Commonly needed for storing comma-separated lists in a single column and querying them relationally. 3/5 SUBSTRING Extract a portion of a string starting at a given position, optionally for a given length. 5/5 TRIM Remove leading and/or trailing characters (typically whitespace) from a string. 5/5 UPPER / LOWER Convert a string to all uppercase or all lowercase characters. 5/5 UUID / GEN_RANDOM_UUID Generating a universally unique identifier (UUID/GUID) within a SQL query or default expression. 4/5 WITHIN GROUP Ordered-set aggregate functions that require a sort order to compute their result: PERCENTILE_CONT (interpolated median), PERCENTILE_DISC (exact value), and MODE (most frequent value). 3/5

Syntax

Joins

Programmability

Administration

Data Types

Security