SQL Functions Reference

Searchable reference of SQL functions across PostgreSQL, MySQL, SQLite, and SQL Server. Filter by category and dialect.

LENGTH
PGMySQLSQLiteSQL

Returns the number of characters in a string.

Syntax

LENGTH(string)

Returns

INTEGER

Example

SELECT LENGTH('hello') -- 5

MSSQLLEN — Does not count trailing spaces

UPPER
PGMySQLSQLiteMSSQLSQL

Converts all characters in a string to uppercase.

Syntax

UPPER(string)

Returns

TEXT

Example

SELECT UPPER('hello') -- 'HELLO'
LOWER
PGMySQLSQLiteMSSQLSQL

Converts all characters in a string to lowercase.

Syntax

LOWER(string)

Returns

TEXT

Example

SELECT LOWER('HELLO') -- 'hello'
SUBSTRING
PGMySQLMSSQLSQL

Extracts a substring starting at position start (1-indexed). Optional length limits characters returned.

Syntax

SUBSTRING(string FROM start [FOR length])

Returns

TEXT

Example

SELECT SUBSTRING('hello world' FROM 7 FOR 5) -- 'world'

SQLiteSUBSTR

MySQLMID — Alias for SUBSTRING

CONCAT
PGMySQLMSSQLSQL

Concatenates two or more strings together.

Syntax

CONCAT(string1, string2, ...)

Returns

TEXT

Example

SELECT CONCAT('hello', ' ', 'world') -- 'hello world'

SQLite|| — Use || operator

CONCAT_WS
PGMySQLMSSQL

Concatenates strings with a separator, skipping NULL values.

Syntax

CONCAT_WS(separator, string1, string2, ...)

Returns

TEXT

Example

SELECT CONCAT_WS(', ', 'Alice', NULL, 'Bob') -- 'Alice, Bob'
REPLACE
PGMySQLSQLiteMSSQLSQL

Replaces all occurrences of a substring with another string.

Syntax

REPLACE(string, from, to)

Returns

TEXT

Example

SELECT REPLACE('hello world', 'world', 'SQL') -- 'hello SQL'
TRIM
PGMySQLSQLiteMSSQLSQL

Removes leading and/or trailing characters (default: spaces) from a string.

Syntax

TRIM([LEADING | TRAILING | BOTH] [chars] FROM string)

Returns

TEXT

Example

SELECT TRIM('  hello  ') -- 'hello'

SQLLTRIM — Leading spaces only

SQLRTRIM — Trailing spaces only

INSTR
MySQLSQLite

Returns the position of the first occurrence of a substring (1-indexed, 0 if not found).

Syntax

INSTR(string, substring)

Returns

INTEGER

Example

SELECT INSTR('hello world', 'world') -- 7

PGPOSITION

MSSQLCHARINDEX

LEFT
PGMySQLMSSQL

Returns the leftmost n characters of a string.

Syntax

LEFT(string, n)

Returns

TEXT

Example

SELECT LEFT('hello world', 5) -- 'hello'

SQLiteSUBSTR

RIGHT
PGMySQLMSSQL

Returns the rightmost n characters of a string.

Syntax

RIGHT(string, n)

Returns

TEXT

Example

SELECT RIGHT('hello world', 5) -- 'world'
REPEAT
PGMySQL

Returns a string repeated count times.

Syntax

REPEAT(string, count)

Returns

TEXT

Example

SELECT REPEAT('ab', 3) -- 'ababab'

MSSQLREPLICATE

REVERSE
PGMySQLMSSQL

Returns the string with characters in reverse order.

Syntax

REVERSE(string)

Returns

TEXT

Example

SELECT REVERSE('hello') -- 'olleh'
LPAD
PGMySQL

Pads a string on the left to a total length using the fill character.

Syntax

LPAD(string, length, fill)

Returns

TEXT

Example

SELECT LPAD('42', 5, '0') -- '00042'

MSSQLRIGHT + REPLICATE

RPAD
PGMySQL

