sqlcmd.net validated sql reference

Intermediate commands

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

85 commands in this rank Step through by experience level
intermediate ddl MySQL MariaDB SQL Server PostgreSQL SQLite

Add a Foreign Key Constraint

Enforce referential integrity by linking a column to the primary key of another table so orphaned rows cannot be inserted.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Add Or Subtract Days From A Date

Calculate a future or past date by adding or subtracting an interval from an existing date.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL

Add Subtotals and a Grand Total With ROLLUP

Use `GROUP BY ROLLUP` to produce subtotals and a grand total alongside regular grouped rows in one query.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Apply a Condition to a Single Aggregate

Count or sum only the rows that match a specific condition without a WHERE clause — using `FILTER (WHERE ...)` in PostgreSQL and SQLite, or `CASE WHEN` inside the aggregate for other engines.

intermediate string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Assemble A Key/Value String

Format several known values into one compact `key=value` string for transport or handoff.

intermediate filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Avoid Duplicate Parent Rows With EXISTS

Use `EXISTS` when you only need to test whether a related row exists, not return one output row per match.

intermediate windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Bucket Rows Into Equal Groups With NTILE

Use `NTILE(n)` to divide an ordered result set into `n` roughly equal buckets and assign each row a bucket number.

intermediate windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate A Running Count With COUNT OVER

Use COUNT as a window function to number how many rows have appeared up to the current row.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate A Weighted Average

Divide the sum of value times weight by the sum of weights instead of averaging pre-aggregated values.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate The Number Of Days Between Two Dates

Find how many days separate two date values using each engine's date difference function.

intermediate ddl MySQL MariaDB SQL Server PostgreSQL

Change a Column's Data Type With ALTER TABLE

Modify the data type, default value, or nullability of an existing column without recreating the table.

intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Choose UNION Or UNION ALL Intentionally

`UNION` removes duplicates, while `UNION ALL` keeps them. Picking the wrong one silently changes row counts.

intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Combine Query Results With UNION

Merge result sets from two `SELECT` statements into one, removing duplicate rows by default.

intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Combine Results With UNION ALL

Append result sets together without removing duplicates.

intermediate null-handling MySQL MariaDB SQL Server PostgreSQL SQLite

Compare Values Including NULLs Safely

Match rows where two values are equal, treating two NULLs as equal instead of unknown.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Compute Standard Deviation and Variance

Measure how spread out values are with `STDDEV_SAMP` / `VAR_SAMP` in MySQL, MariaDB, and PostgreSQL, or `STDEV` / `VAR` in SQL Server.

intermediate sorting MySQL MariaDB SQL Server PostgreSQL SQLite

Control Where NULLs Appear in a Sort

Use `NULLS FIRST` or `NULLS LAST` to explicitly position NULL values at the top or bottom of a sorted result set.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL

Convert a Timestamp to a Different Time Zone

Shift a stored UTC timestamp to a local time zone for display using engine-specific conversion functions.

intermediate updating MySQL MariaDB SQL Server PostgreSQL SQLite

Convert Blank Strings To NULL

Normalize empty or whitespace-only text values to `NULL` with `NULLIF(TRIM(...), '')`.

intermediate casting MySQL MariaDB SQL Server PostgreSQL

Convert Values Without Errors Using Safe Casting

Convert strings to numbers (or other types) while returning `NULL` for values that cannot be converted, instead of raising an error that aborts the query.

intermediate json MySQL MariaDB SQL Server PostgreSQL SQLite

Count Elements In A JSON Array

Return the number of items stored in a JSON array value.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Count Users at Each Step of a Conversion Funnel

Measure how many unique users completed each stage of a multi-step flow using `COUNT(DISTINCT CASE WHEN event_name = '...' THEN user_id END)` per step.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Create A Reusable Query With CREATE VIEW

Save a `SELECT` statement as a named view so it can be queried like a table.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Create a Table From a Query Result

Materialize a query's output as a new table in one step using `CREATE TABLE AS SELECT` or `SELECT INTO`.

intermediate ddl MySQL MariaDB SQL Server PostgreSQL SQLite

Create a Temporary Table

Build a table that exists only for the current session and is discarded automatically when the connection closes.

intermediate date MySQL MariaDB SQL Server PostgreSQL SQLite

Detect Overlapping Date Ranges

Find rows whose date or timestamp intervals intersect by checking that neither range ends before the other begins — using the `OVERLAPS` operator in PostgreSQL or a manual comparison in other engines.

intermediate conversion MySQL MariaDB SQL Server PostgreSQL SQLite

Encode Text As Base64

Turn one plain-text payload into a base64 string for transport or lookup.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Enforce Uniqueness With CREATE UNIQUE INDEX

Create a unique index so the database rejects duplicate values in one or more columns.

intermediate array MySQL SQL Server PostgreSQL SQLite

Expand an Array or JSON Array Into One Row Per Element

