Quick reference

SQL reference

Queries, joins, aggregates, window functions and schema rules you reach for daily.

SQL describes the result you want, not the loop to get there. Write the relationship first, then filter, group and order. Check cardinality before trusting a result. Examples run in the SQL lab unless a note says PostgreSQL only.

Read the full explanationSQL & Databases

Work through the guided lesson, then test yourself with a challenge.

Open course
209 entries

Aggregate functions

array_agg()

array_agg(expression)

Collects group values into an array. PostgreSQL only.

Open entry

bool_and() / bool_or()

bool_and(condition)

True when every or any row matches. PostgreSQL; SQLite uses min()/max() on 0 and 1.

Open entry

count distinct

count(distinct expression)

Counts unique non-null values.

Open entry

every()

every(condition)

PostgreSQL alias for bool_and().

Open entry

group_concat()

group_concat(expression, separator)

Joins values from a group into one string. SQLite name for string_agg.

Open entry

json_group_array()

json_group_array(expression)

Collects group values into a JSON array. SQLite and PostgreSQL.

Open entry

json_group_object()

json_group_object(key, value)

Collects key-value pairs into a JSON object. SQLite only.

Open entry

mode()

mode() within group (order by x)

The most frequent value in a group. PostgreSQL.

Open entry

percentile_cont()

percentile_cont(0.5) within group (order by x)

Continuous percentile, such as the median. PostgreSQL.

Open entry

stddev()

stddev(expression)

Sample standard deviation. PostgreSQL; most engines use a different name.

Open entry

string_agg()

string_agg(expression, delimiter)

Concatenates group values with a delimiter. PostgreSQL and SQL Server.

Open entry

sum(case …)

sum(case when … then 1 else 0 end)

Counts rows that match a condition using only standard aggregate syntax.

Open entry

total()

total(expression)

Like sum() but returns 0.0 instead of NULL when there are no rows. SQLite only.

Open entry

variance()

variance(expression)

Sample variance. PostgreSQL; most engines use a different name.

Open entry

Aggregation and grouping

Array and set-returning functions

Date and time functions

Functions and expressions

cast()

cast(value as type)

Converts between types. Use it explicitly rather than relying on implicit casts.

Open entry

concat()

concat(a, b)

Joins strings, treating NULL as an empty string. The || operator returns NULL if any side is NULL.

Open entry

cte

with name as (select …)

A named temporary result set that makes complex queries readable.

Open entry

current_date / now()

current_date / now()

The current date or timestamp. now() includes time and time zone in PostgreSQL.

Open entry

date_trunc()

date_trunc('month', ts)

Truncates a timestamp to a unit, ideal for grouping by period.

Open entry

exists

where exists (select 1 …)

Tests whether a subquery returns any row. Often clearer and faster than IN with nulls.

Open entry

extract()

extract(year from date)

Reads a field from a date or timestamp. SQLite uses strftime().

Open entry

Greatest / least

greatest(a, b)

Returns the largest or smallest of the arguments. PostgreSQL and SQLite differ in null handling.

Open entry

lag() / lead()

lag(column) over (…)

Reads the previous or next row in a window, useful for deltas.

Open entry

length()

length(text)

Character count of a string.

Open entry

lower() / upper()

lower(text)

Changes case for comparisons and display.

Open entry

partition by

over (partition by course order by …)

Restarts a window calculation for each group.

Open entry

position()

position('x' in text)

Finds a substring position, returning 0 when absent. SQLite uses instr().

Open entry

rank() / dense_rank()

rank() over (…)

Ranks rows, leaving gaps after ties; dense_rank leaves no gaps.

Open entry

recursive cte

with recursive …

Walks a hierarchy such as a management chain or category tree.

Open entry

replace()

replace(text, from, to)

Replaces every occurrence of a substring.

Open entry

round()

round(value, places)

Rounds a numeric value.

Open entry

row_number()

row_number() over (…)

Assigns a sequential number to rows within a window.

Open entry

subquery

where id in (select …)

A query nested inside another. Prefer JOINs when the relationship is simple.

Open entry

substring()

substr(text, start, length)

Extracts part of a string. SQLite uses substr(); PostgreSQL also accepts substring(text from start for length).

Open entry

sum() over()

sum(x) over (order by …)

A running total without collapsing rows, unlike GROUP BY.

Open entry

trim()

trim(text)

Removes spaces from both ends. Use ltrim or rtrim for one side.

Open entry

Joins and set operations

JSON functions

Numeric functions

abs()

abs(number)

The absolute value.

Open entry

asin() / acos() / atan()

asin(number)

Inverse trigonometric functions returning radians.

Open entry

atan2()

atan2(y, x)

The angle of a vector, handling all quadrants.

Open entry

ceil() / floor()

ceil(number) / floor(number)

Rounds up or down to an integer.

Open entry

degrees() / radians()

degrees(radians)

Converts between radians and degrees.

Open entry

exp()

exp(number)

e raised to a power.

Open entry

ln()

ln(number)

The natural logarithm. PostgreSQL and MySQL; SQLite builds without math functions may omit it.

Open entry

log()

log(base, number)

A logarithm. PostgreSQL takes an explicit base; SQLite log(number) is base 10.

Open entry

log10()

log10(number)

The base-10 logarithm.

Open entry

mod()

mod(a, b)

The remainder of a division. SQLite uses the % operator.

Open entry

numeric rounding