Pads a string on the right to a total length using the fill character.

Syntax

RPAD(string, length, fill)

Returns

TEXT

Example

SELECT RPAD('hi', 5, '.') -- 'hi...'
SPLIT_PART
PG

Splits a string by delimiter and returns the nth field (1-indexed).

Syntax

SPLIT_PART(string, delimiter, n)

Returns

TEXT

Example

SELECT SPLIT_PART('a,b,c', ',', 2) -- 'b'

MySQLSUBSTRING_INDEX

REGEXP_REPLACE
PGMySQL

Replaces substrings matching a regular expression with a replacement string.

Syntax

REGEXP_REPLACE(string, pattern, replacement)

Returns

TEXT

Example

SELECT REGEXP_REPLACE('abc123', '[0-9]+', 'N') -- 'abcN'

MSSQLNot built-in — Requires CLR or workaround

NOW
PGMySQLSQLite

Returns the current date and time (including timezone in PostgreSQL).

Syntax

NOW()

Returns

TIMESTAMP

Example

SELECT NOW() -- 2024-06-15 14:30:00

MSSQLGETDATE — No timezone

CURRENT_DATE
PGMySQLSQLiteMSSQLSQL

Returns the current date without a time component.

Syntax

CURRENT_DATE

Returns

DATE

Example

SELECT CURRENT_DATE -- 2024-06-15

MySQLCURDATE

DATE_ADD
MySQL

Adds a time interval to a date or timestamp.

Syntax

DATE_ADD(date, INTERVAL n unit)

Returns

DATE / TIMESTAMP

Example

SELECT DATE_ADD('2024-01-01', INTERVAL 7 DAY) -- '2024-01-08'

PG+

MSSQLDATEADD

SQLiteDATE

DATEDIFF
MySQL

Returns the number of days between two dates.

Syntax

DATEDIFF(date1, date2)

Returns

INTEGER

Example

SELECT DATEDIFF('2024-01-31', '2024-01-01') -- 30

PGSubtraction — Returns INTERVAL or days as INTEGER

MSSQLDATEDIFF

SQLiteJULIANDAY

EXTRACT
PGMySQLSQLiteSQL

Extracts a specific date/time part (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, WEEK, DOW).

Syntax

EXTRACT(part FROM date)

Returns

NUMERIC

Example

SELECT EXTRACT(YEAR FROM NOW()) -- 2024

MSSQLDATEPART

DATE_TRUNC
PG

Truncates a timestamp to the specified precision (year, month, day, hour, minute, etc.).

Syntax

DATE_TRUNC('unit', timestamp)

Returns

TIMESTAMP

Example

SELECT DATE_TRUNC('month', NOW()) -- 2024-06-01 00:00:00

MySQLDATE_FORMAT — Workaround for month truncation

MSSQLDATETRUNC — SQL Server 2022+

TO_CHAR
PG

Formats a date, timestamp, or number as a string using a format pattern.

Syntax

TO_CHAR(value, 'format')

Returns

TEXT

Example

SELECT TO_CHAR(NOW(), 'YYYY-MM-DD') -- '2024-06-15'

MySQLDATE_FORMAT

MSSQLFORMAT

SQLiteSTRFTIME

AGE
PG

Returns the interval between two timestamps expressed in years, months, and days.

Syntax

AGE(timestamp1, timestamp2)

Returns

INTERVAL

Example

SELECT AGE('2024-06-15', '2000-03-01') -- '24 years 3 months 14 days'
ABS
PGMySQLSQLiteMSSQLSQL

Returns the absolute (non-negative) value of a number.

Syntax

ABS(number)

Returns

same as input

Example

SELECT ABS(-42) -- 42
ROUND
PGMySQLSQLiteMSSQLSQL

Rounds a number to the specified number of decimal places (default 0).

Syntax

ROUND(number [, decimals])

Returns

NUMERIC

Example

SELECT ROUND(3.14159, 2) -- 3.14
CEIL
PGMySQLSQLiteSQL

Rounds a number up to the nearest integer.

