sqlcmd.net validated sql reference

#select

Commands grouped around the same concept, pattern, or recurring problem.

72 commands with this tag Browse related patterns quickly
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 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.

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.

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 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.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate Averages With AVG

Compute the arithmetic mean of numeric values across matching rows.

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`.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Change Text Case With UPPER And LOWER

Convert string values to all uppercase or all lowercase using `UPPER` and `LOWER`.

beginner null-handling MySQL MariaDB SQL Server PostgreSQL SQLite

Check For NULL Values With IS NULL

Use `IS NULL` and `IS NOT NULL` to filter rows based on whether a column has a value.

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.

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.

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.

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.

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 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.

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.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Count Rows With COUNT(*)

Aggregate a result set into a single row that reports how many rows matched.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Count Unique Values With COUNT DISTINCT

Count only the distinct values in a column, ignoring duplicates.

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 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 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.

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.

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 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.

beginner filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows Matching A List With IN

Use `IN` to match a column against a list of values in a single `WHERE` clause.

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.

beginner filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows With WHERE

Return only rows that match a condition, with explicit ordering for stable output.

beginner filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows Within A Range With BETWEEN

Use `BETWEEN` to match rows where a column falls within an inclusive lower and upper bound.

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 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.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Find The Smallest And Largest Values With MIN And MAX

Use `MIN` and `MAX` to find the lowest and highest values in a column.

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`.

beginner date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Current Date And Time

Return the current date and time using `CURRENT_TIMESTAMP` or engine-specific functions.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Length Of A String

Return the number of characters in a string using `LENGTH` or `LEN`.

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.

beginner inserting MySQL MariaDB SQL Server PostgreSQL SQLite

Insert Rows From Another Table

Populate a table by selecting rows from another table using `INSERT INTO ... SELECT`.

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.

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.

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.

beginner pagination MySQL MariaDB SQL Server PostgreSQL SQLite

Limit Returned Rows

Return only part of a result set using the row-limiting syntax each engine supports.

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.

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.

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.

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 aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Pivot Rows Into Columns

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

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.

beginner selecting MySQL MariaDB SQL Server PostgreSQL

Rename Output Columns With AS

Use `AS` to give result columns clearer labels without changing the underlying table schema.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Replace Text Within A String With REPLACE

Substitute all occurrences of a substring with a new value using `REPLACE`.

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.

beginner deduplication MySQL MariaDB SQL Server PostgreSQL SQLite

Return Distinct Values

Use `DISTINCT` to remove duplicate rows from a result set.

beginner conditional MySQL MariaDB SQL Server PostgreSQL SQLite

Return the Largest or Smallest of Several Values

Use `GREATEST` and `LEAST` to compare multiple values in a single expression without a `CASE WHEN` chain.

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.

beginner retrieval MySQL MariaDB SQL Server PostgreSQL SQLite

Select All Rows

Return every row from a table with an explicit sort order for deterministic output.

beginner selecting MySQL MariaDB SQL Server PostgreSQL SQLite

Select Computed Columns With Expressions

Include arithmetic, string, or conditional expressions directly in a `SELECT` list and give them an alias with `AS`.

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.

beginner retrieval MySQL MariaDB SQL Server PostgreSQL SQLite

Select The First N Rows From A Result

Retrieve a fixed number of rows from the top of a sorted result set using `LIMIT`, `TOP`, or `FETCH FIRST`.

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.

beginner ordering MySQL MariaDB SQL Server PostgreSQL SQLite

Sort By Multiple Columns

Use more than one sort key so ties are broken deterministically.

beginner ordering MySQL MariaDB SQL Server PostgreSQL SQLite

Sort Rows With ORDER BY

Control the order of result rows explicitly instead of relying on storage order.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Total Values With SUM

Add numeric values across matching rows and return one aggregate total.

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.