SQL function reference
601 functions in 8 categories. Each page has the syntax, examples, the edge cases where engines disagree, and a support table for SQL Server, PostgreSQL, MySQL, SQLite and Oracle that names the stand-in when an engine spells the function differently.
Aggregates
52 functionsOne answer per group: counts, sums, percentiles and the ordering-aware cousins.
-
integer (int on SQL Server, bigint on PostgreSQL, NUMBER on Oracle)COUNT -
numeric; int input gives int on SQL Server, bigint on PostgreSQL, DECIMAL on MySQLSUM -
numericAVG -
same type as the expressionMIN -
same type as the expressionMAX -
integerCOUNT(DISTINCT) -
字符串STRING_AGG / GROUP_CONCAT -
array of the expression's typeARRAY_AGG -
numeric / doubleSTDDEV / STDEV -
numericPERCENTILE_CONT -
字符串LISTAGG -
字符串GROUP_CONCAT -
booleanBOOL_AND -
booleanBOOL_OR -
booleanEVERY -
depends on the aggregateFILTER -
jsonJSON_ARRAYAGG -
jsonJSON_OBJECTAGG -
jsonJSON_GROUP_ARRAY -
numericSTDDEV_SAMP -
numericSTDDEV_POP -
numericVARIANCE -
numericVAR_SAMP -
numericVAR_POP -
numeric (-1 to 1)CORR -
numericCOVAR_SAMP -
numericCOVAR_POP -
numericREGR_SLOPE -
numericREGR_INTERCEPT -
bigintREGR_COUNT -
numeric (0 to 1)REGR_R2 -
same as inputMODE -
numericMEDIAN -
bigintAPPROX_COUNT_DISTINCT -
实际的TOTAL -
integerGROUPING -
integerGROUPING_ID -
one result set per grouping levelGROUPING SETS -
detail rows plus subtotalsROLLUP -
same as inputANY_VALUE -
integerBIT_AND -
integerBIT_OR -
integerBIT_XOR -
same as the aggregateOVER -
numeric or bigintNULL -
numeric or stringDISTINCT -
depends on the aggregateWITHIN GROUP -
integer or numericRANK -
extra subtotal rows with NULL in the rolled-up columnsCUBE -
bigintCOUNT_BIG -
floatAPPROX_PERCENTILE_CONT -
numeric, matching the input typePRODUCT
Strings
172 functionsConcatenate, cut, pad, search and regex-replace text.
-
字符串CONCAT -
字符串SUBSTRING / SUBSTR -
integerLENGTH / LEN -
字符串UPPER -
字符串LOWER -
字符串TRIM / LTRIM / RTRIM -
字符串REPLACE -
字符串LEFT -
字符串RIGHT -
integerINSTR / CHARINDEX / POSITION -
字符串SPLIT_PART -
字符串LPAD / RPAD -
字符串REVERSE -
字符串REGEXP_REPLACE -
字符串CONCAT_WS -
字符串|| -
字符串+ / += -
字符串FORMAT -
字符串FORMAT (MySQL) -
字符串printf / format -
settingCONCAT_NULL_YIELDS_NULL -
字符串FORMATMESSAGE -
字符串ARRAY_TO_STRING -
字符串Implicit casts in concatenation -
字符串INITCAP -
字符串NLS_INITCAP -
字符串NLS_UPPER / NLS_LOWER -
字符串UCASE -
字符串LCASE -
字符串Title-casing a string -
字符串The Turkish I problem -
字符串Case-insensitive comparison -
字符串BTRIM -
字符串SPACE -
字符串REPLICATE / REPEAT -
字符串TRANSLATE -
字符串Zero-padding numbers -
字符串Padding in SQL Server -
字符串Removing newlines -
字符串Removing non-breaking spaces -
字符串Trimming leading zeros -
字符串ZEROFILL -
integerOCTET_LENGTH -
integerBIT_LENGTH -
integerDATALENGTH -
integerLENGTHB -
charsetutf8mb4 -
字符串VARCHAR(n): chars or bytes? -
integerEmoji and string length -
字符串CHR / CHAR -
integerASCII -
integerUNICODE / unicode() -
字符串HEX -
二进制UNHEX -
string / rawRAWTOHEX / HEXTORAW -
字符串TO_BASE64 / encode -
二进制FROM_BASE64 / decode -
字符串Stripping non-ASCII characters -
字符串QUOTE -
字符串QUOTENAME -
字符串STUFF -
字符串SOUNDEX -
integerDIFFERENCE -
字符串unaccent -
字符串Backslash escapes in strings -
字符串Empty string vs NULL -
字符串Checking for empty strings -
字符串CHAR padding and comparisons -
string / binaryHashing strings -
字符串String length limits -
字符串Newlines in string literals -
orderingSorting strings -
字符串Masking strings -
字符串Truncating with an ellipsis -
字符串Collapsing duplicate spaces -
integerCounting substring occurrences -
字符串UNISTR -
字符串Unicode normalization -
identifierQuoting identifiers -
字符串Unicode literals (N'...') -
字符串DUMP -
字符串CHARSET / COLLATION -
integerSTRCMP -
字符串ASCIISTR -
integerPOSITION -
integerSTRPOS -
integerCHARINDEX -
integerLOCATE -
integerPATINDEX -
integerFIND_IN_SET -
integerFIELD -
string or NULLELT -
integerREGEXP_INSTR -
string or NULLREGEXP_SUBSTR -
integerREGEXP_COUNT -
text[] or NULLREGEXP_MATCH -
booleanREGEXP_LIKE -
字符串SUBSTR -
字符串MID -
字符串SUBSTRB -
字符串OVERLAY -
字符串INSERT -
table of value rowsSTRING_SPLIT -
字符串SUBSTRING_INDEX -
string or NULLPARSENAME -
text[]STRING_TO_ARRAY -
text[]REGEXP_SPLIT_TO_ARRAY -
set of text rowsREGEXP_SPLIT_TO_TABLE -
字符串FORMAT -
字符串STRFTIME -
字符串QUOTE_LITERAL -
字符串QUOTE_IDENT -
字符串QUOTE_NULLABLE -
字符串RPAD -
字符串PRINTF -
integerUNICODE -
字符串REPEAT -
integerLEVENSHTEIN -
integerEDITDIST3 -
实际的SIMILARITY -
实际的WORD_SIMILARITY -
字符串METAPHONE -
字符串MD5 -
字符串SHA1 -
字符串SHA2 -
varbinaryHASHBYTES -
unsigned integerCRC32 -
字符串CHR -
integerORD -
字符串NORMALIZE -
字符串TO_BASE64 -
binary stringFROM_BASE64 -
integerCHAR_LENGTH -
字符串LTRIM -
字符串RTRIM -
字符串TO_ASCII -
JSON valueJSON_EXTRACT -
JSON or text-> and ->> -
文本JSON_VALUE -
JSON textJSON_QUERY -
文本JSON_UNQUOTE -
integer or booleanJSON_VALID / ISJSON -
文本JSON_TYPE -
JSON textJSON_ARRAY -
JSON textJSON_OBJECT -
JSON textJSON_SET -
JSON textJSON_INSERT -
JSON textJSON_REPLACE -
JSON textJSON_REMOVE -
integerJSON_CONTAINS -
boolean@> (jsonb) -
boolean? (jsonb) -
JSON array or jsonbJSON_AGG -
rowsetOPENJSON -
rowsetJSON_TABLE -
rowsetjson_each -
JSON array or setof textJSON_KEYS -
integerJSON_LENGTH -
integerJSON_DEPTH -
JSON textJSON_MERGEPATCH -
JSON or jsonbto_json / JSON() -
setof json or jsonbjson_array_elements -
XMLXMLQUERY -
rowsetXMLTABLE -
scalar.value() / XMLCAST -
XMLFOR XML -
booleanJSON_EXISTS -
文本JSON_PRETTY -
文本JSON_QUOTE -
JSON (a path string or an array of paths), or NULLJSON_SEARCH -
二进制AES_ENCRYPT -
intCHECKSUM / BINARY_CHECKSUM
Dates & times
121 functionsBuild, break apart, truncate and measure timestamps.
-
timestamp (text on SQLite)NOW / CURRENT_TIMESTAMP -
date (text on SQLite)CURRENT_DATE -
date / timestampDATEADD / DATE_ADD -
integerDATEDIFF -
timestamp / dateDATE_TRUNC -
integerEXTRACT / DATEPART -
integer 0-6 or 1-7, engine-dependentDay of week -
字符串TO_CHAR / DATE_FORMAT -
dateTO_DATE / STR_TO_DATE -
字符串DATE_FORMAT -
dateLAST_DAY / EOMONTH -
numeric (fractional on Oracle)MONTHS_BETWEEN -
datetime / datetime2 / datetimeoffsetGETDATE / SYSDATETIME -
DATE (with time) / TIMESTAMP WITH TIME ZONESYSDATE -
TIMESTAMP WITH TIME ZONESYSTIMESTAMP -
time (time with time zone on PostgreSQL)CURRENT_TIME -
timestampLOCALTIMESTAMP -
timestamptzclock_timestamp -
timestamptztransaction_timestamp -
datetimeoffsetSYSDATETIMEOFFSET -
datetime / timestampUTC_TIMESTAMP / GETUTCDATE -
dateDATEFROMPARTS -
datetime / timestampDATETIMEFROMPARTS -
时间TIMEFROMPARTS -
date / timestampMAKE_DATE -
dateMAKEDATE -
时间MAKETIME -
datetime / timestampFROM_UNIXTIME -
TEXT (ISO-8601)date() / time() / datetime() -
date / timestampDATE / TIMESTAMP literals -
date / datetimeSTR_TO_DATE -
date / datetime2 (requested type)PARSE / TRY_PARSE -
intervalMAKE_INTERVAL -
varchar / dateCONVERT date styles -
datetimeoffsetTODATETIMEOFFSET -
TIMESTAMP WITH TIME ZONEFROM_TZ -
integerYEAR -
integerMONTH -
integerDAY -
integerHOUR -
integerMINUTE -
integer (fractional on PostgreSQL)SECOND -
integerQUARTER -
integerWEEK / ISO_WEEK -
integerDAYOFYEAR -
double precisionDATE_PART -
integerMILLISECOND / MICROSECOND -
integerYEARWEEK -
dateDATE() -
时间TIME() -
integer (fractional on PostgreSQL)UNIX_TIMESTAMP -
numeric (double precision before PostgreSQL 14)EXTRACT(epoch) -
REAL (days)JULIANDAY -
integerTO_DAYS / FROM_DAYS -
integerTO_SECONDS -
integer / timeTIME_TO_SEC / SEC_TO_TIME -
文本MONTHNAME -
文本DAYNAME -
文本DATENAME -
INTERVAL DAY TO SECOND / YEAR TO MONTHTO_DSINTERVAL -
intervalINTERVAL literal -
text (zone name or offset)SESSIONTIMEZONE -
文本date modifiers -
文本NLS_DATE_FORMAT -
date / datetimeADDDATE -
date / datetimeDATE_SUB / SUBDATE -
dateADD_MONTHS -
intervalAGE -
datetimeTIMESTAMPADD -
integerTIMESTAMPDIFF -
bigintDATEDIFF_BIG -
时间TIMEDIFF -
datetime / timeADDTIME -
datetime / timeSUBTIME -
dateNEXT_DAY -
date / timestampDATE + N -
interval (PG, Oracle) / number (Oracle DATE)TIMESTAMP - TIMESTAMP -
integer (days)DATE - DATE -
text (formatted timestamp)datetime() modifiers -
integer (YYYYMM / months)PERIOD_ADD / PERIOD_DIFF -
integerDays in month -
time / integerSEC_TO_TIME / TIME_TO_SEC -
dateDATE literal -
datetime2 / datetime / datetimeoffsetSYSDATETIME / GETDATE -
same type as input (datetime2 family)DATETRUNC -
dateTRUNC (date) -
dateROUND (date) -
timestampDATE_BIN -
dateEOMONTH -
varcharDATE_FORMAT bucketing -
文本STRFTIME bucketing -
datetimeDATEADD/DATEDIFF trick -
smalldatetimeSMALLDATETIME -
varchar / datetimeCONVERT styles -
nvarcharFORMAT -
文本Date to text -
session variablelc_time_names -
文本ISO 8601 output -
文本TIME_FORMAT -
文本Format codes -
文本12/24-hour -
session settingSET DATEFIRST -
session GUCDateStyle -
integerWeek numbers -
timestamptz / timestamp (PG); datetimeoffset / datetime (SS)AT TIME ZONE -
datetimeCONVERT_TZ -
dateNEW_TIME -
timestamp with time zoneTIMESTAMP WITH TIME ZONE -
timestamp with local time zoneTIMESTAMP WITH LOCAL TIME ZONE -
datetimeoffset(n)DATETIMEOFFSET -
datetimeoffsetTODATETIMEOFFSET / SWITCHOFFSET -
datetime2 / datetime / timestampSYSUTCDATETIME -
session settingSession time zone -
timestampUTC_TIMESTAMP -
keyword (yields a span)INTERVAL n unit -
interval / timestampInterval arithmetic -
intervaljustify_interval -
interval year to monthTO_YMINTERVAL -
interval day to secondNUMTODSINTERVAL -
interval year to monthNUMTOYMINTERVAL -
booleanOVERLAPS
Math
82 functionsRounding, remainders, powers and randomness.
-
numericROUND -
integer / numericFLOOR -
integer / numericCEIL / CEILING -
same type as the inputABS -
integer / numericMOD / % -
float or numericPOWER / POW -
float (numeric for numeric input on PostgreSQL, NUMBER on Oracle)SQRT -
float in [0, 1); a 64-bit integer on SQLiteRANDOM / RAND -
-1, 0 or 1, in the input's type on SQL Server and PostgreSQLSIGN -
numericTRUNCATE / TRUNC (numbers) -
same type as the inputCEILING -
numericROUND(x, d) -
numericROUND(x, -n) -
numericROUND half-up -
numericROUND half-even -
integerSCALE -
integerMIN_SCALE -
numericTRIM_SCALE -
float / doubleEXP -
float / doubleLN -
float / doubleLOG -
float / doubleLOG10 -
float / doubleLOG2 -
double / floatCBRT -
floatSQUARE -
double / numeric^ -
float / numeric / NULLPOWER fractional -
integer / numericFACTORIAL -
float / doublePI -
float / doubleSIN -
float / doubleCOS -
float / doubleTAN -
float / doubleCOT -
float / double (radians)ASIN -
float / double (radians)ACOS -
float / double (radians)ATAN -
float / double (radians)ATAN2 -
float (radians)ATN2 -
double; SQL Server returns the input's typeDEGREES -
double; SQL Server returns the input's typeRADIANS -
float / doubleSINH -
float / doubleCOSH -
float / doubleTANH -
float / doubleASINH -
float / doubleACOSH -
float / doubleATANH -
depends on operand types+ - * / -
integer (decimal where supported)% -
integerDIV -
integer / bigintGCD -
integer / bigintLCM -
void / noneSETSEED -
不适用precedence -
same type as the input- -
integerBITAND -
numericREMAINDER -
error or NULL1 / 0 -
error or NULLMOD(x, 0) -
float / doubleNaN / Infinity -
booleanISNAN -
same type as the inputNANVL -
float / doubleInfinity -
integer / float / errorINT overflow -
numericDECIMAL overflow -
numeric or doubleNUMERIC vs FLOAT -
8-byte IEEE 754 floatDOUBLE PRECISION -
booleanfloat equality -
numeric or REALnumeric literals -
exact decimalNUMERIC(p, s) -
numeric / floatdivision scale -
integerCAST to INT -
integerWIDTH_BUCKET -
float / NULL / errortrig domain -
float / NULL / errorLOG(0) -
float in [0, 1)RAND per row -
integerrandom range -
binary / blobrandom bytes -
numeric or errorcoercion -
NULL / numericNULL math -
numericMOD sign -
integer& | ^ ~ << >> -
floatVECTOR_DISTANCE
条件
43 functionsNULL handling and branching inside a single query.
-
the common type of all argumentsCOALESCE -
type of the first argumentNULLIF -
the common type of all THEN and ELSE resultsCASE -
type of the chosen branchIIF / IF -
type of the first argumentIFNULL / NVL / ISNULL -
type of the first resultDECODE -
same as first argumentNVL -
type of r1 or r2NVL2 -
same as first argumentISNULL -
type of then_val or else_valIF -
highest-precedence argument type (Oracle: first argument's type)GREATEST -
highest-precedence argument type (Oracle: first argument's type)LEAST -
booleanXOR -
booleanANY -
booleanALL -
booleanIN -
booleanIN -
booleanNOT IN -
booleanEXISTS -
booleanNOT EXISTS -
TRUE / FALSE / UNKNOWNNULL -
booleanIS NULL -
booleanBETWEEN -
booleanBETWEEN SYMMETRIC -
booleanLIKE -
booleanESCAPE -
booleanIS DISTINCT FROM -
numericSUM(CASE) -
booleanNULL-safe -
joined rowsJOIN -
boolean / bit / tinyint / integerBOOLEAN -
no typeNULL -
ordering modifierNULLS FIRST -
booleanNULL -
booleanIS TRUE -
constraint behaviourUNIQUE -
行COALESCE -
the highest-precedence type among the valuesCHOOSE -
booleanILIKE -
booleanSIMILAR TO -
boolean<> and != -
booleanSTARTS_WITH -
integer (1, 0 or NULL)GLOB
窗口
79 functionsRank, navigate and compare across rows without collapsing them.
-
bigintROW_NUMBER -
bigintRANK -
bigintDENSE_RANK -
type of the expressionLAG -
type of the expressionLEAD -
integerNTILE -
type of the expressionFIRST_VALUE -
type of the expressionLAST_VALUE -
double precision / floatPERCENT_RANK -
double precision / floatCUME_DIST -
type of the ORDER BY expressionPERCENTILE_DISC -
numeric (CONT) / type of x (DISC)PERCENTILE_CONT vs PERCENTILE_DISC -
bigint / double precisionRANK WITHIN GROUP -
double precision / floatPERCENT_RANK vs CUME_DIST -
integerNTILE for Percentiles -
type of the expressionNTH_VALUE -
type of the expressionIGNORE NULLS -
type of the expressionDifference From Previous Row -
numeric ratioPeriod Over Period Comparison -
integer streak idConsecutive Streaks -
type of the aggregateAggregates with OVER -
bigintCOUNT OVER -
numericSUM OVER -
numericAVG OVER -
type of the expressionMIN and MAX with OVER -
double precision / floatSTDDEV with OVER -
double precision / floatVARIANCE with OVER -
N rows per groupTop N Per Group -
one row per keyDeduplicate Rows -
island boundariesGaps and Islands -
numericRunning Total -
numericMoving Average -
numericMoving Sum -
numericPercent of Total -
numeric fractionCumulative Share -
filtered rowsWindow Functions in CTEs -
rows or groupsWindow vs GROUP BY -
updated rowsWindow Functions in UPDATE -
page of rowsWindow Pagination -
ordered resultWindow in ORDER BY -
per-row aggregate or rankOVER Clause -
per-partition valuePARTITION BY -
per-partition valuePARTITION BY Expressions -
per-row valueORDER BY in OVER -
ordered partitionNULLS FIRST / NULLS LAST -
n/a (clause semantics)OVER ORDER BY vs Outer ORDER BY -
stable per-row valuesDeterministic Window Order -
whole-set aggregateEmpty OVER () -
per-group rows with window valuesOVER with GROUP BY -
implicit frameDefault Window Frame -
per-frame aggregateROWS Frame -
per-partition valueUNBOUNDED Frame -
per-frame aggregaten PRECEDING / n FOLLOWING -
frame boundaryCURRENT ROW Boundary -
frame specificationFrame Shorthand -
per-frame aggregateRANGE Frame -
per-frame countRANGE Numeric Offsets -
frame typeROWS vs RANGE -
per-frame aggregateGROUPS Frame -
frame typeGROUPS Frame Support -
per-frame aggregateRANGE Interval Frames -
per-frame aggregateEXCLUDE Clause -
named window definitionWINDOW Clause -
conditional aggregateFILTER with OVER -
filtered rowsQUALIFY -
filtered rowsQUALIFY Alternatives -
bigint (sequence type)NEXT VALUE FOR OVER -
文本String Aggregates with OVER -
bigintDISTINCT in Window Aggregates -
n/a (version gate)MySQL 8.0 Window Functions -
不适用Window Function Versions -
frame clauseSQL Server Frame Limits -
type of the expressionSQL Server 2022 Window Additions -
per-frame aggregatePostgreSQL Window Features -
per-partition valueOracle Analytic Functions -
type of the aggregateKEEP DENSE_RANK -
NUMBER (a fraction; 0 to 1 for non-negative values)RATIO_TO_REPORT -
n/a (performance)Window Function Performance -
NUMBERROWNUM
Conversion
39 functionsCast values between types, safely or not.
-
the target typeCAST -
the target typeCONVERT -
the target type, or NULLTRY_CAST / TRY_CONVERT -
numericTO_NUMBER -
timestamptz on PostgreSQL, TIMESTAMP on OracleTO_TIMESTAMP -
字符串CONV -
字符串CONVERT ... USING -
the target type:: -
the target type, or NULLTRY_CONVERT -
文本TO_CHAR (numbers) -
the target typeCAST truncation -
二进制BINARY / varbinary casts -
integerSIGNED / UNSIGNED -
decimalCAST AS DECIMAL -
boolean or integerBoolean casts -
date, timestamp or timeDate literals -
文本CAST AS CHAR / VARCHAR -
depends on the winning typeImplicit conversion -
depends on affinityType affinity -
text or byteaENCODE / DECODE -
text or byteaCONVERT (charset) -
same type as the expressionCOLLATE -
text or binaryBase64 -
integerARRAY_LENGTH -
integerCARDINALITY -
setof element typeUNNEST -
arrayARRAY_APPEND -
booleanArray contains -
element typeArray indexing -
setofGENERATE_SERIES -
text (UUID string)UUID -
uuidGEN_RANDOM_UUID -
uniqueidentifierNEWID -
raw(16)SYS_GUID -
blobRANDOMBLOB -
blobZEROBLOB -
int (1 or 0)ISNUMERIC -
int (1 or 0)ISDATE -
varcharSTR
System & session
13 functionsCurrent user, database and session, last inserted ID, rows affected and other metadata.
-
the generated key (numeric)LAST_INSERT_ID / SCOPE_IDENTITY -
integer@@ROWCOUNT / ROW_COUNT -
文本DB_NAME / current_database -
文本CURRENT_USER -
文本CURRENT_SCHEMA / SCHEMA_NAME -
文本VERSION() -
integer@@SPID / CONNECTION_ID -
int, or NULLOBJECT_ID -
文本TYPEOF / pg_typeof -
ROWID (Oracle), integer (SQLite), tid (PostgreSQL)ROWID -
bigint (NUMBER on Oracle)NEXTVAL / NEXT VALUE FOR -
0 (MySQL), void (PostgreSQL)SLEEP -
text (the message), integer or text (the code)ERROR_MESSAGE
No function matches that search.
Try another engine’s spelling (LISTAGG, NVL or CHARINDEX), a category name, or set Available on back to any engine.
SQL functions FAQ
Which databases does this reference cover?
SQL Server, PostgreSQL, MySQL, SQLite and Oracle. Every function page marks which of the five support the function, which use a different name for it, and which have no equivalent.
What do the engine support marks mean?
A filled green dot means the engine has the function under that name. A half-filled amber dot means the capability exists under another name or with different syntax, such as GROUP_CONCAT for STRING_AGG. A hollow grey ring means the engine has no built-in, and the note says what to use instead. Version requirements, such as SQL Server 2022 or SQLite 3.44, are in the notes.
Why do databases disagree about simple functions?
The SQL standard only fixes some functions. The rest grew separately, so the same idea arrived as STRING_AGG, GROUP_CONCAT and LISTAGG, and NULL or collation rules differ per vendor. The pages call out the differences and give the portable form where one exists.
Can I run the examples as they are?
Expressions on literals, such as SELECT ROUND(2.5), run as shown; the expected result is in a trailing comment. Queries against tables like orders and users need your own table and column names. Examples labelled Any engine use syntax all five accept; Oracle before 23ai needs FROM dual on a SELECT without a table. Engine-labelled examples show the dialect that differs.
The right function, before you finish typing
SQLly's editor knows the built-in functions of each engine. Completion offers the ones your connection's dialect has, hover cards explain them, and signature help shows each argument as you type. On macOS, Windows and Linux.