Referência de Funções SQL
Referência pesquisável de funções SQL para PostgreSQL, MySQL, SQLite e SQL Server. Filtre por categoria e dialeto.
Returns the number of characters in a string.
Sintaxe
LENGTH(string)Retorna
INTEGERExemplo
SELECT LENGTH('hello') -- 5MSSQLLEN — Does not count trailing spaces
Converts all characters in a string to uppercase.
Sintaxe
UPPER(string)Retorna
TEXTExemplo
SELECT UPPER('hello') -- 'HELLO'Converts all characters in a string to lowercase.
Sintaxe
LOWER(string)Retorna
TEXTExemplo
SELECT LOWER('HELLO') -- 'hello'Extracts a substring starting at position start (1-indexed). Optional length limits characters returned.
Sintaxe
SUBSTRING(string FROM start [FOR length])Retorna
TEXTExemplo
SELECT SUBSTRING('hello world' FROM 7 FOR 5) -- 'world'SQLiteSUBSTR
MySQLMID — Alias for SUBSTRING
Concatenates two or more strings together.
Sintaxe
CONCAT(string1, string2, ...)Retorna
TEXTExemplo
SELECT CONCAT('hello', ' ', 'world') -- 'hello world'SQLite|| — Use || operator
Concatenates strings with a separator, skipping NULL values.
Sintaxe
CONCAT_WS(separator, string1, string2, ...)Retorna
TEXTExemplo
SELECT CONCAT_WS(', ', 'Alice', NULL, 'Bob') -- 'Alice, Bob'Replaces all occurrences of a substring with another string.
Sintaxe
REPLACE(string, from, to)Retorna
TEXTExemplo
SELECT REPLACE('hello world', 'world', 'SQL') -- 'hello SQL'Removes leading and/or trailing characters (default: spaces) from a string.
Sintaxe
TRIM([LEADING | TRAILING | BOTH] [chars] FROM string)Retorna
TEXTExemplo
SELECT TRIM(' hello ') -- 'hello'SQLLTRIM — Leading spaces only
SQLRTRIM — Trailing spaces only
Returns the position of the first occurrence of a substring (1-indexed, 0 if not found).
Sintaxe
INSTR(string, substring)Retorna
INTEGERExemplo
SELECT INSTR('hello world', 'world') -- 7PGPOSITION
MSSQLCHARINDEX
Returns the leftmost n characters of a string.
Sintaxe
LEFT(string, n)Retorna
TEXTExemplo
SELECT LEFT('hello world', 5) -- 'hello'SQLiteSUBSTR
Returns the rightmost n characters of a string.
Sintaxe
RIGHT(string, n)Retorna
TEXTExemplo
SELECT RIGHT('hello world', 5) -- 'world'Returns a string repeated count times.
Sintaxe
REPEAT(string, count)Retorna
TEXTExemplo
SELECT REPEAT('ab', 3) -- 'ababab'MSSQLREPLICATE
Returns the string with characters in reverse order.
Sintaxe
REVERSE(string)Retorna
TEXTExemplo
SELECT REVERSE('hello') -- 'olleh'Pads a string on the left to a total length using the fill character.
Sintaxe
LPAD(string, length, fill)Retorna
TEXTExemplo
SELECT LPAD('42', 5, '0') -- '00042'MSSQLRIGHT + REPLICATE
Pads a string on the right to a total length using the fill character.
Sintaxe
RPAD(string, length, fill)Retorna
TEXTExemplo
SELECT RPAD('hi', 5, '.') -- 'hi...'Splits a string by delimiter and returns the nth field (1-indexed).
Sintaxe
SPLIT_PART(string, delimiter, n)Retorna
TEXTExemplo
SELECT SPLIT_PART('a,b,c', ',', 2) -- 'b'MySQLSUBSTRING_INDEX
Replaces substrings matching a regular expression with a replacement string.
Sintaxe
REGEXP_REPLACE(string, pattern, replacement)Retorna
TEXTExemplo
SELECT REGEXP_REPLACE('abc123', '[0-9]+', 'N') -- 'abcN'MSSQLNot built-in — Requires CLR or workaround
Returns the current date and time (including timezone in PostgreSQL).
Sintaxe
NOW()Retorna
TIMESTAMPExemplo
SELECT NOW() -- 2024-06-15 14:30:00
MSSQLGETDATE — No timezone
Returns the current date without a time component.
Sintaxe
CURRENT_DATERetorna
DATEExemplo
SELECT CURRENT_DATE -- 2024-06-15
MySQLCURDATE
Adds a time interval to a date or timestamp.
Sintaxe
DATE_ADD(date, INTERVAL n unit)Retorna
DATE / TIMESTAMPExemplo
SELECT DATE_ADD('2024-01-01', INTERVAL 7 DAY) -- '2024-01-08'PG+
MSSQLDATEADD
SQLiteDATE
Returns the number of days between two dates.
Sintaxe
DATEDIFF(date1, date2)Retorna
INTEGERExemplo
SELECT DATEDIFF('2024-01-31', '2024-01-01') -- 30PGSubtraction — Returns INTERVAL or days as INTEGER
MSSQLDATEDIFF
SQLiteJULIANDAY
Extracts a specific date/time part (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, WEEK, DOW).
Sintaxe
EXTRACT(part FROM date)Retorna
NUMERICExemplo
SELECT EXTRACT(YEAR FROM NOW()) -- 2024
MSSQLDATEPART
Truncates a timestamp to the specified precision (year, month, day, hour, minute, etc.).
Sintaxe
DATE_TRUNC('unit', timestamp)Retorna
TIMESTAMPExemplo
SELECT DATE_TRUNC('month', NOW()) -- 2024-06-01 00:00:00MySQLDATE_FORMAT — Workaround for month truncation
MSSQLDATETRUNC — SQL Server 2022+
Formats a date, timestamp, or number as a string using a format pattern.
Sintaxe
TO_CHAR(value, 'format')Retorna
TEXTExemplo
SELECT TO_CHAR(NOW(), 'YYYY-MM-DD') -- '2024-06-15'
MySQLDATE_FORMAT
MSSQLFORMAT
SQLiteSTRFTIME
Returns the interval between two timestamps expressed in years, months, and days.
Sintaxe
AGE(timestamp1, timestamp2)Retorna
INTERVALExemplo
SELECT AGE('2024-06-15', '2000-03-01') -- '24 years 3 months 14 days'Returns the absolute (non-negative) value of a number.
Sintaxe
ABS(number)Retorna
same as inputExemplo
SELECT ABS(-42) -- 42
Rounds a number to the specified number of decimal places (default 0).
Sintaxe
ROUND(number [, decimals])Retorna
NUMERICExemplo
SELECT ROUND(3.14159, 2) -- 3.14
Rounds a number up to the nearest integer.
Sintaxe
CEIL(number)Retorna
INTEGERExemplo
SELECT CEIL(4.2) -- 5
MSSQLCEILING
Rounds a number down to the nearest integer.
Sintaxe
FLOOR(number)Retorna
INTEGERExemplo
SELECT FLOOR(4.9) -- 4
Returns the remainder after division.
Sintaxe
MOD(dividend, divisor)Retorna
same as inputExemplo
SELECT MOD(10, 3) -- 1
SQLite%
MSSQL%
Returns base raised to the power of exponent.
Sintaxe
POWER(base, exponent)Retorna
NUMERICExemplo
SELECT POWER(2, 10) -- 1024
SQLiteNot built-in — Use ROUND(EXP(exponent*LN(base)), 10) workaround
Returns the square root of a non-negative number.
Sintaxe
SQRT(number)Retorna
NUMERICExemplo
SELECT SQRT(16) -- 4
Returns the largest value from a list of expressions.
Sintaxe
GREATEST(value1, value2, ...)Retorna
same as inputsExemplo
SELECT GREATEST(3, 1, 4, 1, 5) -- 5
MSSQLNot built-in — Use CASE WHEN or VALUES workaround
Returns the smallest value from a list of expressions.
Sintaxe
LEAST(value1, value2, ...)Retorna
same as inputsExemplo
SELECT LEAST(3, 1, 4, 1, 5) -- 1
Returns a random floating-point value between 0.0 and 1.0.
Sintaxe
RANDOM()Retorna
FLOATExemplo
SELECT RANDOM() -- 0.7381924...
MySQLRAND
MSSQLRAND
Returns -1 for negative numbers, 0 for zero, and 1 for positive numbers.
Sintaxe
SIGN(number)Retorna
INTEGERExemplo
SELECT SIGN(-42) -- -1
Counts rows. COUNT(*) counts all rows; COUNT(col) skips NULLs; DISTINCT counts unique non-null values.
Sintaxe
COUNT(*) | COUNT(column) | COUNT(DISTINCT column)Retorna
BIGINTExemplo
SELECT COUNT(*) FROM users -- 150
Returns the sum of non-null numeric values.
Sintaxe
SUM(expression)Retorna
NUMERICExemplo
SELECT SUM(amount) FROM orders -- 42000.00
Returns the arithmetic mean of non-null values.
Sintaxe
AVG(expression)Retorna
NUMERICExemplo
SELECT AVG(score) FROM results -- 87.5
Returns the minimum non-null value in the group.
Sintaxe
MIN(expression)Retorna
same as inputExemplo
SELECT MIN(created_at) FROM orders -- 2023-01-01
Returns the maximum non-null value in the group.
Sintaxe
MAX(expression)Retorna
same as inputExemplo
SELECT MAX(score) FROM results -- 100
Concatenates non-null string values from a group with a delimiter.
Sintaxe
STRING_AGG(expression, delimiter)Retorna
TEXTExemplo
SELECT STRING_AGG(name, ', ') FROM users -- 'Alice, Bob, Eve'
MySQLGROUP_CONCAT
Collects values from a group into an array (PostgreSQL) or JSON array.
Sintaxe
ARRAY_AGG(expression [ORDER BY ...])Retorna
ARRAYExemplo
SELECT ARRAY_AGG(id ORDER BY id) FROM users -- {1,2,3}MySQLJSON_ARRAYAGG
Returns TRUE if all non-null input values are true.
Sintaxe
BOOL_AND(expression)Retorna
BOOLEANExemplo
SELECT BOOL_AND(active) FROM users -- false
MySQLBIT_AND workaround — Use MIN(active = 1) as workaround
Assigns a unique sequential integer to each row within a partition, starting at 1.
Sintaxe
ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)Retorna
BIGINTExemplo
SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn FROM employees
Assigns a rank to each row; ties share the same rank and leave gaps in sequence.
Sintaxe
RANK() OVER ([PARTITION BY ...] ORDER BY ...)Retorna
BIGINTExemplo
SELECT RANK() OVER (ORDER BY score DESC) AS rnk FROM results
Like RANK but without gaps: tied rows share the same rank and the next rank is consecutive.
Sintaxe
DENSE_RANK() OVER ([PARTITION BY ...] ORDER BY ...)Retorna
BIGINTExemplo
SELECT DENSE_RANK() OVER (ORDER BY score DESC) FROM results
Returns the value from a row that is offset rows before the current row.
Sintaxe
LAG(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)Retorna
same as expressionExemplo
SELECT LAG(revenue) OVER (ORDER BY month) AS prev_revenue FROM sales
Returns the value from a row that is offset rows after the current row.
Sintaxe
LEAD(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)Retorna
same as expressionExemplo
SELECT LEAD(revenue) OVER (ORDER BY month) AS next_revenue FROM sales
Divides rows into n roughly equal groups (tiles) and returns the tile number for each row.
Sintaxe
NTILE(n) OVER ([PARTITION BY ...] ORDER BY ...)Retorna
INTEGERExemplo
SELECT NTILE(4) OVER (ORDER BY score) AS quartile FROM results
Returns the value of expression from the first row of the window frame.
Sintaxe
FIRST_VALUE(expression) OVER ([PARTITION BY ...] ORDER BY ...)Retorna
same as expressionExemplo
SELECT FIRST_VALUE(salary) OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees
Returns the value from the last row of the window frame. Requires explicit ROWS BETWEEN clause for meaningful results.
Sintaxe
LAST_VALUE(expression) OVER ([PARTITION BY ...] ORDER BY ... ROWS BETWEEN ... AND CURRENT ROW)Retorna
same as expressionExemplo
SELECT LAST_VALUE(salary) OVER (PARTITION BY dept ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM employees
Returns the relative rank of a row as a fraction between 0 and 1.
Sintaxe
PERCENT_RANK() OVER ([PARTITION BY ...] ORDER BY ...)Retorna
FLOATExemplo
SELECT PERCENT_RANK() OVER (ORDER BY score) FROM results
Returns the first non-null value from the list. Short-circuits once a non-null is found.
Sintaxe
COALESCE(value1, value2, ...)Retorna
same as inputsExemplo
SELECT COALESCE(NULL, NULL, 'fallback') -- 'fallback'
Returns NULL if value1 equals value2; otherwise returns value1. Useful to avoid division-by-zero.
Sintaxe
NULLIF(value1, value2)Retorna
same as value1Exemplo
SELECT total / NULLIF(divisor, 0) FROM sales
Evaluates conditions in order and returns the result for the first true condition. Equivalent to if-else.
Sintaxe
CASE WHEN condition THEN result [...] [ELSE default] ENDRetorna
same as result expressionsExemplo
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END FROM results
Short form of CASE WHEN: returns true_value if condition is true, otherwise false_value.
Sintaxe
IIF(condition, true_value, false_value)Retorna
same as true/false expressionsExemplo
SELECT IIF(active = 1, 'Active', 'Inactive') FROM users
MySQLIF
Converts a value to the specified data type. Standard SQL syntax supported by all major databases.
Sintaxe
CAST(expression AS type)Retorna
specified typeExemplo
SELECT CAST('42' AS INTEGER) -- 42PG:: — PostgreSQL shorthand
Converts a value to the specified type. Dialect varies: MySQL/SQL Server have CONVERT; PostgreSQL prefers CAST.
Sintaxe
CONVERT(type, expression)Retorna
specified typeExemplo
SELECT CONVERT(INT, '42') -- 42
Parses a string into a DATE using the specified format pattern.
Sintaxe
TO_DATE(string, 'format')Retorna
DATEExemplo
SELECT TO_DATE('15-Jun-2024', 'DD-Mon-YYYY') -- 2024-06-15MySQLSTR_TO_DATE
MSSQLPARSE
Converts a formatted string to a numeric value.
Sintaxe
TO_NUMBER(string, 'format')Retorna
NUMERICExemplo
SELECT TO_NUMBER('1,234.56', '9,999.99') -- 1234.56MySQLCAST + REPLACE — CAST(REPLACE('1,234.56', ',', '') AS DECIMAL)
MSSQLPARSE
Extracts a value from a JSON document at the specified path.
Sintaxe
JSON_EXTRACT(json, path)Retorna
JSON / scalarExemplo
SELECT JSON_EXTRACT('{"name":"Alice"}', '$.name') -- "Alice"PG-> — Use ->> for text
MSSQLJSON_VALUE — Returns scalar only
PostgreSQL operator: extracts a JSON sub-object or array element. Use ->> to get a text value.
Sintaxe
json_col -> 'key'Retorna
JSONExemplo
SELECT data -> 'address' -> 'city' FROM users
PG->> — Returns text, not JSON
Creates a JSON object from key-value pairs.
Sintaxe
JSON_OBJECT(key, value [, key, value ...])Retorna
JSONExemplo
SELECT JSON_OBJECT('name', 'Alice', 'age', 30) -- {"name":"Alice","age":30}PGjsonb_build_object
Creates a JSON array from the provided values.
Sintaxe
JSON_ARRAY(value1, value2, ...)Retorna
JSONExemplo
SELECT JSON_ARRAY(1, 'two', true) -- [1,"two",true]
PGjson_build_array
Aggregates values as a JSON array. Useful with GROUP BY to collect related rows.
Sintaxe
JSON_AGG(expression)Retorna
JSONExemplo
SELECT dept, JSON_AGG(name) FROM employees GROUP BY dept
MySQLJSON_ARRAYAGG
Expands a JSON object into a set of (key, value) rows. Used in FROM clause.
Sintaxe
JSON_EACH(json)Retorna
TABLE(key TEXT, value JSON)Exemplo
SELECT key, value FROM JSON_EACH('{"a":1,"b":2}')PGjson_each
MSSQLOPENJSON
PostgreSQL: creates a JSONB object from key-value pairs. Prefer over json_build_object when working with JSONB columns.
Sintaxe
JSONB_BUILD_OBJECT(key, value [, ...])Retorna
JSONBExemplo
SELECT JSONB_BUILD_OBJECT('id', id, 'name', name) FROM users68 functions