Turn a list of values into individual rows — using `UNNEST` for native arrays in PostgreSQL, `JSON_TABLE` in MySQL, `OPENJSON` in SQL Server, or `json_each` in SQLite.

intermediate string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Extract Part Of A String With SUBSTRING

Return only part of a text value by position and length.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Extract The Year From A Date

Return the year component from a date or timestamp value.

intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Fetch Rows Including Unmatched With LEFT JOIN

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

intermediate filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter A Date Range With A Half-Open Boundary

Use an inclusive start and exclusive end to match a whole date range without missing rows that include times.

intermediate grouping MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Grouped Results With HAVING

Use `HAVING` to filter aggregate results after `GROUP BY`, the same way `WHERE` filters individual rows before grouping.

intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Filter LEFT JOIN Matches In The ON Clause

Put right-table filters in the `ON` clause when you want to keep unmatched left-side rows.

intermediate json MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows by a Value Inside a JSON Column

Use each engine's JSON path syntax in a `WHERE` clause to keep only rows whose JSON column contains a matching value.

intermediate subqueries MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows Using A Correlated Subquery

Reference the outer query's current row inside a subquery to compute a per-row comparison value.

intermediate data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Find Duplicate Values With GROUP BY And HAVING

Group rows by the candidate key and keep only values that appear more than once.

intermediate data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Find Orphaned Child Rows

Find child rows whose foreign key value does not match any row in the parent table.

intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows Common To Two Queries With INTERSECT

Return only the rows that appear in both result sets using `INTERSECT`.

intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows In One Query But Not Another With EXCEPT

Return rows from the first query that do not appear in the second query using `EXCEPT`.

intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows With No Match Using An Anti-Join

Return rows from one table that have no corresponding row in a second table using a LEFT JOIN with a NULL check.

intermediate joins MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows With No Matching Related Row

Use a `LEFT JOIN` and filter for `NULL` on the joined table to find missing relationships.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Find the Most Frequent Value (Statistical Mode)

Identify the value that appears most often in a column using `GROUP BY` with `ORDER BY COUNT(*) DESC LIMIT 1`, or with `MODE() WITHIN GROUP` in PostgreSQL.

intermediate string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Find The Position Of A Substring Within A String

Locate where a substring first appears inside a string, returning its 1-based character position.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Format A Date As A String

Convert a date value to a formatted string using a custom pattern such as MM/DD/YYYY.

intermediate conversion MySQL MariaDB SQL Server PostgreSQL SQLite

Format A Number As A Decimal String

Convert a numeric value into a formatted string with a fixed number of decimal places, optionally including thousands separators.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Generate Row IDs Automatically

Define an identity or auto-increment column so new rows receive numeric IDs without the insert supplying them.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Day Of Week From A Date

Return the weekday number or name for a date using engine-specific date functions.

intermediate grouping MySQL MariaDB SQL Server PostgreSQL SQLite

Group Rows And Count

Aggregate rows by category with `GROUP BY` and count how many rows fall into each group.

intermediate date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Group Rows By Month

Bucket dates into month starts, then aggregate counts or totals per month.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL

Group Rows By Multiple Columns

Use more than one column in `GROUP BY` when each combination defines a separate aggregate bucket.

intermediate transactions MySQL MariaDB SQL Server PostgreSQL SQLite

Group Statements Into A Transaction

Use `BEGIN`, `COMMIT`, and `ROLLBACK` to execute multiple statements as an atomic unit.

intermediate pagination SQL Server PostgreSQL

Include All Tied Rows When Limiting Results With WITH TIES

Add `WITH TIES` when limiting rows to also return every row that shares the same ORDER BY value as the last included row, preventing arbitrary tie-breaking at the result boundary.

intermediate inserting MySQL MariaDB SQL Server PostgreSQL SQLite

Insert Rows and Silently Skip Duplicates

Insert rows without raising an error when a unique constraint is violated, using each engine's conflict-ignore syntax.

intermediate performance MySQL MariaDB SQL Server PostgreSQL SQLite

Inspect A Query Plan With EXPLAIN

Ask the database how it plans to execute a SELECT so you can understand scans, joins, and index usage.

intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Join Tables On A Range Condition

Join two tables using a comparison other than equality — such as `BETWEEN` or `<` — to match rows based on ranges rather than exact values.

intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Join Tables With INNER JOIN

Combine rows from two tables when matching keys exist in both tables.

intermediate filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Match Multiple Columns at Once With Row Value Constructors

Use `(col_a, col_b) IN ((v1, v2), (v3, v4))` to filter on combinations of columns simultaneously — cleaner and less error-prone than chaining `AND`/`OR` conditions.

intermediate composition MySQL MariaDB SQL Server PostgreSQL SQLite

Name A Subquery With A CTE

Use `WITH` to define a named temporary result set that can be referenced in the main query, improving readability over inline subqueries.

