sqlcmd.net validated sql reference

PostgreSQL commands

Every guide here is marked as supported for PostgreSQL, with examples you can follow directly.

192 commands support PostgreSQL Engine-specific browsing without search noise
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.

beginner defining MySQL MariaDB SQL Server PostgreSQL SQLite

Add A Column To An Existing Table

Extend a table's structure by adding a new column with `ALTER TABLE`.

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.

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.

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.

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.

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.

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

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.

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.

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.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate Averages With AVG

Compute the arithmetic mean of numeric values across matching rows.

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.

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.

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

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.

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.

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.

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

beginner math MySQL MariaDB SQL Server PostgreSQL SQLite

Compute Absolute Value and Remainder

Use `ABS` to strip the sign from a number and `MOD` (or the `%` operator) to get the integer remainder after division.

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.

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.

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.

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(...), '')`.

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.

beginner date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Convert Timestamps To Dates

Strip the time portion from a timestamp so only the calendar date remains.

beginner conversion MySQL MariaDB SQL Server PostgreSQL SQLite

Convert Values With CAST

Change a value from one SQL type to another using an explicit cast.

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.

beginner data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Count Missing Values Per Column

Audit a table for `NULL` values by counting how many rows have no value in each column of interest.

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

beginner defining MySQL MariaDB SQL Server PostgreSQL SQLite

Create A Table

Define a new table with column names and data types using `CREATE 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.

beginner defining MySQL MariaDB SQL Server PostgreSQL SQLite

Delete A Table

Permanently remove a table and all its data with `DROP TABLE`.

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.

beginner deleting MySQL MariaDB SQL Server PostgreSQL SQLite

Delete Rows

Remove matching rows with `DELETE`, then query the remaining table contents.

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.

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.

beginner math MySQL MariaDB SQL Server PostgreSQL SQLite

Determine The Sign Of A Number With SIGN

Use `SIGN` to reduce any number to -1, 0, or 1 based on whether it is negative, zero, or positive.

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.

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.

beginner date-time MySQL MariaDB SQL Server PostgreSQL SQLite

Extract Date Parts From A Date Or Timestamp

Return components such as year, month, and day from a date or timestamp value.

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.

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.

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.

beginner inserting MySQL MariaDB SQL Server PostgreSQL SQLite

Fill Omitted Columns With DEFAULT

Define a column default so inserts can omit routine values and still store a complete row.

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.

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.

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.

beginner filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Rows By Pattern With LIKE

Match string columns against a wildcard pattern using `LIKE`.

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.

beginner filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Text Case-Insensitively

Compare normalized text values with LOWER or UPPER so matching does not depend on stored capitalization.

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.

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.

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

beginner data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows That Violate A Data Rule

Use a `WHERE` predicate to list rows that already break a business or constraint rule.

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.

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

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.

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

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.

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.

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.

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.

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

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.

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.

beginner inserting MySQL MariaDB SQL Server PostgreSQL SQLite

Insert a Row

Add new data to a table, then verify the inserted row with a deterministic query.

beginner inserting MySQL MariaDB SQL Server PostgreSQL SQLite

Insert Multiple Rows

Add several rows in one statement using a multi-value `INSERT`.

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.

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.

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.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Join Strings With CONCAT

Combine multiple text values into one string in the query result.

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.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Join Text Values With Hyphens

Combine multiple text values into one hyphen-separated key-like string.

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.

beginner metadata MySQL MariaDB SQL Server PostgreSQL SQLite

List Columns In A Table

Inspect a table definition to see its column names and data types.

beginner metadata MySQL MariaDB SQL Server PostgreSQL SQLite

List Tables

Inspect the current database or schema to see which tables exist.

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

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.

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.

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.

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.

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.

beginner ddl MySQL MariaDB SQL Server PostgreSQL SQLite

Rename a Column With ALTER TABLE

Change a column's name in place without dropping or recreating the table or its data.

intermediate defining MySQL MariaDB SQL Server PostgreSQL SQLite

Rename a Table

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

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

Repeat or Reverse a String

Use `REPEAT` to duplicate a string a given number of times, and `REVERSE` to flip its character order.

beginner conditional-logic MySQL MariaDB SQL Server PostgreSQL SQLite

Replace NULL Values With COALESCE

Return the first non-null value from a list of expressions.

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.

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.

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.

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

Round Numbers With ROUND, CEIL, and FLOOR

Control the precision or snapping of numeric results using `ROUND` for half-up rounding, `CEIL` to round up to the next integer, and `FLOOR` to round down.

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.

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.

beginner ordering MySQL MariaDB SQL Server PostgreSQL SQLite

Sort By Multiple Columns

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

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.

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.

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.

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.

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.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Total Values With SUM

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

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.

beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Trim Whitespace From Text

Remove leading and trailing whitespace from string values with `TRIM`.

beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Understand COUNT(column) Versus COUNT(*)

`COUNT(column)` skips `NULL` values, while `COUNT(*)` counts every row that made it into the result set.

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.

beginner updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update Rows

Modify existing rows with `UPDATE`, then verify the changed data with a stable query.

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.

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.

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.

beginner pagination MySQL MariaDB SQL Server PostgreSQL SQLite

Use LIMIT Or TOP With ORDER BY For Stable Results

A row limit without an explicit sort can return different rows over time or across engines.

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.

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.