Syntax

CEIL(number)

Returns

INTEGER

Example

SELECT CEIL(4.2) -- 5

MSSQLCEILING

FLOOR
PGMySQLSQLiteMSSQLSQL

Rounds a number down to the nearest integer.

Syntax

FLOOR(number)

Returns

INTEGER

Example

SELECT FLOOR(4.9) -- 4
MOD
PGMySQLSQL

Returns the remainder after division.

Syntax

MOD(dividend, divisor)

Returns

same as input

Example

SELECT MOD(10, 3) -- 1

SQLite%

MSSQL%

POWER
PGMySQLMSSQLSQL

Returns base raised to the power of exponent.

Syntax

POWER(base, exponent)

Returns

NUMERIC

Example

SELECT POWER(2, 10) -- 1024

SQLiteNot built-in — Use ROUND(EXP(exponent*LN(base)), 10) workaround

SQRT
PGMySQLMSSQLSQL

Returns the square root of a non-negative number.

Syntax

SQRT(number)

Returns

NUMERIC

Example

SELECT SQRT(16) -- 4
GREATEST
PGMySQLSQLite

Returns the largest value from a list of expressions.

Syntax

GREATEST(value1, value2, ...)

Returns

same as inputs

Example

SELECT GREATEST(3, 1, 4, 1, 5) -- 5

MSSQLNot built-in — Use CASE WHEN or VALUES workaround

LEAST
PGMySQLSQLite

Returns the smallest value from a list of expressions.

Syntax

LEAST(value1, value2, ...)

Returns

same as inputs

Example

SELECT LEAST(3, 1, 4, 1, 5) -- 1
RANDOM
PGSQLite

Returns a random floating-point value between 0.0 and 1.0.

Syntax

RANDOM()

Returns

FLOAT

Example

SELECT RANDOM() -- 0.7381924...

MySQLRAND

MSSQLRAND

SIGN
PGMySQLMSSQLSQL

Returns -1 for negative numbers, 0 for zero, and 1 for positive numbers.

Syntax

SIGN(number)

Returns

INTEGER

Example

SELECT SIGN(-42) -- -1
COUNT
PGMySQLSQLiteMSSQLSQL

Counts rows. COUNT(*) counts all rows; COUNT(col) skips NULLs; DISTINCT counts unique non-null values.

Syntax

COUNT(*) | COUNT(column) | COUNT(DISTINCT column)

Returns

BIGINT

Example

SELECT COUNT(*) FROM users -- 150
SUM
PGMySQLSQLiteMSSQLSQL

Returns the sum of non-null numeric values.

Syntax

SUM(expression)

Returns

NUMERIC

Example

SELECT SUM(amount) FROM orders -- 42000.00
AVG
PGMySQLSQLiteMSSQLSQL

Returns the arithmetic mean of non-null values.

Syntax

AVG(expression)

Returns

NUMERIC

Example

SELECT AVG(score) FROM results -- 87.5
MIN
PGMySQLSQLiteMSSQLSQL

Returns the minimum non-null value in the group.

Syntax

MIN(expression)

Returns

same as input

Example

SELECT MIN(created_at) FROM orders -- 2023-01-01
MAX
PGMySQLSQLiteMSSQLSQL

Returns the maximum non-null value in the group.

Syntax

MAX(expression)

Returns

same as input

Example

SELECT MAX(score) FROM results -- 100
STRING_AGG
PGMSSQL

Concatenates non-null string values from a group with a delimiter.

Syntax

STRING_AGG(expression, delimiter)

Returns

TEXT

Example

SELECT STRING_AGG(name, ', ') FROM users -- 'Alice, Bob, Eve'

MySQLGROUP_CONCAT

ARRAY_AGG
PG

Collects values from a group into an array (PostgreSQL) or JSON array.

Syntax

ARRAY_AGG(expression [ORDER BY ...])

Returns

ARRAY

Example

SELECT ARRAY_AGG(id ORDER BY id) FROM users -- {1,2,3}