intermediate windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Name a Window Definition for Reuse

Define a window specification once with a `WINDOW` alias and reference it in multiple `OVER` clauses — avoiding repetition when several window functions share the same partition and ordering.

intermediate subqueries MySQL MariaDB SQL Server PostgreSQL SQLite

Nest A Query Inside Another With Subqueries

Embed a `SELECT` inside another query to filter, compute, or supply values that depend on aggregated or derived data.

intermediate string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Pad A String To A Fixed Length With LPAD And RPAD

Left-pad or right-pad a string to a fixed width by filling with a repeated character.

intermediate pagination MySQL MariaDB SQL Server PostgreSQL SQLite

Paginate With Offset

Skip earlier rows and return the next slice of a sorted result set.

intermediate conversion MySQL MariaDB SQL Server PostgreSQL SQLite

Parse A Formatted String Into A Date

Convert a text string in a known format into a native DATE value using engine-specific parsing functions.

intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Pivot Rows Into Columns

Turn distinct row values into separate columns using `CASE WHEN` inside an aggregate.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Remove A Column From A Table With ALTER TABLE DROP COLUMN

Permanently delete a column and all its data from a table using ALTER TABLE.

intermediate deleting MySQL MariaDB SQL Server PostgreSQL SQLite

Remove All Rows From A Table With TRUNCATE

Delete every row in a table quickly with TRUNCATE TABLE, which is faster than DELETE with no WHERE clause.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Remove an Index With DROP INDEX

Drop an index that is no longer useful so writes no longer have to maintain it.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Rename a Table

Change a table name while keeping its existing rows and columns.

intermediate string-manipulation MySQL MariaDB PostgreSQL

Replace Substrings With a Regular Expression

Use `REGEXP_REPLACE` to substitute every match of a pattern in a string with a replacement value.

intermediate conditional-logic MySQL MariaDB SQL Server PostgreSQL SQLite

Return Different Values With CASE WHEN

Evaluate conditions row-by-row inside a `SELECT` to produce computed columns based on branching logic.

intermediate null-handling MySQL MariaDB SQL Server PostgreSQL SQLite

Return NULL When Two Values Are Equal With NULLIF

Use `NULLIF` to convert a specific value to `NULL`, most commonly to prevent division-by-zero errors.

intermediate modification MariaDB SQL Server PostgreSQL SQLite

Return Rows From an INSERT, UPDATE, or DELETE

Get the affected rows back in the same statement — using `RETURNING` in PostgreSQL, MariaDB, and SQLite, or `OUTPUT` in SQL Server.

intermediate selecting MySQL MariaDB SQL Server PostgreSQL SQLite

Select Random Rows

Return a random sample by ordering rows with the engine's random function and applying a row limit.

intermediate select MySQL MariaDB SQL Server PostgreSQL SQLite

Select the First Row Per Group With DISTINCT ON

Use PostgreSQL's `DISTINCT ON (col)` to keep only the first row for each unique value of a column, with `ORDER BY` controlling which row within each group is considered first.

intermediate sorting MySQL MariaDB SQL Server PostgreSQL SQLite

Sort Rows By A Custom Expression

Use a `CASE` expression in `ORDER BY` to apply a custom sort order that is not alphabetical or numeric.

intermediate schema MySQL MariaDB SQL Server PostgreSQL SQLite

Store a Computed Value Automatically With Generated Columns

Define a column whose value is always derived from an expression over other columns — the database recomputes or stores it on every write so queries never need to repeat the formula.

intermediate updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update a Column Based on Conditions With CASE WHEN

Set a column to different values depending on other column values in the same row by using `CASE WHEN` inside a `SET` clause.

intermediate updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update Rows Selected By A Subquery

Use a subquery in the `WHERE` clause of an `UPDATE` to restrict which rows are modified based on data from another table.

intermediate subqueries MySQL MariaDB SQL Server PostgreSQL SQLite

Use A Subquery As A Derived Table In FROM

Wrap a `SELECT` in the `FROM` clause to create a temporary result set you can filter or join against as if it were a real table.

intermediate composition MySQL MariaDB SQL Server PostgreSQL SQLite

Use an Inline Table of Constant Values

Supply a small set of constant rows directly inside a query using a `VALUES` derived table — no temporary table or CTE required.

intermediate null-handling MySQL MariaDB SQL Server PostgreSQL SQLite

Use NOT IN Safely When NULLs Are Possible

Filter `NULL` values out of the right side before using `NOT IN`, or the predicate can exclude everything.

intermediate grouping MySQL MariaDB SQL Server PostgreSQL SQLite

Use WHERE Before GROUP BY And HAVING After

`WHERE` filters individual rows before grouping. `HAVING` filters grouped results after aggregates are computed.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Validate Column Values With CHECK

Use a `CHECK` constraint to reject rows whose values fall outside an allowed rule.