sqlcmd.net validated sql reference

Advanced commands

Guides grouped by the expected difficulty and amount of SQL context they assume.

56 commands in this rank Step through by experience level
advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Access Previous And Next Rows With LAG And LEAD

Reference values from preceding or following rows within an ordered partition without writing a self-join.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Access The First Row In A Window With FIRST_VALUE

Return a value from the first row of a window partition, useful for comparing each row against the group leader.

advanced aggregation SQL Server PostgreSQL

Aggregate Across Arbitrary Dimension Combinations With GROUPING SETS

Produce multiple independent aggregation levels in one query using `GROUPING SETS` — more flexible than `ROLLUP` because you choose exactly which combinations to include.

advanced aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Aggregate Rows Conditionally With CASE Inside An Aggregate

Use `CASE WHEN` inside `SUM` or `COUNT` to produce multiple metrics from a single pass over grouped data.

advanced json MySQL MariaDB SQL Server PostgreSQL SQLite

Aggregate Rows Into A JSON Array

Collect values from multiple rows into a single JSON array, ordered and grouped by other columns.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Assign Session IDs Based on Inactivity Gaps

Group a stream of user events into sessions by labelling each event with a session ID that increments whenever the gap since the previous event exceeds a threshold.

advanced math PostgreSQL

Bin Numeric Values Into Equal-Width Buckets With WIDTH_BUCKET

Use `WIDTH_BUCKET(value, low, high, n)` to assign each row to one of `n` equal-width buckets between `low` and `high` — the foundation for building numeric histograms directly in SQL.

advanced json MySQL MariaDB SQL Server PostgreSQL SQLite

Build A JSON Object From Column Values

Construct a JSON object literal from individual column values within a query, returning structured data without a separate serialization step.

advanced recursion MySQL MariaDB SQL Server PostgreSQL SQLite

Build A Path String While Traversing A Hierarchy

Accumulate a breadcrumb path string as a recursive CTE walks a parent-child tree.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate A Running Total With SUM OVER

Accumulate a column's values row by row using `SUM` as a window function.

advanced windowing MySQL MariaDB SQL Server PostgreSQL

Calculate Percent Of Total With A Window Function

Use `SUM(...) OVER ()` to compare each row's value to the total without collapsing the result set.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate Relative Rank With PERCENT_RANK And CUME_DIST

Use percent-rank window functions to express each row's position within an ordered group.

advanced composition MySQL MariaDB SQL Server PostgreSQL SQLite

Chain Multiple CTEs in a Single WITH Clause

Define several named subqueries in one `WITH` block, each building on the previous, before the final `SELECT`.

advanced joining SQL Server PostgreSQL SQLite

Combine All Rows From Both Tables With FULL OUTER JOIN

Return all rows from both tables, filling NULLs on either side when there is no matching row.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Compare a Metric Year-Over-Year Using LAG

Pull the prior year's value into the current row with `LAG`, then compute the percentage change — a common pattern for revenue, signups, and other business KPIs.

advanced aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Compute a Median or Arbitrary Percentile

Find the median or any percentile value using `PERCENTILE_CONT` in PostgreSQL, MariaDB, and SQL Server, or a window-function workaround in MySQL and SQLite.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Compute a Rolling Moving Average With a Window Frame

Smooth time-series data by computing a rolling average over a fixed window of preceding rows using `AVG … OVER (ORDER BY … ROWS BETWEEN n PRECEDING AND CURRENT ROW)`.

advanced aggregation SQL Server PostgreSQL

Compute Every Grouping Combination at Once With CUBE

Use `GROUP BY CUBE(col_a, col_b)` to generate subtotals for every possible combination of those columns — the full power set — in a single query.

advanced aggregation PostgreSQL

Compute Pearson Correlation and Covariance

Measure the strength of a linear relationship between two columns with `CORR(y, x)` and covariance with `COVAR_SAMP` / `COVAR_POP` in PostgreSQL.

advanced aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Concatenate Values Within A Group

Aggregate multiple string values from grouped rows into a single delimited string.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Control the Window Frame With ROWS BETWEEN

Use `ROWS BETWEEN` in a window function to aggregate only the rows immediately surrounding each row.

advanced reshaping MySQL MariaDB SQL Server PostgreSQL SQLite

Convert Columns to Rows With UNPIVOT

Reshape a wide table by turning multiple columns into key-value row pairs — the inverse of a PIVOT operation.

advanced deduplication MySQL MariaDB SQL Server PostgreSQL SQLite

Delete Duplicate Rows While Keeping One

Use `ROW_NUMBER()` to identify duplicate rows and delete every copy except the one you want to keep.

advanced deleting MySQL MariaDB SQL Server PostgreSQL SQLite

Delete Orphaned Child Rows

Remove child rows that reference missing parent rows before enforcing referential integrity.

advanced deleting MySQL MariaDB SQL Server PostgreSQL SQLite

Delete Rows Based On A Condition In Another Table

Remove rows from one table when a matching row exists in another table using a subquery.

advanced deleting MySQL MariaDB SQL Server PostgreSQL SQLite

Delete Rows Using A Join Condition

Remove rows from one table based on matching rows in another table.

advanced aggregation MariaDB SQL Server PostgreSQL

Detect Outliers Using the IQR Method

Flag values that fall outside the interquartile fence `[Q1 − 1.5 × IQR, Q3 + 1.5 × IQR]` using `PERCENTILE_CONT` in PostgreSQL, MariaDB, and SQL Server.

