SQL query examples
Ready-to-copy SQL for the queries developers look up most — each with the code across PostgreSQL, MySQL, SQL Server, and SQLite, plus a plain-English explanation of how it works.
Need a query for your own schema? Describe it in plain English with the AI SQL Generator →
Ranking & top-N
Get the second largest value in a column (e.g. the second highest salary).
Find the Nth highest valueGet the Nth largest value in a column using DENSE_RANK.
Number and rank rowsAdd a sequential number or rank to rows with window functions.
Get the top N rows per groupReturn the highest N rows within each group (greatest-n-per-group).
Grouping & aggregation
Count how many rows fall into each category with GROUP BY.
Group by monthSummarize rows per calendar month from a date or timestamp column.
Calculate a running totalCompute a cumulative sum that grows row by row.
Pivot rows into columnsTurn row values into columns using conditional aggregation.