round(number, decimals)

Rounds to a number of decimal places.

Open entry

pi()

pi()

The constant pi.

Open entry

power()

power(base, exponent)

Raises a number to a power.

Open entry

random()

random()

A pseudo-random integer. Use it for sampling, not security.

Open entry

randomblob()

randomblob(bytes)

Random bytes, useful for generating ids in SQLite.

Open entry

sign()

sign(number)

Returns -1, 0 or 1 depending on the sign.

Open entry

sin() / cos() / tan()

sin(radians)

Trigonometric functions that take radians.

Open entry

sqrt()

sqrt(number)

The square root.

Open entry

to_number()

to_number(text, format)

Parses a formatted number. PostgreSQL.

Open entry

trunc()

trunc(number, decimals)

Truncates decimals without rounding. SQLite builds without math functions can use CAST.

Open entry

Reading data

and / or / not

where a and (b or c)

Combines predicates. Use parentheses because AND binds tighter than OR.

Open entry

between

where value between a and b

An inclusive range test.

Open entry

case expression

case when … then … else … end

Returns different values based on conditions. It is an expression, so it can appear in SELECT, WHERE and ORDER BY.

Open entry

coalesce

coalesce(value, fallback)

Returns the first non-null argument.

Open entry

column alias

select minutes * 60 as seconds

Renames an output column. Quote aliases that contain spaces.

Open entry

comparison operators

= <> < > <= >=

Compare values. Use IS NULL and IS NOT NULL for null checks, never = NULL.

Open entry

distinct

select distinct column

Removes duplicate result rows. Use it deliberately because it costs sorting or hashing.

Open entry

distinct on

select distinct on (key) …

PostgreSQL keeps the first row per key according to the ORDER BY. SQLite does not support it.

Open entry

fetch first

fetch first 10 rows only

Standard SQL pagination. PostgreSQL also supports LIMIT and OFFSET; SQLite only supports LIMIT.

Open entry

in list

where status in (…)

Matches any value in a list. Faster to read than chained ORs.

Open entry

is null

where column is null

Tests for the absence of a value. NULL never equals anything, including itself.

Open entry

like / ilike

where title like '%sql%'

Pattern matching with % and _. LIKE is case-sensitive in PostgreSQL; ILIKE is not.

Open entry

limit

limit 10 offset 20

Returns a page of rows. Offset pagination gets slower and can skip rows under concurrent writes.

Open entry

nullif

nullif(a, b)

Returns null when the two values are equal. Useful for avoiding division by zero.

Open entry

order by

order by column desc

Sorts the result. Add a unique tie-breaker for stable pagination.

Open entry

select

select columns from table;

Chooses the columns returned by a query. Prefer explicit columns over select * in application code.

Open entry

select *

select * from table;

Returns every column. Convenient in exploration, risky in production because schema changes leak into results.

Open entry

where

where condition

Filters rows before grouping. It cannot reference aggregate results; use HAVING for that.

Open entry

Schema and constraints

String functions

ascii()

ascii(text)

The code of the first character. SQLite uses unicode().

Open entry

char_length()

char_length(text)

The number of characters. SQLite uses length().

Open entry

chr()

chr(code)

The character for a code point. SQLite uses char().

Open entry

concat_ws()

concat_ws(separator, …values)

Joins values, skipping NULLs. SQLite 3.44+ and PostgreSQL.

Open entry

format()

format(template, …values)

Builds a string with placeholders. SQLite 3.38+ and PostgreSQL.

Open entry

initcap()

initcap(text)

Capitalises each word. PostgreSQL only.

Open entry

instr() with start

instr(text, substring)

Finds a substring and returns a one-based position, or 0.

Open entry

left() / right()

left(text, n) / right(text, n)

Takes characters from one end. PostgreSQL and SQL Server; SQLite uses substr().

Open entry

like with escape

like '%\%' escape '\'

Escapes wildcard characters so they match literally.

Open entry

lpad() / rpad()

lpad(text, length, fill)

Pads a string to a fixed width. PostgreSQL; use printf() in SQLite.

Open entry

md5()

md5(text)

The MD5 hash of a string. PostgreSQL and MySQL; never use it for passwords.

Open entry

octet_length()

octet_length(text)

The number of bytes in a string’s encoding. PostgreSQL.

Open entry

printf()

printf(format, …values)

Formats numbers and strings with printf-style placeholders. Very useful for padding in SQLite.

Open entry

quote_literal()

quote_literal(text)

Escapes a value for safe inclusion in SQL. PostgreSQL.

Open entry

repeat()

repeat(text, times)

Repeats a string. PostgreSQL and MySQL; not built into SQLite.

Open entry

reverse()

reverse(text)

Reverses a string. PostgreSQL and MySQL; not built into SQLite.

Open entry

split_part()

split_part(text, delimiter, n)

Returns one part of a delimited string. PostgreSQL.

Open entry

strpos()

strpos(text, substring)

The one-based position of a substring, or 0. SQLite uses instr().

Open entry

substr() with negative start

substr(text, -n)

A negative start counts from the end of the string.

Open entry

to_hex()

to_hex(integer)

Formats an integer as hexadecimal. PostgreSQL.

Open entry

trim() variants

trim(text, chars) / ltrim() / rtrim()

Removes characters from both ends or one side.

Open entry

System and metadata

Transactions and integrity

Window functions

Writing data

Keep going

Turn the reference into recall.

Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.