🗄️ SQL examples

SQL examples

Copy-ready SQL examples for common query patterns, joins, aggregation, window functions, data quality checks and reporting workflows. Each page includes syntax, five practical examples, mistakes to avoid, FAQs and useful resources.

76 SQL pages380 practical examplesCopy-ready queries

💡 Ideas for You

Learning resources for SQL queries, databases and reporting workflows.

4 useful links

Some links in this section may be affiliate links. Choose only what is useful for your own work.

Browse SQL examples

Use the filters to find basic queries, joins, aggregation, logic, CTEs, window functions and practical reporting workflows.

Basics

SELECT Examples

Select columns and build simple result sets.

Basics

WHERE Examples

Filter rows with conditions.

Basics

ORDER BY Examples

Sort query results by one or more columns.

Basics

LIMIT and TOP Examples

Return only a small number of rows for previews or reports.

Basics

DISTINCT Examples

Return unique values and remove duplicates from a result set.

Basics

BETWEEN Examples

Filter values inside a range such as dates, amounts or scores.

Basics

IN Examples

Filter rows where a value matches one of several options.

Basics

LIKE Examples

Search text using wildcard patterns.

Basics

IS NULL Examples

Find missing, blank or unassigned values.

Basics

Aliases Examples

Rename columns or tables in a query result.

Aggregation

COUNT Examples

Count rows, customers, orders or records.

Aggregation

COUNT DISTINCT Examples

Count unique customers, products or IDs.

Aggregation

SUM Examples

Add amounts such as sales, units or costs.

Aggregation

AVG Examples

Calculate average amounts, scores or durations.

Aggregation

MIN and MAX Examples

Find earliest, latest, smallest or largest values.

Aggregation

GROUP BY Examples

Summarize data by category, month, region or customer.

Aggregation

HAVING Examples

Filter grouped summary results.

Aggregation

GROUP BY Date Examples

Summarize records by day, month or year.

Aggregation

ROLLUP Examples

Add subtotal and grand total rows to grouped results.

Aggregation

Percent of Total Examples

Calculate a row or group as a share of the total.

Joins

JOIN Examples

Combine rows from related tables with matching keys.

Joins

INNER JOIN Examples

Return rows that match in both tables.

Joins

LEFT JOIN Examples

Keep all rows from the left table and matched rows from the right table.

Joins

RIGHT JOIN Examples

Keep all rows from the right table and matched rows from the left table.

Joins

FULL OUTER JOIN Examples

Return matched and unmatched rows from both tables.

Joins

CROSS JOIN Examples

Create every combination of rows from two tables.

Joins

SELF JOIN Examples

Join a table to itself to compare related rows.

Joins

Multiple Joins Examples

Join several tables in one report query.

Joins

Anti Join Examples

Find rows in one table that do not have a match in another table.

Joins

Semi Join Examples

Find rows that have at least one match in another table.

Joins

Duplicate Rows After Join Examples

Understand and fix unexpected duplicated rows after joining tables.

Logic

CASE WHEN Examples

Create conditional labels, buckets and flags.

Logic

COALESCE Examples

Return the first non-null value from a list.

Logic

NULLIF Examples

Return NULL when two values are equal.

Logic

CAST and CONVERT Examples

Change a value from one data type to another.

Logic

CONCAT Examples

Combine text values such as names, codes or labels.

Logic

UPPER LOWER TRIM Examples

Clean and standardize text values.

Logic

SUBSTRING Examples

Extract part of a text value.

Logic

Date Functions Examples

Extract, compare and transform dates.

Logic

Date Difference Examples

Calculate days or months between dates.

Logic

Conditional Aggregation Examples

Use CASE inside SUM or COUNT for business summaries.

Subqueries & CTEs

Subquery Examples

Use a query inside another query.

Subqueries & CTEs

EXISTS Examples

Check whether related rows exist.

Subqueries & CTEs

NOT EXISTS Examples

Find records with no related rows.

Subqueries & CTEs

CTE Examples

Use WITH clauses to organize complex queries.

Subqueries & CTEs

Recursive CTE Examples

Walk hierarchies such as employees, categories or folder trees.

Subqueries & CTEs

Derived Table Examples

Query from a subquery in the FROM clause.

Subqueries & CTEs

Temp Table Examples

Store intermediate results during multi-step analysis.

Subqueries & CTEs

UNION Examples

Stack compatible result sets.

Subqueries & CTEs

UNION ALL Examples

Stack result sets without removing duplicates.

Subqueries & CTEs

INTERSECT and EXCEPT Examples

Compare sets of rows between queries.

Window Functions

OVER Examples

Calculate values across rows without collapsing detail.

Window Functions

PARTITION BY Examples

Restart a window calculation for each group.

Window Functions

ROW_NUMBER Examples

Number rows inside each group.

Window Functions

RANK Examples

Rank rows while allowing ties to skip numbers.

Window Functions

DENSE_RANK Examples

Rank rows while keeping tied ranks compact.

Window Functions

LAG Examples

Return the previous row value.

Window Functions

LEAD Examples

Return the next row value.

Window Functions

Running Total Examples

Calculate cumulative totals over time.

Window Functions

Moving Average Examples

Calculate rolling averages for trends.

Window Functions

NTILE Examples

Split rows into buckets such as quartiles or deciles.

Workflows

Find Duplicates Examples

Find duplicate emails, IDs or records.

Workflows

Remove Duplicates Examples

Choose one row from duplicate groups before deleting or exporting.

Workflows

Latest Record Per Group Examples

Get the newest order, status or event per customer.

Workflows

First Record Per Group Examples

Get the earliest order, signup or event per entity.

Workflows

Missing Records Examples

Find expected records that are not present.

Workflows

Gaps in Dates Examples

Find missing days, months or sequence numbers.

Workflows

Top N Per Group Examples

Return top products, customers or orders within each group.

Workflows

Sales by Month Examples

Summarize sales into monthly reporting rows.

Workflows

Month over Month Examples

Compare current period to the previous period.

Workflows

Customer Retention Examples

Track customers who return after their first purchase.

Workflows

Cohort Analysis Examples

Group users by first purchase or signup month.

Workflows

Funnel Analysis Examples

Count users through ordered steps in a funnel.

Workflows

Inventory Reorder Examples

Flag products below reorder thresholds.

Workflows

Aging Buckets Examples

Put invoices, tickets or tasks into age ranges.

Workflows

Safe UPDATE Examples

Preview and update rows with careful filters.