MySQLJSON_ARRAYAGG

BOOL_AND
PG

Returns TRUE if all non-null input values are true.

Syntax

BOOL_AND(expression)

Returns

BOOLEAN

Example

SELECT BOOL_AND(active) FROM users -- false

MySQLBIT_AND workaround — Use MIN(active = 1) as workaround

ROW_NUMBER
PGMySQLSQLiteMSSQLSQL

Assigns a unique sequential integer to each row within a partition, starting at 1.

Syntax

ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)

Returns

BIGINT

Example

SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn FROM employees
RANK
PGMySQLSQLiteMSSQLSQL

Assigns a rank to each row; ties share the same rank and leave gaps in sequence.

Syntax

RANK() OVER ([PARTITION BY ...] ORDER BY ...)

Returns

BIGINT

Example

SELECT RANK() OVER (ORDER BY score DESC) AS rnk FROM results
DENSE_RANK
PGMySQLSQLiteMSSQLSQL

Like RANK but without gaps: tied rows share the same rank and the next rank is consecutive.

Syntax

DENSE_RANK() OVER ([PARTITION BY ...] ORDER BY ...)

Returns

BIGINT

Example

SELECT DENSE_RANK() OVER (ORDER BY score DESC) FROM results
LAG
PGMySQLSQLiteMSSQLSQL

Returns the value from a row that is offset rows before the current row.

Syntax

LAG(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)

Returns

same as expression

Example

SELECT LAG(revenue) OVER (ORDER BY month) AS prev_revenue FROM sales
LEAD
PGMySQLSQLiteMSSQLSQL

Returns the value from a row that is offset rows after the current row.

Syntax

LEAD(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)

Returns

same as expression

Example

SELECT LEAD(revenue) OVER (ORDER BY month) AS next_revenue FROM sales
NTILE
PGMySQLSQLiteMSSQLSQL

Divides rows into n roughly equal groups (tiles) and returns the tile number for each row.

Syntax

NTILE(n) OVER ([PARTITION BY ...] ORDER BY ...)

Returns

INTEGER

Example

SELECT NTILE(4) OVER (ORDER BY score) AS quartile FROM results
FIRST_VALUE
PGMySQLSQLiteMSSQLSQL

Returns the value of expression from the first row of the window frame.

Syntax

FIRST_VALUE(expression) OVER ([PARTITION BY ...] ORDER BY ...)

Returns

same as expression

Example

SELECT FIRST_VALUE(salary) OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees
LAST_VALUE
PGMySQLMSSQLSQL

Returns the value from the last row of the window frame. Requires explicit ROWS BETWEEN clause for meaningful results.

Syntax

LAST_VALUE(expression) OVER ([PARTITION BY ...] ORDER BY ... ROWS BETWEEN ... AND CURRENT ROW)

Returns

same as expression

Example

