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.