advanced string-processing MySQL MariaDB PostgreSQL

Extract A Substring Matching A Regular Expression

Return the portion of a string that matches a regular expression pattern, useful for parsing structured text without fixed delimiters.

advanced joining MySQL MariaDB SQL Server PostgreSQL SQLite

Fetch Rows Including Unmatched From Right Table

Return all rows from the right table and matching rows from the left, filling NULL where no match exists.

advanced date MySQL MariaDB SQL Server PostgreSQL SQLite

Fill Gaps in a Time Series

Produce a row for every date in a range — even dates with no data — by generating a date spine and left-joining actual records onto it.

advanced json MySQL MariaDB SQL Server PostgreSQL SQLite

Filter JSON Arrays Containing A Value

Return rows where a JSON array contains a specific scalar value.

advanced data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Find Gaps In An Integer Sequence

Generate the expected numbers and left join to the existing table to find missing ids or sequence values.

advanced aggregation PostgreSQL

Fit a Linear Regression With REGR_SLOPE and REGR_INTERCEPT

Compute the least-squares slope, intercept, and R² of a linear regression directly in SQL using `REGR_SLOPE(y, x)`, `REGR_INTERCEPT(y, x)`, and `REGR_R2(y, x)` in PostgreSQL.

advanced composition MySQL MariaDB SQL Server PostgreSQL SQLite

Generate a Sequence of Numbers

Produce a consecutive sequence of integers without a base table — using `generate_series` in PostgreSQL or a recursive CTE in all other engines.

advanced joining MySQL MariaDB SQL Server PostgreSQL SQLite

Generate All Row Combinations With CROSS JOIN

Produce every possible pairing of rows from two tables using `CROSS JOIN`.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Last Value In A Window Partition

Use LAST_VALUE with an explicit full-partition frame to compare each row with the final row in its group.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Group Consecutive Rows With A ROW_NUMBER Difference

Create stable run groups without a primary key by subtracting two `ROW_NUMBER()` calculations over the same ordered events.

advanced upserting MySQL MariaDB SQL Server PostgreSQL SQLite

Insert Or Update A Row With UPSERT

Atomically insert a row if it does not exist or update it if it does, using the database's native conflict-resolution syntax.

advanced joining MySQL MariaDB SQL Server PostgreSQL SQLite

Join A Table To Itself With A Self-Join

Reference the same table twice using aliases to compare or relate rows within the same dataset.

advanced transactions MySQL MariaDB SQL Server PostgreSQL

Lock Rows for Update With SELECT FOR UPDATE

Acquire a row-level write lock inside a transaction so no other session can modify those rows before your update completes.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Normalise Values to Z-Scores

Rescale each row's value to the number of standard deviations it sits above or below the mean using `(value − AVG … OVER ()) / STDDEV_SAMP … OVER ()`.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Number Rows Within Groups Using ROW_NUMBER

Assign sequential integers to rows within a partition without collapsing the result set the way `GROUP BY` does.

advanced transactions MySQL MariaDB SQL Server PostgreSQL SQLite

Partially Roll Back With SAVEPOINT

Mark a named checkpoint inside an open transaction so you can roll back to that point without aborting the whole transaction.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Rank Rows With Gaps Using RANK And DENSE_RANK

Assign rank numbers to rows within a partition, controlling whether tied ranks leave gaps in the sequence.

advanced json MySQL MariaDB SQL Server PostgreSQL SQLite

Read a Value From a JSON Column

Extract a scalar value from a JSON column using the JSON function or operator each engine supports.

advanced joining MySQL SQL Server PostgreSQL

Reference Outer Columns Inside a Subquery With LATERAL

Use `LATERAL` (or `CROSS APPLY` on SQL Server) to let a subquery reference columns from the preceding table in the `FROM` clause.

advanced date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Round a Timestamp Down to a Specific Unit

Truncate a timestamp to the start of a month, day, or hour using engine-specific functions.

advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Select The Top Row Per Group

Use `ROW_NUMBER()` to rank rows within each group and keep only the highest-ranked row.

advanced transactions MySQL MariaDB SQL Server PostgreSQL SQLite

Set Transaction Isolation Level

Control how much a transaction can see concurrent changes made by other transactions.

advanced defining MySQL MariaDB SQL Server PostgreSQL SQLite

Speed Up Queries With CREATE INDEX

Create an index on one or more columns to make lookups and joins faster.

advanced string-processing SQL Server PostgreSQL

Split A Delimited String Into Rows

Expand a comma-separated or delimited string into one row per element, turning a single cell into a proper set of rows.

advanced modification SQL Server PostgreSQL

Sync a Target Table From a Source With MERGE

Use `MERGE` to insert new rows, update matching ones, and delete rows that should be removed — all in a single statement against a source table.

advanced filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Test For Row Existence With EXISTS

Use a correlated subquery inside `EXISTS` to include rows only when related rows are found in another table.

advanced recursion MySQL MariaDB SQL Server PostgreSQL SQLite

Traverse Hierarchies With A Recursive CTE

Use `WITH RECURSIVE` to repeatedly join a query to its own results, enabling traversal of tree or graph structures.

advanced updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update Rows Using Values From Another Table

Use a join inside an `UPDATE` statement to copy or derive values from a related table.

advanced metadata MySQL MariaDB SQL Server PostgreSQL SQLite

Why Structure Outlives Query Text

Schema and metadata choices tend to survive longer than any one statement, which is why naming and structure deserve more care than a temporary query draft.