SQL Functions Cheatsheet A comprehensive cheatsheet covering all SQL functions, including Aggregate, String, Math, Date & Time, Comparison & Logical, Window Functions, Type Conversion, Security & Hashing, JSON, NULL Handling, and Common Patterns. Includes inline and table-level syntax, add/drop/modify examples, cross-engine compatibility.
Posted Apr 22, 2026 Updated Apr 23, 2026 SQL Functions Cheatsheet
1. π SQL Functions Cheatsheet Grouped by category Β· Common syntax examples Β· Cross-engine compatibility
1.1. Legend | Symbol | Meaning | |βββ|βββ| | β
| Supported (same or very similar syntax) | | β οΈ | Supported with different syntax | | β | Not supported / no direct equivalent |
Hereβs your SQL Functions Cheatsheet! It covers 11 categories :
Aggregate β COUNT, SUM, AVG, GROUP_CONCAT, STDDEVβ¦String β CONCAT, TRIM, SUBSTRING, REPLACE, LPADβ¦Math / Numeric β ROUND, FLOOR, CEIL, MOD, RAND, GREATESTβ¦Date & Time β NOW, DATEDIFF, DATE_FORMAT, TIMESTAMPDIFFβ¦Comparison & Logical β BETWEEN, IN, LIKE, COALESCE, CASE, IFβ¦Window Functions β ROW_NUMBER, RANK, LAG, LEAD, NTILEβ¦Type Conversion β CAST, HEX, ASCII, TO_BASE64β¦Security & Hashing β MD5, SHA2, AES_ENCRYPT, UUIDβ¦JSON β JSON_EXTRACT, JSON_SET, JSON_ARRAYAGGβ¦NULL Handling β engine-by-engine quick referenceCommon Patterns β running totals, top-N per group, age calc, pivot aggregationEach section includes a cross-engine compatibility table for MySQL, SQLite, PostgreSQL, SQL Server, Oracle, and MS Access with β
/ β οΈ / β indicators.
1.2. π’ Aggregate Functions Operate on a set of rows and return a single summary value.
Function Description MySQL Syntax Example COUNT()Count rows SELECT COUNT(*) FROM orders;COUNT(DISTINCT)Count unique values SELECT COUNT(DISTINCT customer_id) FROM orders;SUM()Sum of values SELECT SUM(price) FROM products;AVG()Average value SELECT AVG(salary) FROM employees;MIN()Minimum value SELECT MIN(price) FROM products;MAX()Maximum value SELECT MAX(salary) FROM employees;GROUP_CONCAT()Concatenate group values SELECT GROUP_CONCAT(name) FROM employees GROUP BY dept;STD() / STDDEV()Population std deviation SELECT STDDEV(salary) FROM employees;VARIANCE()Population variance SELECT VARIANCE(score) FROM results;
1.2.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access COUNT()β
β
β
β
β
β
SUM()β
β
β
β
β
β
AVG()β
β
β
β
β
β
GROUP_CONCAT()β
β
β οΈ STRING_AGG(col, ',') β οΈ STRING_AGG(col, ',') β οΈ LISTAGG(col, ',') β STDDEV()β
β β οΈ STDDEV_POP() β οΈ STDEV() β
β VARIANCE()β
β β οΈ VAR_POP() β οΈ VAR() β
β
1.3. π€ String Functions Manipulate and analyze text data.
Function Description Syntax Example CONCAT()Join strings SELECT CONCAT(first_name, ' ', last_name) FROM users;CONCAT_WS()Join with separator SELECT CONCAT_WS(', ', city, country) FROM addresses;LENGTH()Length in bytes SELECT LENGTH(email) FROM users;CHAR_LENGTH()Length in characters SELECT CHAR_LENGTH(name) FROM users;UPPER()Uppercase SELECT UPPER(name) FROM users;LOWER()Lowercase SELECT LOWER(email) FROM users;TRIM()Remove leading/trailing spaces SELECT TRIM(' hello ');LTRIM()Remove leading spaces SELECT LTRIM(' hello');RTRIM()Remove trailing spaces SELECT RTRIM('hello ');SUBSTRING()Extract part of string SELECT SUBSTRING(phone, 1, 3) FROM users;LEFT()Leftmost N characters SELECT LEFT(name, 5) FROM users;RIGHT()Rightmost N characters SELECT RIGHT(code, 4) FROM products;REPLACE()Replace occurrences SELECT REPLACE(phone, '-', '') FROM users;INSTR()Position of substring SELECT INSTR(email, '@') FROM users;LOCATE()Position of first occurrence SELECT LOCATE('@', email) FROM users;LPAD()Left-pad string SELECT LPAD(id, 6, '0') FROM orders;RPAD()Right-pad string SELECT RPAD(name, 20, '.') FROM products;REVERSE()Reverse string SELECT REVERSE(name) FROM users;REPEAT()Repeat string N times SELECT REPEAT('*', 5);FORMAT()Format number as string SELECT FORMAT(price, 2) FROM products;STRCMP()Compare two strings SELECT STRCMP('abc', 'abd');SOUNDEX()Phonetic encoding SELECT SOUNDEX('Robert');
1.3.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access CONCAT()β
β οΈ Use || operator β
β
β
β οΈ & operator LENGTH()β
β
β οΈ CHAR_LENGTH() for chars β οΈ LEN() β
bytes only β οΈ LEN() SUBSTRING()β
β
SUBSTR() β
β
β
SUBSTR() β οΈ MID() INSTR()β
β
β οΈ POSITION() β οΈ CHARINDEX() β
β οΈ InStr() LPAD() / RPAD()β
β β
β β
β REPLACE()β
β
β
β
β
β
TRIM()β
β
β
β
β
β
SOUNDEX()β
β β
β
β
β
FORMAT()β
β β οΈ TO_CHAR() β οΈ FORMAT() β οΈ TO_CHAR() β οΈ Format()
1.4. π’ Math / Numeric Functions Perform calculations on numeric data.
Function Description Syntax Example ABS()Absolute value SELECT ABS(-42); β 42ROUND()Round to N decimals SELECT ROUND(3.14159, 2); β 3.14CEIL() / CEILING()Round up SELECT CEIL(4.1); β 5FLOOR()Round down SELECT FLOOR(4.9); β 4TRUNCATE()Truncate decimals SELECT TRUNCATE(3.999, 1); β 3.9MOD() / %Modulo (remainder) SELECT MOD(10, 3); β 1POWER() / POW()Raise to power SELECT POW(2, 8); β 256SQRT()Square root SELECT SQRT(144); β 12EXP()e raised to power SELECT EXP(1); β 2.718...LN()Natural logarithm SELECT LN(2.718);LOG()Natural log / log base N SELECT LOG(100);LOG2()Base-2 logarithm SELECT LOG2(8); β 3LOG10()Base-10 logarithm SELECT LOG10(1000); β 3PI()Value of Ο SELECT PI(); β 3.14159...RAND()Random float 0β1 SELECT RAND();SIGN()Sign of number (-1, 0, 1) SELECT SIGN(-50); β -1GREATEST()Largest of arguments SELECT GREATEST(3, 7, 2); β 7LEAST()Smallest of arguments SELECT LEAST(3, 7, 2); β 2DIVInteger division SELECT 17 DIV 5; β 3
1.4.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access ABS()β
β
β
β
β
β
ROUND()β
β
β
β
β
β
CEIL()β
β β
β οΈ CEILING() β
β FLOOR()β
β β
β
β
β TRUNCATE()β
β β οΈ TRUNC() β β οΈ TRUNC() β MOD()β
β οΈ % only β
β οΈ % only β
β οΈ MOD() RAND()β
β β οΈ RANDOM() β
β οΈ DBMS_RANDOM.VALUE β οΈ Rnd() GREATEST()β
β β
β β
β LEAST()β
β β
β β
β LOG()β
β
β
β οΈ base-10 default β
β
1.5. π
Date & Time Functions Work with date and time values.
Function Description Syntax Example NOW()Current date and time SELECT NOW(); β 2025-02-26 14:30:00CURDATE()Current date only SELECT CURDATE(); β 2025-02-26CURTIME()Current time only SELECT CURTIME(); β 14:30:00DATE()Extract date from datetime SELECT DATE(created_at) FROM orders;TIME()Extract time from datetime SELECT TIME(created_at) FROM orders;YEAR()Extract year SELECT YEAR(birth_date) FROM users;MONTH()Extract month (1β12) SELECT MONTH(order_date) FROM orders;DAY()Extract day of month SELECT DAY(invoice_date) FROM invoices;HOUR()Extract hour SELECT HOUR(login_time) FROM sessions;MINUTE()Extract minute SELECT MINUTE(login_time) FROM sessions;SECOND()Extract second SELECT SECOND(login_time) FROM sessions;DAYNAME()Day name (Mondayβ¦) SELECT DAYNAME(order_date) FROM orders;MONTHNAME()Month name (Januaryβ¦) SELECT MONTHNAME(order_date) FROM orders;DAYOFWEEK()Day index (1=Sun) SELECT DAYOFWEEK(order_date) FROM orders;WEEK()Week number SELECT WEEK(order_date) FROM orders;DATE_FORMAT()Format a date SELECT DATE_FORMAT(NOW(), '%Y-%m-%d');DATE_ADD()Add interval to date SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);DATE_SUB()Subtract interval from date SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);DATEDIFF()Days between two dates SELECT DATEDIFF('2025-12-31', '2025-01-01'); β 364TIMESTAMPDIFF()Difference in specified unit SELECT TIMESTAMPDIFF(YEAR, birth_date, NOW()) AS age FROM users;STR_TO_DATE()Parse string to date SELECT STR_TO_DATE('26/02/2025', '%d/%m/%Y');UNIX_TIMESTAMP()Date to Unix epoch SELECT UNIX_TIMESTAMP(NOW());FROM_UNIXTIME()Unix epoch to datetime SELECT FROM_UNIXTIME(1708905600);LAST_DAY()Last day of the month SELECT LAST_DAY('2025-02-01'); β 2025-02-28
1.5.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access NOW()β
β οΈ datetime('now') β
β οΈ GETDATE() β οΈ SYSDATE β οΈ Now() CURDATE()β
β οΈ date('now') β οΈ CURRENT_DATE β οΈ CAST(GETDATE() AS DATE) β οΈ TRUNC(SYSDATE) β οΈ Date() DATE_FORMAT()β
β οΈ strftime('%Y-%m-%d', col) β οΈ TO_CHAR(col, 'YYYY-MM-DD') β οΈ FORMAT(col, 'yyyy-MM-dd') β οΈ TO_CHAR() β οΈ Format() DATEDIFF()β
β οΈ julianday(d1) - julianday(d2) β οΈ col1 - col2 (returns interval) β
different arg order β οΈ col1 - col2 β οΈ DateDiff() DATE_ADD()β
β οΈ datetime(col, '+7 days') β οΈ col + INTERVAL '7 days' β οΈ DATEADD(day, 7, col) β οΈ col + 7 β οΈ DateAdd() YEAR() / MONTH() / DAY()β
β οΈ strftime('%Y', col) β οΈ EXTRACT(YEAR FROM col) β
β οΈ EXTRACT(YEAR FROM col) β οΈ Year() UNIX_TIMESTAMP()β
β οΈ strftime('%s', col) β οΈ EXTRACT(EPOCH FROM col) β οΈ DATEDIFF(s,'1970-01-01',col) β complex β
1.6. βοΈ Comparison & Logical Operators Filter and evaluate conditions.
Operator / Function Description Syntax Example =Equal WHERE status = 'active'<> / !=Not equal WHERE status <> 'deleted'>, <, >=, <=Numeric comparisons WHERE salary >= 50000<=>NULL-safe equal WHERE col1 <=> col2BETWEEN ... AND ...Range check WHERE price BETWEEN 10 AND 50IN()Value in a list WHERE country IN ('US', 'UK', 'CA')NOT IN()Value not in a list WHERE status NOT IN ('deleted', 'banned')LIKEPattern match (% wildcard) WHERE name LIKE 'John%'NOT LIKEPattern non-match WHERE email NOT LIKE '%@spam.com'IS NULLNULL check WHERE phone IS NULLIS NOT NULLNon-NULL check WHERE email IS NOT NULLAND / &&Logical AND WHERE age > 18 AND active = 1ORLogical OR WHERE role = 'admin' OR role = 'mod'NOT / !Logical NOT WHERE NOT deletedCOALESCE()First non-NULL value SELECT COALESCE(phone, email, 'N/A') FROM users;NULLIF()Returns NULL if equal SELECT NULLIF(score, 0) FROM results;IF()Inline if/else SELECT IF(score >= 50, 'Pass', 'Fail') FROM results;IFNULL()Replace NULL SELECT IFNULL(phone, 'Unknown') FROM users;CASEMulti-condition logic See below
CASE example:
1
2
3
4
5
6
7
8
SELECT name ,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 75 THEN 'B'
WHEN score >= 60 THEN 'C'
ELSE 'F'
END AS grade
FROM students ;
1.6.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access BETWEEN / IN / LIKEβ
β
β
β
β
β
COALESCE()β
β
β
β
β
β
CASEβ
β
β
β
β
β
IF()β
β β use CASE β β β οΈ IIF() IFNULL()β
β
β οΈ COALESCE() β οΈ ISNULL() β οΈ NVL() β οΈ Nz() NULLIF()β
β
β
β
β
β <=> NULL-safe equalβ
β β οΈ IS NOT DISTINCT FROM β β β
1.7. πͺ Window Functions Calculations across a set of rows related to the current row β no GROUP BY collapse.
Function Description Syntax Example ROW_NUMBER()Sequential row number SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn FROM employees;RANK()Rank with gaps SELECT RANK() OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees;DENSE_RANK()Rank without gaps SELECT DENSE_RANK() OVER (ORDER BY score DESC) FROM results;NTILE(n)Divide into N buckets SELECT NTILE(4) OVER (ORDER BY salary) AS quartile FROM employees;LAG()Previous row value SELECT LAG(sales, 1) OVER (ORDER BY month) AS prev_sales FROM revenue;LEAD()Next row value SELECT LEAD(sales, 1) OVER (ORDER BY month) AS next_sales FROM revenue;FIRST_VALUE()First value in window SELECT FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees;LAST_VALUE()Last value in window SELECT LAST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary) FROM employees;CUME_DIST()Cumulative distribution SELECT CUME_DIST() OVER (ORDER BY salary) FROM employees;PERCENT_RANK()Relative rank 0β1 SELECT PERCENT_RANK() OVER (ORDER BY score) FROM results;
Full example:
1
2
3
4
5
6
7
8
SELECT
name ,
dept ,
salary ,
RANK () OVER ( PARTITION BY dept ORDER BY salary DESC ) AS dept_rank ,
SUM ( salary ) OVER ( PARTITION BY dept ) AS dept_total ,
LAG ( salary ) OVER ( PARTITION BY dept ORDER BY salary DESC ) AS prev_salary
FROM employees ;
1.7.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access ROW_NUMBER()β
8.0+ β
3.25+ β
β
β
β RANK()β
8.0+ β
3.25+ β
β
β
β DENSE_RANK()β
8.0+ β
3.25+ β
β
β
β LAG() / LEAD()β
8.0+ β
3.25+ β
β
β
β FIRST_VALUE()β
8.0+ β
3.25+ β
β
β
β NTILE()β
8.0+ β
3.25+ β
β
β
β
1.8. π Conversion & Type Functions Cast or convert between data types.
Function Description Syntax Example CAST()Convert to type SELECT CAST('42' AS UNSIGNED);CONVERT()Convert value/charset SELECT CONVERT(price, CHAR);HEX()To hexadecimal SELECT HEX(255); β FFUNHEX()From hexadecimal SELECT UNHEX('FF');BIN()To binary string SELECT BIN(10); β 1010OCT()To octal string SELECT OCT(8); β 10ASCII()ASCII code of char SELECT ASCII('A'); β 65CHAR()Char from ASCII code SELECT CHAR(65); β ATO_BASE64()Encode base64 SELECT TO_BASE64('hello');FROM_BASE64()Decode base64 SELECT FROM_BASE64('aGVsbG8=');
1.8.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MS Access CAST()β
β
β
β
β
β
CONVERT()β
β β οΈ CAST preferred β
β β HEX()β
β
β οΈ TO_HEX() β οΈ CONVERT(VARBINARY...) β οΈ RAWTOHEX() β ASCII()β
β
β
β
β
β
TO_BASE64()β
β β οΈ encode(col,'base64') β β β
1.9. π Security & Hash Functions Function Description Syntax Example MD5()MD5 hash SELECT MD5('password');SHA1()SHA-1 hash SELECT SHA1('password');SHA2()SHA-2 (224/256/384/512) SELECT SHA2('password', 256);AES_ENCRYPT()AES encryption SELECT AES_ENCRYPT('secret', 'key');AES_DECRYPT()AES decryption SELECT AES_DECRYPT(ciphertext, 'key');UUID()Generate UUID SELECT UUID(); β 550e8400-e29b-41d4-a716...
1.9.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle MD5()β
β β
β οΈ HASHBYTES('MD5', col) β SHA2()β
β β οΈ digest(col,'sha256') pgcrypto β οΈ HASHBYTES('SHA2_256', col) β UUID()β
β β οΈ gen_random_uuid() β οΈ NEWID() β οΈ SYS_GUID()
1.10. π JSON Functions (MySQL 5.7+) Function Description Syntax Example JSON_EXTRACT()Extract value by path SELECT JSON_EXTRACT(data, '$.name') FROM users;->Shorthand for JSON_EXTRACT SELECT data->'$.name' FROM users;->>Extract + unquote result SELECT data->>'$.name' FROM users;JSON_OBJECT()Create JSON object SELECT JSON_OBJECT('name', name, 'age', age) FROM users;JSON_ARRAY()Create JSON array SELECT JSON_ARRAY(1, 2, 3);JSON_SET()Insert or update path UPDATE t SET data = JSON_SET(data, '$.age', 30);JSON_REMOVE()Remove a path UPDATE t SET data = JSON_REMOVE(data, '$.temp');JSON_CONTAINS()Check if value exists at path SELECT JSON_CONTAINS(data, '"admin"', '$.role') FROM users;JSON_ARRAYAGG()Aggregate rows as JSON array SELECT JSON_ARRAYAGG(name) FROM employees GROUP BY dept;JSON_VALID()Validate JSON SELECT JSON_VALID('{"a":1}'); β 1
1.10.1. Cross-Engine Compatibility Function MySQL SQLite PostgreSQL SQL Server Oracle JSON_EXTRACT()β
β
json_extract() β οΈ ->> operator β οΈ JSON_VALUE() β οΈ JSON_VALUE() JSON_OBJECT()β
β
json_object() β οΈ json_build_object() β οΈ FOR JSON PATH β
JSON_ARRAYAGG()β
8.0+ β β οΈ JSON_AGG() β οΈ FOR JSON PATH β
12c+ JSON_VALID()β
β
json_valid() β οΈ try casting β οΈ ISJSON() β
12c+
1.11. β‘ NULL Handling β Quick Reference 1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- Replace NULL with a default value
SELECT COALESCE ( phone , 'N/A' ) FROM users ; -- All engines β
SELECT IFNULL ( phone , 'N/A' ) FROM users ; -- MySQL, SQLite
SELECT ISNULL ( phone , 'N/A' ) FROM users ; -- SQL Server
SELECT NVL ( phone , 'N/A' ) FROM users ; -- Oracle
SELECT IIF ( phone IS NULL , 'N/A' , phone ) FROM users ; -- MS Access
-- Return NULL when two values are equal (avoid division by zero etc.)
SELECT NULLIF ( score , 0 ) FROM results ; -- MySQL, PostgreSQL, SQL Server, SQLite
-- NULL-safe equality (never use = with NULLs!)
WHERE col IS NULL -- All engines β
WHERE col <=> NULL -- MySQL only
WHERE col IS NOT DISTINCT FROM NULL -- PostgreSQL
1.12. π Useful Patterns 1.12.1. Age Calculation 1
2
3
4
5
6
7
8
9
10
11
-- MySQL
SELECT TIMESTAMPDIFF ( YEAR , birth_date , CURDATE ()) AS age FROM users ;
-- SQL Server
SELECT DATEDIFF ( YEAR , birth_date , GETDATE ()) AS age FROM users ;
-- PostgreSQL
SELECT DATE_PART ( 'year' , AGE ( birth_date )) AS age FROM users ;
-- SQLite
SELECT ( strftime ( '%Y' , 'now' ) - strftime ( '%Y' , birth_date )) AS age FROM users ;
1.12.2. Running Total 1
2
3
4
5
6
7
8
SELECT
order_date ,
amount ,
SUM ( amount ) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders ;
1.12.3. Top N Per Group 1
2
3
4
5
6
SELECT * FROM (
SELECT * ,
ROW_NUMBER () OVER ( PARTITION BY dept ORDER BY salary DESC ) AS rn
FROM employees
) ranked
WHERE rn <= 3 ;
1.12.4. Conditional Aggregation (Pivot-style) 1
2
3
4
5
6
SELECT
dept ,
SUM ( CASE WHEN gender = 'M' THEN salary END ) AS male_total ,
SUM ( CASE WHEN gender = 'F' THEN salary END ) AS female_total
FROM employees
GROUP BY dept ;
1.12.5. Deduplicate β Keep Latest Row 1
2
3
4
DELETE FROM orders
WHERE id NOT IN (
SELECT MAX ( id ) FROM orders GROUP BY order_ref
);
Based on MySQL 8.x built-in function reference. Version requirements noted where applicable.