SELECT LAST_VALUE(salary) OVER (PARTITION BY dept ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM employees
PERCENT_RANK
PGMySQLSQLiteMSSQLSQL

Returns the relative rank of a row as a fraction between 0 and 1.

Syntax

PERCENT_RANK() OVER ([PARTITION BY ...] ORDER BY ...)

Returns

FLOAT

Example

SELECT PERCENT_RANK() OVER (ORDER BY score) FROM results
COALESCE
PGMySQLSQLiteMSSQLSQL

Returns the first non-null value from the list. Short-circuits once a non-null is found.

Syntax

COALESCE(value1, value2, ...)

Returns

same as inputs

Example

SELECT COALESCE(NULL, NULL, 'fallback') -- 'fallback'
NULLIF
PGMySQLSQLiteMSSQLSQL

Returns NULL if value1 equals value2; otherwise returns value1. Useful to avoid division-by-zero.

Syntax

NULLIF(value1, value2)

Returns

same as value1

Example

SELECT total / NULLIF(divisor, 0) FROM sales
CASE
PGMySQLSQLiteMSSQLSQL

Evaluates conditions in order and returns the result for the first true condition. Equivalent to if-else.

Syntax

CASE WHEN condition THEN result [...] [ELSE default] END

Returns

same as result expressions

Example

SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END FROM results
IIF
MSSQL

Short form of CASE WHEN: returns true_value if condition is true, otherwise false_value.

Syntax

IIF(condition, true_value, false_value)

Returns

same as true/false expressions

Example

SELECT IIF(active = 1, 'Active', 'Inactive') FROM users

MySQLIF

CAST
PGMySQLSQLiteMSSQLSQL

Converts a value to the specified data type. Standard SQL syntax supported by all major databases.

Syntax

CAST(expression AS type)

Returns

specified type

Example

SELECT CAST('42' AS INTEGER) -- 42

PG:: — PostgreSQL shorthand

CONVERT
MySQLMSSQL

Converts a value to the specified type. Dialect varies: MySQL/SQL Server have CONVERT; PostgreSQL prefers CAST.

Syntax

CONVERT(type, expression)

Returns

specified type

Example

SELECT CONVERT(INT, '42') -- 42
TO_DATE
PG

Parses a string into a DATE using the specified format pattern.

Syntax

TO_DATE(string, 'format')

Returns

DATE

Example

SELECT TO_DATE('15-Jun-2024', 'DD-Mon-YYYY') -- 2024-06-15

MySQLSTR_TO_DATE

MSSQLPARSE

TO_NUMBER
PG

Converts a formatted string to a numeric value.

Syntax

TO_NUMBER(string, 'format')

Returns

NUMERIC

Example

SELECT TO_NUMBER('1,234.56', '9,999.99') -- 1234.56

MySQLCAST + REPLACE — CAST(REPLACE('1,234.56', ',', '') AS DECIMAL)

MSSQLPARSE

JSON_EXTRACT
MySQLSQLite

Extracts a value from a JSON document at the specified path.

Syntax

JSON_EXTRACT(json, path)

Returns

JSON / scalar

Example

SELECT JSON_EXTRACT('{"name":"Alice"}', '$.name') -- "Alice"

PG-> — Use ->> for text

MSSQLJSON_VALUE — Returns scalar only

->
PG

PostgreSQL operator: extracts a JSON sub-object or array element. Use ->> to get a text value.

Syntax

json_col -> 'key'

Returns

JSON

Example

SELECT data -> 'address' -> 'city' FROM users

PG->> — Returns text, not JSON

JSON_OBJECT
MySQLSQLiteMSSQL

Creates a JSON object from key-value pairs.

Syntax

JSON_OBJECT(key, value [, key, value ...])

Returns

JSON

Example

SELECT JSON_OBJECT('name', 'Alice', 'age', 30) -- {"name":"Alice","age":30}

PGjsonb_build_object

JSON_ARRAY
MySQLSQLiteMSSQL

Creates a JSON array from the provided values.

Syntax

JSON_ARRAY(value1, value2, ...)

Returns

JSON

Example

SELECT JSON_ARRAY(1, 'two', true) -- [1,"two",true]

PGjson_build_array

JSON_AGG
PG

Aggregates values as a JSON array. Useful with GROUP BY to collect related rows.

Syntax

JSON_AGG(expression)

Returns

JSON

Example

SELECT dept, JSON_AGG(name) FROM employees GROUP BY dept

MySQLJSON_ARRAYAGG

JSON_EACH
PGSQLite

Expands a JSON object into a set of (key, value) rows. Used in FROM clause.

Syntax

JSON_EACH(json)

Returns

TABLE(key TEXT, value JSON)

Example

SELECT key, value FROM JSON_EACH('{"a":1,"b":2}')

PGjson_each

MSSQLOPENJSON

JSONB_BUILD_OBJECT
PG

PostgreSQL: creates a JSONB object from key-value pairs. Prefer over json_build_object when working with JSONB columns.

Syntax

JSONB_BUILD_OBJECT(key, value [, ...])

Returns

JSONB

Example

SELECT JSONB_BUILD_OBJECT('id', id, 'name', name) FROM users

68 functions