{"id":"sql-functions/abs","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ABS function","description":"Absolute value with SQL ABS in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: differences, overflow on the most negative integer and common uses.","body":{"slug":"abs","name":"ABS","h1":"SQL ABS function","category":"math","lede":"Returns the magnitude of a number without its sign: ABS(-42) is 42. It is mostly used to measure how far apart two values are, whichever is bigger.","syntax":"ABS(number)","return_type":"same type as the input","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The most negative integer has no positive counterpart in its type: ABS of an int -2147483648 raises an overflow error on SQL Server and PostgreSQL. MySQL promotes it to BIGINT and returns 2147483648, but errors on the most negative BIGINT; SQLite raises 'integer overflow' there too.","ABS(actual - forecast) loses the direction of the miss. Keep the signed difference too when over and under mean different things.","It returns the input type: ABS of an int stays an int, of a numeric stays numeric."],"examples":[{"engine_slug":"all","sql":"SELECT ABS(-42) AS magnitude;  -- 42"},{"engine_slug":"all","sql":"SELECT ABS(actual - forecast) AS miss\nFROM projections\nORDER BY miss DESC;"}],"faqs":[{"question":"What does ABS do with a negative number?","answer":"Drops the sign: ABS(-5) is 5. For integer types, the single most negative value (such as -2147483648 for int) has no positive counterpart and raises an overflow error on most engines."},{"question":"Does ABS work on decimals and money types?","answer":"Yes, and it preserves the type. ABS of a DECIMAL column stays DECIMAL. No precision surprises."}],"related":["sign","round","mod"],"novel_uses":[{"body":"Two float-computed totals rarely hold bit-identical values, so ABS(a - b) < 0.005 expresses equal to the cent where = would fail. Pick the tolerance from the money scale, not from hope.","sql":"SELECT id FROM recon\nWHERE ABS(total_a - total_b) >= 0.005;"},{"body":"Ordering by the absolute distance to a target and taking one row finds the closest event to a moment with no geometry, no index and no window function. For timestamp columns convert to epoch seconds first so the subtraction is numeric.","sql":"SELECT id, at\nFROM events\nORDER BY ABS(EXTRACT(epoch FROM at) - 1785000000)\nLIMIT 1;"}]},"source_url":"https://sqlly.app/sql-functions/abs","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/acos","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ACOS function","description":"ACOS(x) returns the angle whose cosine is x, in radians. ACOS(-1) is pi on every engine, which is how Oracle code gets pi without a PI() function.","body":{"slug":"acos","name":"ACOS","h1":"SQL ACOS function","category":"math","lede":"Returns the arc cosine in radians for input in [-1, 1]: ACOS(1) is 0 and ACOS(-1) is pi.","syntax":"ACOS(number)","return_type":"float / double (radians)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Added with the math functions in 3.35.0; on a build without the flag, acos is an unknown function and the statement fails"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Domain [-1, 1] like ASIN; outside it MySQL and SQLite return NULL, while PostgreSQL, Oracle and SQL Server raise an error.","ACOS(-1) is the standard way to obtain pi where PI() is missing, which means every Oracle release.","Distance formulas feed ACOS values like 1.0000000000000002 from float error. Clamp before calling: LEAST(1, GREATEST(-1, x)) (SQL Server 2022 and later), or MAX(-1, MIN(1, x)) on SQLite."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ACOS(1) AS zero, ACOS(-1) AS pi_value;  -- 0, 3.14159..."},{"engine_slug":"postgresql","sql":"SELECT ACOS(1) AS zero, ACOS(-1) AS pi_value;  -- 0, 3.14159..."},{"engine_slug":"mysql","sql":"SELECT ACOS(1) AS zero, ACOS(-1) AS pi_value;  -- 0, 3.14159..."},{"engine_slug":"sqlite","sql":"SELECT ACOS(1) AS zero, ACOS(-1) AS pi_value;  -- 0, 3.14159..."},{"engine_slug":"oracle","sql":"SELECT ACOS(-1) AS pi_value FROM dual;  -- 3.14159265..."},{"engine_slug":"postgresql","sql":"SELECT DEGREES(ACOS(0.5)) AS sixty;  -- 60.00000000000001"}],"faqs":[{"question":"Why do people write ACOS(-1) for pi?","answer":"ACOS(-1) returns pi to the precision of the type, and the expression works on every engine. On Oracle it is the only option, because Oracle has no PI() function."},{"question":"What does ACOS(2) return?","answer":"Nothing valid: NULL on MySQL and SQLite, an error on PostgreSQL, Oracle and SQL Server. The arc cosine only exists for inputs between -1 and 1."},{"question":"Is the ACOS result in radians?","answer":"Yes, always. ACOS(0.5) is about 1.047 radians, which is 60 degrees; use DEGREES() for degree output."}],"related":["cos","asin","pi","inverse-trig-domain"],"novel_uses":[{"body":"ACOS of the dot product over the magnitudes gives the angle between two feature or sensor vectors, the standard similarity check in SQL. Keep the ratio in [-1, 1] by clamping it first (LEAST/GREATEST, or MAX/MIN on SQLite), or float noise will break the ACOS. Write 1.0 * before the division, because integer columns divide to 0 and every angle comes out 90.","sql":"SELECT DEGREES(ACOS(1.0 * (a.x * b.x + a.y * b.y) / (a.len * b.len))) AS angle_deg FROM vectors a JOIN vectors b ON b.id = a.partner;"},{"body":"The law of cosines solved for the angle, ACOS((a2 + b2 - c2) / (2.0 * a * b)), returns an interior angle from side lengths alone. Survey QA uses it to check measured angles against measured distances.","sql":"SELECT DEGREES(ACOS((a*a + b*b - c*c) / (2.0 * a * b))) AS angle_c FROM triangles;"}]},"source_url":"https://sqlly.app/sql-functions/acos","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/acosh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ACOSH function","description":"ACOSH(x) inverts COSH for x >= 1. Below 1, PostgreSQL raises an error and SQLite returns NULL. SQL Server, MySQL and Oracle need the LN identity.","body":{"slug":"acosh","name":"ACOSH","h1":"SQL ACOSH function","category":"math","lede":"Returns the inverse hyperbolic cosine for inputs of 1 or more: ACOSH(1) is 0 and ACOSH(COSH(2)) is 2.","syntax":"ACOSH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; use LN(x + SQRT(x * x - 1)) for x >= 1"},{"engine_slug":"postgresql","status":"yes","note":"Built in from PostgreSQL 12"},{"engine_slug":"mysql","status":"no","note":"No ACOSH in MySQL; use LN(x + SQRT(x * x - 1)) for x >= 1"},{"engine_slug":"sqlite","status":"yes","note":"Needs 3.35+ with the math functions compiled in at build time"},{"engine_slug":"oracle","status":"no","note":"No ACOSH; use LN(x + SQRT(x * x - 1))"}],"gotchas":["Domain is [1, infinity): ACOSH(0.5) returns NULL on SQLite and raises 'input is out of range' on PostgreSQL.","The log formula LN(x + SQRT(x * x - 1)) works for x >= 1; SQRT of a negative number inside it is a domain error in disguise: PostgreSQL and SQL Server raise an error, while MySQL and SQLite return NULL.","ACOSH returns non-negative results only, since COSH is symmetric and the inverse conventionally takes the positive branch."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ACOSH(1) AS zero;  -- 0"},{"engine_slug":"sql-server","sql":"SELECT LOG(2 + SQRT(POWER(2.0, 2) - 1)) AS acosh_two;  -- about 1.3170"},{"engine_slug":"sqlite","sql":"SELECT ACOSH(0.5) AS out_of_domain;  -- NULL"}],"faqs":[{"question":"Why does ACOSH return NULL or error for 0.5?","answer":"COSH never produces values below 1, so the inverse is undefined there. SQLite returns NULL; PostgreSQL raises an out-of-range error."},{"question":"What is the portable ACOSH formula?","answer":"LN(x + SQRT(x * x - 1)), valid for x >= 1. SQL Server spells LN as LOG; MySQL and Oracle use LN directly."},{"question":"What is ACOSH(1)?","answer":"Exactly 0: the only input whose hyperbolic cosine is 1 is zero."}],"related":["cosh","asinh","inverse-trig-domain"],"novel_uses":[{"body":"Data encoded with COSH, say a catenary fit, comes back with ACOSH: the inverse restores the magnitude of the original argument for fitting or comparison: ACOSH(COSH(-2)) is 2, so a negative input comes back positive. An input below 1 means the decode ran against the wrong column.","sql":"SELECT ACOSH(encoded) AS x FROM catenary_fits;"},{"body":"ACOSH(x) minus LN(2 * x) shrinks like 1/(4x^2), within the last digit past about ten million, so engines without ACOSH can substitute LN(2 * x) when inputs are that large. Check the gap at your smallest real input first.","sql":"SELECT ACOSH(10000000.0), LN(2.0 * 10000000.0);  -- differ only in the last double digits"}]},"source_url":"https://sqlly.app/sql-functions/acosh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/add-months","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ADD_MONTHS function","description":"ADD_MONTHS in Oracle: add whole months with the month-end rule, and how DATEADD, + interval and DATE_ADD differ from it at the last day of a month.","body":{"slug":"add-months","name":"ADD_MONTHS","h1":"SQL ADD_MONTHS function","category":"datetime","lede":"Adds whole months to a date. Its signature behaviour: a month-end date in yields a month-end date out.","syntax":"ADD_MONTHS(date, n)","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(MONTH, n, d); no month-end preservation"},{"engine_slug":"postgresql","status":"partial","note":"d + n * INTERVAL '1 month'; clamps, does not preserve month ends"},{"engine_slug":"mysql","status":"partial","note":"DATE_ADD(d, INTERVAL n MONTH); clamps"},{"engine_slug":"sqlite","status":"partial","note":"date(d, '+' || n || ' months')"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ADD_MONTHS(DATE '2026-02-28', 1) returns 2026-03-31, because 2026-02-28 is the last day of February. PostgreSQL and MySQL would return 2026-03-28, the biggest practical difference between ADD_MONTHS and them.","ADD_MONTHS(DATE '2026-01-31', 1) returns 2026-02-28, same as PostgreSQL, MySQL and SQL Server; SQLite returns 2026-03-03. The rule only bites when the input is itself a month end.","The second argument is a whole number; fractional months are truncated before the add."],"examples":[{"engine_slug":"oracle","sql":"SELECT ADD_MONTHS(DATE '2026-01-31', 1) FROM dual;  -- 2026-02-28"},{"engine_slug":"oracle","sql":"SELECT ADD_MONTHS(DATE '2026-02-28', 1) FROM dual;  -- 2026-03-31"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-02-28' + INTERVAL '1 month';  -- 2026-03-28"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MONTH, 1, '2026-02-28');  -- 2026-03-28, no month-end promotion"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-02-28', INTERVAL 1 MONTH);  -- 2026-03-28"},{"engine_slug":"sqlite","sql":"SELECT date('2026-02-28', '+1 month');  -- 2026-03-28"}],"faqs":[{"question":"What is the equivalent of ADD_MONTHS in PostgreSQL?","answer":"d + INTERVAL '1 month'. Watch the month-end rule though: PostgreSQL never promotes 2026-02-28 to 2026-03-31."},{"question":"How do I match Oracle's month-end behaviour elsewhere?","answer":"Check whether the input is the last day of its month. If it is, add the months and then take the last day of the result month; otherwise add the months and let the engine clamp. Adding one month and checking the day, or taking last_day first, both give 2026-03-28 for 2026-02-28, not 2026-03-31, and last_day first gives 2026-02-28 for 2026-01-15 instead of 2026-02-15."}],"related":["months-between","last-day","dateadd","adddate"],"novel_uses":[{"body":"Contracts often store only the end date and the term in months. Subtracting the term rebuilds the original start, with the month-end rule applied in reverse.","sql":"SELECT ADD_MONTHS(DATE '2028-02-29', -12) FROM dual;  -- 2027-02-28"},{"body":"TRUNC to the quarter, add three months, then back off one day. The three-step chain lands on the quarter's last date in one SELECT.","sql":"SELECT ADD_MONTHS(TRUNC(DATE '2026-08-15', 'Q'), 3) - 1 FROM dual;  -- 2026-09-30"},{"body":"ADD_MONTHS(d, -12) gives the same calendar day one year back, the exact lower bound for a year-over-year comparison on date-partitioned tables.","sql":"SELECT ADD_MONTHS(DATE '2026-08-01', -12) FROM dual;  -- 2025-08-01"}]},"source_url":"https://sqlly.app/sql-functions/add-months","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/adddate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ADDDATE function","description":"ADDDATE in MySQL: add days or an INTERVAL to a date, plus the DATEADD, + interval and date() modifier equivalents in the other four engines.","body":{"slug":"adddate","name":"ADDDATE","h1":"SQL ADDDATE function","category":"datetime","lede":"Adds a number of days, or any INTERVAL unit, to a date or datetime. With an INTERVAL argument it is a synonym for DATE_ADD.","syntax":"ADDDATE(date, days)  |  ADDDATE(date, INTERVAL n unit)","return_type":"date / datetime","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(day, n, d) or DATEADD(month, n, d)"},{"engine_slug":"postgresql","status":"partial","note":"d + INTERVAL '1 day' / d + INTERVAL '1 month'"},{"engine_slug":"mysql","status":"partial","note":null},{"engine_slug":"sqlite","status":"yes","note":"date(d, '+7 days')"},{"engine_slug":"oracle","status":"partial","note":"d + INTERVAL '1' DAY or ADD_MONTHS(d, 1)"}],"gotchas":["Month arithmetic clamps in MySQL: ADDDATE('2026-01-31', INTERVAL 1 MONTH) gives 2026-02-28, not a March 3 overflow.","ADDDATE(d, 7) with a bare number always means days; only the INTERVAL form takes other units.","Oracle's ADD_MONTHS differs at month ends: ADD_MONTHS(DATE '2026-02-28', 1) is 2026-03-31, while ADDDATE('2026-02-28', INTERVAL 1 MONTH) is 2026-03-28."],"examples":[{"engine_slug":"mysql","sql":"SELECT ADDDATE('2026-01-31', INTERVAL 1 MONTH);  -- 2026-02-28"},{"engine_slug":"mysql","sql":"SELECT ADDDATE('2026-08-01', 7);  -- 2026-08-08"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-01-31' + INTERVAL '1 month';  -- 2026-02-28 00:00:00"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MONTH, 1, '2026-01-31');  -- 2026-02-28"},{"engine_slug":"sqlite","sql":"SELECT date('2026-01-31', '+7 days');  -- 2026-02-07"},{"engine_slug":"oracle","sql":"SELECT DATE '2026-01-31' + INTERVAL '7' DAY FROM dual;  -- 2026-02-07"}],"faqs":[{"question":"Is ADDDATE the same as DATE_ADD?","answer":"With an INTERVAL argument, yes: ADDDATE is a synonym for DATE_ADD. Only ADDDATE accepts a bare day count: DATE_ADD('2026-08-01', 7) is a syntax error."},{"question":"How do I add a month in PostgreSQL?","answer":"date + INTERVAL '1 month'. PostgreSQL clamps the day to the month's last day, so 2026-01-31 plus one month is 2026-02-28."}],"related":["dateadd","date-sub","add-months","date-format"],"novel_uses":[{"body":"MySQL has no start-of-month function, so step back one month to its last day and add a day. The two-step walk gives the first of the current month without string surgery.","sql":"SELECT LAST_DAY(ADDDATE('2026-08-15', INTERVAL -1 MONTH)) + INTERVAL 1 DAY;  -- 2026-08-01"},{"body":"For trial or billing dates that must land on a month end, add the interval first and flatten with LAST_DAY. Every result is a month end whatever the input day was.","sql":"SELECT LAST_DAY(ADDDATE('2026-08-15', INTERVAL 1 MONTH));  -- 2026-09-30"},{"body":"MySQL lacks quarter truncation, so rebuild the quarter's first month with MAKEDATE and QUARTER, then flatten it to the last day.","sql":"SELECT LAST_DAY(MAKEDATE(YEAR('2026-08-15'), 1) + INTERVAL QUARTER('2026-08-15') * 3 - 1 MONTH);  -- 2026-09-30"}]},"source_url":"https://sqlly.app/sql-functions/adddate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/addtime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ADDTIME function","description":"ADDTIME in MySQL: shift a datetime or time by a time value, with the interval-addition equivalents on the other four engines.","body":{"slug":"addtime","name":"ADDTIME","h1":"SQL ADDTIME function","category":"datetime","lede":"Adds a time span to a datetime or another time. A TIME first argument returns TIME and a DATETIME first argument returns DATETIME; a string literal returns text, and a DATE or TIMESTAMP first argument returns DATETIME.","syntax":"ADDTIME(dt, time_value)","return_type":"datetime / time","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(SECOND, ..., d) with the parts split out"},{"engine_slug":"postgresql","status":"partial","note":"dt + INTERVAL '2 hours 30 minutes'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"datetime(d, '+2 hours', '+30 minutes')"},{"engine_slug":"oracle","status":"partial","note":"dt + INTERVAL '2:30' HOUR TO MINUTE"}],"gotchas":["The span is a TIME value and may include a day part: ADDTIME(d, '1 02:30:00') adds 26.5 hours. Months and years are out of reach; use DATE_ADD with INTERVAL for those.","A TIME first argument gives a TIME result that does not wrap at midnight: ADDTIME('23:30:00', '02:30:00') is 26:00:00. Pass a datetime when you want the date to roll over.","PostgreSQL's + interval and Oracle's interval types also cover months and years, which a TIME span cannot express."],"examples":[{"engine_slug":"mysql","sql":"SELECT ADDTIME('2026-08-01 23:30:00', '02:30:00');  -- 2026-08-02 02:00:00"},{"engine_slug":"postgresql","sql":"SELECT '2026-08-01 23:30:00'::timestamp + INTERVAL '2:30';"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MINUTE, 150, '2026-08-01 23:30:00');  -- 2026-08-02 02:00:00"},{"engine_slug":"sqlite","sql":"SELECT datetime('2026-08-01 23:30:00', '+2 hours', '+30 minutes');  -- 2026-08-02 02:00:00"},{"engine_slug":"oracle","sql":"SELECT TIMESTAMP '2026-08-01 23:30:00' + INTERVAL '2:30' HOUR TO MINUTE FROM dual;  -- 2026-08-02 02:00:00"}],"faqs":[{"question":"How do I add 90 minutes in MySQL?","answer":"ADDTIME(d, '01:30:00') or DATE_ADD(d, INTERVAL 90 MINUTE); the INTERVAL form reads better and scales past a day."},{"question":"Why did my time go past 24:00?","answer":"MySQL's TIME doubles as a duration type and runs to 838:59:59, so ADDTIME on a TIME keeps counting past midnight. Add to a datetime if you want the day to roll over instead."}],"related":["adddate","subtime","timediff","interval-arithmetic"],"novel_uses":[{"body":"Store a recurring offset once as TIME and compose it with any date at query time, so schedule changes touch one column instead of every datetime row.","sql":"SELECT ADDTIME(slot_date, run_offset) FROM schedules;"},{"body":"The TIME span carries fractional seconds, so a literal like a quarter second shifts a DATETIME(6) value for jittered retries or paced test inserts.","sql":"SELECT ADDTIME('2026-08-01 10:00:00.000000', '00:00:00.250000');  -- 2026-08-01 10:00:00.250000"}]},"source_url":"https://sqlly.app/sql-functions/addtime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/aes-encrypt","corpus":"sql-functions","engine":null,"language":"en","title":"SQL AES_ENCRYPT and ENCRYPTBYPASSPHRASE","description":"Symmetric encryption functions in SQL: MySQL's AES_ENCRYPT, SQL Server's ENCRYPTBYPASSPHRASE, Oracle's DBMS_CRYPTO and pgcrypto, with the key-handling traps.","body":{"slug":"aes-encrypt","name":"AES_ENCRYPT","h1":"SQL AES_ENCRYPT and ENCRYPTBYPASSPHRASE","category":"string","lede":"AES_ENCRYPT(text, key) returns ciphertext bytes and AES_DECRYPT reverses it. The function is easy; keeping the key out of logs is the hard part.","syntax":"AES_ENCRYPT(str, key [, iv])  |  ENCRYPTBYPASSPHRASE(passphrase, text)","return_type":"binary","support":[{"engine_slug":"sql-server","status":"partial","note":"ENCRYPTBYPASSPHRASE, or ENCRYPTBYKEY with a symmetric key"},{"engine_slug":"postgresql","status":"no","note":"not built in; the pgcrypto extension (pgp_sym_encrypt, encrypt)"},{"engine_slug":"mysql","status":"yes","note":"AES_ENCRYPT / AES_DECRYPT"},{"engine_slug":"sqlite","status":"no","note":"none; encryption builds such as SQLCipher encrypt the whole file"},{"engine_slug":"oracle","status":"partial","note":"DBMS_CRYPTO.ENCRYPT, a PL/SQL package"}],"gotchas":["MySQL's default block_encryption_mode is aes-128-ecb: no IV, so equal plaintexts encrypt to equal ciphertexts. Set block_encryption_mode to 'aes-256-cbc' and pass a random IV from RANDOM_BYTES(16) as the third argument.","The key is part of the SQL text, so it can end up in the general log, slow log, binary log or monitoring tools. Encrypting in the application, or using the engine's key management, keeps it out.","A wrong key does not raise an error. DECRYPTBYPASSPHRASE returns NULL; MySQL's AES_DECRYPT usually returns NULL but can return garbage bytes.","ENCRYPTBYPASSPHRASE is non-deterministic: the same input encrypts differently each time, so you cannot index or search on the ciphertext."],"examples":[{"engine_slug":"mysql","sql":"SELECT HEX(AES_ENCRYPT('secret', 'k')) AS cipher_hex,\n       CAST(AES_DECRYPT(AES_ENCRYPT('secret', 'k'), 'k') AS CHAR) AS plain;  -- E8B5783E9F4703DD32E1688CD2106E66, secret"},{"engine_slug":"mysql","sql":"SET block_encryption_mode = 'aes-256-cbc';\nSET @iv = RANDOM_BYTES(16);\nSET @k = UNHEX(SHA2('my passphrase', 256));\nSELECT CAST(AES_DECRYPT(AES_ENCRYPT('secret', @k, @iv), @k, @iv) AS CHAR) AS plain;  -- secret"},{"engine_slug":"sql-server","sql":"DECLARE @c VARBINARY(8000) = ENCRYPTBYPASSPHRASE('k', 'secret');\nSELECT CAST(DECRYPTBYPASSPHRASE('k', @c) AS VARCHAR(100)) AS plain, DECRYPTBYPASSPHRASE('wrong', @c) AS wrong_key;  -- secret, NULL"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(DBMS_CRYPTO.ENCRYPT(UTL_I18N.STRING_TO_RAW('secret', 'AL32UTF8'),\n       DBMS_CRYPTO.ENCRYPT_AES128 + DBMS_CRYPTO.CHAIN_CBC + DBMS_CRYPTO.PAD_PKCS5,\n       HEXTORAW('00112233445566778899AABBCCDDEEFF'))) AS cipher_hex FROM dual;"}],"faqs":[{"question":"Should I encrypt passwords with AES_ENCRYPT?","answer":"No. Passwords should be hashed with a slow password hash (bcrypt, scrypt, Argon2) in the application, so they cannot be decrypted at all."},{"question":"What column type holds the ciphertext?","answer":"A binary type: VARBINARY or BLOB on MySQL, VARBINARY on SQL Server, RAW or BLOB on Oracle. Storing it in a text column corrupts it under character set conversion."}],"related":["sha2","hashbytes","md5","random-bytes"],"novel_uses":[{"body":"WHERE email = AES_ENCRYPT(?, k) only matches rows encrypted with the same key and IV, so equality search forces a fixed IV and reintroduces the equal-values-equal-ciphertext leak. The standard split is a random-IV ciphertext column plus a separate keyed-hash column that the lookup indexes.","sql":"SELECT SHA2(CONCAT(@pepper, 'needle'), 256) AS index_value;  -- @pepper from config, index this, not the ciphertext"},{"body":"block_encryption_mode is a session variable on MySQL: a connection left on aes-128-ecb cannot read rows written by one on aes-256-cbc, and no error explains why. Pin the mode in the application's connection setup and record which mode wrote legacy rows.","sql":"SELECT @@SESSION.block_encryption_mode AS my_mode;  -- aes-128-ecb until you change it"}]},"source_url":"https://sqlly.app/sql-functions/aes-encrypt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/age","corpus":"sql-functions","engine":null,"language":"en","title":"SQL AGE function","description":"AGE in PostgreSQL: the gap between two timestamps as a years-months-days interval, the single-argument form, and what other engines use instead.","body":{"slug":"age","name":"AGE","h1":"SQL AGE function","category":"datetime","lede":"Returns the interval between two timestamps, broken into years, months and days, built for ages and tenure, not stopwatch timing.","syntax":"AGE(timestamp, timestamp)  |  AGE(timestamp)","return_type":"interval","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"MONTHS_BETWEEN plus arithmetic, or timestamp subtraction"}],"gotchas":["AGE returns calendar fields, not a length of time: AGE('2026-03-01', '2026-02-01') is 1 mon, not 28 days. Read whole years with EXTRACT(YEAR FROM AGE(...)).","The single-argument form subtracts from CURRENT_DATE at midnight, so AGE(ts) measures from today's 00:00, not from the current time. A time of day in ts shows as hours: on 2026-11-29, AGE(TIMESTAMP '2026-11-28 13:00') is 11:00:00.","Negative results are signed per field: AGE('1999-01-01', '2000-01-15') gives -1 years -14 days, not one negative total."],"examples":[{"engine_slug":"postgresql","sql":"SELECT AGE(TIMESTAMP '2026-08-01', TIMESTAMP '2020-01-15');  -- 6 years 6 mons 17 days"},{"engine_slug":"postgresql","sql":"SELECT AGE(birth_date) FROM people;"},{"engine_slug":"oracle","sql":"SELECT TRUNC(MONTHS_BETWEEN(DATE '2026-08-01', DATE '2020-01-15') / 12) FROM dual;  -- 6"}],"faqs":[{"question":"How do I get someone's age in years outside PostgreSQL?","answer":"MySQL: TIMESTAMPDIFF(YEAR, birth, CURDATE()) counts completed years. Oracle: TRUNC(MONTHS_BETWEEN(SYSDATE, birth) / 12). SQL Server: DATEDIFF(YEAR, ...) counts year boundaries, so subtract 1 when this year's birthday has not happened yet."},{"question":"Does AGE keep hours and minutes?","answer":"Yes, when the inputs have them: AGE(TIMESTAMP '2026-08-01 18:00', TIMESTAMP '2026-08-01 06:30') is 11:30:00. Use plain subtraction (ts1 - ts2) when you want days and time without the month split."}],"related":["months-between","timestampdiff","datediff","now"],"novel_uses":[{"body":"Multiply the years field by twelve and add the months field for total completed months in one expression. The day borrow is already handled inside AGE, unlike manual month counting.","sql":"SELECT EXTRACT(YEAR FROM AGE(TIMESTAMP '2026-08-01', TIMESTAMP '2025-01-15')) * 12 + EXTRACT(MONTH FROM AGE(TIMESTAMP '2026-08-01', TIMESTAMP '2025-01-15'));  -- 18"},{"body":"Pass a frozen reference timestamp instead of relying on the current-date default, so fixture ages never drift as real time passes.","sql":"SELECT AGE(TIMESTAMP '2026-08-01', birth_date) FROM people;"}]},"source_url":"https://sqlly.app/sql-functions/age","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/aggregate-filter","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FILTER clause","description":"FILTER (WHERE ...) on aggregate functions: conditional counts and sums without CASE on PostgreSQL, SQLite and recent Oracle, with the CASE fallback for other engines.","body":{"slug":"aggregate-filter","name":"FILTER","h1":"SQL FILTER clause","category":"aggregate","lede":"Attaches its own WHERE to a single aggregate so one SELECT can carry several conditional aggregates.","syntax":"COUNT(x) FILTER (WHERE cond) | SUM(x) FILTER (WHERE cond)","return_type":"depends on the aggregate","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"works on every aggregate, window aggregates included"},{"engine_slug":"mysql","status":"no","note":"use SUM(CASE WHEN cond THEN x END)"},{"engine_slug":"sqlite","status":"yes","note":"3.30+"},{"engine_slug":"oracle","status":"yes","note":"Oracle AI Database 26ai, release update 23.26.1+; SUM(CASE WHEN cond THEN x END) on 23ai and earlier"}],"gotchas":["Rows failing the predicate are excluded from that one aggregate but still counted by the others in the same SELECT.","The CASE fallback works because CASE without ELSE yields NULL and aggregates ignore NULLs, so SUM(CASE WHEN cond THEN x END) equals the FILTER form.","PostgreSQL, SQLite and Oracle 23.26.1+ accept FILTER on window aggregates too: COUNT(*) FILTER (WHERE x > 1) OVER (PARTITION BY g)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT COUNT(*) FILTER (WHERE status = 'open') AS open_count, COUNT(*) FILTER (WHERE status = 'closed') AS closed_count FROM tickets;"},{"engine_slug":"sqlite","sql":"SELECT SUM(amount) FILTER (WHERE kind = 'refund') AS refunds FROM payments;"},{"engine_slug":"all","sql":"SELECT SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open_count, SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) AS closed_count FROM tickets;"}],"faqs":[{"question":"How is FILTER different from WHERE?","answer":"WHERE drops whole rows before grouping; FILTER drops rows from a single aggregate while the group and the other aggregates keep them."},{"question":"Which engines support FILTER?","answer":"PostgreSQL on all aggregates, SQLite since 3.30, and Oracle from release update 23.26.1. MySQL, SQL Server and older Oracle releases need the SUM(CASE WHEN ...) pattern."},{"question":"Can FILTER be used with COUNT(*)?","answer":"Yes: COUNT(*) FILTER (WHERE cond) counts only the rows matching the predicate inside each group."}],"related":["conditional-aggregation","count","sum","case","aggregate-over"],"novel_uses":[{"body":"Divide one FILTER aggregate by the unfiltered one to get a ratio per group; no self-join and no CTE.","sql":"SELECT dept, SUM(amount) FILTER (WHERE paid) * 1.0 / NULLIF(SUM(amount), 0) AS paid_share FROM invoices GROUP BY dept;"},{"body":"AVG(x) FILTER (WHERE x >= 0) drops -1 style sentinel values from the mean while COUNT(*) still counts every row of the group.","sql":"SELECT COUNT(*) AS rows_read, AVG(latency_ms) FILTER (WHERE latency_ms >= 0) AS clean_avg FROM probes;"},{"body":"PostgreSQL accepts FILTER after WITHIN GROUP, so a p90 per kind needs one pass instead of one query per slice.","sql":"SELECT kind, percentile_cont(0.9) WITHIN GROUP (ORDER BY ms) FILTER (WHERE env = 'prod') FROM requests GROUP BY kind;"}]},"source_url":"https://sqlly.app/sql-functions/aggregate-filter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/aggregate-nulls","corpus":"sql-functions","engine":null,"language":"en","title":"SQL aggregates and NULL","description":"SUM, AVG, MIN, MAX and COUNT(col) skip NULLs: COUNT(col) versus COUNT(*), AVG dividing by non-NULL values, SUM returning NULL for an empty group and TOTAL's 0.0 escape.","body":{"slug":"aggregate-nulls","name":"NULL","h1":"SQL aggregates and NULL","category":"aggregate","lede":"How the five engines ignore NULL inside SUM, AVG, COUNT and friends, and what that does to your denominators.","syntax":"COUNT(x) | AVG(x) | SUM(x)","return_type":"integer (COUNT) or numeric (SUM, AVG), typed from the input","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["COUNT(*) counts rows; COUNT(col) counts rows where col is not NULL. The two diverge exactly on NULLs.","AVG and SUM use only non-NULL values, and AVG divides by their count rather than the row count, so NULL rows never dilute the result; wrap the column in COALESCE if you want NULLs to count as zero.","SUM or AVG over an empty or all-NULL group returns NULL, not 0; COUNT returns 0.","A handy side effect: AVG(flag) over 0/1 values is the fraction of 1s among non-NULL rows. On SQL Server AVG of an int column returns an int (0 for one row in three) and AVG of a bit column is an error, so write AVG(1.0 * flag) there."],"examples":[{"engine_slug":"all","sql":"SELECT COUNT(*) AS rows_read, COUNT(shipped_at) AS rows_shipped, AVG(total) AS avg_total FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT SUM(amount), TOTAL(amount) FROM ledger WHERE 0 = 1;"}],"faqs":[{"question":"Why does SUM return NULL for no rows?","answer":"The standard defines aggregates over the empty set as NULL, except COUNT; use COALESCE(SUM(x), 0) or SQLite's TOTAL."},{"question":"Do NULLs lower AVG?","answer":"No: AVG ignores them, dividing by the count of present values only."},{"question":"How do I make NULLs count as zero?","answer":"AVG(COALESCE(x, 0)), or AVG(1.0 * COALESCE(x, 0)) on SQL Server when x is an integer, but decide first whether that is the number you actually want."}],"related":["total","count","avg","sum","coalesce","conditional-aggregation"],"novel_uses":[{"body":"In MySQL and SQLite a comparison yields 1, 0 or NULL, so COUNT(price > 0) counts every row with a price, matched or not; SUM(price > 0) is the count that means it.","sql":"SELECT COUNT(price > 0) AS non_null_prices, SUM(price > 0) AS actually_over_zero FROM products;"},{"body":"COUNT over COUNT(*) is a completeness score per column in one row of output, the number that decides whether to backfill or drop the column.","sql":"SELECT 100.0 * COUNT(email) / NULLIF(COUNT(*), 0) AS email_fill, 100.0 * COUNT(phone) / NULLIF(COUNT(*), 0) AS phone_fill FROM users;"}]},"source_url":"https://sqlly.app/sql-functions/aggregate-nulls","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/aggregate-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL aggregate functions with OVER","description":"COUNT, SUM, AVG, MIN and MAX over a window: group-level totals on every row without collapsing the result set.","body":{"slug":"aggregate-over","name":"Aggregates with OVER","h1":"SQL aggregate functions with OVER","category":"window","lede":"Most aggregate functions gain an OVER clause to become a window aggregate: the rows stay, and each one carries the aggregate of its frame or partition. Some, such as GROUP_CONCAT and STRING_AGG, are rejected with OVER; see the FAQ.","syntax":"SUM(x) OVER (PARTITION BY g) | COUNT(*) OVER ()","return_type":"type of the aggregate","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+; only some aggregates (COUNT, SUM, AVG, MIN, MAX, STDDEV, VARIANCE, BIT_*, JSON aggregates) work as windows"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; all built-in aggregates including group_concat work"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Aggregates in the same SELECT as GROUP BY run over the groups, not the rows: SUM(SUM(x)) OVER () is the legal way to total group sums, a frequent 'invalid column' confusion. SQLite raises no error for it: the bare column returns a value from one row of each group.","The empty OVER () means the whole result set: COUNT(*) OVER () is the total row count on every row, useful for ratios and progress bars.","FILTER (WHERE ...) after the aggregate is the clean conditional form on PostgreSQL, SQLite 3.30+ and Oracle 23.26.1+; on SQL Server and MySQL put a CASE inside the aggregate."],"examples":[{"engine_slug":"all","sql":"SELECT department, salary,\n       SUM(salary) OVER (PARTITION BY department) AS dept_total,\n       AVG(salary) OVER (PARTITION BY department) AS dept_avg\nFROM employees;"},{"engine_slug":"all","sql":"SELECT order_id, amount,\n       amount * 100.0 / SUM(amount) OVER () AS pct_of_revenue\nFROM orders;"}],"faqs":[{"question":"Why use SUM OVER instead of GROUP BY?","answer":"GROUP BY collapses to one row per group; SUM OVER stamps the group total on every row. They can even coexist: with GROUP BY in the query, window aggregates run over the grouped results."},{"question":"Which aggregates can be window functions?","answer":"Nearly every built-in aggregate on PostgreSQL, Oracle and SQLite (PostgreSQL excludes ordered-set aggregates such as PERCENTILE_CONT). SQL Server allows the numeric ones but not STRING_AGG. MySQL allows COUNT, SUM, AVG, MIN, MAX, the STDDEV/VARIANCE family, BIT_* and the JSON aggregates, but not GROUP_CONCAT."}],"related":["count-over","sum-over","window-vs-group-by"],"novel_uses":[{"body":"Divide two window sums and every row carries its group's weighted average: SUM(amount * units) OVER (PARTITION BY region) divided by SUM(units) OVER (PARTITION BY region). A plain AVG prices a 1-unit sale the same as a 1000-unit sale.","sql":"SELECT region, amount, units,\n       SUM(amount * units) OVER (PARTITION BY region) * 1.0\n         / NULLIF(SUM(units) OVER (PARTITION BY region), 0) AS weighted_price\nFROM sales;"},{"body":"The grand total minus the partition total is the rest of the company, computed beside each row with two windows. Comparing a department to everyone else beats comparing it to an average that includes itself.","sql":"SELECT department, salary,\n       SUM(salary) OVER () - SUM(salary) OVER (PARTITION BY department) AS everyone_else\nFROM employees;"}]},"source_url":"https://sqlly.app/sql-functions/aggregate-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/aggregate-over-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL aggregates with OVER window","description":"SUM, AVG, COUNT and friends gain row-level detail with OVER: window aggregates keep every row, default frames include peers, and ROWS beats RANGE for running totals.","body":{"slug":"aggregate-over-window","name":"OVER","h1":"SQL aggregates with OVER window","category":"aggregate","lede":"Window aggregates compute a group statistic but hand it to every row instead of collapsing the group.","syntax":"SUM(x) OVER (PARTITION BY g) | SUM(x) OVER (ORDER BY d)","return_type":"same as the aggregate","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Unlike GROUP BY, the window form never collapses rows: detail and total sit side by side.","With ORDER BY in the OVER clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so rows with tied ORDER BY values all get the same total; use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a strict running total.","PARTITION BY without ORDER BY gives the group total on every row of the partition.","SUM over an all-NULL window returns NULL, not 0."],"examples":[{"engine_slug":"all","sql":"SELECT order_id, SUM(total) OVER (PARTITION BY customer_id) AS lifetime FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT order_id, SUM(total) OVER (ORDER BY order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT AVG(total) OVER (PARTITION BY customer_id) AS avg_order FROM orders;"}],"faqs":[{"question":"OVER vs GROUP BY for SUM?","answer":"GROUP BY returns one row per group; OVER keeps every row and annotates it with the group statistic."},{"question":"Why does my running total jump?","answer":"The default RANGE frame includes peer rows with equal ORDER BY values; switch to ROWS for one-row-at-a-time totals."},{"question":"Do NULLs count in window aggregates?","answer":"The same rules as plain aggregates: NULLs are skipped and an all-NULL window returns NULL for SUM and AVG."}],"related":["aggregate-filter","sum","row-number","lag","first-value"],"novel_uses":[{"body":"Divide the row by the window total for each region's percentage in one pass; the 1.0 prefix keeps integer division from flattening it to 0 on SQL Server, PostgreSQL and SQLite.","sql":"SELECT order_id, amount, 1.0 * amount / SUM(amount) OVER (PARTITION BY region) AS share FROM orders;"},{"body":"Subtract the window average to score every row against its own region without a self-join, the first step of any outlier list; the 1.0 factor stops SQL Server from truncating AVG of an integer column.","sql":"SELECT order_id, amount - AVG(1.0 * amount) OVER (PARTITION BY region) AS vs_region FROM orders;"},{"body":"Windows are illegal in WHERE on every engine, so compute the average in a derived table and filter outside it.","sql":"SELECT * FROM (SELECT region, amount, AVG(amount) OVER (PARTITION BY region) AS region_avg FROM orders) w WHERE amount > region_avg;"}]},"source_url":"https://sqlly.app/sql-functions/aggregate-over-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/all","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ALL operator","description":"ALL quantifies a comparison against every row of a subquery: x > ALL (subquery), when it equals a MAX comparison, NULL and empty-set pitfalls, engine support.","body":{"slug":"all","name":"ALL","h1":"SQL ALL operator","category":"conditional","lede":"True when the comparison holds for every element of the list or subquery.","syntax":"x > ALL (subquery) | x <> ALL (subquery)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"subqueries only"},{"engine_slug":"postgresql","status":"yes","note":"subqueries and arrays"},{"engine_slug":"mysql","status":"partial","note":"subqueries only"},{"engine_slug":"sqlite","status":"no","note":"no ALL; use NOT EXISTS or a MAX/MIN subquery"},{"engine_slug":"oracle","status":"yes","note":"subqueries and literal lists"}],"gotchas":["x > ALL (subquery) equals x > (SELECT MAX(...)) only when the subquery returns at least one row and no NULLs. On an empty subquery ALL is TRUE while the MAX comparison is UNKNOWN.","x <> ALL (list) is the same as NOT IN: one NULL in the subquery empties your result set.","An empty subquery makes ALL vacuously true (and ANY false), so a broken subquery can silently pass every row."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'budget');"},{"engine_slug":"oracle","sql":"SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'budget');"},{"engine_slug":"sql-server","sql":"SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'budget');"},{"engine_slug":"mysql","sql":"SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'budget');"}],"faqs":[{"question":"ALL vs MAX?","answer":"x > ALL (SELECT y FROM t) matches x > (SELECT MAX(y) FROM t) when t has rows and y has no NULLs. On an empty t the ALL form keeps every row and the MAX form keeps none."},{"question":"What does ALL return for an empty subquery?","answer":"TRUE. Vacuously, every (zero) comparison passed. ANY returns FALSE for the same input."},{"question":"Why did <> ALL return nothing?","answer":"A NULL in the subquery: NOT IN's trap. Filter the NULLs or use NOT EXISTS."}],"related":["any","not-in","in","exists","max"],"novel_uses":[{"body":"price < ALL (subquery) is the strictly-cheapest test; guard it with EXISTS because an empty competitor list makes ALL vacuously true and every row pass.","sql":"SELECT * FROM products p WHERE EXISTS (SELECT 1 FROM competitor_prices c WHERE c.sku = p.sku) AND p.price < ALL (SELECT c.price FROM competitor_prices c WHERE c.sku = p.sku);"},{"body":"Oracle takes literals directly after ALL, so a floor check against a fixed set needs no subquery.","sql":"SELECT * FROM inventory WHERE stock > ALL (0, 5);"}]},"source_url":"https://sqlly.app/sql-functions/all","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/any","corpus":"sql-functions","engine":null,"language":"en","title":"SQL =ANY operator","description":"=ANY matches a value against a subquery, list or array: subquery support in four engines, PostgreSQL arrays, Oracle literal lists, and the <> ANY trap.","body":{"slug":"any","name":"ANY","h1":"SQL =ANY operator","category":"conditional","lede":"True when the comparison holds for at least one element of the list, array or subquery.","syntax":"x = ANY (subquery) | x = ANY (ARRAY[...]) | x = SOME (...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"subqueries only: x = ANY (SELECT ...)"},{"engine_slug":"postgresql","status":"yes","note":"= ANY works on arrays and subqueries"},{"engine_slug":"mysql","status":"partial","note":"subqueries only: x = ANY (SELECT ...)"},{"engine_slug":"sqlite","status":"no","note":"no ANY/SOME/ALL; use IN or EXISTS"},{"engine_slug":"oracle","status":"yes","note":"subqueries and literal lists: x = ANY (1, 2)"}],"gotchas":["x <> ANY (list) is almost never what you want: it is true when at least one element differs, which is nearly always. You probably meant NOT IN or <> ALL.","= ANY handles NULL members exactly like IN: a match is TRUE, but no match with a NULL present is UNKNOWN rather than FALSE.","In PostgreSQL, a constant IN (1, 2, 3) list is planned as = ANY ('{1,2,3}'), but = ANY itself takes only an array or a subquery, never a bare list; the array form also accepts one bound parameter for a whole array.","SQL Server and MySQL accept ANY, SOME and ALL only in front of a subquery; x = ANY (1, 2) is a syntax error there, so use IN for literal lists."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM orders WHERE id = ANY(ARRAY[1, 3, 7]);"},{"engine_slug":"oracle","sql":"SELECT * FROM orders WHERE id = ANY (SELECT id FROM big_orders);"},{"engine_slug":"sql-server","sql":"SELECT * FROM orders WHERE total = ANY (SELECT total FROM flagged_orders);"},{"engine_slug":"mysql","sql":"SELECT * FROM orders WHERE total = ANY (SELECT total FROM flagged_orders);"}],"faqs":[{"question":"ANY vs IN?","answer":"x IN (subquery) is defined as x = ANY (subquery) on every engine that has ANY. ANY also works with other operators (> ANY, < ANY), and in PostgreSQL with arrays."},{"question":"Why does x <> ANY (...) surprise me?","answer":"It is true whenever x differs from at least one element, so x = 1 still passes against the values 1 and 2. For 'different from every element' use <> ALL or NOT IN."},{"question":"What does =ANY do with NULLs in the list?","answer":"One matching element is enough: TRUE OR UNKNOWN is TRUE, so the row is kept. With no match and a NULL present the result is UNKNOWN, so the row is dropped, and NOT (x = ANY ...) drops it too."}],"related":["all","in","not-in","exists","distinct-from"],"novel_uses":[{"body":"> ANY keeps products priced above at least one competitor, so someone undercuts them; the strictly-cheapest test flips the operator as well as the quantifier: price < ALL (subquery).","sql":"SELECT * FROM products WHERE price > ANY (SELECT price FROM competitor_prices);"},{"body":"PostgreSQL feeds an entire id list through one bound array parameter, which keeps the plan cache intact on repeated IN-style lookups.","sql":"SELECT * FROM orders WHERE id = ANY($1::bigint[]);"}]},"source_url":"https://sqlly.app/sql-functions/any","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/any-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ANY_VALUE function","description":"ANY_VALUE picks an arbitrary value from the group and silences strict GROUP BY checks: MySQL's ONLY_FULL_GROUP_BY, PostgreSQL 16+, Oracle 19c+, NULL differences.","body":{"slug":"any-value","name":"ANY_VALUE","h1":"SQL ANY_VALUE function","category":"aggregate","lede":"Returns one arbitrary value from the group, bypassing full GROUP BY validation.","syntax":"ANY_VALUE(x)","return_type":"same as input","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 16+"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"19c+"}],"gotchas":["The engine picks the value: it is arbitrary and can differ between runs, so never build logic on which row it came from.","MySQL added it to escape ONLY_FULL_GROUP_BY errors; PostgreSQL 16 and Oracle 19c+ followed.","PostgreSQL and Oracle skip NULLs and return NULL only for an all-NULL group. MySQL's ANY_VALUE is not a real aggregate: it can return NULL even when the group has a non-NULL value.","Older engines: MIN(x), MAX(x), a window FIRST_VALUE, or PostgreSQL's DISTINCT ON."],"examples":[{"engine_slug":"mysql","sql":"SELECT customer_id, ANY_VALUE(region) FROM orders GROUP BY customer_id;"},{"engine_slug":"postgresql","sql":"SELECT customer_id, any_value(region) FROM orders GROUP BY customer_id;"},{"engine_slug":"oracle","sql":"SELECT customer_id, ANY_VALUE(region) FROM orders GROUP BY customer_id;"}],"faqs":[{"question":"Is ANY_VALUE deterministic?","answer":"No. It returns some value from the group; which one is not guaranteed. SQL Server has no ANY_VALUE; use MIN or MAX there."},{"question":"What is ONLY_FULL_GROUP_BY?","answer":"MySQL's mode of rejecting selected columns that are neither grouped nor aggregated; ANY_VALUE declares one column exempt."},{"question":"What replaces it on PostgreSQL 15 or older?","answer":"MIN, MAX, FIRST_VALUE over a partition, or DISTINCT ON."}],"related":["aggregate-nulls","min","max","grouping"],"novel_uses":[{"body":"MySQL: when region is fixed per customer but no primary or unique key says so, ANY_VALUE(region) states that knowledge and keeps ONLY_FULL_GROUP_BY enforcing everything else.","sql":"SELECT customer_id, ANY_VALUE(region) FROM orders GROUP BY customer_id;"},{"body":"One attribute per user falls out of a plain GROUP BY, handy for a quick audit when the row it comes from does not matter.","sql":"SELECT user_id, ANY_VALUE(email) FROM logins GROUP BY user_id;"}]},"source_url":"https://sqlly.app/sql-functions/any-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/approx-count-distinct","corpus":"sql-functions","engine":null,"language":"en","title":"SQL APPROX_COUNT_DISTINCT function","description":"APPROX_COUNT_DISTINCT counts uniques with a small error bound: SQL Server 2019+ and Oracle 12c+ support, when to trust it, and the exact COUNT(DISTINCT) fallback.","body":{"slug":"approx-count-distinct","name":"APPROX_COUNT_DISTINCT","h1":"SQL APPROX_COUNT_DISTINCT function","category":"aggregate","lede":"Counts distinct values with bounded error and fixed memory instead of exact counting.","syntax":"APPROX_COUNT_DISTINCT(x)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":"about 2% error guarantee, since SQL Server 2019"},{"engine_slug":"postgresql","status":"no","note":"no built-in; the HLL extension fills the gap"},{"engine_slug":"mysql","status":"no","note":"no built-in; use COUNT(DISTINCT)"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"12.1.0.2+"}],"gotchas":["The SQL Server guarantee is statistical: 97% of results land within 2% of the true count, never a promise of exactness.","It streams with constant memory, which is why it wins on huge, high-cardinality sets where COUNT(DISTINCT) spills or times out.","PostgreSQL has no built-in; HyperLogLog extensions or sampling fill the gap.","Never use it for billing, deduplication or anything a user will check by hand."],"examples":[{"engine_slug":"sql-server","sql":"SELECT APPROX_COUNT_DISTINCT(visitor_id) FROM hits WHERE day = '2026-11-19';"},{"engine_slug":"oracle","sql":"SELECT APPROX_COUNT_DISTINCT(session_id) FROM events;"}],"faqs":[{"question":"How accurate is APPROX_COUNT_DISTINCT?","answer":"SQL Server guarantees about 2% error with 97% probability; Oracle is similar in spirit but treat both as estimates."},{"question":"Why is it faster than COUNT(DISTINCT)?","answer":"It never builds the full distinct set: fixed-memory sketches replace the sort or hash of every value."},{"question":"Does PostgreSQL have it?","answer":"Not built-in; use a HyperLogLog extension or accept exact COUNT(DISTINCT)."}],"related":["count-distinct","count","aggregate-nulls","distinct-aggregates"],"novel_uses":[{"body":"Rows per distinct key is a skew number: near 1 means almost every row is a new value, far above 1 means a few users dominate the table.","sql":"SELECT COUNT(*) * 1.0 / NULLIF(APPROX_COUNT_DISTINCT(user_id), 0) AS rows_per_user FROM hits;"},{"body":"A sketch of this kind holds its error steady across runs, so a trend chart of daily distincts stays readable while the query stays cheap; leave exact numbers to the billing path.","sql":"SELECT day, APPROX_COUNT_DISTINCT(session_id) FROM events GROUP BY day;"}]},"source_url":"https://sqlly.app/sql-functions/approx-count-distinct","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/approx-percentile-cont","corpus":"sql-functions","engine":null,"language":"en","title":"SQL APPROX_PERCENTILE_CONT function","description":"SQL Server 2022's APPROX_PERCENTILE_CONT and _DISC and Oracle's APPROX_PERCENTILE estimate medians and p95 from a sketch, trading a small error for speed and memory.","body":{"slug":"approx-percentile-cont","name":"APPROX_PERCENTILE_CONT","h1":"SQL APPROX_PERCENTILE_CONT function","category":"aggregate","lede":"Exact percentiles sort the whole group. The approximate versions build a small sketch instead, so a p95 over a billion rows needs far less memory.","syntax":"APPROX_PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY expr)","return_type":"float","support":[{"engine_slug":"sql-server","status":"yes","note":"APPROX_PERCENTILE_CONT and APPROX_PERCENTILE_DISC, 2022+"},{"engine_slug":"postgresql","status":"no","note":"no; exact percentile_cont, or an extension such as tdigest"},{"engine_slug":"mysql","status":"no","note":"no percentile aggregates"},{"engine_slug":"sqlite","status":"no","note":"no approximate version; 3.47+ adds exact median, percentile_cont and percentile_disc through the percentile extension, which the sqlite3 CLI includes"},{"engine_slug":"oracle","status":"partial","note":"APPROX_PERCENTILE(p) WITHIN GROUP (ORDER BY x) from 12.2; add DETERMINISTIC for repeatable results"}],"gotchas":["SQL Server builds a KLL sketch, a randomized algorithm: Microsoft documents a rank-based error of up to 1.33% at 99% confidence, and results can differ between runs.","It is a plain aggregate with GROUP BY. SQL Server's exact PERCENTILE_CONT needs an OVER clause instead.","On small groups the estimate is usually exact, so tests on toy data will not show the approximation."],"examples":[{"engine_slug":"sql-server","sql":"SELECT APPROX_PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) AS median_cont,\n       APPROX_PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) AS median_disc\nFROM (VALUES (1), (2), (3), (4)) AS t(x);  -- 2.5, 2"},{"engine_slug":"sql-server","sql":"SELECT g, APPROX_PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY x) AS p95\nFROM (VALUES ('a', 1), ('a', 9), ('b', 5)) AS t(g, x)\nGROUP BY g;"},{"engine_slug":"oracle","sql":"SELECT APPROX_PERCENTILE(0.5 DETERMINISTIC) WITHIN GROUP (ORDER BY x) AS median\nFROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 4);  -- 2"}],"faqs":[{"question":"When should I use the approximate version?","answer":"For dashboards and monitoring over large tables, where a rank error of up to 1.33% is acceptable. Use PERCENTILE_CONT when the number must match a report exactly."},{"question":"What does PostgreSQL offer?","answer":"Exact percentile_cont and percentile_disc as ordered-set aggregates with GROUP BY. Approximate percentiles need an extension."}],"related":["percentile-cont","percentile-disc","median","approx-count-distinct"],"novel_uses":[{"body":"The approximate pass can narrow where the tail starts, but its p99 is not a safe cutoff: the estimate lands on either side of the true value from run to run, and PERCENTILE_CONT(0.99) over the filtered rows is the p99 of those rows, not of the table. Take a lower bound with room for the 1.33% rank error, count the rows below it, and rescale the fraction so the exact PERCENTILE_CONT over the small remainder lands on the table's p99. The expensive sort touches a sliver of the data.","sql":"DECLARE @lo float, @n bigint;\nSELECT @lo = APPROX_PERCENTILE_CONT(0.97) WITHIN GROUP (ORDER BY x), @n = COUNT_BIG(x)\nFROM events;  -- 0.97 leaves room for the rank error\nDECLARE @below bigint = (SELECT COUNT_BIG(*) FROM events WHERE x < @lo),\n        @m bigint = (SELECT COUNT_BIG(*) FROM events WHERE x >= @lo);\nSELECT DISTINCT PERCENTILE_CONT((0.99 * (@n - 1) - @below) / (@m - 1))\n       WITHIN GROUP (ORDER BY x) OVER () AS exact_p99\nFROM events\nWHERE x >= @lo;"},{"body":"The KLL sketch holds a bounded number of values per group, so the aggregate flows through memory in one pass. Exact PERCENTILE_CONT must materialize and sort the whole group before it can answer, which is the cost the sketch avoids on wide groups.","sql":null}]},"source_url":"https://sqlly.app/sql-functions/approx-percentile-cont","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/arithmetic-operators","corpus":"sql-functions","engine":null,"language":"en","title":"SQL arithmetic operators","description":"The four basic operators: NULL propagation everywhere, / truncating integers on three engines but not MySQL or Oracle, type promotion, and overflow.","body":{"slug":"arithmetic-operators","name":"+ - * /","h1":"SQL arithmetic operators","category":"math","lede":"Adds, subtracts, multiplies and divides. A NULL operand makes the result NULL, and 7 / 2 is 3 on SQL Server, PostgreSQL and SQLite but 3.5 on MySQL and Oracle.","syntax":"a + b  |  a - b  |  a * b  |  a / b","return_type":"depends on operand types","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Any NULL operand makes the whole expression NULL: 5 + NULL is NULL, not 5. Wrap with COALESCE when zero is the intent.","Integer / integer truncates on SQL Server, PostgreSQL and SQLite: 7 / 2 is 3. MySQL returns 3.5000 and Oracle 3.5. Multiply one side by 1.0 to get the fraction everywhere.","Type promotion decides the result type: int + decimal is decimal, decimal + float is float, so the same expression can be exact on one column and lossy on another. SQLite has no decimal type, so both come out REAL there."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 7 + 2 AS nine, 7 / 2 AS truncated, 7 / 2.0 AS exact;  -- 9, 3, 3.5000000000000000"},{"engine_slug":"mysql","sql":"SELECT 7 / 2 AS not_truncated, 7 DIV 2 AS truncated;  -- 3.5000, 3"},{"engine_slug":"all","sql":"SELECT 5 + NULL AS null_result;  -- NULL"},{"engine_slug":"sql-server","sql":"DECLARE @discount decimal(4, 2) = 0.10;\nSELECT price * quantity * (1 - @discount) AS net\nFROM order_items;"},{"engine_slug":"oracle","sql":"SELECT 7 / 2 AS not_truncated FROM dual;  -- 3.5: Oracle / never truncates"}],"faqs":[{"question":"What does 5 + NULL return in SQL?","answer":"NULL. Arithmetic with any NULL operand yields NULL on every engine: the value is unknown, so the sum is unknown. Use COALESCE(x, 0) when a zero default is what you mean."},{"question":"Why does 7 / 2 give 3?","answer":"On SQL Server, PostgreSQL and SQLite, two integer operands mean integer division, which truncates. 7 / 2.0 produces 3.5, and so does CASTing one side to a decimal type on SQL Server and PostgreSQL. On SQLite use CAST(x AS REAL), because CAST(x AS DECIMAL) still truncates there. MySQL and Oracle already return 3.5 for 7 / 2."},{"question":"Do operators overflow the same way everywhere?","answer":"No. SQL Server and PostgreSQL raise an error when INT arithmetic passes 2147483647. MySQL computes integer expressions in 64 bits and errors only past BIGINT. SQLite promotes to float past the 64-bit range. Oracle NUMBER errors only past about 1e126."}],"related":["integer-division","null-arithmetic","integer-overflow","operator-precedence"],"novel_uses":[{"body":"SQLite has no decimal type, so sums like 0.1 + 0.2 drift in REAL. Storing cents as INTEGER and dividing by 100.0 only for display keeps totals exact to the cent.","sql":"SELECT SUM(cents) / 100.0 AS total FROM ledger;"},{"body":"COALESCE(bonus, 0) + salary treats a missing bonus as zero, while COALESCE(bonus + salary, 0) turns the whole total into 0 when either side is missing. Moving one call changes which rows show 0 and which show NULL.","sql":"SELECT COALESCE(bonus, 0) + salary AS with_zero_bonus, COALESCE(bonus + salary, 0) AS any_missing_becomes_0 FROM pay;"},{"body":"int * int can overflow before a later cast helps: CAST one operand to BIGINT or DECIMAL first and the whole chain computes wide. The cast has to come first, not after the overflow.","sql":"SELECT CAST(qty AS BIGINT) * price AS safe_total FROM order_lines;"}]},"source_url":"https://sqlly.app/sql-functions/arithmetic-operators","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-agg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ARRAY_AGG function","description":"ARRAY_AGG collects a group's values into an array in PostgreSQL, with JSON array aggregates standing in on SQL Server, MySQL, SQLite and Oracle.","body":{"slug":"array-agg","name":"ARRAY_AGG","h1":"SQL ARRAY_AGG function","category":"aggregate","lede":"Gathers every value of a group into one array, in the order you choose. Unlike STRING_AGG you get typed elements you can index, unnest or turn into JSON.","syntax":"ARRAY_AGG(expression ORDER BY ...)  -- PostgreSQL","return_type":"array of the expression's type","support":[{"engine_slug":"sql-server","status":"no","note":"no array type; STRING_AGG, or JSON_ARRAYAGG on SQL Server 2025 and Azure SQL"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no array type; JSON_ARRAYAGG returns a JSON array"},{"engine_slug":"sqlite","status":"no","note":"no array type; json_group_array returns a JSON array"},{"engine_slug":"oracle","status":"no","note":"no ARRAY_AGG; JSON_ARRAYAGG (12.2+) or COLLECT into a collection type"}],"gotchas":["ARRAY_AGG returns NULL for an empty group. Wrap it in COALESCE(ARRAY_AGG(x), '{}') when you need an empty array.","NULL values are kept as elements: two NULL rows give {NULL,NULL}. Add FILTER (WHERE x IS NOT NULL) to drop them.","Without ORDER BY inside the call the element order is whatever order the rows arrived in. Write ARRAY_AGG(product ORDER BY product) when order matters."],"examples":[{"engine_slug":"postgresql","sql":"SELECT customer_id,\n       ARRAY_AGG(product ORDER BY product) AS basket\nFROM order_items\nGROUP BY customer_id;"},{"engine_slug":"postgresql","sql":"-- and back to one row per element\nWITH baskets AS (\n  SELECT customer_id, ARRAY_AGG(product) AS basket\n  FROM order_items GROUP BY customer_id\n)\nSELECT customer_id, unnest(basket) AS product FROM baskets;"}],"faqs":[{"question":"Does SQL Server have ARRAY_AGG?","answer":"No. SQL Server has no array type. STRING_AGG builds delimited text, FOR JSON builds JSON from a query, and SQL Server 2025 adds JSON_ARRAYAGG."},{"question":"How do I get an array in MySQL or SQLite?","answer":"Neither has arrays. MySQL's JSON_ARRAYAGG and SQLite's json_group_array both collect values into a JSON array, which covers most of the same ground."}],"related":["string-agg","row-number","concat"],"novel_uses":[{"body":"ARRAY_AGG(DISTINCT category ORDER BY category) dedupes and sorts in a single step, giving set semantics with no subquery. PostgreSQL requires the ORDER BY expression to match the DISTINCT argument.","sql":"SELECT customer_id,\n       ARRAY_AGG(DISTINCT category ORDER BY category) AS categories_bought\nFROM order_items\nGROUP BY customer_id;"},{"body":"The array is a value, so it can be grouped and joined on like any scalar. Bucketing customers by their sorted category list answers who buys the same things in two levels of grouping.","sql":"WITH baskets AS (\n  SELECT customer_id,\n         ARRAY_AGG(DISTINCT category ORDER BY category) AS cats\n  FROM order_items GROUP BY customer_id\n)\nSELECT cats, COUNT(*) AS customers\nFROM baskets\nGROUP BY cats;"}]},"source_url":"https://sqlly.app/sql-functions/array-agg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-append","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ARRAY_APPEND function","description":"Growing arrays on PostgreSQL: ARRAY_APPEND, ARRAY_PREPEND and ARRAY_CAT, the overloaded || operator, and the untyped-literal error that || throws.","body":{"slug":"array-append","name":"ARRAY_APPEND","h1":"SQL ARRAY_APPEND function","category":"conversion","lede":"array_append(tags, 'sql') returns the array with one more element. The || operator does the same, but an untyped string literal on its right is read as an array.","syntax":"ARRAY_APPEND(array, element)  |  array || element  |  array || array","return_type":"array","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"array_append, array_prepend, array_cat, ||"},{"engine_slug":"mysql","status":"no","note":"no array type; JSON_ARRAY_APPEND for JSON"},{"engine_slug":"sqlite","status":"no","note":"no array type; json functions for JSON"},{"engine_slug":"oracle","status":"no","note":"collection procedures in PL/SQL, not SQL functions"}],"gotchas":["|| is overloaded: array || element appends, array || array concatenates, element || array prepends. With an untyped literal, PostgreSQL tries the array form: tags || 'db' fails with 'malformed array literal: \"db\"'. Write tags || 'db'::text or use array_append.","An append rewrites the full array value on every UPDATE, and a jsonb column rewrites its whole value the same way; append-heavy workloads on wide arrays behave better as a child table with one row per element.","A NULL array is treated as empty here: array_append(NULL::text[], 'a') is {a}, and so is NULL::text[] || 'a'::text. That differs from most SQL functions, where NULL in means NULL out."],"examples":[{"engine_slug":"postgresql","sql":"UPDATE articles\nSET tags = array_append(tags, 'sql');"},{"engine_slug":"postgresql","sql":"UPDATE articles SET tags = tags || 'db'::text;"},{"engine_slug":"postgresql","sql":"SELECT ARRAY_CAT(ARRAY['a'], ARRAY['b']) AS both;"}],"faqs":[{"question":"How do I prepend instead?","answer":"array_prepend(x, a), or the reversed ||: x || a puts the scalar in front. The function names are unambiguous; the operator's meaning depends on side."},{"question":"Why does tags || 'db' say malformed array literal?","answer":"The literal 'db' has no type yet, and PostgreSQL resolves it as text[] to match the array || array operator. Cast it, 'db'::text, or call array_append(tags, 'db')."}],"related":["array-to-string","unnest","array-contains","json-set"],"novel_uses":[{"body":"Guard with a membership test and the append becomes set-like: UPDATE ... SET tags = array_append(tags, 'sql') WHERE tags IS NULL OR NOT ('sql' = ANY(tags)) never grows duplicates, no matter how often the job reruns. The IS NULL branch matters: 'sql' = ANY(NULL) is NULL, so without it rows whose array is NULL are silently skipped.","sql":"UPDATE articles SET tags = array_append(tags, 'sql')\nWHERE tags IS NULL OR NOT ('sql' = ANY(tags));"},{"body":"array_agg the rows you want, then || them on: tags = tags || (SELECT COALESCE(array_agg(t), '{}') FROM staged_tags WHERE article_id = a.id). One UPDATE replaces a read-modify-write loop.","sql":"UPDATE articles a SET tags = a.tags || (SELECT COALESCE(array_agg(t.name), '{}') FROM staged_tags t WHERE t.article_id = a.id);"}]},"source_url":"https://sqlly.app/sql-functions/array-append","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-contains","corpus":"sql-functions","engine":null,"language":"en","title":"SQL array membership tests","description":"PostgreSQL's ANY and @> test membership in real arrays, Oracle's MEMBER OF for collections, MySQL's MEMBER OF for JSON arrays, and the json_each shape SQLite needs.","body":{"slug":"array-contains","name":"Array contains","h1":"SQL array membership tests","category":"conversion","lede":"WHERE 'sql' = ANY(tags) tests whether a PostgreSQL array contains a value without unnesting it. Its negation is not != ANY, which is the usual mistake.","syntax":"value = ANY(array)  |  array @> array  -- PostgreSQL  |  value MEMBER OF (collection)  -- Oracle","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"no array type; EXISTS over OPENJSON"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"no array type; MEMBER OF or JSON_CONTAINS over JSON arrays"},{"engine_slug":"sqlite","status":"partial","note":"EXISTS over json_each"},{"engine_slug":"oracle","status":"partial","note":"MEMBER OF condition over nested tables"}],"gotchas":["x != ANY(arr) means 'not equal to at least one element' and is true for most arrays. The correct no-match test is NOT (x = ANY(arr)) or x != ALL(arr).","tags @> ARRAY['sql', 'db'] requires every listed element; tags && ARRAY['sql', 'db'] requires at least one. A GIN index on the array column serves @>, <@ and &&.","SQLite and MySQL hold lists in JSON or delimited text. SQLite tests a JSON array with EXISTS (SELECT 1 FROM json_each(tags) WHERE value = 'sql'); MySQL has no json_each and uses 'sql' MEMBER OF (tags) or JSON_CONTAINS(tags, '\"sql\"') instead."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM articles WHERE 'sql' = ANY(tags);"},{"engine_slug":"postgresql","sql":"SELECT * FROM articles\nWHERE tags @> ARRAY['sql', 'db'];"},{"engine_slug":"mysql","sql":"SELECT * FROM articles WHERE 'sql' MEMBER OF (tags);"},{"engine_slug":"oracle","sql":"SELECT * FROM articles WHERE 'sql' MEMBER OF (tags);"},{"engine_slug":"sqlite","sql":"SELECT * FROM articles WHERE EXISTS\n  (SELECT 1 FROM json_each(tags) WHERE value = 'sql');"}],"faqs":[{"question":"Why does != ANY return true?","answer":"It is read as 'some element differs', which is almost always true. Negate the positive test, NOT ('sql' = ANY(tags)), or use != ALL for 'differs from every element'."},{"question":"How do I index array membership?","answer":"Create a GIN index on the array column and write the test as tags @> ARRAY['sql']. The planner does not use a GIN index for 'sql' = ANY(tags), so the two spellings can have very different plans."}],"related":["json-contains","jsonb-contains","unnest","cardinality"],"novel_uses":[{"body":"= ANY(ARRAY(SELECT ...)) tests membership against a computed set and returns the same rows as IN (SELECT ...). The difference is that ANY takes one array value, so the same test also works with a bound array parameter, = ANY($1).","sql":"SELECT id FROM accounts WHERE id = ANY(ARRAY(SELECT owner_id FROM admins));"},{"body":"A self-join on tags && tags lists articles that share at least one tag, the overlap test behind related-content queries. The a.id < b.id guard keeps each pair once.","sql":"SELECT a.id, b.id FROM articles a JOIN articles b ON a.tags && b.tags AND a.id < b.id;"}]},"source_url":"https://sqlly.app/sql-functions/array-contains","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-index","corpus":"sql-functions","engine":null,"language":"en","title":"SQL array subscripting","description":"Reading the nth element: 1-based subscripts on PostgreSQL arrays, 0-based JSON paths on MySQL, SQL Server and SQLite, and how each engine reaches the last element.","body":{"slug":"array-index","name":"Array indexing","h1":"SQL array subscripting","category":"conversion","lede":"tags[1] on a PostgreSQL array and '$[0]' in a JSON path both mean the first element. Out-of-range reads return NULL rather than an error, except under a strict JSON path on SQL Server.","syntax":"array[subscript]  -- PostgreSQL, 1-based  |  json_path '$[i]'  -- JSON, 0-based","return_type":"element type","support":[{"engine_slug":"sql-server","status":"partial","note":"JSON paths only: JSON_VALUE(config, '$.tags[0]')"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"no array subscripts in SQL over collections; use TABLE() and rownum"}],"gotchas":["PostgreSQL arrays are 1-based: tags[1] is the first element and tags[0] is NULL. JSON paths on MySQL, SQL Server and SQLite are 0-based: '$[0]' is first. Same data, two conventions.","Out-of-range array subscripts return NULL on PostgreSQL instead of erroring; writing beyond the current end pads with NULLs up to the index.","Last element: tags[array_upper(tags, 1)] on PostgreSQL arrays, data->-1 on PostgreSQL jsonb, '$[last]' on MySQL, '$[#-1]' on SQLite, and on SQL Server 2022 a path built from the OPENJSON count minus one. '$[-1]' is an invalid path on MySQL and SQLite, and arr[-1] on a PostgreSQL array is just NULL."],"examples":[{"engine_slug":"postgresql","sql":"SELECT tags[1] AS first_tag FROM articles;"},{"engine_slug":"mysql","sql":"SELECT config->>'$.tags[0]' AS first_tag FROM settings;"},{"engine_slug":"sqlite","sql":"SELECT json_extract(payload, '$.items[0]') AS first_item\nFROM events;"},{"engine_slug":"sql-server","sql":"SELECT JSON_VALUE(config, '$.tags[0]') AS first_tag\nFROM settings;"}],"faqs":[{"question":"Why is arr[0] NULL?","answer":"PostgreSQL arrays start at 1. The first element is arr[1]; index 0 sits below the lower bound and reads as NULL rather than erroring."},{"question":"Which indexing does my JSON use?","answer":"Zero-based, always, in the JSON path of MySQL, SQL Server and SQLite, even though PostgreSQL array columns are 1-based. Check the type before writing the subscript."}],"related":["array-length","json-extract","unnest","json-path-operator"],"novel_uses":[{"body":"tags[1:3] returns the first three elements as a smaller array, a preview or a page of the list without unnesting. Bounds beyond the array simply stop early.","sql":"SELECT tags[1:3] AS preview FROM articles;"},{"body":"SET tags[2] = 'sql' rewrites a single position and leaves the rest of the array alone. On a NULL array it does not fail: it builds [2:2]={sql}, so tags[1] reads NULL and the lower bound is 2. Use array_append when the column may be NULL.","sql":"UPDATE articles SET tags[2] = 'sql' WHERE id = 7;"}]},"source_url":"https://sqlly.app/sql-functions/array-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ARRAY_LENGTH function","description":"PostgreSQL's ARRAY_LENGTH(arr, dim), returning NULL for an empty array, beside CARDINALITY on PostgreSQL and Oracle and JSON array lengths on the other engines.","body":{"slug":"array-length","name":"ARRAY_LENGTH","h1":"SQL ARRAY_LENGTH function","category":"conversion","lede":"ARRAY_LENGTH(tags, 1) counts the elements in the first dimension of a PostgreSQL array. Only PostgreSQL has array columns and Oracle has nested-table collections; the other engines keep lists in JSON.","syntax":"ARRAY_LENGTH(array, dimension)  -- PostgreSQL  |  CARDINALITY(collection)  -- Oracle","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"no array type; count via OPENJSON or a subquery"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no array type; JSON_LENGTH over JSON arrays"},{"engine_slug":"sqlite","status":"partial","note":"no array type; json_array_length over JSON arrays"},{"engine_slug":"oracle","status":"partial","note":"CARDINALITY over nested tables (not varrays)"}],"gotchas":["PostgreSQL's ARRAY_LENGTH takes a dimension: ARRAY_LENGTH(tags, 1) for the first. On an empty array it returns NULL while CARDINALITY returns 0; the two disagree on empties.","The dimension argument is required: ARRAY_LENGTH(tags) is an error. For a multidimensional array, ARRAY_LENGTH(grid, 2) counts the second dimension.","SQL Server and MySQL have no array type: length belongs to JSON (OPENJSON row count, JSON_LENGTH) or, on SQL Server, to COUNT over STRING_SPLIT for delimited text."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ARRAY_LENGTH(tags, 1) AS n FROM articles;"},{"engine_slug":"postgresql","sql":"SELECT CARDINALITY(tags) AS n FROM articles;"},{"engine_slug":"oracle","sql":"SELECT CARDINALITY(phone_list) AS n FROM contacts;"},{"engine_slug":"sqlite","sql":"SELECT json_array_length(tags) AS n FROM articles;"}],"faqs":[{"question":"Why is ARRAY_LENGTH NULL for an empty array?","answer":"PostgreSQL's empty array has no elements in any dimension, so the length is NULL. CARDINALITY(empty) is 0; prefer it in WHERE clauses to dodge the trap."},{"question":"Do arrays start at 0 or 1?","answer":"PostgreSQL arrays are 1-based unless built with explicit bounds such as '[0:2]={a,b,c}'; array_lower(arr, 1) tells you. JSON array paths are 0-based on every engine."}],"related":["cardinality","unnest","array-index","json-length"],"novel_uses":[{"body":"PostgreSQL has no array_last, but arrays are 1-based, so tags[ARRAY_LENGTH(tags, 1)] is the final element. An empty array subscripts to NULL, which is usually the wanted behavior.","sql":"SELECT tags[ARRAY_LENGTH(tags, 1)] AS last_tag FROM articles;"},{"body":"ARRAY_LENGTH(grid, 1) = ARRAY_LENGTH(grid, 2) finds the non-square matrices in a data-quality pass, the kind of thing that breaks matrix math three queries later.","sql":"SELECT id FROM sheets WHERE ARRAY_LENGTH(grid, 1) <> ARRAY_LENGTH(grid, 2);"}]},"source_url":"https://sqlly.app/sql-functions/array-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/array-to-string","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ARRAY_TO_STRING function","description":"PostgreSQL's array_to_string flattens an array into one delimited string: NULL handling via the third argument, and string_to_array to go back.","body":{"slug":"array-to-string","name":"ARRAY_TO_STRING","h1":"SQL ARRAY_TO_STRING function","category":"string","lede":"Joins the elements of an array column into a single string with your separator, the array counterpart of STRING_AGG over rows.","syntax":"ARRAY_TO_STRING(array, separator [, null_string])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"arrays are a PostgreSQL type; other engines have no array columns"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["NULL elements are skipped by default; pass a third argument to render them: array_to_string(a, ',', '*') prints * where the array held NULL.","An empty array produces an empty string, not NULL. Guard downstream parsing.","The reverse is string_to_array('a,b', ','), with a third argument for NULL placeholders.","To aggregate rows instead of array elements, use STRING_AGG; to aggregate across a group from an array, unnest first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT array_to_string(ARRAY['a', NULL, 'c'], ',') AS flat;  -- a,c"},{"engine_slug":"postgresql","sql":"SELECT array_to_string(ARRAY[1, NULL, 3], ',', '*') AS flat;  -- 1,*,3"},{"engine_slug":"postgresql","sql":"SELECT string_to_array('a,b,c', ',') AS back;  -- {a,b,c}"}],"faqs":[{"question":"How does array_to_string handle NULLs?","answer":"It drops them, giving no separator gap. Supply a third argument to print a placeholder for each NULL instead."},{"question":"Is there an array_to_string in MySQL or SQL Server?","answer":"No. Neither has array columns. The row-based equivalents are GROUP_CONCAT and STRING_AGG, which fold rows rather than array elements."},{"question":"How do I split a string back into an array?","answer":"string_to_array('a,b', ',') in PostgreSQL. Without a third argument it never returns NULL, so an empty element comes back as '' and a NULL that array_to_string dropped is gone. Pass the same third argument to both functions (for example '-') to get NULLs back."}],"related":["concat-ws","string-agg","split-part"],"novel_uses":[{"body":"The third argument preserves position: array_to_string with '-' for NULLs and string_to_array with the same marker brings the array back with NULLs still in place, which plain comma joins cannot do.","sql":"SELECT string_to_array(array_to_string(ARRAY[10, NULL, 30], ',', '-'), ',', '-') AS round_trip;\n-- {10,NULL,30}"},{"body":"array_to_string of an empty array is '', which downstream parsing treats as a real value; NULLIF(array_to_string(tags, ','), '') makes empty and NULL indistinguishable.","sql":"SELECT NULLIF(array_to_string(tags, ','), '') AS csv FROM docs;"}]},"source_url":"https://sqlly.app/sql-functions/array-to-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ascii","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ASCII function","description":"ASCII returns the code of a string's first character, the engine-standard call, plus ORD for MySQL multibyte and unicode() for SQLite.","body":{"slug":"ascii","name":"ASCII","h1":"SQL ASCII function","category":"string","lede":"The inverse of CHR/CHAR: text in, integer code out. Only the first character is read, and encoding decides what multibyte input returns.","syntax":"ASCII(string)  |  ORD(string)  |  unicode(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no ASCII(); unicode(X) returns the code point"},{"engine_slug":"oracle","status":"yes","note":"multibyte characters return their encoded bytes as one number: ASCII('é') is 50089"}],"gotchas":["Only the first character counts: ASCII('Banana') is 66. An empty string gives 0 on MySQL and PostgreSQL but NULL on SQL Server, and NULL on Oracle because '' is NULL there.","Multibyte input splits the engines: MySQL's ASCII('é') returns the first UTF-8 byte (195); MySQL's ORD() and Oracle's ASCII() return both bytes as one number (0xC3A9 = 50089); PostgreSQL's ASCII returns 233, and SQL Server's returns 233 under a Latin-1 collation (a Cyrillic or Japanese collation best-fits é to 101).","SQLite has no ASCII(); unicode(X) returns the full Unicode code point (unicode('é') is 233).","SQL Server's ASCII works on varchar codepages; for nvarchar, UNICODE() is the matching function, and a character outside the code page comes back as 63 ('?'): ASCII(N'中') is 63 where UNICODE(N'中') is 20013."],"examples":[{"engine_slug":"mysql","sql":"SELECT ASCII('A') AS code;  -- 65"},{"engine_slug":"mysql","sql":"SELECT ASCII('é') AS first_byte, ORD('é') AS ord;\n-- 195, 50089"},{"engine_slug":"sqlite","sql":"SELECT unicode('é') AS cp;  -- 233"},{"engine_slug":"sql-server","sql":"SELECT ASCII('B') AS code;  -- 66, first character only"},{"engine_slug":"postgresql","sql":"SELECT ascii('B') AS code, ascii('é') AS cp;  -- 66, 233: the code point, not the first UTF-8 byte"},{"engine_slug":"oracle","sql":"SELECT ASCII('B') AS code, ASCII('é') AS bytes FROM dual;  -- 66, 50089: multibyte input returns its encoded bytes"}],"faqs":[{"question":"Why is ASCII('é') not 233?","answer":"On MySQL it reads the first stored byte, and UTF-8 encodes é as two bytes (195, 169). ORD() and Oracle's ASCII give 50089, the two bytes read as one number. PostgreSQL's ascii() and SQLite's unicode() give the code point 233."},{"question":"What does ASCII('') return?","answer":"0 on MySQL and PostgreSQL; NULL on SQL Server, and on Oracle, whose empty string is NULL. Check the length first when empty strings are possible."},{"question":"How do I go from code back to character?","answer":"CHR(n) on PostgreSQL and Oracle, CHAR(n) on SQL Server and SQLite, the exact inverse for the same code space. MySQL's CHAR(n) takes bytes, so CHAR(233) is the single byte 0xE9 and CHAR(233 USING utf8mb4) is NULL; build é with CHAR(195, 169 USING utf8mb4)."}],"related":["chr","unicode-function","dump"],"novel_uses":[{"body":"Comparing the first character's code against 65 and 90 sorts every value into A-Z buckets or a catch-all #, which builds directory listings in one GROUP BY.","sql":"SELECT CASE WHEN ASCII(UPPER(SUBSTRING(name, 1, 1))) BETWEEN 65 AND 90\n            THEN UPPER(SUBSTRING(name, 1, 1)) ELSE '#' END AS bucket,\n       COUNT(*) AS n\nFROM users GROUP BY bucket ORDER BY bucket;"},{"body":"A leading code below 32 or at 127 means paste or protocol damage that never shows on screen, and the ASCII range check finds it on import.","sql":"SELECT id FROM imports WHERE code <> '' AND (ASCII(code) < 32 OR ASCII(code) = 127);"}]},"source_url":"https://sqlly.app/sql-functions/ascii","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/asciistr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ASCIISTR function","description":"Oracle's ASCIISTR converts non-ASCII characters to \\XXXX hex escapes and leaves ASCII alone, UNISTR in reverse, for debugging and ASCII-safe output.","body":{"slug":"asciistr","name":"ASCIISTR","h1":"SQL ASCIISTR function","category":"string","lede":"Turns any string into an ASCII-safe form: regular characters pass through, everything else becomes its UTF-16 code in \\XXXX notation.","syntax":"ASCIISTR(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ASCII characters pass through untouched; non-ASCII become 4-hex UTF-16 escapes: ASCIISTR('café') gives caf\\00E9.","Supplementary characters escape as surrogate pairs: ASCIISTR of an emoji yields \\D83D\\DE00, two escapes for one character.","UNISTR reverses the escapes: UNISTR(ASCIISTR(s)) gives back s when s contains no backslash, since UNISTR reads a backslash as the start of an escape.","Oracle-only. Elsewhere: PostgreSQL's encode(convert_to(s, 'utf8'), 'hex'), MySQL's HEX, or the application layer for presentation-safe output."],"examples":[{"engine_slug":"oracle","sql":"SELECT ASCIISTR('café') AS a FROM dual;  -- caf\\00E9"},{"engine_slug":"oracle","sql":"SELECT UNISTR(ASCIISTR('café')) AS back FROM dual;  -- café"}],"faqs":[{"question":"What is ASCIISTR used for?","answer":"ASCII-safe transport and debugging: logs, feeds and file names that mangle non-ASCII survive as \\XXXX escapes, and UNISTR restores them later."},{"question":"Why does an emoji become two escapes?","answer":"ASCIISTR emits UTF-16 code units, and an emoji is a surrogate pair: \\D83D\\DE00. UNISTR understands the pair and reassembles the character."},{"question":"Is ASCIISTR the same as RAWTOHEX?","answer":"No. RAWTOHEX shows the stored bytes; ASCIISTR shows UTF-16 code units in escape notation and passes plain ASCII through readable."}],"related":["unistr","chr","dump"],"novel_uses":[{"body":"ASCIISTR keeps the structure of a name and escapes only the non-ASCII characters, so generated file names survive ASCII-only file systems and logs.","sql":"SELECT ASCIISTR('café-note-' || id) AS safe_name FROM docs;"},{"body":"ASCIISTR(col) <> col is true exactly when something non-ASCII is present, a regex-free scan that works wherever the function exists.","sql":"SELECT id FROM notes WHERE ASCIISTR(body) <> body;"}]},"source_url":"https://sqlly.app/sql-functions/asciistr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/asin","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ASIN function","description":"ASIN(x) returns the angle whose sine is x, in radians. Only valid for x between -1 and 1; outside that, engines return NULL or raise an error.","body":{"slug":"asin","name":"ASIN","h1":"SQL ASIN function","category":"math","lede":"Returns the arc sine in radians: ASIN(1) is PI()/2 and ASIN(0.5) is about 0.5236 (30 degrees).","syntax":"ASIN(number)","return_type":"float / double (radians)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Part of the 3.35+ math set; embedded SQLite builds often ship without SQLITE_ENABLE_MATH_FUNCTIONS, so test on the exact library you deploy"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The domain is [-1, 1]. ASIN(2) returns NULL on MySQL and SQLite, raises 'input is out of range' on PostgreSQL, ORA-01428 on Oracle and an invalid floating point operation on SQL Server.","A computed ratio such as opposite / hypotenuse can come out at 1.0000000000000002 and then fails. Clamp it: ASIN(LEAST(1, GREATEST(-1, x))), or ASIN(MAX(-1, MIN(1, x))) on SQLite, which has no LEAST/GREATEST. SQL Server needs 2022+ for LEAST.","The result is radians; multiply by 180/PI() or wrap in DEGREES() for display."],"examples":[{"engine_slug":"all","sql":"SELECT ASIN(1) AS half_pi;  -- 1.5707963...  (Oracle before 23ai: FROM dual, see the Oracle example)"},{"engine_slug":"postgresql","sql":"SELECT DEGREES(ASIN(0.5)) AS thirty;  -- 30.000000000000004"},{"engine_slug":"mysql","sql":"SELECT ASIN(1.2) AS out_of_domain;  -- NULL"},{"engine_slug":"oracle","sql":"SELECT ASIN(1) AS half_pi FROM dual;  -- 1.5707963267949"}],"faqs":[{"question":"Why does ASIN return NULL for my value?","answer":"The input is outside [-1, 1], the only range where arc sine exists. MySQL and SQLite return NULL; PostgreSQL, Oracle and SQL Server raise an error instead. Clamp with LEAST/GREATEST (MAX/MIN on SQLite) when float noise may push values out."},{"question":"Is the ASIN result in degrees?","answer":"No, radians on all engines. ASIN(0.5) is about 0.5236 radians, which is 30 degrees; wrap in DEGREES() to show it that way."},{"question":"What is ASIN(1)?","answer":"PI()/2, about 1.5708 radians: the angle whose sine is 1 is a right angle."}],"related":["sin","acos","atan","inverse-trig-domain"],"novel_uses":[{"body":"DEGREES(ASIN(rise / length)) recovers the incline angle when the survey recorded rise and slope length, the hypotenuse form of what ATAN takes as rise over run. Prefilter ABS(rise) <= length and length > 0 to keep the ratio in [-1, 1]: a downhill rise is negative, and a zero length divides by zero. The * 1.0 stops integer columns from truncating to zero.","sql":"SELECT DEGREES(ASIN(rise_m * 1.0 / length_m)) AS incline_deg FROM conveyors WHERE ABS(rise_m) <= length_m AND length_m > 0;"},{"body":"ASIN(chord / (2 * radius)) gives the half angle a chord subtends, the arc-to-angle conversion for anything stored as chord lengths: pipes, arches, antenna beamwidth. A chord longer than the diameter has no real angle, so filter it out first.","sql":"SELECT DEGREES(ASIN(chord_m * 1.0 / (2 * radius_m))) AS half_angle_deg FROM arcs WHERE chord_m <= 2 * radius_m AND radius_m > 0;"}]},"source_url":"https://sqlly.app/sql-functions/asin","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/asinh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ASINH function","description":"ASINH(x) inverts SINH and accepts every real number, returning a value with the input's sign. PostgreSQL 12+ and SQLite only; the LN identity covers the rest.","body":{"slug":"asinh","name":"ASINH","h1":"SQL ASINH function","category":"math","lede":"Returns the inverse hyperbolic sine: ASINH(0) is 0 and ASINH is defined for all real inputs, no domain restriction.","syntax":"ASINH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; use LN(x + SQRT(x * x + 1))"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 12 and newer; asinh arrived with the rest of the hyperbolic family"},{"engine_slug":"mysql","status":"no","note":"MySQL has no ASINH; LN(x + SQRT(x * x + 1)) reproduces it"},{"engine_slug":"sqlite","status":"yes","note":"3.35+ and SQLITE_ENABLE_MATH_FUNCTIONS"},{"engine_slug":"oracle","status":"no","note":"No ASINH; use LN(x + SQRT(x * x + 1))"}],"gotchas":["No domain limits: unlike ASIN or ACOS, ASINH accepts any real number and never returns a domain NULL or error.","The log formula LN(x + SQRT(x * x + 1)) reproduces it, but for large negative x the sum cancels toward 0 and loses precision: at x = -1000000 it is off by about 8e-6, and at x = -100000000 it cancels to exactly 0, which PostgreSQL rejects with an error, MySQL and SQLite turn into NULL, and SQL Server raises an invalid floating point error. Use -LN(-x + SQRT(x * x + 1)) for negative x, or the built-in.","Odd function: ASINH(-x) = -ASINH(x), so sign handling comes free."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ASINH(0) AS zero, ASINH(2) AS two;  -- 0, 1.4436354751788103"},{"engine_slug":"sql-server","sql":"SELECT LOG(2 + SQRT(POWER(2.0, 2) + 1)) AS asinh_two;  -- 1.4436354751788103"},{"engine_slug":"postgresql","sql":"SELECT ASINH(x) AS inv_sinh FROM measurements;"},{"engine_slug":"sqlite","sql":"SELECT asinh(0) AS zero, asinh(2) AS two;  -- 0.0, 1.44363547517881"}],"faqs":[{"question":"Which engines have ASINH?","answer":"PostgreSQL 12+ and SQLite 3.35+. SQL Server, MySQL and Oracle do not; the identity LN(x + SQRT(x*x + 1)) is the replacement (LOG on SQL Server)."},{"question":"Does ASINH have a domain error like ASIN?","answer":"No. ASIN accepts only [-1, 1]; ASINH accepts every real number, negative included, and returns a value with the same sign."},{"question":"Why does the log formula give a slightly different answer?","answer":"LN and SQRT are separate float operations, so the composed result can drift in the last digits versus the engine's purpose-built ASINH. Prefer the built-in."}],"related":["sinh","acosh","ln"],"novel_uses":[{"body":"ASINH compresses huge magnitudes like a log but keeps sign and accepts zero, which LN cannot. Sensor deltas, profit and loss and other signed data plot and compare far better on an asinh scale.","sql":"SELECT ASINH(pnl) AS symlog_pnl FROM daily_positions;"},{"body":"Return series mix tiny and enormous percentages with both signs. ASINH(return) behaves like the return near zero and like a log far from it, keeping outliers visible without letting them dominate.","sql":"SELECT ASINH(pct_return) AS scaled_return FROM trades;"}]},"source_url":"https://sqlly.app/sql-functions/asinh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/at-time-zone","corpus":"sql-functions","engine":null,"language":"en","title":"SQL AT TIME ZONE function","description":"AT TIME ZONE in PostgreSQL and SQL Server: convert between wall time and time-zone-aware values in both directions, with DST and naming gotchas.","body":{"slug":"at-time-zone","name":"AT TIME ZONE","h1":"SQL AT TIME ZONE function","category":"datetime","lede":"Tags a naive timestamp with a zone or renders an aware timestamp in a zone: the same clause, meaning opposite things depending on the input type.","syntax":"ts AT TIME ZONE 'zone'","return_type":"timestamptz / timestamp (PG); datetimeoffset / datetime (SS)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"native: timestamptz and timestamp both"},{"engine_slug":"mysql","status":"partial","note":"CONVERT_TZ(dt, from_zone, to_zone)"},{"engine_slug":"sqlite","status":"no","note":"no zone support beyond localtime/utc modifiers"},{"engine_slug":"oracle","status":"yes","note":"ts AT TIME ZONE 'zone' on TIMESTAMP types; FROM_TZ to tag a naive value"}],"gotchas":["Direction depends on input type: on PostgreSQL, timestamp AT TIME ZONE 'Europe/Paris' produces a timestamptz (interprets), while timestamptz AT TIME ZONE 'Europe/Paris' produces a timestamp (renders). Applying it twice flips the type back.","SQL Server (2016+) uses Windows zone names ('Central European Standard Time'), PostgreSQL and Oracle use IANA names ('Europe/Paris'); one mapping table does not serve both.","Wall times inside a DST gap move forward: 2026-03-08 02:30 in America/New_York ('Eastern Standard Time' on SQL Server) comes back as 03:30 -04:00 on both PostgreSQL and SQL Server, so a round-trip changes the value."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TIMESTAMP '2026-08-01 14:30' AT TIME ZONE 'Europe/Paris';"},{"engine_slug":"sql-server","sql":"SELECT CAST('2026-08-01 14:30' AS datetime2) AT TIME ZONE 'Central European Standard Time';  -- 2026-08-01 14:30:00 +02:00"},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AT TIME ZONE 'Europe/Paris' FROM dual;"},{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ('2026-08-01 14:30:00', 'UTC', 'Europe/Paris');  -- 2026-08-01 16:30:00"}],"faqs":[{"question":"Why does AT TIME ZONE sometimes add and sometimes drop the zone?","answer":"Input type decides: naive in means 'interpret this wall time in the zone' (adds awareness). On PostgreSQL, aware in means 'show me this instant as the zone's wall time' (drops awareness). SQL Server returns datetimeoffset for both input types, so an aware input is re-offset to the zone and keeps its offset."},{"question":"Do the two engines accept the same zone names?","answer":"No. PostgreSQL wants IANA identifiers; SQL Server wants Windows time zone registry names. Store the right kind per engine."}],"related":["convert-tz","from-tz","timestamp-with-time-zone","session-time-zone"],"novel_uses":[{"body":"Applying the clause twice converts a naive wall time from one zone to another: interpret in Paris, render in New York, in one expression.","sql":"SELECT TIMESTAMP '2026-08-01 14:30' AT TIME ZONE 'Europe/Paris' AT TIME ZONE 'America/New_York';  -- 08:30"},{"body":"SQL Server does not treat AT TIME ZONE as deterministic, so a PERSISTED computed column over it fails with error 4936 on SQL Server 2022. Keep the UTC value in a plain column that the writer fills.","sql":"ALTER TABLE logs ADD utc_at datetime2 NULL;\nINSERT INTO logs (local_at, utc_at) VALUES ('2026-08-01 14:30', CAST(CAST('2026-08-01 14:30' AS datetime2) AT TIME ZONE 'Central European Standard Time' AT TIME ZONE 'UTC' AS datetime2));  -- utc_at = 2026-08-01 12:30"},{"body":"An expression index on the Tokyo-rendered date lets per-day queries for one region hit an index instead of scanning every row.","sql":"CREATE INDEX events_tokyo_day ON events (((created_at AT TIME ZONE 'Asia/Tokyo')::date));"}]},"source_url":"https://sqlly.app/sql-functions/at-time-zone","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/atan","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ATAN function","description":"ATAN(x) returns the angle whose tangent is x, in radians. Defined for every real input (no domain errors), but it cannot tell which quadrant you meant.","body":{"slug":"atan","name":"ATAN","h1":"SQL ATAN function","category":"math","lede":"Returns the arc tangent in radians for any real input: ATAN(0) is 0 and ATAN(1) is PI()/4.","syntax":"ATAN(number)","return_type":"float / double (radians)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"3.35+ with SQLITE_ENABLE_MATH_FUNCTIONS set at compile time; system SQLite libraries sometimes leave the math set out"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The result is between -PI()/2 and PI()/2. ATAN(1) and ATAN(-1) both point at 45-degree lines but cannot distinguish quadrants; use ATAN2 for that.","Unlike ASIN and ACOS there is no domain restriction: any real number, including huge ones, returns a valid angle.","ATAN(1) matches PI()/4 to the last bit on every engine tested, but that value is only the nearest double to pi/4, so compare trig results with a tolerance rather than =."],"examples":[{"engine_slug":"all","sql":"SELECT ATAN(0) AS zero, ATAN(1) AS quarter_pi;  -- 0, 0.7853..."},{"engine_slug":"postgresql","sql":"SELECT DEGREES(ATAN(slope)) AS angle_deg\nFROM ramps;"},{"engine_slug":"sql-server","sql":"SELECT ATAN(1000000) AS near_right_angle;  -- 1.5707953267948966"},{"engine_slug":"oracle","sql":"SELECT ATAN(0) AS zero, ATAN(1) AS quarter_pi FROM dual;  -- 0, 0.7853981..."}],"faqs":[{"question":"What is the difference between ATAN and ATAN2?","answer":"ATAN takes one number and returns an angle in (-PI/2, PI/2), losing quadrant information. ATAN2(y, x) takes both coordinates and returns the angle in the correct quadrant across the full circle. MySQL also accepts ATAN(y, x) with two arguments, the same function as ATAN2(y, x)."},{"question":"Does ATAN have a domain error?","answer":"No. The tangent covers every real number, so ATAN accepts anything from minus to plus infinity without returning NULL or erroring."},{"question":"Is the ATAN result in degrees?","answer":"No, radians. ATAN(1) is PI()/4, about 0.7854 radians, which is 45 degrees; wrap in DEGREES() for degrees."}],"related":["atan2","tan","degrees","inverse-trig-domain"],"novel_uses":[{"body":"DEGREES(ATAN(rise * 1.0 / NULLIF(run, 0))) turns stored rise and run columns into angles a compliance rule can compare. One computed column gives every segment's angle, so a WHERE on it flags the segments over the limit without exporting anything.","sql":"SELECT id, DEGREES(ATAN(rise * 1.0 / NULLIF(run, 0))) AS slope_deg FROM segments;"},{"body":"ATAN maps ratios to (-PI/2, PI/2), so a single near-infinite ratio cannot dominate an average of click-through or cost ratios. Average ATAN(r), then TAN the result to get a robust central ratio.","sql":"SELECT TAN(AVG(ATAN(cur * 1.0 / prev))) AS central_ratio FROM snapshots WHERE prev > 0;"}]},"source_url":"https://sqlly.app/sql-functions/atan","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/atan2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ATAN2 function","description":"ATAN2(y, x) returns the angle of a point in the correct quadrant, unlike ATAN. The order is y first on every engine, though SQL Server spells it ATN2.","body":{"slug":"atan2","name":"ATAN2","h1":"SQL ATAN2 function","category":"math","lede":"Returns the angle between the positive x-axis and the point (x, y), in radians, using the signs of both arguments to pick the quadrant.","syntax":"ATAN2(y, x)","return_type":"float / double (radians)","support":[{"engine_slug":"sql-server","status":"partial","note":"No ATAN2 name ('not a recognized built-in function'); ATN2(y, x) does the same job"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"ATAN2(y, x), also spelled ATAN(y, x)"},{"engine_slug":"sqlite","status":"yes","note":"In the math function set since 3.35.0; a build without SQLITE_ENABLE_MATH_FUNCTIONS reports 'no such function: atan2'"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Arguments are (y, x) in that order on all five engines, SQL Server's ATN2(y, x) included. Swapping them silently returns PI()/2 minus the intended angle (for positive x and y) rather than erroring.","ATAN2(1, 1) is PI()/4 but ATAN2(-1, 1) is -PI()/4: the sign of y picks the lower half of the circle, which single-argument ATAN cannot express.","ATAN2(0, 0) has no meaningful angle. PostgreSQL, MySQL and SQLite return 0, while SQL Server's ATN2(0, 0) raises an invalid floating point operation and Oracle raises ORA-01426. Filter out the origin first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ATAN2(1, 1) AS quarter_pi;  -- 0.7853981633974483"},{"engine_slug":"sql-server","sql":"SELECT ATN2(1, 1) AS quarter_pi;  -- same value, different name"},{"engine_slug":"postgresql","sql":"SELECT DEGREES(ATAN2(delta_x, delta_y)) AS bearing_deg\nFROM vectors;"},{"engine_slug":"mysql","sql":"SELECT ATAN2(1, 1) AS quarter_pi;  -- 0.7853981633974483"},{"engine_slug":"sqlite","sql":"SELECT atan2(1, 1) AS quarter_pi;  -- 0.785398163397448"},{"engine_slug":"oracle","sql":"SELECT ATAN2(1, 1) AS quarter_pi FROM dual;  -- 0.7853981633974483..."}],"faqs":[{"question":"What is the difference between ATAN and ATAN2?","answer":"ATAN(y/x) loses the quadrant because y/x collapses two numbers into one. ATAN2(y, x) keeps both signs and returns the angle in [-pi, pi], the right one for bearings and vectors."},{"question":"What is the argument order of ATAN2?","answer":"Y first, X second: ATAN2(y, x) on MySQL, PostgreSQL, SQLite, Oracle, and on SQL Server, where the function is spelled ATN2."},{"question":"Why is ATAN2 called ATN2 on SQL Server?","answer":"Historical T-SQL naming. It computes the same thing with the same (y, x) order; SQL Server has no ATAN2 alias, so a cross-engine query has to swap the name."}],"related":["atan","atn2","tan","degrees"],"novel_uses":[{"body":"DEGREES(ATAN2(delta_x, delta_y)) gives the bearing from north between two local grid points, quadrant included, which single-argument ATAN cannot do. Wrap negatives with +360 when the feed expects 0-360.","sql":"SELECT DEGREES(ATAN2(lon2 - lon1, lat2 - lat1)) AS bearing_deg FROM legs;"},{"body":"Wind feeds store east and north components as u and v. DEGREES(ATAN2(u, v)) returns the flow direction; a CASE adds 360 to negatives, and you still need to check whether the feed means direction from or direction to.","sql":"SELECT DEGREES(ATAN2(u, v)) + CASE WHEN DEGREES(ATAN2(u, v)) < 0 THEN 360 ELSE 0 END AS wind_dir FROM wind_readings;"},{"body":"ORDER BY ATAN2(y - cy, x - cx) walks rows counterclockwise around a point when y points up (clockwise when y points down, as on screen), the first step of radial layouts and angular sweeps. Add the name as a tiebreaker: SQL does not define the order of rows with equal angles.","sql":"SELECT name FROM pois ORDER BY ATAN2(y - 0.0, x - 0.0), name;"}]},"source_url":"https://sqlly.app/sql-functions/atan2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/atanh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ATANH function","description":"ATANH(x) inverts TANH for x in (-1, 1). At exactly 1, PostgreSQL and SQLite return Infinity. SQL Server, MySQL and Oracle need the LN identity.","body":{"slug":"atanh","name":"ATANH","h1":"SQL ATANH function","category":"math","lede":"Returns the inverse hyperbolic tangent for inputs in (-1, 1): ATANH(0) is 0 and ATANH(0.5) is about 0.5493.","syntax":"ATANH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; use 0.5 * LOG((1 + x) / (1 - x))"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 12 introduced atanh alongside sinh and cosh"},{"engine_slug":"mysql","status":"no","note":"MySQL lacks ATANH; 0.5 * LN((1 + x) / (1 - x)) is the stand-in"},{"engine_slug":"sqlite","status":"yes","note":"In the 3.35+ math set; PRAGMA compile_options confirms the flag"},{"engine_slug":"oracle","status":"no","note":"No ATANH; use 0.5 * LN((1 + x) / (1 - x))"}],"gotchas":["At the edges the answer is infinite: ATANH(1) returns Infinity on PostgreSQL and Inf on SQLite, not an error. Past the edge, ATANH(1.5) is an error on PostgreSQL and NULL on SQLite.","Clamp correlations before calling: r computed in floats can be 1.0000000000000002, which errors on PostgreSQL, and a perfect r = 1 gives an infinite z that breaks later averages.","The artanh formula 0.5 * LN((1+x)/(1-x)) is the portable path; SQL Server spells LN as LOG."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ATANH(0) AS zero, ATANH(1) AS edge;  -- 0, Infinity"},{"engine_slug":"sql-server","sql":"SELECT 0.5 * LOG((1 + 0.5) / (1 - 0.5)) AS atanh_half;  -- about 0.5493"},{"engine_slug":"postgresql","sql":"SELECT ATANH(LEAST(0.999999, GREATEST(-0.999999, r))) AS fisher_z\nFROM correlations;"},{"engine_slug":"sqlite","sql":"SELECT atanh(0) AS zero, atanh(0.5) AS half;  -- 0.0, 0.5493061443340549"}],"faqs":[{"question":"What does ATANH return for exactly 1?","answer":"TANH reaches 1 only at infinity, so the inverse at 1 is infinite. PostgreSQL returns Infinity and SQLite Inf, so the query does not fail but the value poisons any later SUM or AVG. Values beyond 1 error on PostgreSQL and give NULL on SQLite."},{"question":"What is the portable ATANH formula?","answer":"0.5 * LN((1 + x) / (1 - x)) for |x| < 1. On SQL Server, write LOG for LN."},{"question":"How is ATANH used in statistics?","answer":"It is the Fisher z-transformation of a correlation coefficient, which is exactly why inputs of exactly 1 show up and need clamping."}],"related":["tanh","asinh","inverse-trig-domain"],"novel_uses":[{"body":"If a pipeline stored (a - b) / (a + b) or a tanh score, EXP(2 * ATANH(score)) returns a / b, up to float rounding (PostgreSQL gives 2.9999999999999996 for a / b = 3): the ratio comes back from the bounded value. It is the inverse half of the tanh relative-difference trick.","sql":"SELECT EXP(2 * ATANH(score)) AS ratio FROM comparisons;"},{"body":"2 * ATANH(2 * p - 1) is the logit of a probability on PostgreSQL and SQLite, no LN gymnastics needed. Guard p against exactly 0 and 1, where the result goes infinite.","sql":"SELECT 2 * ATANH(2 * 0.7 - 1) AS logit;  -- 0.8472978603872037 on PostgreSQL; SQLite prints 0.847297860387203"}]},"source_url":"https://sqlly.app/sql-functions/atanh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/atn2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ATN2 function (SQL Server)","description":"ATN2(y, x) is SQL Server's name for the two-argument arc tangent. Same math and the same y-then-x order as ATAN2 on the other engines.","body":{"slug":"atn2","name":"ATN2","h1":"SQL ATN2 function (SQL Server)","category":"math","lede":"Returns the angle whose tangent is y/x, using both signs to place the angle in the correct quadrant: ATN2(1, 1) is PI()/4.","syntax":"ATN2(y, x)","return_type":"float (radians)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"Use atan2(y, x)"},{"engine_slug":"mysql","status":"no","note":"Use ATAN2(y, x) or ATAN(y, x)"},{"engine_slug":"sqlite","status":"no","note":"Use atan2(y, x) on 3.35+"},{"engine_slug":"oracle","status":"no","note":"Use ATAN2(y, x)"}],"gotchas":["The order is y first, x second, matching ATAN2 everywhere else, so a cross-engine rewrite only renames the function.","ATN2(-1, 1) is -PI()/4 and ATN2(1, -1) is 3*PI()/4: signs matter, unlike ATAN which folds everything into (-PI/2, PI/2). ATN2(0, 0) raises an invalid floating point operation.","The result is a float in radians; DEGREES(ATN2(y, x)) converts for display."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ATN2(1, 1) AS quarter_pi;  -- 0.7853981..."},{"engine_slug":"sql-server","sql":"SELECT DEGREES(ATN2(delta_y, delta_x)) AS bearing_deg\nFROM nav_fixes;"}],"faqs":[{"question":"Is ATN2 the same as ATAN2?","answer":"Yes: same math, same (y, x) argument order. SQL Server spells it ATN2; PostgreSQL, MySQL, SQLite and Oracle spell it ATAN2."},{"question":"What does ATN2(0, -1) return?","answer":"PI(), about 3.14159: the point (-1, 0) sits on the negative x-axis, and only a two-argument arc tangent can place it there."},{"question":"How do I convert ATN2 output to degrees?","answer":"Wrap it: DEGREES(ATN2(y, x)). The function itself always returns radians as a float."}],"related":["atan2","atan","degrees"],"novel_uses":[{"body":"ATN2(u, v) on SQL Server returns the same wind or bearing angle as ATAN2 elsewhere, with the arguments in the same order. A ported formula needs only the name changed.","sql":"SELECT DEGREES(ATN2(u, v)) AS flow_dir FROM wind_readings;"},{"body":"T-SQL's % rejects float operands, so normalize an ATN2 result with the FLOOR form: d - FLOOR(d / 360.0) * 360 maps any angle into [0, 360), except that a tiny negative angle such as -5.7e-19 degrees rounds up to exactly 360. It avoids the operator error a bare % would raise.","sql":"SELECT DEGREES(ATN2(u, v)) - FLOOR(DEGREES(ATN2(u, v)) / 360.0) * 360.0 AS dir_0_360 FROM wind_readings;"}]},"source_url":"https://sqlly.app/sql-functions/atn2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/avg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL AVG function","description":"How AVG works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: NULL handling, integer division surprises and how to average a subset of rows.","body":{"slug":"avg","name":"AVG","h1":"SQL AVG function","category":"aggregate","lede":"Averages the non-null values of an expression across a group. AVG ignores NULLs entirely, so the denominator is the count of non-null values, not COUNT(*).","syntax":"AVG(expression)  |  AVG(DISTINCT expression)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["AVG ignores NULLs: a column with values 10, 20 and NULL averages to 15, not 10.","On SQL Server, AVG of an int column returns int, truncated: AVG of 1 and 2 is 1. Cast to a decimal type for a real average. PostgreSQL returns numeric, MySQL DECIMAL and SQLite a float, so 1.5 there.","AVG(DISTINCT x) averages the distinct values only: 1, 1 and 4 give 2.5, not 2."],"examples":[{"engine_slug":"all","sql":"SELECT customer_id, AVG(amount) AS avg_order\nFROM orders\nGROUP BY customer_id;"},{"engine_slug":"sql-server","sql":"SELECT AVG(CAST(duration_seconds AS DECIMAL(10,2))) AS avg_duration\nFROM runs;"}],"faqs":[{"question":"Does AVG count NULL values?","answer":"No. NULLs are excluded from both the sum and the count. To treat NULL as zero, write AVG(COALESCE(x, 0)), but think first whether that is really the average you mean."},{"question":"Why is my AVG of whole numbers a whole number?","answer":"Integer input gives integer output on SQL Server, with the fraction dropped. CAST the column to DECIMAL, or average x * 1.0. PostgreSQL, MySQL, SQLite and Oracle already return a fractional result."}],"related":["sum","count","percentile-cont"],"novel_uses":[{"body":"AVG treats every row equally, which is wrong when rows carry different weights. A volume-weighted price is SUM(price * volume) / NULLIF(SUM(volume), 0); the NULLIF keeps an all-zero weight group from dividing by zero and returns NULL instead.","sql":"SELECT SUM(price * volume) / NULLIF(SUM(volume), 0) AS weighted_price\nFROM trades;"},{"body":"The average of a 1/0 indicator is the share of rows that pass: AVG(CASE WHEN shipped THEN 1.0 ELSE 0.0 END) is the ship rate. The .0 matters on SQL Server, where 1 and 0 would average as integers and truncate to 0.","sql":"SELECT region,\n       AVG(CASE WHEN shipped THEN 1.0 ELSE 0.0 END) AS ship_rate\nFROM orders\nGROUP BY region;"},{"body":"AVG over ROWS BETWEEN 6 PRECEDING AND CURRENT ROW gives a seven-day moving average that recenters itself on every row. SQL Server has window frames from 2012, MySQL 8+, SQLite 3.25+; Oracle allows offset frames on window aggregates from 12c.","sql":"SELECT day,\n       AVG(sessions) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma_7\nFROM traffic;"}]},"source_url":"https://sqlly.app/sql-functions/avg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/avg-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL AVG with OVER","description":"AVG() OVER for partition means, moving averages and benchmark-per-row comparisons, plus the integer-division trap that quietly truncates it.","body":{"slug":"avg-over","name":"AVG OVER","h1":"SQL AVG with OVER","category":"window","lede":"Averages the window frame or partition and keeps every row: the group mean next to each value for variance-from-average analysis.","syntax":"AVG(x) OVER (PARTITION BY g) | AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["On SQL Server, AVG of an int column returns int: AVG(x) over 1 and 2 is 1, not 1.5. PostgreSQL returns numeric, MySQL decimal, SQLite always a float, Oracle NUMBER. Cast on SQL Server, in window form too.","NULL rows are skipped in the numerator and denominator alike; rows where x is NULL contribute nothing, they do not drag the average down.","ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a 7-row trailing average, not a 7-day one: missing dates stretch it over a longer period."],"examples":[{"engine_slug":"all","sql":"SELECT department, salary,\n       salary - AVG(salary * 1.0) OVER (PARTITION BY department) AS vs_dept_avg\nFROM employees;"},{"engine_slug":"all","sql":"-- trailing 7-row moving average\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7\nFROM prices;"}],"faqs":[{"question":"Why is AVG OVER returning whole numbers?","answer":"You are on SQL Server and the column is an integer type: AVG returns the input type there. Cast: AVG(x * 1.0) OVER (...) or AVG(CAST(x AS DECIMAL(10,2))) OVER (...). The other four engines already return a fractional result."},{"question":"AVG OVER or moving average: which do I have?","answer":"AVG(x) OVER (PARTITION BY g) is one average per group; adding ORDER BY with a frame makes it row-by-row. ORDER BY alone gives a running average from the first row, not a moving one. Both can appear in one query with different OVER clauses."}],"related":["moving-average","aggregate-over","stddev-window"],"novel_uses":[{"body":"Partition by the truncated month and order by day inside it: the average restarts on the first of every month with no date arithmetic in the outer query. PostgreSQL writes date_trunc('month', d); MySQL reaches the same grouping with DATE_FORMAT(d, '%Y-%m').","sql":"-- PostgreSQL. MySQL: replace DATE_TRUNC('month', day) with DATE_FORMAT(day, '%Y-%m')\nSELECT day, sales,\n       AVG(sales) OVER (PARTITION BY DATE_TRUNC('month', day) ORDER BY day) AS mtd_avg\nFROM daily_sales;"},{"body":"Wrap the delta in a CTE, then average ABS of it over a trailing frame: a volatility proxy that needs no STDDEV at all. This is the dispersion measure on engines like SQLite that ship without standard deviation.","sql":"WITH d AS (\n  SELECT day, price, price - LAG(price) OVER (ORDER BY day) AS move\n  FROM prices\n)\nSELECT day, price,\n       AVG(ABS(move)) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_abs_move\nFROM d;"}]},"source_url":"https://sqlly.app/sql-functions/avg-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/backslash-escapes","corpus":"sql-functions","engine":null,"language":"en","title":"SQL backslash escapes in strings","description":"MySQL processes \\n, \\t and \\' inside literals; PostgreSQL needs E'' strings; SQLite, Oracle and SQL Server treat the backslash as a plain character.","body":{"slug":"backslash-escapes","name":"Backslash escapes in strings","h1":"SQL backslash escapes in strings","category":"string","lede":"The same literal 'a\\tb' is a tab on MySQL and four characters everywhere else, the root of many migration bugs and LIKE-pattern surprises.","syntax":"'a\\tb'  -- MySQL: tab  |  PostgreSQL: needs E'a\\tb'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL processes backslash escapes in string literals by default; SET SESSION sql_mode = CONCAT(@@SESSION.sql_mode, ',NO_BACKSLASH_ESCAPES') turns that off for the session, because a bare SET sql_mode = NO_BACKSLASH_ESCAPES drops every other mode. Stored values are not rewritten; the literals in the SQL text read differently, so a WHERE clause that matched before can stop matching.","PostgreSQL follows the standard: 'a\\tb' is a literal backslash-t. The escape-processing form is E'a\\tb' (or the \\n CHR/CHAR equivalents).","Oracle, SQL Server and SQLite never process backslashes in literals: code written for MySQL carries stray backslashes into them.","MySQL's LIKE also uses backslash as its default escape character, so matching a literal backslash takes '\\\\\\\\' in the pattern. Portable SQL avoids backslash escapes and builds characters with CHR(10) or CHAR(10)."],"examples":[{"engine_slug":"mysql","sql":"SELECT 'a\\tb' AS s;  -- a (tab) b"},{"engine_slug":"postgresql","sql":"SELECT E'a\\tb' AS escaped, 'a\\tb' AS plain;  -- tab vs a\\tb"},{"engine_slug":"oracle","sql":"SELECT 'a\\tb' AS s FROM dual;  -- a\\tb, backslash is literal"},{"engine_slug":"sql-server","sql":"SELECT 'a\\tb' AS s, LEN('a\\tb') AS len;  -- a\\tb is 4 characters: backslashes are never escapes here"},{"engine_slug":"sqlite","sql":"SELECT 'a\\tb' AS s, length('a\\tb') AS len;  -- a\\tb, 4: no escape processing"}],"faqs":[{"question":"Why is my backslash literal different on PostgreSQL?","answer":"Standard strings treat backslashes literally; only E'' strings process escapes. MySQL processes them by default, which is the difference you are seeing."},{"question":"How do I write a portable newline in a literal?","answer":"Do not use backslashes; build it: CHAR(13) + CHAR(10) on SQL Server, CHR(10) on Oracle, char(10) on SQLite, E'\\n' on PostgreSQL when you accept engine-specific syntax."},{"question":"What does NO_BACKSLASH_ESCAPES change?","answer":"MySQL stops processing backslashes in literals: 'a\\tb' becomes the literal text a\\tb. Existing queries whose literals rely on escapes behave differently; stored values are not rewritten."}],"related":["newline-literal","quote","unistr","chr"],"novel_uses":[{"body":"SQL Server, Oracle and SQLite read the backslash literally, so file paths need no doubling; MySQL processes them, and a path like 'C:\\temp' becomes C:, a tab, and emp.","sql":"SELECT 'C:\\logs\\app.log' AS path;  -- fine on SQL Server, Oracle and SQLite"},{"body":"Rows containing doubled backslashes were almost certainly written for MySQL and migrated literally; instr against two backslashes lists them on SQLite.","sql":"SELECT id FROM notes WHERE instr(body, '\\\\') > 0;  -- doubled backslashes came from MySQL-escaped text"}]},"source_url":"https://sqlly.app/sql-functions/backslash-escapes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/base64","corpus":"sql-functions","engine":null,"language":"en","title":"SQL base64 functions","description":"Base64 in SQL: TO_BASE64 and FROM_BASE64 on MySQL, encode/decode on PostgreSQL, BASE64_ENCODE on SQL Server 2025, UTL_ENCODE on Oracle, and SQLite's shell-only base64().","body":{"slug":"base64","name":"Base64","h1":"SQL base64 functions","category":"conversion","lede":"Base64 carries binary through text-only channels: TO_BASE64('SQL') is 'U1FM'. Every engine spells it differently, and most of them wrap long output across lines.","syntax":"TO_BASE64(x) / FROM_BASE64(x)  -- MySQL  |  encode(x, 'base64') / decode(x, 'base64')  -- PostgreSQL","return_type":"text or binary","support":[{"engine_slug":"sql-server","status":"partial","note":"BASE64_ENCODE/BASE64_DECODE on SQL Server 2025; the xs:base64Binary XQuery trick before"},{"engine_slug":"postgresql","status":"yes","note":"encode(bytea, 'base64') and decode(text, 'base64')"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"base64() is built into the sqlite3 shell, not the core library"},{"engine_slug":"oracle","status":"partial","note":"UTL_ENCODE.BASE64_ENCODE over RAW, callable from SQL"}],"gotchas":["Output is the padded standard alphabet (+ and / with = padding). URL-safe base64 (- and _ without padding) needs REPLACE or translate() before it goes into a link.","PostgreSQL's encode inserts a newline every 76 characters, and MySQL's TO_BASE64 does the same; SQLite's shell base64() breaks every 72 characters and ends even short output with a newline. Strip them when the value must be one line.","Decoding strictness differs: MySQL's FROM_BASE64 returns NULL on invalid input while PostgreSQL's decode raises an error.","SQLite's base64() is an extension compiled into the sqlite3 command-line shell; applications linking the plain library do not have it. It switches direction by argument type: a BLOB encodes, TEXT decodes."],"examples":[{"engine_slug":"mysql","sql":"SELECT TO_BASE64('SQL') AS enc, FROM_BASE64('U1FM') AS decoded;"},{"engine_slug":"postgresql","sql":"SELECT encode('SQL'::bytea, 'base64') AS enc,\n       decode('U1FM', 'base64') AS decoded;"},{"engine_slug":"sql-server","sql":"SELECT BASE64_ENCODE(CAST('SQL' AS varbinary(10))) AS enc,\n       CAST(BASE64_DECODE('U1FM') AS varchar(10)) AS decoded;"},{"engine_slug":"sqlite","sql":"SELECT rtrim(base64(cast('SQL' AS blob)), char(10)) AS enc,\n       cast(base64('U1FM') AS text) AS decoded;  -- sqlite3 shell"},{"engine_slug":"oracle","sql":"SELECT UTL_RAW.CAST_TO_VARCHAR2(\n  UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW('SQL'))) AS enc\nFROM dual;"}],"faqs":[{"question":"Why is base64 output a third longer than the input?","answer":"Every 3 bytes become 4 characters, and the last group is padded to 4 with '='. A 16-byte value encodes to 24 characters, two of them padding."},{"question":"Can I decode base64 to text directly?","answer":"Not in one call on most engines: decode returns bytes, so chain a cast: convert_from(decode(x, 'base64'), 'UTF8') on PostgreSQL or CONVERT(FROM_BASE64(x) USING utf8mb4) on MySQL."}],"related":["encode-bytea","hex","unhex","string-cast"],"novel_uses":[{"body":"Before BASE64_ENCODE existed, T-SQL got base64 by casting an empty string to xml: xs:hexBinary renders the varbinary as hex and xs:base64Binary converts that to base64. It still works everywhere, which matters for shared scripts.","sql":"SELECT CAST('' AS xml).value('xs:base64Binary(xs:hexBinary(sql:column(\"b.data\")))', 'varchar(max)') AS b64 FROM (SELECT CONVERT(varbinary(16), token) AS data FROM sessions WHERE id = 1) AS b;"},{"body":"CONCAT the credentials with a colon, TO_BASE64 the result, and strip the 76-character line breaks with REPLACE so the header stays one line. Handy when a webhook or API config lives in the database.","sql":"SELECT CONCAT('Basic ', REPLACE(TO_BASE64(CONCAT(user_name, ':', token)), '\\n', '')) AS auth FROM service_accounts;"},{"body":"Encoded values give themselves away: length divisible by 4, only letters, digits, + and /, at most two = at the end. A REGEXP filter with the length check finds tokens or payloads hiding in a text column.","sql":"SELECT v FROM secrets WHERE LENGTH(v) % 4 = 0 AND v REGEXP '^[A-Za-z0-9+/]+={0,2}$';"}]},"source_url":"https://sqlly.app/sql-functions/base64","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/base64-decode","corpus":"sql-functions","engine":null,"language":"en","title":"SQL base64 decoding","description":"How FROM_BASE64, decode(..., 'base64') and BASE64_DECODE turn Base64 back into bytes in MySQL, PostgreSQL and SQL Server 2025: bad input, whitespace, text output.","body":{"slug":"base64-decode","name":"FROM_BASE64","h1":"SQL base64 decoding","category":"string","lede":"Decodes Base64 text back into the original bytes.","syntax":"FROM_BASE64(string)  |  PostgreSQL: decode(value, 'base64')","return_type":"binary string","support":[{"engine_slug":"sql-server","status":"partial","note":"BASE64_DECODE(text) in SQL Server 2025 and Azure SQL; returns varbinary."},{"engine_slug":"postgresql","status":"partial","note":"decode(str, 'base64') returns bytea; convert_from turns it into text."},{"engine_slug":"mysql","status":"yes","note":"FROM_BASE64 is built in."},{"engine_slug":"sqlite","status":"no","note":"No Base64 in the core library; the sqlite3 shell has base64(), which encodes a BLOB and decodes TEXT."},{"engine_slug":"oracle","status":"partial","note":"UTL_ENCODE.BASE64_DECODE on RAW values."}],"gotchas":["Invalid Base64 returns NULL in MySQL with no warning, so a NULL can mean corrupt input rather than missing data. PostgreSQL raises an error instead.","The result is bytes: in MySQL CONVERT(FROM_BASE64(x) USING utf8mb4) for text; in PostgreSQL convert_from(decode(x, 'base64'), 'UTF8').","Whitespace inside the input is skipped by MySQL (FROM_BASE64('aGVs bG8=') is 'hello') and by PostgreSQL, so MIME line breaks decode fine. Other stray characters still fail."],"examples":[{"engine_slug":"mysql","sql":"SELECT FROM_BASE64('aGVsbG8=') AS decoded;  -- hello"},{"engine_slug":"postgresql","sql":"SELECT convert_from(decode('aGVsbG8=', 'base64'), 'UTF8') AS decoded;  -- hello"},{"engine_slug":"sql-server","sql":"SELECT BASE64_DECODE('aGVsbG8=') AS decoded;"},{"engine_slug":"oracle","sql":"SELECT UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW('aGVsbG8='))) AS decoded\nFROM dual;  -- hello"}],"faqs":[{"question":"Why does FROM_BASE64 return NULL for my string?","answer":"The input is not valid Base64: illegal characters (often the - and _ of base64url), bad padding, or a truncated value. Translate base64url back to + and / and restore padding first."},{"question":"How do I get text back instead of bytes?","answer":"In PostgreSQL wrap the bytes: convert_from(decode(v, 'base64'), 'UTF8'). In MySQL convert the result: CONVERT(FROM_BASE64(v) USING utf8mb4)."},{"question":"Does FROM_BASE64 accept line breaks?","answer":"Yes. MySQL and PostgreSQL skip spaces, tabs and newlines, so 76-character MIME lines decode as one value."}],"related":["to-base64","hex","quote","sha2"],"novel_uses":[{"body":"Captured Basic headers decode in one chain: take the part after the space, decode it, then split at the colon that separates user from secret.","sql":"SELECT SUBSTRING_INDEX(CONVERT(FROM_BASE64(SUBSTRING_INDEX(hdr, ' ', -1)) USING utf8mb4), ':', 1) AS api_user\nFROM request_log\nWHERE hdr LIKE 'Basic %';"},{"body":"Valid base64 without embedded whitespace is a multiple of 4 characters, so a length test catches truncated or mangled tokens before FROM_BASE64 turns them into a NULL.","sql":"SELECT id FROM tokens\nWHERE CHAR_LENGTH(value) % 4 <> 0;"}]},"source_url":"https://sqlly.app/sql-functions/base64-decode","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/base64-encode","corpus":"sql-functions","engine":null,"language":"en","title":"SQL base64 encoding","description":"How TO_BASE64, encode(..., 'base64') and BASE64_ENCODE encode data as Base64 in MySQL, PostgreSQL, SQL Server 2025 and Oracle: line breaks, URL safety, inverses.","body":{"slug":"base64-encode","name":"TO_BASE64","h1":"SQL base64 encoding","category":"string","lede":"Encodes a string or binary value as Base64 text for transport through text-only channels.","syntax":"TO_BASE64(string)  |  PostgreSQL: encode(bytes, 'base64')","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"BASE64_ENCODE(varbinary) in SQL Server 2025 and Azure SQL; older versions use an XML .value('xs:base64Binary(...)') trick."},{"engine_slug":"postgresql","status":"partial","note":"encode(convert_to(str, 'UTF8'), 'base64')."},{"engine_slug":"mysql","status":"yes","note":"TO_BASE64 is built in."},{"engine_slug":"sqlite","status":"no","note":"base64(X) is built in on SQLite 3.51.0: a blob is encoded, text is decoded."},{"engine_slug":"oracle","status":"partial","note":"UTL_ENCODE.BASE64_ENCODE on RAW values."}],"gotchas":["MySQL's TO_BASE64 and PostgreSQL's encode(..., 'base64') both break the output into 76-character lines. Strip the newlines before putting the value in a URL, JSON field or HTTP header.","The output uses the standard alphabet with + and / and = padding, so it is not URL-safe. Replace + with -, / with _ and drop the padding for base64url.","PostgreSQL's encode and Oracle's UTL_ENCODE take bytes, so text must be converted first: encode(convert_to(str, 'UTF8'), 'base64')."],"examples":[{"engine_slug":"mysql","sql":"SELECT TO_BASE64('hello') AS encoded;  -- aGVsbG8="},{"engine_slug":"postgresql","sql":"SELECT encode(convert_to(payload, 'UTF8'), 'base64') AS encoded\nFROM messages;"},{"engine_slug":"sql-server","sql":"SELECT BASE64_ENCODE(CAST('hello' AS varbinary(10))) AS encoded;  -- aGVsbG8="},{"engine_slug":"oracle","sql":"SELECT UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW('hello')) AS encoded\nFROM dual;  -- aGVsbG8="}],"faqs":[{"question":"Why does the Base64 output contain newlines?","answer":"MySQL and PostgreSQL follow the MIME rule of 76-character lines. Remove them with REPLACE(result, '\\n', '') in MySQL or replace(result, E'\\n', '') in PostgreSQL."},{"question":"Is SQL Base64 URL-safe?","answer":"No. The standard alphabet includes +, / and =. For URLs, replace + with -, / with _ and drop the padding after encoding."},{"question":"How do I decode Base64 back?","answer":"FROM_BASE64 in MySQL, decode(value, 'base64') in PostgreSQL, BASE64_DECODE in SQL Server 2025, then convert the bytes back to text."}],"related":["from-base64","hex","quote","md5"],"novel_uses":[{"body":"Base64 is a compact way to print the first bytes of a binary column when hex would double the length, which makes blob content skimmable in query logs.","sql":"SELECT id, TO_BASE64(LEFT(payload, 8)) AS head\nFROM messages;"},{"body":"The Authorization header value is base64 of user colon password, so one CONCAT and TO_BASE64 produce it from stored seed data. Strip the 76-character line breaks before sending.","sql":"SELECT CONCAT('Basic ', TO_BASE64(CONCAT(api_user, ':', api_token))) AS auth_header\nFROM service_accounts;"}]},"source_url":"https://sqlly.app/sql-functions/base64-encode","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/between","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BETWEEN operator","description":"BETWEEN tests an inclusive range: both bounds count, date-range pitfalls at midnight, NULL making the test UNKNOWN, NOT BETWEEN and BETWEEN SYMMETRIC.","body":{"slug":"between","name":"BETWEEN","h1":"SQL BETWEEN operator","category":"conditional","lede":"True when the value is greater than or equal to the low bound and less than or equal to the high bound.","syntax":"x BETWEEN low AND high | x NOT BETWEEN low AND high","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Both bounds are inclusive, so BETWEEN 100 AND 500 includes exactly 100 and 500.","Date ranges bite: BETWEEN '2026-01-01' AND '2026-12-31' misses everything on Dec 31 after midnight; prefer col >= '2026-01-01' AND col < '2027-01-01'.","If the tested value is NULL, the result is UNKNOWN and the row drops, even with NOT BETWEEN; a NULL bound is subtler, because the other bound can settle it, so 10 BETWEEN NULL AND 5 is FALSE and 10 NOT BETWEEN NULL AND 5 is TRUE.","Reversed bounds (low > high) are always FALSE; PostgreSQL's BETWEEN SYMMETRIC swaps them instead."],"examples":[{"engine_slug":"all","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500;"},{"engine_slug":"all","sql":"SELECT * FROM events WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01';"}],"faqs":[{"question":"Is BETWEEN inclusive?","answer":"Yes, on both ends, in every one of the five engines."},{"question":"How do I filter a whole month?","answer":"Half-open: col >= first_day AND col < first_day_next_month; BETWEEN first_day AND last_day misses the last day's timestamps after midnight, and BETWEEN the two first-days pulls in rows stamped exactly midnight on the next month's first day."},{"question":"What does BETWEEN do with NULL?","answer":"A NULL tested value gives UNKNOWN and the row is filtered, and NOT BETWEEN does not rescue it; a NULL bound can still let NOT BETWEEN return TRUE when the other bound decides the answer."}],"related":["between-symmetric","three-valued-logic","null","date-trunc","dateadd"],"novel_uses":[{"body":"The midnight trap belongs to timestamps; on a plain DATE column BETWEEN the first and last day includes every day of the quarter.","sql":"SELECT * FROM daily_totals WHERE day BETWEEN '2026-10-01' AND '2026-12-31';"},{"body":"UI range controls are inclusive at both ends, which is exactly BETWEEN's contract, so the query needs no fudge factors.","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500;"}]},"source_url":"https://sqlly.app/sql-functions/between","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/between-symmetric","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BETWEEN SYMMETRIC operator","description":"BETWEEN SYMMETRIC swaps reversed bounds so low > high still matches: PostgreSQL-only among the five engines, when it helps, and the data bugs it can hide.","body":{"slug":"between-symmetric","name":"BETWEEN SYMMETRIC","h1":"SQL BETWEEN SYMMETRIC operator","category":"conditional","lede":"BETWEEN that swaps its bounds when the first is larger than the second.","syntax":"x BETWEEN SYMMETRIC low AND high","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL only"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Plain BETWEEN with reversed bounds is always FALSE; SYMMETRIC normalizes them first.","It can hide data bugs: a swapped lower/upper bound that would have returned nothing now silently widens the match.","Portable form: x BETWEEN LEAST(a, b) AND GREATEST(a, b) on SQL Server 2022+ and MySQL (SQLite spells it min(a, b) and max(a, b)), but check NULL semantics: PostgreSQL and SQL Server skip a NULL argument, while MySQL and SQLite return NULL."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE n BETWEEN SYMMETRIC 500 AND 100;"},{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE n BETWEEN LEAST(500, 100) AND GREATEST(500, 100);"}],"faqs":[{"question":"What does SYMMETRIC mean here?","answer":"The bounds are symmetric: the engine swaps them if needed, so low > high still matches the range."},{"question":"Which engines support it?","answer":"PostgreSQL only among the big five; elsewhere wrap the bounds in LEAST and GREATEST (SQL Server 2022+, MySQL) or SQLite's two-argument min and max."},{"question":"Why not always use SYMMETRIC?","answer":"It can mask reversed-bound bugs that an empty result would have exposed."}],"related":["between","greatest","least","any"],"novel_uses":[{"body":"Two text fields or a slider can deliver max before min; BETWEEN SYMMETRIC absorbs the swap server-side instead of rejecting the query.","sql":"SELECT * FROM t WHERE n BETWEEN SYMMETRIC 500 AND 100;"},{"body":"SYMMETRIC normalizes the bounds' order only; a NULL bound still yields UNKNOWN and drops the row, so validate inputs before relying on it.","sql":"SELECT * FROM t WHERE n BETWEEN SYMMETRIC NULL AND 100;"}]},"source_url":"https://sqlly.app/sql-functions/between-symmetric","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/binary-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BINARY cast","description":"Casting text to bytes: MySQL's CAST AS BINARY, SQL Server's varbinary, PostgreSQL's bytea and SQLite's BLOB. The encoding behind the bytes differs per engine.","body":{"slug":"binary-cast","name":"BINARY / varbinary casts","h1":"SQL BINARY cast","category":"conversion","lede":"CAST(value AS BINARY) turns a value into raw bytes. Which bytes depends on the engine: the string's character set on MySQL, UTF-16 for nvarchar on SQL Server, the database encoding for bytea.","syntax":"CAST(expression AS BINARY)  -- MySQL  |  CONVERT(varbinary(n), expression)  -- SQL Server  |  CAST(expression AS BLOB)  -- SQLite","return_type":"binary","support":[{"engine_slug":"sql-server","status":"partial","note":"CONVERT(varbinary(n), value)"},{"engine_slug":"postgresql","status":"partial","note":"value::bytea or convert_to(text, encoding)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"CAST(x AS BLOB) keeps the text's bytes"},{"engine_slug":"oracle","status":"partial","note":"UTL_RAW.CAST_TO_RAW(text); HEXTORAW for hex strings"}],"gotchas":["MySQL's BINARY cast compares bytes: case folding disappears, and trailing spaces count even under PAD SPACE collations such as utf8mb4_general_ci. It is a one-off comparison change; a case-sensitive collation (utf8mb4_0900_as_cs, or utf8mb4_bin, which still ignores trailing spaces) is the persistent fix.","MySQL 8.0.27 deprecated the BINARY operator spelling (BINARY expr) in favour of CAST(expr AS BINARY). Old code still runs but raises warning 1287.","On SQL Server, CONVERT(varbinary(8), N'SQL') is 0x530051004C00 (UTF-16, two bytes per character) while CONVERT(varbinary(8), 'SQL') is 0x53514C. The same text casts to different bytes depending on its type.","PostgreSQL bytea is not a string type: it prints as hex with a \\x prefix, concatenates with || and needs convert_from(bytes, 'UTF8') to become text again."],"examples":[{"engine_slug":"mysql","sql":"SELECT CAST(name AS BINARY) = 'MATT' AS exact_match\nFROM users;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varbinary(16), token) AS bytes\nFROM sessions;"},{"engine_slug":"postgresql","sql":"SELECT decode('4d415454', 'hex') AS bytes;"},{"engine_slug":"sqlite","sql":"SELECT CAST('SQL' AS BLOB) AS b;"},{"engine_slug":"oracle","sql":"SELECT UTL_RAW.CAST_TO_RAW('SQL') AS b FROM dual;"}],"faqs":[{"question":"Is BINARY the same as a binary collation?","answer":"No. BINARY casts the value to bytes for one comparison; a binary or case-sensitive collation (utf8mb4_bin, utf8mb4_0900_as_cs) keeps the string type and changes the comparison rule. For case-sensitive matching, the collation is the intended tool."},{"question":"Why do my hashes differ between engines?","answer":"Because the bytes differ: MySQL hashes the string in its character set, SQL Server hashes nvarchar as UTF-16. HEX both inputs and compare the bytes before blaming the hash function."}],"related":["collate","hex","encode-bytea","cast"],"novel_uses":[{"body":"Casting to BLOB and printing with hex() shows the exact bytes a column holds, which is how you catch zero-width characters, stray control bytes and double-encoded accents that make two visible-equal strings refuse to join.","sql":"SELECT label, hex(CAST(label AS BLOB)) AS bytes FROM items WHERE id = 17;"},{"body":"convert_to and convert_from turn text into bytes in a named encoding and back, so UTF-8 that was once misread as LATIN1 (café stored as cafÃ©) is fixed by re-encoding to LATIN1 and decoding the bytes as UTF-8. Run it only on the damaged rows: a correctly stored é raises 'invalid byte sequence for encoding \"UTF8\"'.","sql":"SELECT convert_from(convert_to(legacy_name, 'LATIN1'), 'UTF8') AS cleaned FROM old_users WHERE legacy_name LIKE '%Ã%';"},{"body":"substring() works on varbinary, so the first four bytes compare directly against a binary literal. Testing the signature is cheaper than trusting a client-supplied extension.","sql":"SELECT file_name FROM uploads WHERE substring(contents, 1, 4) = 0x25504446;"}]},"source_url":"https://sqlly.app/sql-functions/binary-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bit-and","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BIT_AND function","description":"BIT_AND aggregates bitmasks: PostgreSQL and MySQL support, MySQL's 18446744073709551615 for an empty group, Oracle 21c+ BIT_AND_AGG, and no SQL Server or SQLite form.","body":{"slug":"bit-and","name":"BIT_AND","h1":"SQL BIT_AND function","category":"aggregate","lede":"ANDs the values of a group together bit by bit.","syntax":"BIT_AND(x) | BIT_AND_AGG(x)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"aggregate over integer and bit types; empty group returns NULL"},{"engine_slug":"mysql","status":"yes","note":"empty or all-NULL group returns all-ones 18446744073709551615, not 0"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"21c+: BIT_AND_AGG; empty or all-NULL group returns 0"}],"gotchas":["The AND identity is all ones, so MySQL's empty-group answer is 18446744073709551615, surprising next to BIT_OR's 0. PostgreSQL returns NULL for an empty group, and Oracle's BIT_AND_AGG returns 0.","NULLs are skipped, like every standard aggregate.","Check 'all rows grant this permission' with BIT_AND(perm_bits) & mask = mask: any row with a 0 in one of those bits clears it."],"examples":[{"engine_slug":"mysql","sql":"SELECT user_id, BIT_AND(perm_bits) FROM grants GROUP BY user_id;"},{"engine_slug":"postgresql","sql":"SELECT bit_and(x) FROM (VALUES (6), (3)) v(x); -- 2"},{"engine_slug":"oracle","sql":"SELECT user_id, BIT_AND_AGG(perm_bits) FROM grants GROUP BY user_id;"}],"faqs":[{"question":"Why does MySQL return all ones for an empty group?","answer":"All-ones is the AND identity: AND-ing nothing together must not change anything. PostgreSQL returns NULL instead, following the usual aggregate rule."},{"question":"How do I check all flags are set?","answer":"BIT_AND(perm_bits) & mask = mask: if any row lacks one of those bits, the aggregate loses it and the test fails."},{"question":"What about PostgreSQL?","answer":"bit_and(x) is a built-in aggregate over smallint, integer, bigint and bit columns: SELECT bit_and(perm_bits) FROM grants works as-is."}],"related":["bit-or","bit-xor","aggregate-nulls","mod"],"novel_uses":[{"body":"Each row holds one person's free-slot mask for a day; BIT_AND over the day returns the slots open for the whole team, one bit per agreed meeting.","sql":"SELECT day, BIT_AND(free_mask) AS team_free FROM calendars GROUP BY day;"},{"body":"As a window function in MySQL or PostgreSQL, BIT_AND(mask) OVER (PARTITION BY team_id) stamps each grant row with the mask the whole team shares.","sql":"SELECT user_id, perm_bits, BIT_AND(perm_bits) OVER (PARTITION BY team_id) AS team_common FROM grants;"}]},"source_url":"https://sqlly.app/sql-functions/bit-and","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bit-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BIT_LENGTH function","description":"BIT_LENGTH returns a string's size in bits (8 times the byte length) on PostgreSQL and MySQL, for protocol and encoding-level arithmetic.","body":{"slug":"bit-length","name":"BIT_LENGTH","h1":"SQL BIT_LENGTH function","category":"string","lede":"Counts bits rather than bytes or characters. Rarely needed, and it inherits every encoding surprise of byte length.","syntax":"BIT_LENGTH(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["It is literally OCTET_LENGTH * 8: 'héllo' is 48 bits in UTF-8, 5 characters. All the same encoding caveats apply.","PostgreSQL and MySQL have it; SQL Server, SQLite and Oracle do not. Multiply DATALENGTH by 8 instead (LENGTHB by 8 on Oracle is unverified here); on nvarchar DATALENGTH counts UTF-16 bytes, so N'héllo' gives 80 bits where BIT_LENGTH gives 48.","MySQL's BIT_LENGTH always reflects the string's charset encoding: utf8mb4 data counts real UTF-8 bytes.","For a blob or binary column it counts the raw bytes' bits, which is the one case where it is unambiguous."],"examples":[{"engine_slug":"postgresql","sql":"SELECT BIT_LENGTH('héllo') AS bits, OCTET_LENGTH('héllo') AS bytes;\n-- 48, 6"},{"engine_slug":"mysql","sql":"SELECT BIT_LENGTH('é') AS bits, CHAR_LENGTH('é') AS chars;\n-- 16, 1"}],"faqs":[{"question":"When would I use bits instead of bytes?","answer":"Mostly when a protocol or document spec states limits in bits. Bytes are the practical unit everywhere else."},{"question":"Is BIT_LENGTH affected by charset?","answer":"Yes. It measures the encoded bytes' bits, so the same string has different BIT_LENGTH under latin1 and utf8mb4 in MySQL."},{"question":"What is the Oracle equivalent?","answer":"LENGTHB * 8. Oracle has no BIT_LENGTH; its byte counter is LENGTHB."}],"related":["octet-length","length","varchar-char-semantics"],"novel_uses":[{"body":"Mojibake such as the two-character rendering of e-acute costs twice the bits of the real character, but it also has two characters, so BIT_LENGTH divided by CHAR_LENGTH stays at 16 for both. Flag it by its characters instead, for example a LIKE '%Ã%' search.","sql":"SELECT BIT_LENGTH('é') AS ok, BIT_LENGTH('Ã©') AS mojibake;  -- 16, 32"},{"body":"Base64 emits four characters per three bytes, so CEIL(BIT_LENGTH(payload) / 24.0) * 4 gives the encoded length before you allocate a column or buffer for it. That is the unwrapped length: past 57 bytes, PostgreSQL's encode(..., 'base64') and MySQL's TO_BASE64 insert a line break every 76 characters.","sql":"SELECT CEIL(BIT_LENGTH(payload) / 24.0) * 4 AS b64_chars FROM blobs;"}]},"source_url":"https://sqlly.app/sql-functions/bit-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bit-or","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BIT_OR function","description":"BIT_OR aggregates bitmasks: PostgreSQL and MySQL support, Oracle 21c+ BIT_OR_AGG, the 0 identity for empty groups, and the 'any row sets the flag' use case.","body":{"slug":"bit-or","name":"BIT_OR","h1":"SQL BIT_OR function","category":"aggregate","lede":"ORs the values of a group together bit by bit.","syntax":"BIT_OR(x) | BIT_OR_AGG(x)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"aggregate over integer and bit types; empty group returns NULL"},{"engine_slug":"mysql","status":"yes","note":"empty or all-NULL group returns 0"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"21c+: BIT_OR_AGG; empty or all-NULL group returns 0"}],"gotchas":["The OR identity is 0, so MySQL and Oracle return 0 for an empty group; PostgreSQL returns NULL.","NULLs are skipped.","Use it to collect every flag seen in a group: any row setting a bit keeps it set in the result."],"examples":[{"engine_slug":"mysql","sql":"SELECT user_id, BIT_OR(perm_bits) AS all_granted FROM grants GROUP BY user_id;"},{"engine_slug":"oracle","sql":"SELECT user_id, BIT_OR_AGG(perm_bits) FROM grants GROUP BY user_id;"},{"engine_slug":"postgresql","sql":"SELECT user_id, BIT_OR(perm_bits) AS all_granted FROM grants GROUP BY user_id;"}],"faqs":[{"question":"What does an empty group return?","answer":"0 in MySQL and Oracle, the OR identity; NULL in PostgreSQL, following the usual aggregate rule."},{"question":"BIT_OR vs MAX for flags?","answer":"They agree when each row holds one flag value of 0 or 1. With masks they differ: MAX(4, 3) is 4, BIT_OR(4, 3) is 7."},{"question":"Does PostgreSQL have an aggregate BIT_OR?","answer":"Yes, bit_or(x) is a built-in aggregate over integer and bit types."}],"related":["bit-and","bit-xor","aggregate-nulls","mod"],"novel_uses":[{"body":"MySQL: BIT_OR(1 << DAYOFWEEK(login_at)) packs the weekdays each user has logged in on into one integer per user (bits 1 to 7, Sunday to Saturday), so a whole login history collapses to one row per user; the app decodes it with shifts.","sql":"SELECT user_id, BIT_OR(1 << DAYOFWEEK(login_at)) AS week_mask FROM logins GROUP BY user_id;"},{"body":"BIT_AND collects bits every row has, BIT_OR collects bits any row has, so the OR bits with the AND bits masked out are exactly the sometimes-on bits of a role. Mask with & ~ rather than subtracting: in MySQL a role whose perm_bits are all NULL gets BIT_AND = 18446744073709551615 and BIT_OR = 0, and the subtraction fails with a BIGINT UNSIGNED out-of-range error.","sql":"SELECT role_id, BIT_AND(perm_bits) AS always_on, BIT_OR(perm_bits) & ~BIT_AND(perm_bits) AS sometimes_on FROM grants GROUP BY role_id;"}]},"source_url":"https://sqlly.app/sql-functions/bit-or","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bit-xor","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BIT_XOR function","description":"BIT_XOR aggregates bitmasks: MySQL and PostgreSQL 14+ support, Oracle 21c+ BIT_XOR_AGG, the 0 identity, self-inverse behaviour and parity use cases.","body":{"slug":"bit-xor","name":"BIT_XOR","h1":"SQL BIT_XOR function","category":"aggregate","lede":"XORs the values of a group together bit by bit.","syntax":"BIT_XOR(x) | BIT_XOR_AGG(x)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 14+ aggregate; # is the scalar XOR operator"},{"engine_slug":"mysql","status":"yes","note":"empty or all-NULL group returns 0"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"21c+: BIT_XOR_AGG; empty or all-NULL group returns 0"}],"gotchas":["XOR is self-inverse: any value that appears an even number of times cancels out, which powers parity checks and find-the-odd-one-out tricks.","MySQL and Oracle return 0 for empty and all-NULL groups, the XOR identity; PostgreSQL returns NULL.","NULLs are skipped."],"examples":[{"engine_slug":"mysql","sql":"SELECT BIT_XOR(id) FROM nodes;"},{"engine_slug":"oracle","sql":"SELECT BIT_XOR_AGG(checksum) FROM chunks;"},{"engine_slug":"postgresql","sql":"SELECT BIT_XOR(id) AS parity FROM nodes;"}],"faqs":[{"question":"What is BIT_XOR good for?","answer":"Parity checks, cheap checksums and the classic 'every id appears twice, find the odd one' puzzle: XOR all ids."},{"question":"What does an empty group return?","answer":"0 in MySQL and Oracle, NULL in PostgreSQL."},{"question":"Why does XOR-ing twice cancel?","answer":"x XOR x = 0, so feeding the same values again restores the identity."}],"related":["bit-and","bit-or","aggregate-nulls","mod"],"novel_uses":[{"body":"MySQL: XOR is order-free, so one number per copy flags tables that differ; run the same CRC of every row on both sides and compare (a match is very likely, not proof, since 32-bit CRCs can collide).","sql":"SELECT BIT_XOR(CRC32(CONCAT_WS('#', id, status, updated_at))) FROM accounts;"},{"body":"Equal values cancel under XOR, so grouping transfer legs by pair id and requiring BIT_XOR(amount_cents) = 0 proves both legs agree.","sql":"SELECT pair_id, BIT_XOR(amount_cents) AS mismatch FROM transfer_legs GROUP BY pair_id HAVING BIT_XOR(amount_cents) <> 0;"}]},"source_url":"https://sqlly.app/sql-functions/bit-xor","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bitand","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BITAND function","description":"Bitwise AND across integers: Oracle spells it BITAND(x, y), the other four use the & operator. Counts as arithmetic for flags, masks and permissions.","body":{"slug":"bitand","name":"BITAND","h1":"SQL BITAND function","category":"math","lede":"Returns the bitwise AND of two integers: BITAND(12, 10) is 8: each output bit is set only where both inputs have it.","syntax":"BITAND(a, b)  -- Oracle  |  a & b  -- the other engines","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"& operator; BITAND does not exist as a name"},{"engine_slug":"postgresql","status":"partial","note":"& operator on integer types"},{"engine_slug":"mysql","status":"partial","note":"& operator; also | ^ ~ << >> (^ is bitwise XOR)"},{"engine_slug":"sqlite","status":"partial","note":"& operator on integers"},{"engine_slug":"oracle","status":"yes","note":"BITAND(a, b) function; there is no & operator in Oracle SQL"}],"gotchas":["Same operation, different syntax: Oracle wraps it in a function, everyone else uses the infix & operator.","Fractional operands are handled inconsistently: SQL Server and PostgreSQL reject them with a type error, while MySQL rounds (12.5 & 3 is 13 & 3 = 1) and SQLite and Oracle BITAND truncate (12 & 3 = 0).","Flags decode with masks: (flags & 4) <> 0 tests the third bit; BITAND(flags, 4) on Oracle does the same."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 12 & 10 AS and_result;  -- 8, also on SQL Server, MySQL and SQLite"},{"engine_slug":"oracle","sql":"SELECT BITAND(12, 10) AS and_result FROM dual;  -- 8"},{"engine_slug":"postgresql","sql":"SELECT COUNT(*) FROM users WHERE (permissions & 4) <> 0;  -- has the write flag"},{"engine_slug":"sql-server","sql":"SELECT 12 & 10 AS and_result;  -- 8"},{"engine_slug":"mysql","sql":"SELECT 12 & 10 AS and_result;  -- 8"},{"engine_slug":"sqlite","sql":"SELECT 12 & 10 AS and_result;  -- 8"}],"faqs":[{"question":"Is BITAND available outside Oracle?","answer":"The name is Oracle-only, but the operation is universal: write a & b on SQL Server, PostgreSQL, MySQL and SQLite for the identical result."},{"question":"How do I test whether a bit flag is set?","answer":"Mask and compare: (flags & 4) <> 0 checks the bit worth 4. Oracle: BITAND(flags, 4) > 0."},{"question":"Can I use & on decimal columns?","answer":"Not reliably. SQL Server and PostgreSQL reject decimal operands; MySQL and SQLite silently convert them to integers, which can hide a wrong column. Cast to an integer type first, or store flags as integers."}],"related":["bitwise-operators","exponent-operator","arithmetic-operators","modulo-operator"],"novel_uses":[{"body":"(value >> 4) & 15 pulls the second nibble out of a packed integer, turning one status column into several fields. MySQL, PostgreSQL, SQLite and SQL Server all have the shift; Oracle divides and TRUNCs instead.","sql":"SELECT (flags >> 4) & 15 AS field2 FROM packed;"},{"body":"x & (x - 1) = 0 holds only for powers of two and zero, so a config scan flags bucket counts that would break even distribution. One WHERE clause replaces a log-and-compare dance.","sql":"SELECT * FROM shard_config WHERE bucket_count > 0 AND (bucket_count & (bucket_count - 1)) <> 0;"}]},"source_url":"https://sqlly.app/sql-functions/bitand","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bitwise-operators","corpus":"sql-functions","engine":null,"language":"en","title":"SQL bitwise operators","description":"Bitwise &, |, ^ (# in PostgreSQL), ~ and shifts across SQL Server, PostgreSQL, MySQL and SQLite, and Oracle's BITAND. Includes BIT_COUNT for counting set bits.","body":{"slug":"bitwise-operators","name":"& | ^ ~ << >>","h1":"SQL bitwise operators","category":"math","lede":"Bit flags packed into one integer are tested with bitwise operators. The symbols are mostly shared, with two traps: ^ and Oracle.","syntax":"a & b  |  a | b  |  a ^ b  |  ~a  |  a << n  |  a >> n","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"& | ^ ~; << >>, LEFT_SHIFT, RIGHT_SHIFT, BIT_COUNT, GET_BIT and SET_BIT from 2022"},{"engine_slug":"postgresql","status":"yes","note":"# is XOR (^ is power); bit_count() for bit strings and bytea"},{"engine_slug":"mysql","status":"yes","note":"all six plus BIT_COUNT(); results are unsigned 64-bit"},{"engine_slug":"sqlite","status":"yes","note":"& | ~ << >>; no XOR operator"},{"engine_slug":"oracle","status":"partial","note":"BITAND() is the documented scalar; BIT_AND_AGG, BIT_OR_AGG and BIT_XOR_AGG aggregates from 21c"}],"gotchas":["^ is XOR on SQL Server and MySQL but exponentiation on PostgreSQL: 5 ^ 3 is 6 on MySQL and 125 on PostgreSQL. PostgreSQL's XOR is #; SQLite has none, so write (a | b) - (a & b).","MySQL returns unsigned 64-bit results: ~5 is 18446744073709551610, not -6.","On SQL Server, << and >> and the BIT_COUNT, GET_BIT and SET_BIT functions arrived in SQL Server 2022.","A filter such as WHERE flags & 4 <> 0 cannot seek an index on flags. Separate boolean columns or a computed column can be indexed."],"examples":[{"engine_slug":"mysql","sql":"SELECT 5 & 3 AS b_and, 5 | 3 AS b_or, 5 ^ 3 AS b_xor, 1 << 4 AS shl, BIT_COUNT(255) AS ones;  -- 1, 7, 6, 16, 8"},{"engine_slug":"postgresql","sql":"SELECT 5 & 3 AS b_and, 5 | 3 AS b_or, 5 # 3 AS b_xor, 5 ^ 3 AS power, ~5 AS b_not;  -- 1, 7, 6, 125, -6"},{"engine_slug":"sql-server","sql":"SELECT 5 & 3 AS b_and, 5 ^ 3 AS b_xor, 1 << 4 AS shl, BIT_COUNT(255) AS ones, GET_BIT(5, 0) AS bit0;  -- 1, 6, 16, 8, 1"},{"engine_slug":"oracle","sql":"SELECT BITAND(5, 3) AS b_and, 5 + 3 - 2 * BITAND(5, 3) AS b_xor FROM dual;  -- 1, 6"},{"engine_slug":"sqlite","sql":"SELECT 5 & 3 AS b_and, 5 | 3 AS b_or, (5 | 3) - (5 & 3) AS b_xor, ~5 AS b_not, 1 << 4 AS shl, 16 >> 2 AS shr;  -- 1, 7, 6, -6, 16, 4"}],"faqs":[{"question":"How do I check whether a flag bit is set?","answer":"AND with the flag and compare with zero: WHERE flags & 4 <> 0. In Oracle: WHERE BITAND(flags, 4) <> 0."},{"question":"What is the XOR operator in PostgreSQL?","answer":"#. The ^ operator raises to a power, so 2 ^ 3 is 8."}],"related":["bitand","bit-and","bit-or","xor"],"novel_uses":[{"body":"BIT_COUNT(a ^ b) is the Hamming distance between two flag words: the XOR isolates the bits that differ and the popcount totals them. SQL Server 2022 and MySQL ship BIT_COUNT, PostgreSQL calls it bit_count for bit strings and bytea.","sql":"SELECT BIT_COUNT(10 ^ 6) AS changed;  -- 2, on MySQL"},{"body":"MySQL treats operands as unsigned 64-bit, so -1 >> 60 returns 15. PostgreSQL and SQLite shift arithmetically and return -1. SQL Server shifts logically within the operand's type, so -1 >> 1 is 2147483647 on an int and -1 >> 60 is 0, because 60 is past the 32-bit width. The same right shift disagrees across engines the moment negative numbers appear.","sql":"SELECT -1 >> 60 AS shift_result;  -- 15 on MySQL, -1 on PostgreSQL and SQLite, 0 on SQL Server"}]},"source_url":"https://sqlly.app/sql-functions/bitwise-operators","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bool-and","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BOOL_AND function","description":"BOOL_AND in PostgreSQL: true only when every non-NULL row is true, the MIN(condition) recipes for MySQL, SQL Server and SQLite, and how NULL rows are ignored.","body":{"slug":"bool-and","name":"BOOL_AND","h1":"SQL BOOL_AND function","category":"aggregate","lede":"Returns true only when every input row that is not NULL evaluates to true.","syntax":"BOOL_AND(boolean) | BOOL_AND(boolean) FILTER (WHERE ...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"use MIN(col = 1) or SUM(col = 1) = COUNT(col)"},{"engine_slug":"sqlite","status":"no","note":"use MIN(col) over 0/1 values"},{"engine_slug":"oracle","status":"partial","note":"23ai+ spells it BOOLEAN_AND_AGG; older releases use MIN over a 0/1 CASE"}],"gotchas":["NULL inputs are skipped entirely, not treated as false; a group where the non-NULL rows are all true still yields true.","An empty group or an all-NULL group returns NULL, not false; wrap with COALESCE(BOOL_AND(x), true) if you want the vacuously-true reading.","SQL Server, MySQL and SQLite have no BOOL_AND. MIN(status = 1) or SUM(status = 1) = COUNT(status) reproduces it with 0/1 values in MySQL and SQLite; SQL Server rejects a predicate as an aggregate argument, so use MIN(CASE WHEN status = 1 THEN 1 WHEN status IS NOT NULL THEN 0 END) there. Oracle 23ai has it as BOOLEAN_AND_AGG.","MySQL's BIT_AND is bitwise, not logical; do not use it as a substitute for booleans."],"examples":[{"engine_slug":"postgresql","sql":"SELECT bool_and(active) FROM users WHERE tenant_id = 42;"},{"engine_slug":"postgresql","sql":"SELECT project_id, bool_and(done) FILTER (WHERE assigned) FROM tasks GROUP BY project_id;"},{"engine_slug":"mysql","sql":"SELECT project_id, MIN(done = 1) AS all_done FROM tasks GROUP BY project_id;"},{"engine_slug":"oracle","sql":"SELECT dept_id, BOOLEAN_AND_AGG(active) FROM employees GROUP BY dept_id;"}],"faqs":[{"question":"What does BOOL_AND return for NULL values?","answer":"NULLs are ignored. Only rows that are not NULL count, so the result is true when every non-NULL row is true."},{"question":"How do I write BOOL_AND in MySQL or SQL Server?","answer":"Use MIN(condition) where the condition yields 1 or 0: MIN(status = 1) in MySQL, MIN(CASE WHEN status = 1 THEN 1 WHEN status IS NOT NULL THEN 0 END) in SQL Server. A result of 1 means every row passed. A plain ELSE 0 would count NULL rows as failures, which BOOL_AND does not."},{"question":"Is BOOL_AND the same as EVERY?","answer":"Yes. EVERY is the standard SQL name; PostgreSQL accepts both spellings, and Oracle 23ai accepts EVERY alongside BOOLEAN_AND_AGG."}],"related":["every","bool-or","aggregate-filter","min","count","case"],"novel_uses":[{"body":"Stamp every row with its group verdict: bool_and(ok) OVER (PARTITION BY batch_id) marks each row of a failed batch, so one later filter skips the whole batch without collapsing rows or re-querying.","sql":"SELECT batch_id, step, bool_and(ok) OVER (PARTITION BY batch_id) AS batch_ok FROM checks;"},{"body":"FILTER drops rows from just this aggregate: bool_and(ok) FILTER (WHERE stage <> 'draft') keeps drafts visible to COUNT(*) in the same SELECT instead of hiding them in a WHERE.","sql":"SELECT bool_and(ok) FILTER (WHERE stage <> 'draft') AS real_ok, COUNT(*) AS all_rows FROM checks;"},{"body":"One GROUP BY lists every tenant with at least one failed rule, the query a nightly data-quality job runs before humans ever look.","sql":"SELECT tenant_id FROM users GROUP BY tenant_id HAVING NOT bool_and(email_verified);"}]},"source_url":"https://sqlly.app/sql-functions/bool-and","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bool-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BOOLEAN cast","description":"Booleans across engines: real BOOLEAN on PostgreSQL and Oracle 23ai, BIT on SQL Server, a TINYINT alias on MySQL and the 0/1 convention on SQLite.","body":{"slug":"bool-cast","name":"Boolean casts","h1":"SQL BOOLEAN cast","category":"conversion","lede":"CAST(x AS BOOLEAN) works on PostgreSQL and Oracle 23ai, is a syntax error on MySQL, and has no target on SQL Server, where bit plays the part. Each engine stores truth differently.","syntax":"CAST(expression AS BOOLEAN)  -- PostgreSQL, Oracle 23ai  |  CAST(expression AS bit)  -- SQL Server","return_type":"boolean or integer","support":[{"engine_slug":"sql-server","status":"partial","note":"bit: 0, 1 and NULL only"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"BOOL is a column-type alias for TINYINT(1); not a CAST target"},{"engine_slug":"sqlite","status":"partial","note":"no boolean type; TRUE and FALSE are 1 and 0"},{"engine_slug":"oracle","status":"yes","note":"SQL BOOLEAN from 23ai; PL/SQL only before that"}],"gotchas":["MySQL has no BOOLEAN cast target: CAST(x AS BOOLEAN) and CAST(x AS BOOL) are syntax errors. A BOOL column is TINYINT(1) and stores 2 as 2, so col = TRUE is false for it while col IS TRUE is true.","SQL Server bit stores 0, 1 and NULL and has no TRUE/FALSE keywords. Any non-zero number casts to 1, and the strings 'true' and 'false' convert to 1 and 0.","Oracle added a SQL BOOLEAN type in 23ai; CAST(1 AS BOOLEAN) and CAST('yes' AS BOOLEAN) both return TRUE there. Older releases store CHAR(1) 'Y'/'N' or NUMBER(1) and compare explicitly.","SQLite has no boolean storage class: TRUE and FALSE are keywords for 1 and 0, and filters treat any non-zero value as true. CAST(x AS BOOLEAN) only applies NUMERIC affinity."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'true'::boolean, 1::boolean AS t;"},{"engine_slug":"sql-server","sql":"SELECT CAST(1 AS bit) AS active;"},{"engine_slug":"oracle","sql":"SELECT CAST(1 AS BOOLEAN) AS flag FROM dual;  -- 23ai"},{"engine_slug":"mysql","sql":"SELECT (score >= 50) AS passed\nFROM results;"},{"engine_slug":"sqlite","sql":"SELECT TRUE AS t, FALSE AS f;"}],"faqs":[{"question":"Why does true fail on SQL Server?","answer":"SQL Server has no TRUE or FALSE keywords: bit columns take 1 and 0 (or the strings 'true' and 'false'). PostgreSQL, Oracle 23ai, MySQL and SQLite all accept TRUE and FALSE, though MySQL and SQLite read them as 1 and 0."},{"question":"How do I get a strict 0/1 flag on MySQL?","answer":"Compare instead of casting: (x <> 0) returns exactly 0 or 1, or NULL for NULL. MySQL has no boolean cast, and a BOOL column will store any TINYINT value you give it."}],"related":["cast","case","implicit-conversion"],"novel_uses":[{"body":"SUM and AVG refuse bit operands, so cast first: SUM(CAST(flag AS INT)) counts the true rows, and AVG(CAST(flag AS DECIMAL(5,2))) * 100 gives the percent true. Casting to INT for the average would truncate it to 0 unless every row is true. The cast keeps the pass in a single scan.","sql":"SELECT SUM(CAST(flag AS INT)) AS trues, COUNT(*) AS total FROM flags_table;"},{"body":"Mask, then cast: (flags & 4)::bool turns the 0-or-4 mask result into an actual boolean column, so clients get true and false instead of numbers. Only integer casts to boolean; for a smallint or bigint column write (flags & 4) <> 0 instead. It reads far better in API rows and CSV exports.","sql":"SELECT (flags & 4)::bool AS can_edit FROM members;"}]},"source_url":"https://sqlly.app/sql-functions/bool-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/bool-or","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BOOL_OR function","description":"BOOL_OR in PostgreSQL: true when any non-NULL row is true; MAX(condition) on MySQL and SQLite, MAX(CASE WHEN ...) on SQL Server, and NULL handling.","body":{"slug":"bool-or","name":"BOOL_OR","h1":"SQL BOOL_OR function","category":"aggregate","lede":"Returns true when at least one input row that is not NULL evaluates to true.","syntax":"BOOL_OR(boolean) | BOOL_OR(boolean) FILTER (WHERE ...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"use MAX(col = 1)"},{"engine_slug":"sqlite","status":"no","note":"use MAX(col) over 0/1 values"},{"engine_slug":"oracle","status":"partial","note":"23ai+ spells it BOOLEAN_OR_AGG; older releases use MAX over a 0/1 CASE"}],"gotchas":["NULL inputs are skipped; a group of all NULLs returns NULL, not false. Use COALESCE(BOOL_OR(x), false) for a two-valued result.","Without BOOL_OR, MAX over 0/1 values does the job: MAX(col = 1) in MySQL or MAX(CASE WHEN cond THEN 1 END) everywhere; leave out ELSE 0, since with it an all-NULL group returns 0 instead of NULL. Oracle 23ai ships it as BOOLEAN_OR_AGG.","bool_or(x) is exactly NOT bool_and(NOT x) for non-NULL inputs, which matters when porting between engines that only have one of them."],"examples":[{"engine_slug":"postgresql","sql":"SELECT bool_or(has_exception) FROM runs WHERE day = '2026-11-19';"},{"engine_slug":"mysql","sql":"SELECT project_id, MAX(blocked = 1) AS any_blocked FROM tasks GROUP BY project_id;"},{"engine_slug":"oracle","sql":"SELECT dept_id, BOOLEAN_OR_AGG(blocked) FROM rules GROUP BY dept_id;"}],"faqs":[{"question":"What does BOOL_OR return for an empty group?","answer":"NULL, not false. COALESCE(BOOL_OR(x), false) if you need a strict boolean."},{"question":"What is the MySQL equivalent of BOOL_OR?","answer":"MAX(flag = 1): MySQL compares yield 1 or 0, and MAX picks out the 1 if any row has it."},{"question":"How does BOOL_OR treat NULL rows?","answer":"They are ignored. A NULL row never makes the result true or false; only non-NULL rows decide."}],"related":["bool-and","every","max","aggregate-nulls","case"],"novel_uses":[{"body":"bool_or(has_error) OVER (PARTITION BY batch_id) copies the batch verdict onto every row, so the load job filters failed batches after staging instead of re-querying per batch.","sql":"SELECT batch_id, row_no, bool_or(has_error) OVER (PARTITION BY batch_id) AS batch_bad FROM staged_rows;"},{"body":"MySQL: one MAX(dow = n) column per weekday builds an attendance grid, one row per user with no CASE and no self-join.","sql":"SELECT user_id, MAX(dow = 1) AS mon, MAX(dow = 2) AS tue, MAX(dow = 3) AS wed FROM logins GROUP BY user_id;"}]},"source_url":"https://sqlly.app/sql-functions/bool-or","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/boolean","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BOOLEAN type","description":"The BOOLEAN type across engines: PostgreSQL's true boolean, SQL Server's BIT, MySQL's TINYINT(1) alias, SQLite's 0/1 integers and Oracle's 23ai SQL boolean.","body":{"slug":"boolean","name":"BOOLEAN","h1":"SQL BOOLEAN type","category":"conditional","lede":"What TRUE and FALSE actually are on each of the five engines.","syntax":"col BOOLEAN | col BIT | col BOOLEAN -- really TINYINT(1)","return_type":"boolean / bit / tinyint / integer","support":[{"engine_slug":"sql-server","status":"partial","note":"BIT: 0, 1 or NULL; no TRUE/FALSE literals"},{"engine_slug":"postgresql","status":"yes","note":"real BOOLEAN type"},{"engine_slug":"mysql","status":"partial","note":"BOOLEAN is an alias for TINYINT(1); TRUE and FALSE are just 1 and 0"},{"engine_slug":"sqlite","status":"partial","note":"INTEGER 0/1; TRUE and FALSE keywords since 3.23"},{"engine_slug":"oracle","status":"partial","note":"BOOLEAN column type and TRUE/FALSE literals in 23ai; earlier releases use NUMBER(1) plus a CHECK"}],"gotchas":["MySQL's BOOLEAN stores any tinyint: 2 is not an error, so 'boolean' columns need a CHECK to stay 0/1.","SQL Server has no TRUE/FALSE literals: write 1 and 0, or CAST(1 AS BIT). The strings 'TRUE' and 'FALSE' do convert to BIT 1 and 0.","Oracle only gained a SQL BOOLEAN with 23ai; for decades the pattern has been NUMBER(1) with a CHECK constraint.","PostgreSQL and Oracle 23ai are the two where a boolean column holds real TRUE/FALSE values; MySQL and SQLite let you select a condition too, but it comes back as the integer 1 or 0, and SQL Server cannot select one at all."],"examples":[{"engine_slug":"postgresql","sql":"SELECT true, false, NULL::bool;"},{"engine_slug":"sql-server","sql":"SELECT CAST(1 AS BIT) AS t, CAST(0 AS BIT) AS f;"},{"engine_slug":"mysql","sql":"SELECT TRUE = 1 AS one, TRUE + 1 AS two;"},{"engine_slug":"sqlite","sql":"SELECT TRUE = 1 AS t, FALSE = 0 AS f;"},{"engine_slug":"oracle","sql":"SELECT 1 < 2 AS flag FROM dual;"}],"faqs":[{"question":"Is MySQL's BOOLEAN a real boolean?","answer":"No, it is TINYINT(1) with TRUE/FALSE mapped to 1/0; any value from -128 to 127 fits unless you add a CHECK."},{"question":"How do I write TRUE in SQL Server?","answer":"You cannot; use 1 (or CAST(1 AS BIT)) in comparisons."},{"question":"Does Oracle support BOOLEAN in SQL?","answer":"Only since 23ai; before that NUMBER(1) with a CHECK (col IN (0, 1))."}],"related":["is-true","three-valued-logic","bool-and","cast"],"novel_uses":[{"body":"A plain index on a boolean matches about half the table for either value, so the planner rarely uses it; a partial or filtered index on the active subset stays tiny and gets used.","sql":"CREATE INDEX ON orders (created_at) WHERE is_open;"},{"body":"PostgreSQL needs a cast to sum them, SUM(flag::int); MySQL and SQLite add the 0 or 1 directly; SQL Server spells out the CASE.","sql":"SELECT SUM(flag::int) AS open_count FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/boolean","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/btrim","corpus":"sql-functions","engine":null,"language":"en","title":"SQL BTRIM function","description":"PostgreSQL's BTRIM strips any of the given characters from both ends of a string, the explicit form of TRIM(BOTH chars FROM s).","body":{"slug":"btrim","name":"BTRIM","h1":"SQL BTRIM function","category":"string","lede":"Removes every leading and trailing character that appears in a character set. Spaces by default; name the set to strip quotes, slashes, zeros.","syntax":"BTRIM(string [, characters])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"ltrim/rtrim are the one-sided siblings"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["It strips any combination of the given characters, in any order and count: BTRIM('xyxabcxy', 'xy') is 'abc'; it is not a prefix/suffix match.","Without the second argument it strips spaces only, never tabs or newlines.","Set trims elsewhere: trim(s, 'xy') in SQLite (which has no TRIM ... FROM syntax) and TRIM('xy' FROM s) in SQL Server 2017+. MySQL's TRIM(BOTH 'xy' FROM s) removes the substring 'xy', not the characters, so 'xyxabcxy' becomes 'xabc'. Oracle's TRIM takes a single character only; LTRIM(RTRIM(s, 'xy'), 'xy') handles a set.","Interior characters are untouched; only the ends are cleaned."],"examples":[{"engine_slug":"postgresql","sql":"SELECT BTRIM('xyxabcxy', 'xy') AS core;  -- abc"},{"engine_slug":"postgresql","sql":"SELECT BTRIM('  padded  ') AS plain;  -- padded"},{"engine_slug":"postgresql","sql":"SELECT BTRIM('\"quoted\"', '\"') AS unquoted;  -- quoted"}],"faqs":[{"question":"Is BTRIM the same as TRIM?","answer":"Yes in PostgreSQL: BTRIM(s, chars) equals TRIM(BOTH chars FROM s). The other engines spell it TRIM; BTRIM is the PostgreSQL name."},{"question":"Why did BTRIM eat more characters than I wanted?","answer":"It removes characters from the set at both ends until it meets one outside the set. BTRIM('000120', '0') returns '12' because the trailing zero goes too; use LTRIM(s, '0') to strip leading zeros only."},{"question":"Does BTRIM remove tabs and newlines?","answer":"Not unless you list them: BTRIM(s, E' \\t\\n'). The default set is just the space character."}],"related":["trim","space","trim-leading-zeros"],"novel_uses":[{"body":"BTRIM(val, '\"') removes surrounding double quotes from either side, so one expression casts both '\"42\"' and bare '42' without a CASE.","sql":"SELECT BTRIM(val, '\"')::numeric AS n FROM staged;"},{"body":"Trimming slashes from both sides before gluing means 'https://x' and 'https://x/' produce the same join, with exactly one separator added back.","sql":"SELECT BTRIM(base, '/') || '/' || BTRIM(path, '/') AS joined FROM endpoints;"}]},"source_url":"https://sqlly.app/sql-functions/btrim","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cardinality","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CARDINALITY function","description":"CARDINALITY counts the elements of a PostgreSQL array or an Oracle nested table, and returns 0 for an empty array where ARRAY_LENGTH returns NULL.","body":{"slug":"cardinality","name":"CARDINALITY","h1":"SQL CARDINALITY function","category":"conversion","lede":"CARDINALITY(tags) is the SQL-standard element count. On a multidimensional PostgreSQL array it counts every element across all dimensions.","syntax":"CARDINALITY(collection)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"no collection types"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no collection types; JSON_LENGTH for JSON"},{"engine_slug":"sqlite","status":"partial","note":"json_array_length for JSON arrays"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["CARDINALITY(empty) is 0 while ARRAY_LENGTH(empty, 1) is NULL on PostgreSQL; CARDINALITY is the right tool for WHERE clauses over possibly empty arrays.","On Oracle it works on nested tables only; a VARRAY raises ORA-00932. A NULL collection (as opposed to an empty one) returns NULL, so COALESCE(CARDINALITY(c), 0) when zero matters.","For a 3x2 PostgreSQL array, CARDINALITY is 6 while ARRAY_LENGTH(arr, 1) is 3. Use CARDINALITY for 'how many values', ARRAY_LENGTH for the size of one dimension."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM articles WHERE CARDINALITY(tags) > 0;"},{"engine_slug":"oracle","sql":"SELECT CARDINALITY(phone_list) AS n FROM contacts;"},{"engine_slug":"sqlite","sql":"SELECT * FROM articles WHERE json_array_length(tags) > 0;"}],"faqs":[{"question":"CARDINALITY or ARRAY_LENGTH?","answer":"CARDINALITY for counts: standard spelling, 0 on empty. ARRAY_LENGTH when you need one dimension of a multidimensional PostgreSQL array."},{"question":"Why NULL instead of 0?","answer":"The array or collection itself is SQL NULL, not empty. An empty one counts 0; COALESCE folds the NULL case into zero."}],"related":["array-length","unnest","array-contains","count"],"novel_uses":[{"body":"CARDINALITY is immutable, so a functional index on ((CARDINALITY(tags))) serves queries that filter or sort by list size without touching every array.","sql":"CREATE INDEX ix_article_tag_count ON articles ((cardinality(tags)));"},{"body":"GROUP BY CARDINALITY(phone_list) shows the distribution of nested-table sizes, which is how you size storage and spot the one row holding ten thousand phones.","sql":"SELECT CARDINALITY(phone_list) AS n, COUNT(*) AS contacts FROM contacts GROUP BY CARDINALITY(phone_list) ORDER BY n;"}]},"source_url":"https://sqlly.app/sql-functions/cardinality","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/case","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CASE expression","description":"The SQL CASE expression in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: searched and simple forms, NULL pitfalls, ORDER BY tricks and aggregate pivots.","body":{"slug":"case","name":"CASE","h1":"SQL CASE expression","category":"conditional","lede":"SQL's if/else inside a query. It is an expression that returns a value (usable in SELECT, WHERE, ORDER BY, GROUP BY and inside aggregates), not a statement.","syntax":"CASE WHEN cond THEN result [WHEN ...] [ELSE result] END  |  CASE value WHEN v THEN r ... END","return_type":"the common type of all THEN and ELSE results","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Two forms: searched (CASE WHEN x > 5 THEN ...) and simple (CASE status WHEN 'new' THEN ...). The simple form cannot use operators or IS NULL.","Comparisons with NULL never match: WHEN col = NULL is never true. Write WHEN col IS NULL, or handle NULL in the ELSE.","Branch order matters: the first true WHEN wins, and later branches are skipped. One documented exception on SQL Server: aggregates inside the branches are computed first, so CASE WHEN COUNT(*) = 0 THEN 0 ELSE 1 / MIN(x) END can still divide by zero.","The result type is resolved across every branch. On SQL Server, CASE WHEN ok THEN 1 ELSE 'n/a' END is an int expression and fails when the 'n/a' branch is taken.","In aggregates, CASE builds conditional sums: SUM(CASE WHEN status = 'paid' THEN amount END) works on every engine, where PIVOT syntax exists only on SQL Server and Oracle."],"examples":[{"engine_slug":"all","sql":"SELECT name,\n       CASE WHEN amount >= 1000 THEN 'big'\n            WHEN amount >= 100  THEN 'mid'\n            ELSE 'small' END AS size_band\nFROM orders;"},{"engine_slug":"all","sql":"SELECT SUM(CASE WHEN status = 'paid' THEN amount END) AS paid_total\nFROM invoices;"},{"engine_slug":"all","sql":"SELECT id, status,\n       CASE status WHEN 'new' THEN 1 WHEN 'paid' THEN 2 ELSE 3 END AS sort_key\nFROM orders\nORDER BY sort_key;"}],"faqs":[{"question":"What is the difference between simple and searched CASE?","answer":"Simple CASE compares one expression for equality against values; searched CASE evaluates full boolean conditions. Only the searched form can express ranges and IS NULL."},{"question":"Why doesn't WHEN col = NULL work in CASE?","answer":"NULL never equals anything in SQL, including another NULL. Use WHEN col IS NULL, or let the ELSE catch it."},{"question":"Can CASE be used in WHERE and ORDER BY?","answer":"Yes. It is an expression anywhere a value goes. ORDER BY CASE status ... END is the standard custom-sort trick."}],"related":["coalesce","nullif","iif"],"novel_uses":[{"body":"NULLS LAST exists on PostgreSQL, Oracle and SQLite 3.30+; MySQL and SQL Server emulate it by sorting a flag first: NULL rows get 1, everything else 0, and the real column sorts within each tier.","sql":"SELECT name, reviewed_at\nFROM docs\nORDER BY CASE WHEN reviewed_at IS NULL THEN 1 ELSE 0 END, reviewed_at;"},{"body":"One CASE across candidate columns must merge all their types into one, which is where int-and-text sorting dies. Stacking one CASE per column keeps every type pure: the inactive ones are all NULL and sort together, so the active column decides the order.","sql":"-- :sort is 'name' or 'amount'\nSELECT name, amount\nFROM orders\nORDER BY CASE WHEN :sort = 'name' THEN name END,\n         CASE WHEN :sort = 'amount' THEN amount END;"}]},"source_url":"https://sqlly.app/sql-functions/case","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/case-insensitive-collation","corpus":"sql-functions","engine":null,"language":"en","title":"SQL case-insensitive comparison","description":"Match case-insensitively the way each engine intends: collations on SQL Server and MySQL, ILIKE and citext on PostgreSQL, NOCASE on SQLite.","body":{"slug":"case-insensitive-collation","name":"Case-insensitive comparison","h1":"SQL case-insensitive comparison","category":"string","lede":"UPPER(col) = UPPER(?) kills indexes. Every engine has a collation-level answer that keeps matching fast and locale-correct.","syntax":"col = 'value' COLLATE ci_collation  |  col ILIKE 'value'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server: default collations are already case-insensitive; pick a _CS collation per column or query for the rare case-sensitive match.","PostgreSQL: = is case-sensitive; use ILIKE, the citext extension type, or a nondeterministic ICU collation (PG 12+; CREATE COLLATION ... (provider = icu, locale = '...', deterministic = false)).","MySQL: default collations end in _ci (case-insensitive); _bin and utf8mb4_0900_as_cs are the case-sensitive ones.","SQLite: = is case-sensitive while LIKE is case-insensitive for ASCII only; declare columns COLLATE NOCASE to make = insensitive too."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM users WHERE email ILIKE 'matt@example.com';"},{"engine_slug":"sqlite","sql":"SELECT 'abc' = 'ABC' COLLATE NOCASE AS eq;  -- 1"},{"engine_slug":"oracle","sql":"SELECT * FROM users\nWHERE email = 'matt@example.com';  -- with NLS_COMP=LINGUISTIC + NLS_SORT=BINARY_CI"},{"engine_slug":"sql-server","sql":"SELECT IIF('Apple' = 'apple' COLLATE Latin1_General_CI_AS, 1, 0) AS ci,\n       IIF('Apple' = 'apple' COLLATE Latin1_General_CS_AS, 1, 0) AS cs;  -- 1, 0"},{"engine_slug":"mysql","sql":"SELECT 'Apple' = 'apple' AS eq;  -- 1: default collations end in _ci"}],"faqs":[{"question":"Is UPPER(col) = UPPER('x') wrong?","answer":"It works but disables a plain index on col and can be locale-wrong (Turkish I). A case-insensitive collation or citext does the same job and can use an ordinary index; PostgreSQL's ILIKE matches case-insensitively but cannot use a plain b-tree index either."},{"question":"Why does my WHERE clause behave differently in SQLite?","answer":"SQLite's LIKE ignores case for ASCII only, while = is exact. Adding COLLATE NOCASE to the column definition lines them up."},{"question":"Do case-insensitive collations ignore accents?","answer":"SQL Server's _AI collations and MySQL's _ai_ci do; _AS/_as_cs keep accents significant. Pick the combination deliberately per column."}],"related":["upper","lower","turkish-i","string-sort"],"novel_uses":[{"body":"Grouping under a case-insensitive collation surfaces the 'A' versus 'a' families before you merge them, on SQL Server with a _CI collation or on PostgreSQL with citext and lower().","sql":"SELECT name COLLATE Latin1_General_CI_AS AS folded, COUNT(*) AS variants\nFROM users\nGROUP BY name COLLATE Latin1_General_CI_AS\nHAVING COUNT(*) > 1;"},{"body":"With a case-insensitive column collation, LIKE 'matt%' walks the index; wrapping the column in UPPER(email) LIKE forces a scan instead.","sql":"SELECT * FROM users WHERE email LIKE 'matt%';  -- index seek on a CI collation"}]},"source_url":"https://sqlly.app/sql-functions/case-insensitive-collation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CAST function","description":"CAST in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the standard type conversion, with integer division, truncation and parse-failure behaviour per engine.","body":{"slug":"cast","name":"CAST","h1":"SQL CAST function","category":"conversion","lede":"Converts a value to a target type: text to number, number to text, timestamp to date. CAST is the SQL-standard spelling and the one to reach for when portability matters.","syntax":"CAST(expression AS type)","return_type":"the target type","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Integer division happens before any CAST of the result: 7/2 is 3 on SQL Server, PostgreSQL and SQLite, so CAST(7/2 AS DECIMAL(5,2)) is 3.00. Cast an operand instead: CAST(7 AS DECIMAL(5,2)) / 2. MySQL's / already returns 3.5.","Bad input: CAST('abc' AS INT) raises an error on SQL Server, PostgreSQL and Oracle. MySQL returns 0 with a warning in a SELECT, and SQLite returns 0 silently. CAST('12abc' AS INTEGER) is 12 on SQLite.","Target type names differ: MySQL's CAST takes SIGNED, UNSIGNED, DECIMAL, CHAR, DATE and a few others, not INTEGER or VARCHAR, so CAST(x AS INTEGER) is a syntax error there.","Shorthands: PostgreSQL also accepts expression::type; SQL Server and MySQL have CONVERT. CAST is the standard form."],"examples":[{"engine_slug":"postgresql","sql":"-- CAST('42' AS SIGNED) on MySQL\nSELECT CAST('42' AS INTEGER) AS n;"},{"engine_slug":"all","sql":"SELECT CAST(total AS DECIMAL(10, 2)) AS money\nFROM orders;"},{"engine_slug":"postgresql","sql":"SELECT created_at::date AS day FROM orders;"}],"faqs":[{"question":"What is the difference between CAST and CONVERT?","answer":"CAST is SQL standard with one fixed syntax. CONVERT exists in SQL Server (with style numbers) and MySQL (with reversed argument order). Prefer CAST unless you need a CONVERT-only feature like SQL Server's styles."},{"question":"Why is 1/2 equal to 0 in my query?","answer":"Both operands are integers, so SQL Server, PostgreSQL and SQLite do integer division and drop the fraction. CAST(1 AS DECIMAL(10,2)) / 2, or 1.0 / 2, gives 0.5. MySQL returns 0.5000 already, and Oracle has no integer division."}],"related":["try-cast","convert","numeric-trunc"],"novel_uses":[{"body":"MySQL and SQLite coerce numbers into strings inside their concatenation paths, but PostgreSQL errors on integer || text. CAST(n AS text) (or n::text) fixes it, and making the cast explicit keeps the query portable to engines where it was never needed.","sql":"SELECT CAST(dept_id AS text) || '-' || name AS dept_ref\nFROM departments;"},{"body":"Converting to a fixed scale rounds to it, so CAST(total AS DECIMAL(10, 2)) snaps to cents in the same step that types the column. Do it once at the storage boundary; a float source already carries binary error that no cast can remove. SQLite ignores the scale, so round explicitly there.","sql":"SELECT CAST(SUM(amount) AS DECIMAL(10, 2)) AS billable\nFROM charges;"}]},"source_url":"https://sqlly.app/sql-functions/cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cast-to-int","corpus":"sql-functions","engine":null,"language":"en","title":"SQL cast decimal to integer","description":"CAST(12.9 AS INT) is 13 on MySQL, PostgreSQL and Oracle but 12 on SQL Server and SQLite: the same expression, two different numbers, per engine.","body":{"slug":"cast-to-int","name":"CAST to INT","h1":"SQL cast decimal to integer","category":"math","lede":"Shows whether converting a decimal to an integer rounds or truncates: MySQL, PostgreSQL and Oracle round to nearest, while SQL Server and SQLite chop the fraction.","syntax":"CAST(12.9 AS INT)  |  12.9::int  |  CAST(12.9 AS SIGNED)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"Truncates toward zero: CAST(12.9 AS INT) is 12, CAST(-12.9 AS INT) is -12"},{"engine_slug":"postgresql","status":"yes","note":"Rounds to nearest: 12.9::int is 13. numeric ties go away from zero (2.5::int is 3), double precision ties go to even (2.5::float8::int is 2)"},{"engine_slug":"mysql","status":"yes","note":"CAST(x AS SIGNED) rounds to nearest: 12.9 becomes 13"},{"engine_slug":"sqlite","status":"yes","note":"CAST truncates toward zero: CAST(12.9 AS INTEGER) is 12"},{"engine_slug":"oracle","status":"yes","note":"CAST to INT is a NUMBER(38, 0) cast and rounds to nearest: CAST(12.9 AS INT) is 13; TRUNC(x) truncates explicitly"}],"gotchas":["Negative values follow the same per-engine rule: SQL Server and SQLite go toward zero (-12.9 to -12), MySQL, PostgreSQL and Oracle go to nearest (-12.9 to -13).","FLOOR and CEILING remove the ambiguity: FLOOR(x) always down, CEILING(x) always up, on every engine; prefer them when the intent matters.","Out-of-range casts error or clamp per the overflow rules; PostgreSQL's 1e20::int raises 'integer out of range' rather than wrapping."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(12.9 AS INT) AS truncated;  -- 12"},{"engine_slug":"postgresql","sql":"SELECT 12.9::int AS rounded;  -- 13"},{"engine_slug":"mysql","sql":"SELECT CAST(12.9 AS SIGNED) AS rounded;  -- 13"},{"engine_slug":"sqlite","sql":"SELECT CAST(12.9 AS INTEGER) AS truncated;  -- 12"},{"engine_slug":"oracle","sql":"SELECT CAST(12.9 AS INT) AS rounded FROM dual;  -- 13"}],"faqs":[{"question":"Does CAST to INT round or truncate?","answer":"Depends on the engine: MySQL, PostgreSQL and Oracle round to nearest (12.9 becomes 13); SQL Server and SQLite truncate the fraction (12.9 becomes 12). Use FLOOR or CEILING when the direction matters."},{"question":"Why do engines disagree?","answer":"The SQL standard leaves it open. The engines split historically and kept their behaviour for compatibility, which is exactly why the explicit FLOOR/CEILING/ROUND trio exists."},{"question":"What happens to the fractional part of a negative?","answer":"Truncators (SQL Server, SQLite) go toward zero: -12.9 becomes -12. Rounders (MySQL, PostgreSQL, Oracle) go to nearest: -12.9 becomes -13."}],"related":["cast","floor","ceiling","round","numeric-trunc"],"novel_uses":[{"body":"FLOOR(rating * 2) / 2.0 snaps 4.6 to 4.5 and 4.4 to 4.0, the always-down display rule. A CAST looks equivalent, but PostgreSQL, MySQL and Oracle round on cast, which flips 4.4 to 4.5; keep FLOOR.","sql":"SELECT FLOOR(rating * 2) / 2.0 AS stars FROM reviews;"},{"body":"SQL Server's TRY_CAST(raw_value AS INT) returns NULL for values an integer conversion would reject, so one SELECT finds them before the load job. The sweep cannot abort itself.","sql":"SELECT * FROM staged WHERE TRY_CAST(raw_value AS INT) IS NULL AND raw_value IS NOT NULL;"}]},"source_url":"https://sqlly.app/sql-functions/cast-to-int","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cast-truncation","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CAST truncation behaviour","description":"What a lossy CAST does per engine: decimal to integer rounds on PostgreSQL, MySQL and Oracle but truncates on SQL Server and SQLite, and text is cut without an error.","body":{"slug":"cast-truncation","name":"CAST truncation","h1":"SQL CAST truncation behaviour","category":"conversion","lede":"A cast that loses information does not lose it the same way everywhere: CAST(2.7 AS INT) is 3 on some engines and 2 on others.","syntax":"CAST(expression AS INTEGER)  |  CAST(expression AS SIGNED)  -- MySQL","return_type":"the target type","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Exact decimal to integer: PostgreSQL, MySQL and Oracle round half away from zero (2.5 becomes 3, -2.5 becomes -3); SQL Server and SQLite truncate toward zero (2.7 becomes 2). PostgreSQL rounds a float8 2.5 to 2, half to even.","Text with a fraction: CAST('123.9' AS INTEGER) errors on PostgreSQL and SQL Server, returns 124 on Oracle, and returns 123 on SQLite. MySQL's CAST('123.9' AS SIGNED) gives 123 with a warning. Cast to DECIMAL first, then round on purpose.","Shrinking text: CAST('abcdefgh' AS varchar(4)) is 'abcd' with no error on SQL Server, PostgreSQL and Oracle. MySQL rejects varchar as a cast target; CAST('abcdefgh' AS CHAR(4)) gives 'abcd' with a warning. SQLite ignores the length entirely and returns all eight characters.","MySQL has no INTEGER cast target: CAST(x AS INTEGER) is a syntax error there. Write CAST(x AS SIGNED) or CAST(x AS UNSIGNED).","Casting a timestamp to date drops the time without rounding on SQL Server, PostgreSQL and MySQL. Oracle is the exception: its DATE type has a time part, so CAST(ts AS DATE) keeps hours, minutes and seconds and drops only fractional seconds. SQLite has no DATE type: CAST('2024-01-01 23:59:59' AS DATE) applies NUMERIC affinity and returns 2024, so use date(ts) there."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(2.7 AS INT) AS n;  -- 2"},{"engine_slug":"postgresql","sql":"SELECT CAST(2.7 AS integer) AS n;  -- 3"},{"engine_slug":"mysql","sql":"SELECT CAST(2.7 AS SIGNED) AS n;  -- 3"},{"engine_slug":"sql-server","sql":"SELECT CAST('abcdefgh' AS varchar(4)) AS cut;  -- abcd"},{"engine_slug":"sqlite","sql":"SELECT CAST(2.7 AS INTEGER) AS n;  -- 2"},{"engine_slug":"oracle","sql":"SELECT CAST(2.7 AS INTEGER) AS n FROM dual;  -- 3"}],"faqs":[{"question":"How do I get the same answer on every engine?","answer":"Say which rounding you want instead of relying on the cast: ROUND(x) or TRUNC(x) on PostgreSQL and Oracle, ROUND(x, 0) or TRUNCATE(x, 0) on MySQL, ROUND(x, 0) or ROUND(x, 0, 1) to truncate on SQL Server, then cast the result."},{"question":"Does CAST ever warn about lost data?","answer":"MySQL does: truncated text and partly numeric strings add warnings you can read with SHOW WARNINGS. SQL Server, PostgreSQL and Oracle cut text silently. Numeric overflow, such as CAST(300 AS TINYINT) on SQL Server or CAST(40000 AS smallint) on PostgreSQL, raises an error there; MySQL clamps instead, so CAST(1000 AS DECIMAL(2,0)) is 99 with a warning, and SQLite silently clamps to the 64-bit integer limit."}],"related":["cast","numeric-trunc","decimal-cast","string-cast"],"novel_uses":[{"body":"On PostgreSQL, MySQL, SQL Server and Oracle a recast to a smaller scale rounds, so CAST(net AS DECIMAL(10,0)) kills the pennies in one token. SQLite's NUMERIC cast keeps 2.5 as 2.5, so the trick does not transfer there.","sql":"SELECT CAST(net AS DECIMAL(10,0)) AS whole_dollars FROM invoices;"},{"body":"Those two engines truncate toward zero, so for non-negative values CAST(x AS INT) is FLOOR(x) without a function call. The two diverge on negatives: the cast moves toward zero, FLOOR moves down.","sql":"SELECT CAST(disk_gb AS INT) AS full_disks FROM servers WHERE disk_gb >= 0;"},{"body":"Recasting to a shorter text type hard-cuts overflow on PostgreSQL, SQL Server and Oracle, so CAST(note AS varchar(500)) enforces a length cap inside INSERT ... SELECT with no CASE. SQLite ignores the length; write substr(note, 1, 500) there.","sql":"INSERT INTO clean.notes (body) SELECT CAST(raw AS varchar(500)) FROM staging.raw_notes;"}]},"source_url":"https://sqlly.app/sql-functions/cast-truncation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cbrt","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CBRT function","description":"CBRT(x) returns the real cube root, negatives included: CBRT(-27) is -3 to double precision. POWER(-27, 1.0/3) errors or returns NULL instead. Only PostgreSQL has it.","body":{"slug":"cbrt","name":"CBRT","h1":"SQL CBRT function","category":"math","lede":"Returns the cube root of a number, defined for negatives too: CBRT(27) is 3 and CBRT(-27) is -3, both to double precision.","syntax":"CBRT(number)","return_type":"double / float","support":[{"engine_slug":"sql-server","status":"no","note":"No CBRT; POWER(x, 1.0/3.0) raises an invalid floating point operation for negative x"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL has cbrt(double precision)"},{"engine_slug":"mysql","status":"no","note":"No CBRT; POWER(-27, 1/3) raises 'DOUBLE value is out of range'"},{"engine_slug":"sqlite","status":"no","note":"No CBRT in the 3.35+ math set; power(-27, 1.0/3) returns NULL"},{"engine_slug":"oracle","status":"no","note":"No CBRT; POWER(-27, 1/3) raises ORA-01428"}],"gotchas":["POWER(x, 1.0/3) has no real result for negative x: pow() refuses a negative base with a non-integer exponent. CBRT handles the sign explicitly.","Emulate elsewhere with SIGN(x) * POWER(ABS(x), 1e0/3). Write the exponent as 1e0/3: on MySQL and SQL Server 1.0/3 is a short decimal (0.333333 on SQL Server), so POWER(27.0e0, 1.0/3) gives 2.9999967 on SQL Server and 2.999999997 on MySQL, not 3. SQL Server POWER also returns its first argument's type, so cast an INT x to FLOAT.","CBRT works in double precision, and PostgreSQL 18 returns 3.0000000000000004 for CBRT(27). Round before comparing to an integer."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CBRT(27) AS pos, CBRT(-27) AS neg;  -- 3.0000000000000004, -3.0000000000000004"},{"engine_slug":"sql-server","sql":"SELECT SIGN(-27) * POWER(ABS(CAST(-27 AS FLOAT)), 1e0/3) AS cbrt;  -- -3"},{"engine_slug":"mysql","sql":"SELECT SIGN(x) * POWER(ABS(x), 1e0/3) AS signed_root FROM t;"}],"faqs":[{"question":"Why does POWER(-27, 1.0/3.0) fail?","answer":"A negative number raised to a non-integer power has no real result in pow(), so engines return NULL or raise an error instead of the -3 you expect. CBRT is the sign-aware fix."},{"question":"Which engines have CBRT?","answer":"PostgreSQL only among the five. Elsewhere use SIGN(x) * POWER(ABS(x), 1e0/3), which keeps the sign of the original number. On SQL Server cast x to FLOAT so POWER does not return an integer."},{"question":"Is CBRT(27) exactly 3?","answer":"Not on PostgreSQL 18, which returns 3.0000000000000004. CBRT works in double precision, so round before display or comparison."}],"related":["power","fractional-powers","sqrt"],"novel_uses":[{"body":"A value that grew by a total factor over three equal periods compounded at CBRT(factor) per period. A total decline has a factor below 1, so its per-period factor is also below 1: CBRT(0.5) is 0.7937, about -20.6% per period.","sql":"SELECT CBRT(1.728) AS per_period_factor;  -- 1.2 on PostgreSQL"},{"body":"WHERE ABS(CBRT(volume) - side) > 1e-9 finds rows where a stored cube disagrees with its side column. Derived-column drift like this survives every equality check on the raw columns.","sql":"SELECT id FROM boxes WHERE ABS(CBRT(volume) - side) > 1e-9;"}]},"source_url":"https://sqlly.app/sql-functions/cbrt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ceil","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CEIL function","description":"Round up with CEIL and CEILING in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: pagination math, negative numbers and the spelling differences.","body":{"slug":"ceil","name":"CEIL / CEILING","h1":"SQL CEIL function","category":"math","lede":"Returns the smallest integer not less than the input. Its common job is page counts: CEIL(total_rows * 1.0 / page_size).","syntax":"CEIL(number)  |  CEILING(number)  -- SQL Server","return_type":"integer / numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"spelled CEILING only"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"CEIL and CEILING, math functions from 3.35+"},{"engine_slug":"oracle","status":"yes","note":"CEIL only"}],"gotchas":["Spelling: CEILING only on SQL Server, CEIL only on Oracle, both on PostgreSQL, MySQL and SQLite.","CEIL rounds toward positive infinity: CEIL(-2.1) is -2.","Integer division happens before CEIL: on SQL Server, PostgreSQL and SQLite, CEIL(7/2) is CEIL(3) = 3, not 4. MySQL's / returns 3.5, so it gives 4 there. Make one operand a decimal first."],"examples":[{"engine_slug":"postgresql","sql":"-- CEILING(2.1) on SQL Server\nSELECT CEIL(2.1) AS up;  -- 3"},{"engine_slug":"sql-server","sql":"SELECT CEILING(CAST(total_rows AS DECIMAL(18, 2)) / page_size) AS pages\nFROM stats;"},{"engine_slug":"mysql","sql":"SELECT CEIL(2.1) AS up;  -- 3"},{"engine_slug":"sqlite","sql":"-- ceil() and ceiling() are 3.35+ math functions\nSELECT ceil(2.1) AS up;  -- 3"},{"engine_slug":"oracle","sql":"SELECT CEIL(2.1) AS up FROM dual;  -- 3"}],"faqs":[{"question":"Why does CEIL(7/2) return 3 instead of 4?","answer":"On SQL Server, PostgreSQL and SQLite, 7/2 is integer division and already truncated to 3 before CEIL sees it. Make one operand a decimal: CEIL(7.0 / 2) or CEIL(CAST(a AS DECIMAL) / b). MySQL returns 4, because its / is decimal division."},{"question":"Is it CEIL or CEILING?","answer":"Both exist on PostgreSQL, MySQL and SQLite. SQL Server only has CEILING; Oracle only has CEIL."}],"related":["floor","round","mod"],"novel_uses":[{"body":"Usage past the included amount rounds up to the next billable unit: CEILING over the excess divided by the step size. Older SQL Server has no GREATEST, so the CASE form is the safe one there, and the CAST keeps integer division from eating the remainder first.","sql":"SELECT user_id,\n       CASE WHEN used > included\n            THEN CEILING(CAST(used - included AS DECIMAL(18, 2)) / step)\n            ELSE 0 END AS overage_units\nFROM usage;"},{"body":"date_trunc plus one hour overshoots timestamps that already sit exactly on the hour. The CASE gives the ceiling of the timestamp instead of the following one, which is what valid-until columns usually mean.","sql":"SELECT CASE WHEN DATE_TRUNC('hour', ts) = ts THEN ts\n            ELSE DATE_TRUNC('hour', ts) + INTERVAL '1 hour' END AS valid_until\nFROM sessions;"}]},"source_url":"https://sqlly.app/sql-functions/ceil","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ceiling","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CEILING function","description":"CEILING rounds a number up to the next whole value. CEIL and CEILING spellings, what each engine returns for numeric and float input, and the traps with negatives.","body":{"slug":"ceiling","name":"CEILING","h1":"SQL CEILING function","category":"math","lede":"Rounds a number up to the nearest integer, toward positive infinity: CEILING(2.1) is 3 and CEILING(-2.1) is -2.","syntax":"CEILING(number)  |  CEIL(number)","return_type":"same type as the input on SQL Server and SQLite; PostgreSQL and MySQL differ (see gotchas)","support":[{"engine_slug":"sql-server","status":"yes","note":"Only CEILING; CEIL is not a T-SQL function"},{"engine_slug":"postgresql","status":"yes","note":"CEIL and CEILING are both built in"},{"engine_slug":"mysql","status":"yes","note":"CEIL and CEILING are both built in"},{"engine_slug":"sqlite","status":"yes","note":"Requires SQLite 3.35+ with the math functions built in; both spellings exist and return REAL for REAL input"},{"engine_slug":"oracle","status":"yes","note":"Only CEIL; there is no CEILING keyword"}],"gotchas":["CEILING moves toward positive infinity, so CEILING(-2.1) is -2, not -3. FLOOR(-2.1) is -3.","SQL Server and PostgreSQL keep decimal input as a decimal with scale 0, and float input as a float. PostgreSQL returns double precision for integer, bigint and real input, MySQL returns BIGINT for integer and decimal input, and SQL Server returns float for real input. SQLite returns 3.0, not 3, for REAL input.","Integer division eats the rounding: on SQL Server, PostgreSQL and SQLite, CEILING(7/2) on integer columns is CEILING(3) = 3, not 4. MySQL's / returns a decimal, so there it is 4. Compute CEILING(7/2.0) for 4 everywhere."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CEILING(2.1) AS up, CEILING(-2.1) AS neg_up;  -- 3, -2"},{"engine_slug":"oracle","sql":"SELECT CEIL(2.1) AS up, CEIL(-2.1) AS neg_up FROM dual;  -- 3, -2"},{"engine_slug":"postgresql","sql":"SELECT CEIL(total_pages / 500.0) AS page_batches\nFROM print_jobs;"},{"engine_slug":"sql-server","sql":"SELECT CEILING(disk_gb / 100.0) AS billed_units\nFROM usage;"},{"engine_slug":"mysql","sql":"SELECT CEILING(2.1) AS up, CEIL(-2.1) AS neg_up;  -- 3, -2"},{"engine_slug":"sqlite","sql":"SELECT ceiling(2.1) AS up, ceil(-2.1) AS neg_up;  -- 3.0, -2.0: REAL in, REAL out"}],"faqs":[{"question":"Is it CEIL or CEILING?","answer":"Both names work on PostgreSQL, MySQL and SQLite. SQL Server only accepts CEILING and Oracle only accepts CEIL, so no single spelling runs on all five."},{"question":"Why does CEILING(7/2) return 3 instead of 4?","answer":"On SQL Server, PostgreSQL and SQLite, 7/2 is integer division and evaluates to 3 before CEILING sees it. Force decimal division with 7/2.0, or CAST one operand, then CEILING gets 3.5 and returns 4. MySQL's / already returns 3.5000, so CEILING(7/2) is 4 there."},{"question":"What does CEILING return for a negative number?","answer":"The next integer toward positive infinity: CEILING(-2.1) is -2. If you want -3 you are thinking of FLOOR."}],"related":["floor","round","numeric-trunc"],"novel_uses":[{"body":"CEILING(x / 5.0) * 5 rounds a value up to the next multiple of 5, where ROUND(x / 5.0) * 5 rounds to the nearest one. Packaging and shipping rules are the usual reason you want always-up.","sql":"SELECT CEILING(units / 5.0) * 5 AS billed_units FROM shipments;"},{"body":"On SQL Server, CEILING(DATEDIFF(minute, start_utc, stop_utc) / 1440.0) turns a partial day into a full billable day. FLOOR always drops the leftover minutes, and ROUND drops them whenever they are under half a day.","sql":"SELECT CEILING(DATEDIFF(minute, start_utc, stop_utc) / 1440.0) AS billed_days FROM sessions;"},{"body":"Ceiling division lands an event on the slot that contains or follows it: CEILING(epoch_seconds / 900.0) * 900 gives the quarter hour a job must not run before. ROUND would allow an early start.","sql":"SELECT CEILING(CAST(epoch_seconds AS FLOAT) / 900.0) * 900 AS next_slot FROM events;"}]},"source_url":"https://sqlly.app/sql-functions/ceiling","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/char-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHAR_LENGTH function","description":"How CHAR_LENGTH counts characters, not bytes, in PostgreSQL and MySQL, and LEN and LENGTH elsewhere: emoji counting, trailing spaces, and MySQL's byte-counting LENGTH.","body":{"slug":"char-length","name":"CHAR_LENGTH","h1":"SQL CHAR_LENGTH function","category":"string","lede":"Returns the number of characters in a string, however many bytes each one occupies.","syntax":"CHAR_LENGTH(string)  |  CHARACTER_LENGTH(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"No CHAR_LENGTH; LEN(v) counts UTF-16 code units (an emoji is 2 under non-_SC collations) and ignores trailing spaces."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"No CHAR_LENGTH; length(x) counts characters for text."},{"engine_slug":"oracle","status":"partial","note":"No CHAR_LENGTH; LENGTH counts characters."}],"gotchas":["Characters, not bytes: 'héllo' is 5 characters and 6 UTF-8 bytes, and an emoji is 1 character and 4 bytes.","SQL Server's LEN ignores trailing spaces (LEN('ab  ') is 2), while the other engines count them in VARCHAR, TEXT and literal values. In MySQL CHAR(n) and PostgreSQL char(n), trailing spaces are padding, so CHAR_LENGTH returns 2 for 'ab  ' stored in a CHAR(10) or char(4) column. DATALENGTH counts bytes including the spaces.","CHARACTER_LENGTH is the standard spelling and an exact synonym in PostgreSQL and MySQL. MySQL's LENGTH is not a synonym: it counts bytes."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CHAR_LENGTH('héllo') AS chars;  -- 5"},{"engine_slug":"mysql","sql":"SELECT CHAR_LENGTH(name) AS chars, LENGTH(name) AS bytes\nFROM products;"},{"engine_slug":"sql-server","sql":"SELECT LEN(name) AS chars\nFROM products;"},{"engine_slug":"sqlite","sql":"SELECT length('héllo') AS chars;  -- 5"},{"engine_slug":"oracle","sql":"SELECT LENGTH('héllo') AS chars\nFROM dual;  -- 5"}],"faqs":[{"question":"Why does my emoji count as one character but more bytes?","answer":"CHAR_LENGTH counts code points; an emoji is one code point encoded as four UTF-8 bytes, so OCTET_LENGTH reports 4."},{"question":"Is CHAR_LENGTH the same as LEN in SQL Server?","answer":"Close: LEN counts UTF-16 code units and drops trailing spaces, so under non-_SC collations an emoji counts as 2 (1 under _SC). MySQL's CHAR_LENGTH counts every character, spaces included, except in fixed-width CHAR(n) columns, which treat trailing spaces as padding."},{"question":"Is there a difference between CHAR_LENGTH and CHARACTER_LENGTH?","answer":"No. They are synonyms; CHARACTER_LENGTH is the SQL-standard name, CHAR_LENGTH the common short form."}],"related":["length","octet-length","bit-length","substr"],"novel_uses":[{"body":"Rows whose value sits exactly at a known cap were probably cut off, which is how MySQL non-strict mode stores overlong input. The equality test finds them for re-review.","sql":"SELECT id FROM notes\nWHERE CHAR_LENGTH(body) = 500;"},{"body":"PostgreSQL substr does not accept a negative start, but length minus 2 lands three characters from the end, which covers the common RIGHT-style tail read.","sql":"SELECT substr(code, CHAR_LENGTH(code) - 2) AS last_three\nFROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/char-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/char-padding-compare","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHAR padding and string comparison","description":"CHAR columns blank-pad and comparisons ignore trailing spaces, until LIKE, NO PAD collations and cross-engine casts disagree with your expectations.","body":{"slug":"char-padding-compare","name":"CHAR padding and comparisons","h1":"SQL CHAR padding and string comparison","category":"string","lede":"Blank-padded types and PAD SPACE collations make 'abc' and 'abc ' compare equal, except on modern MySQL NO PAD collations. LIKE does not ignore spaces on VARCHAR or literal operands, but a CHAR(n) operand carries its padding into LIKE on SQL Server.","syntax":"'abc' = 'abc '  -- true on SQL Server and MySQL PAD SPACE, false on PostgreSQL text and MySQL NO PAD","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["CHAR(n) values are blank-padded on storage; SQL Server and PostgreSQL comparisons ignore the padding, so char equality is insensitive to trailing spaces.","MySQL collations differ: legacy utf8mb4_general_ci is PAD SPACE ('abc' = 'abc ' is true), while utf8mb4_0900_* collations are NO PAD (false). Same server, different answers per collation.","SQL Server: = ignores trailing spaces; 'abc' = 'abc ' is 1 while 'abc' LIKE 'abc ' is 0 for VARCHAR and literal operands. A CHAR(5) column keeps its padding in LIKE, so CHAR(5) 'abc' LIKE 'abc ' is 1.","PostgreSQL: varchar comparisons are exact ('abc' = 'abc ' is false); only the bpchar (char) type trims for comparison."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'abc'::char(5) = 'abc  ' AS char_eq,  -- true\n       'abc' = 'abc  ' AS text_eq;             -- false"},{"engine_slug":"sql-server","sql":"SELECT IIF('abc' = 'abc ', 1, 0) AS eq, IIF('abc' LIKE 'abc ', 1, 0) AS like_;\n-- 1, 0"},{"engine_slug":"mysql","sql":"SELECT 'abc' = 'abc ' COLLATE utf8mb4_general_ci AS pad_space,\n       'abc' = 'abc ' COLLATE utf8mb4_0900_ai_ci AS no_pad;\n-- 1, 0"},{"engine_slug":"sqlite","sql":"SELECT 'ab' = 'ab  ' AS eq;  -- 0: TEXT never pads"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN CAST('ab' AS CHAR(4)) = 'ab  ' THEN 1 ELSE 0 END AS char_eq,\n       CASE WHEN CAST('ab' AS VARCHAR2(4)) = 'ab  ' THEN 1 ELSE 0 END AS varchar2_eq FROM dual;  -- expected 1, 0 (not run)"}],"faqs":[{"question":"Why does = ignore trailing spaces but LIKE does not?","answer":"SQL Server's = ignores trailing spaces on every string type. LIKE matches the stored characters for VARCHAR and literal operands, so 'abc' LIKE 'abc ' is 0. A CHAR(n) operand still carries its padding into LIKE, so RTRIM the value before LIKE when it matters."},{"question":"What is PAD SPACE?","answer":"A collation property that makes comparisons skip trailing spaces. MySQL 8's 0900 collations dropped it (NO PAD), so equality got stricter when upgrading."},{"question":"Should I use CHAR for fixed-length codes?","answer":"Rarely. The padding behaviour leaks into comparisons and concatenations. VARCHAR plus a CHECK or trim-on-write is more predictable across engines."}],"related":["trim","varchar-char-semantics","string-sort","empty-string-check"],"novel_uses":[{"body":"Before a CHAR-to-VARCHAR migration, fold the VARCHAR source to char(n) and count its exact values: any folded group with more than one exact value shows the trailing-space variants that CHAR would merge.","sql":"SELECT col::char(10)::text AS folded, COUNT(DISTINCT col) AS variants, COUNT(*) AS rows_ FROM src GROUP BY 1 HAVING COUNT(DISTINCT col) > 1;"},{"body":"Equality ignores trailing spaces, so adding LEN(code) = DATALENGTH(code) keeps only varchar values with no padding, the strict match a CI collation will not give you. For NVARCHAR, DATALENGTH counts two bytes per character, so the test becomes DATALENGTH(code) = 2 * LEN(code).","sql":"SELECT * FROM items WHERE code = 'ABC' AND LEN(code) = DATALENGTH(code);"}]},"source_url":"https://sqlly.app/sql-functions/char-padding-compare","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/charindex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHARINDEX function","description":"How CHARINDEX finds a substring in SQL Server: argument order, the optional start position, case-sensitivity by collation, and the LOCATE, POSITION and INSTR twins.","body":{"slug":"charindex","name":"CHARINDEX","h1":"SQL CHARINDEX function","category":"string","lede":"SQL Server's substring search: it returns where a substring starts, or 0 when it is not there.","syntax":"CHARINDEX(substr, string)  |  CHARINDEX(substr, string, start_position)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"Use POSITION(substr IN str) or STRPOS(str, substr)."},{"engine_slug":"mysql","status":"partial","note":"LOCATE(substr, str, start) has the same argument order."},{"engine_slug":"sqlite","status":"partial","note":"Use INSTR(str, substr); no start argument."},{"engine_slug":"oracle","status":"partial","note":"Use INSTR(str, substr, start)."}],"gotchas":["The substring comes first: CHARINDEX(substr, string). INSTR in Oracle, MySQL and SQLite takes the string first, so ported code silently searches the wrong way round.","The optional third argument is where the search starts, and the result is still counted from the start of the string: CHARINDEX('a', 'banana', 3) is 4.","Case sensitivity follows the collation: the default case-insensitive collations find 'A' in 'apple'; a _CS or _BIN collation does not."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('@', email) AS at_pos\nFROM users;"},{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('/', url, CHARINDEX('//', url) + 2) AS path_start\nFROM links;"},{"engine_slug":"postgresql","sql":"SELECT position('world' in 'hello world') AS pos;  -- 7"},{"engine_slug":"mysql","sql":"SELECT LOCATE('world', 'hello world') AS pos;  -- 7"},{"engine_slug":"sqlite","sql":"SELECT INSTR('hello world', 'world') AS pos;  -- 7"},{"engine_slug":"oracle","sql":"SELECT INSTR('hello world', 'world') AS pos\nFROM dual;"}],"faqs":[{"question":"How do I search from the end of a string with CHARINDEX?","answer":"There is no reverse flag. For a single character, LEN(s) - CHARINDEX(x, REVERSE(s)) + 1 gives the last position, but it returns LEN(s) + 1 when x is absent, and LEN ignores trailing spaces, so when s ends in spaces the result is wrong (0 for 'ab ' where 'a' sits at position 1)."},{"question":"Does CHARINDEX respect case?","answer":"Only through collation. Under a case-insensitive collation (the usual install default) it matches any casing; write COLLATE Latin1_General_CS_AS on the column inside the call for an exact match."},{"question":"What does CHARINDEX return for an empty substring?","answer":"0. CHARINDEX('', 'abc') treats the empty string as not found, while PostgreSQL's STRPOS(s, '') returns 1."}],"related":["position","locate","instr","patindex"],"novel_uses":[{"body":"LEN(email) minus the position of the @ is exactly the number of characters after it, so RIGHT returns the domain in one expression. When the @ is missing CHARINDEX returns 0 and the whole address comes back, so guard with CHARINDEX(...) > 0 when that matters.","sql":"SELECT RIGHT(email, LEN(email) - CHARINDEX('@', email)) AS domain\nFROM users\nWHERE CHARINDEX('@', email) > 0;"},{"body":"STUFF removes one span while REPLACE removes every occurrence, and CHARINDEX supplies the span start in SQL Server. A missing token makes STUFF return NULL because the start becomes 0, so the CASE needs an ELSE line branch that keeps rows where the token is absent.","sql":"UPDATE logs\nSET line = CASE WHEN CHARINDEX('DEBUG', line) > 0\n           THEN STUFF(line, CHARINDEX('DEBUG', line), 5, '') ELSE line END;"},{"body":"One less than the position of the first space is the length of the first word, which LEFT consumes. Strings without a space fall through to the ELSE branch; without the guard LEFT receives -1 and the query fails with error 537.","sql":"SELECT CASE WHEN CHARINDEX(' ', full_name) > 0\n            THEN LEFT(full_name, CHARINDEX(' ', full_name) - 1)\n            ELSE full_name END AS first_name\nFROM people;"}]},"source_url":"https://sqlly.app/sql-functions/charindex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/charset-function","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MySQL CHARSET and COLLATION functions","description":"MySQL's CHARSET() and COLLATION() report a string's encoding and collation, the pair that explains why CHAR(160) is binary and mixed-charset joins misbehave.","body":{"slug":"charset-function","name":"CHARSET / COLLATION","h1":"SQL MySQL CHARSET and COLLATION functions","category":"string","lede":"Introspection for strings: which charset and collation does this value carry right now? Check it before converting or debugging a comparison.","syntax":"CHARSET(string)  |  COLLATION(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["The classic result: CHARSET(CHAR(160)) is binary; MySQL's CHAR() returns raw bytes unless you add USING, and then the bytes must be valid: CHAR(0xC2A0 USING utf8mb4) is an NBSP, CHAR(160 USING utf8mb4) is NULL.","Literals inherit the connection charset, so the same query shows different charsets per client. SET NAMES changes it for the session.","Column charset vs literal charset mismatches force conversions at compare time; the conversion adds no warning, and the index can still be used, so check EXPLAIN before assuming it is the cause.","CHARSET returns the string's charset; COLLATION its collation. A utf8mb4 string can carry any utf8mb4_* collation, which decides its sorting and padding rules; a literal needs the _utf8mb4 introducer to take one, or a latin1 connection rejects it with ERROR 1253."],"examples":[{"engine_slug":"mysql","sql":"SELECT CHARSET('x') AS cs, COLLATION('x') AS col;"},{"engine_slug":"mysql","sql":"SELECT CHARSET(CHAR(160)) AS cs;  -- binary"}],"faqs":[{"question":"Why is my CHAR(160) comparison failing?","answer":"CHAR(160) produced the single binary byte 0xA0, which never matches the two-byte UTF-8 NBSP in utf8mb4 text. Use CHAR(0xC2A0 USING utf8mb4); CHARSET() confirms the diagnosis."},{"question":"Do CHARSET() and COLLATION() look at the column or the value?","answer":"The value. Pass a column and you get its charset/collation; pass a literal and you get the connection's. That asymmetry is the debugging value."},{"question":"Do other engines have this?","answer":"PostgreSQL exposes encoding via server settings and pg_encoding_to_char(), and collation per value via pg_collation_for(); SQL Server via COLLATIONPROPERTY on named collations. MySQL's CHARSET() and COLLATION() are the direct per-value pair for charset and collation together."}],"related":["convert-using","utf8mb4","varchar-char-semantics","char-padding-compare"],"novel_uses":[{"body":"Listing every text column with its CHARACTER_SET_NAME from information_schema exposes the utf8mb3 stragglers that make joins convert and drop indexes.","sql":"SELECT TABLE_NAME, COLUMN_NAME, CHARACTER_SET_NAME\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = 'app' AND CHARACTER_SET_NAME IS NOT NULL\nORDER BY CHARACTER_SET_NAME, TABLE_NAME;"},{"body":"Comparing CHARSET('x') with @@character_set_connection proves whether the literal really travels in the charset you think, the first check when converted values look wrong.","sql":"SELECT CHARSET('x'), @@character_set_connection;"}]},"source_url":"https://sqlly.app/sql-functions/charset-function","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/checksum","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server CHECKSUM and BINARY_CHECKSUM","description":"SQL Server's CHECKSUM hashes values to an int for change detection, ignores case under CI collations and collides easily. BINARY_CHECKSUM, ORA_HASH and CRC32 compared.","body":{"slug":"checksum","name":"CHECKSUM / BINARY_CHECKSUM","h1":"SQL Server CHECKSUM and BINARY_CHECKSUM","category":"string","lede":"CHECKSUM(col1, col2) reduces a row to one int, handy for spotting rows that may have changed. It is a quick filter, not a reliable fingerprint.","syntax":"CHECKSUM(* | expression [, ...])  |  BINARY_CHECKSUM(* | expression [, ...])","return_type":"int","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"no documented equivalent; md5(row::text) for change detection"},{"engine_slug":"mysql","status":"partial","note":"CRC32(str) for one string"},{"engine_slug":"sqlite","status":"no","note":"no hash functions in the core library"},{"engine_slug":"oracle","status":"partial","note":"ORA_HASH(expr [, max_bucket [, seed]])"}],"gotchas":["CHECKSUM follows the collation: under a case-insensitive collation CHECKSUM('abc') equals CHECKSUM('ABC'), and Windows case-sensitive collations such as Latin1_General_CS_AS still give both the same value; only SQL_ case-sensitive and BIN collations tell them apart. BINARY_CHECKSUM works on the bytes, so case changes show.","A 32-bit result collides: different rows can share a checksum. Use it to narrow the candidates, then compare the columns, or use HASHBYTES('SHA2_256', ...) when collisions matter.","Oracle's ORA_HASH returns 0 to 4294967295 by default and takes a maximum bucket: WHERE ORA_HASH(id, 9) = 0 keeps roughly a tenth of the rows, a common sampling trick."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CHECKSUM('abc') AS ci_lower, CHECKSUM('ABC') AS ci_upper, BINARY_CHECKSUM('abc') AS bin_lower, BINARY_CHECKSUM('ABC') AS bin_upper;  -- 34400, 34400, 26435, 17763 under a CI collation"},{"engine_slug":"sql-server","sql":"SELECT s.id\nFROM (VALUES (1, 'a', 10), (2, 'b', 20)) AS s(id, name, qty)\nJOIN (VALUES (1, 'a', 10), (2, 'b', 25)) AS t(id, name, qty) ON t.id = s.id\nWHERE BINARY_CHECKSUM(s.name, s.qty) <> BINARY_CHECKSUM(t.name, t.qty);  -- 2"},{"engine_slug":"oracle","sql":"SELECT ORA_HASH('abc') AS h, ORA_HASH('abc', 9) AS bucket FROM dual;  -- 1194017796, 6"},{"engine_slug":"mysql","sql":"SELECT CRC32('abc') AS h, CRC32('ABC') AS h2;  -- 891568578, 2743272264"}],"faqs":[{"question":"CHECKSUM or HASHBYTES?","answer":"CHECKSUM is fast and 32-bit, good for a first pass over many rows. HASHBYTES with SHA2_256 is slower but collisions are negligible, so use it when a match must mean 'unchanged'."},{"question":"Can I index a checksum?","answer":"Yes. Add a computed column such as row_chk AS BINARY_CHECKSUM(name, qty) and index it to find candidate matches quickly."}],"related":["hashbytes","crc32","md5","string-hash"],"novel_uses":[{"body":"CHECKSUM_AGG(BINARY_CHECKSUM(*)) reduces a table to one int for cheap snapshot comparisons, but BINARY_CHECKSUM ignores columns it cannot compare, text and image included: a change in those never moves the number. Fingerprint the comparable columns and HASHBYTES the rest when it matters.","sql":"SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) AS fingerprint\nFROM (VALUES (1, 'a'), (2, 'b')) AS t(id, name);"},{"body":"A generated column of CRC32(name) with an index turns a string lookup into an int seek plus one confirmation compare: WHERE name_crc = CRC32('needle') AND name = 'needle'. The 32-bit collision risk is why the string check stays in the predicate.","sql":"ALTER TABLE users ADD COLUMN name_crc INT UNSIGNED GENERATED ALWAYS AS (CRC32(name)) STORED,\n  ADD INDEX ix_name_crc (name_crc);\nSELECT id FROM users WHERE name_crc = CRC32('needle') AND name = 'needle';"}]},"source_url":"https://sqlly.app/sql-functions/checksum","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/choose","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHOOSE function","description":"CHOOSE(index, a, b, c) returns the value at a 1-based position and NULL when out of range. Equivalents with ELT, DECODE, array subscripts and CASE.","body":{"slug":"choose","name":"CHOOSE","h1":"SQL CHOOSE function","category":"conditional","lede":"CHOOSE(2, 'low', 'medium', 'high') returns 'medium'. It is shorthand for a CASE on a position number.","syntax":"CHOOSE(index, value_1, value_2 [, ...])","return_type":"the highest-precedence type among the values","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"(ARRAY[a, b, c])[i]"},{"engine_slug":"mysql","status":"partial","note":"ELT(i, a, b, c), which returns strings"},{"engine_slug":"sqlite","status":"no","note":"no function; CASE i WHEN 1 THEN a WHEN 2 THEN b END"},{"engine_slug":"oracle","status":"partial","note":"DECODE(i, 1, a, 2, b, 3, c)"}],"gotchas":["The index is 1-based and truncated to an integer: CHOOSE(1.9, 'x', 'y') returns 'x'.","An index out of range returns NULL, not an error: CHOOSE(5, 'a', 'b') is NULL.","The result takes the highest-precedence type of the values, as CASE does. CHOOSE(1, 'a', 2) fails converting 'a' to int even though 2 is never chosen.","The equivalents round a fractional index instead of truncating it: (ARRAY['x', 'y'])[1.9] on PostgreSQL and ELT(1.9, 'x', 'y') on MySQL both return 'y', where CHOOSE(1.9, 'x', 'y') returns 'x'."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CHOOSE(2, 'low', 'medium', 'high') AS level, CHOOSE(5, 'a', 'b') AS out_of_range;  -- medium, NULL"},{"engine_slug":"sql-server","sql":"SELECT CHOOSE(DATEPART(QUARTER, '2026-08-15'), 'Q1', 'Q2', 'Q3', 'Q4') AS quarter_label;  -- Q3"},{"engine_slug":"postgresql","sql":"SELECT (ARRAY['low', 'medium', 'high'])[2] AS level;  -- medium"},{"engine_slug":"mysql","sql":"SELECT ELT(2, 'low', 'medium', 'high') AS level;  -- medium"},{"engine_slug":"oracle","sql":"SELECT DECODE(2, 1, 'low', 2, 'medium', 3, 'high') AS lvl, DECODE(5, 1, 'a', 2, 'b') AS out_of_range FROM dual;  -- medium, NULL"}],"faqs":[{"question":"CHOOSE or IIF?","answer":"IIF picks between two values on a condition; CHOOSE picks among many by position. Both expand to CASE internally."},{"question":"Is CHOOSE zero-based?","answer":"No. The first value is index 1, and CHOOSE(0, ...) returns NULL."}],"related":["elt","case","decode","iif"],"novel_uses":[{"body":"ABS(CHECKSUM(NEWID())) % 3 + 1 gives a random integer from 1 to 3 per row on SQL Server, and CHOOSE turns it into a random value from a list, which seeds test tables without a generator script. Compute the number once in CROSS APPLY first: CHOOSE expands to CASE WHEN i = 1 ... WHEN i = 2 ..., so a NEWID() written inside it runs again for each branch, and about 30% of rows come back NULL with the rest skewed toward 'low'.","sql":"SELECT CHOOSE(r.i, 'low', 'medium', 'high') AS tier\nFROM (VALUES (1), (2), (3), (4), (5)) AS t(n)\nCROSS APPLY (SELECT ABS(CHECKSUM(NEWID())) % 3 + 1 AS i) AS r;"},{"body":"Oracle's DECODE, the usual CHOOSE stand-in, treats a NULL first argument as equal to a NULL key, so a DECODE ladder matches NULL where CHOOSE returns NULL. When the index can be NULL, write CASE instead and the two engines agree.","sql":"SELECT DECODE(NULL, NULL, 'matched', 'no') AS d FROM dual;  -- matched"}]},"source_url":"https://sqlly.app/sql-functions/choose","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/chr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHR / CHAR function","description":"Turn a code point into a character: CHR on PostgreSQL and Oracle, CHAR on SQL Server, MySQL and SQLite, and how to build control characters in each engine.","body":{"slug":"chr","name":"CHR / CHAR","h1":"SQL CHR / CHAR function","category":"string","lede":"The inverse of ASCII: numbers become characters, which is how SQL builds newlines, tabs and symbols without literals that editors mangle.","syntax":"CHR(n)  |  CHAR(n)  (MySQL and SQLite also take CHAR(n [, n ...]))","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"CHAR() accepts a comma-separated list and returns binary unless you add USING"},{"engine_slug":"sqlite","status":"yes","note":"spelled char(), also takes a list"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Names split: CHAR on SQL Server, MySQL and SQLite; CHR on PostgreSQL and Oracle. MySQL's CHAR(65, 66) takes a list; SQLite's char() too.","Oracle: embedded CHR(0) acts like an end-of-string marker in many interfaces; the value truncates silently in binds and clients.","SQL Server CHAR(n) works on the varchar codepage: CHAR(233) may be é on Latin1 and something else elsewhere. NCHAR(n) is the Unicode call; values above 65535 need a supplementary-character (_SC) collation, otherwise NCHAR returns NULL.","MySQL's CHAR() takes byte values and returns a binary string. CHAR(n USING utf8mb4) reads n as UTF-8 bytes, so an NBSP is CHAR(0xC2A0 USING utf8mb4), not CHAR(160 USING utf8mb4), which is a lone 0xA0 byte, invalid UTF-8, and returns NULL."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 'line1' + CHAR(13) + CHAR(10) + 'line2' AS two_lines;"},{"engine_slug":"postgresql","sql":"SELECT CHR(233) AS e_acute;  -- é"},{"engine_slug":"sqlite","sql":"SELECT 'line1' || char(10) || 'line2' AS two_lines;"},{"engine_slug":"mysql","sql":"SELECT CHAR(72, 73) AS hi, CHAR(0xC3A9 USING utf8mb4) AS e;  -- HI, é: byte values, binary result without USING"},{"engine_slug":"oracle","sql":"SELECT CHR(72) || CHR(73) AS hi, CHR(233) AS e FROM dual;  -- HI, é"}],"faqs":[{"question":"Is it CHR or CHAR?","answer":"Both: SQL Server, MySQL and SQLite call it CHAR, PostgreSQL and Oracle call it CHR. Same job: integer code point in, one-character string out."},{"question":"Why does CHAR(233) show a different character on SQL Server?","answer":"CHAR returns varchar, interpreted in the column's or database's codepage. NCHAR(233) returns nvarchar and always means Unicode code point 233."},{"question":"Is CHR(0) safe?","answer":"On Oracle it behaves as a string terminator in many contexts, silently truncating. On SQL Server and MySQL it embeds, but clients and drivers may still cut there. PostgreSQL refuses it outright: chr(0) fails with \"null character not permitted\"."}],"related":["ascii","newline-literal","unicode-function"],"novel_uses":[{"body":"CHR(1) almost never occurs in real text, so order_id || CHR(1) || line_no builds import keys that split back unambiguously, unlike dashes or pipes that data can contain.","sql":"SELECT order_id || CHR(1) || line_no AS import_key FROM orders;"},{"body":"Two NCHAR calls for the surrogate halves assemble an emoji on any SQL Server collation, the workaround for versions and collations where NCHAR(128512) returns NULL.","sql":"SELECT NCHAR(55357) + NCHAR(56832) AS emoji;  -- builds the surrogate pair without an _SC collation"}]},"source_url":"https://sqlly.app/sql-functions/chr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/chr-codepoint","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CHR code point","description":"How CHR and CHAR turn a number into a character in each engine: code points versus bytes, newlines and tabs, NUL handling, and the ASCII and UNICODE inverses.","body":{"slug":"chr-codepoint","name":"CHR","h1":"SQL CHR code point","category":"string","lede":"Returns the character for a numeric code: a code point in some engines, a byte value in others.","syntax":"CHR(code)  |  SQL Server and MySQL: CHAR(code)  |  SQLite: char(code)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"CHAR(n) uses the collation's code page and returns NULL above 255; NCHAR(n) takes UTF-16 code units, 0 to 65535, so NCHAR(128512) is NULL and an emoji needs a surrogate pair."},{"engine_slug":"postgresql","status":"yes","note":"chr(n) takes a code point in UTF8 databases; chr(0) is an error."},{"engine_slug":"mysql","status":"partial","note":"CHAR(n) treats n as bytes; CHAR(n USING utf32) takes a code point."},{"engine_slug":"sqlite","status":"partial","note":"char(n, ...) takes code points and accepts several."},{"engine_slug":"oracle","status":"yes","note":"CHR(n) takes a byte value in the database character set; NCHR(n) takes a code point."}],"gotchas":["Engines disagree on what the number means: a code point (PostgreSQL in UTF8, SQLite, SQL Server's NCHAR), a code-page byte (SQL Server's CHAR) or encoded bytes (MySQL's CHAR, Oracle's CHR). Below 128 they all agree.","The line-break codes: 10 is newline, 13 carriage return, 9 tab. Windows line endings are CHR(13) || CHR(10).","PostgreSQL cannot store the NUL character in text, so chr(0) raises an error; SQL Server, MySQL and SQLite accept a NUL character."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CHR(65) AS letter;  -- A"},{"engine_slug":"postgresql","sql":"SELECT split_part(note, chr(10), 1) AS first_line\nFROM logs;"},{"engine_slug":"sql-server","sql":"SELECT CHAR(65) + CHAR(66) + CHAR(67) AS letters;  -- ABC"},{"engine_slug":"oracle","sql":"SELECT CHR(233) AS letter\nFROM dual;  -- é"},{"engine_slug":"oracle","sql":"SELECT ASCIISTR('café') AS escaped\nFROM dual;  -- cafe\\00E9"},{"engine_slug":"mysql","sql":"SELECT CHAR(233 USING utf32) AS letter;  -- é"},{"engine_slug":"sqlite","sql":"SELECT char(233) AS letter;  -- é"}],"faqs":[{"question":"What is CHR(10) used for?","answer":"Newlines. Splitting or replacing on CHR(10) (CHAR(10) in SQL Server and MySQL) is how you handle multi-line text stored in a column."},{"question":"Is CHR the same as CHAR in SQL Server?","answer":"SQL Server has no CHR function, so CHR(65) fails as an unrecognized built-in function. Use CHAR(n) for byte codes, which follow the collation's code page and return NULL past 255, or NCHAR(n) for Unicode code points up to 65535."},{"question":"How do I convert a character back to its code?","answer":"ASCII(ch) in most engines for 0 to 127; UNICODE(ch) in SQLite for any code point, and in SQL Server for code points up to 65535 (UNICODE(NCHAR(55357) + NCHAR(56832)) returns 55357, the high surrogate); ascii(ch) in PostgreSQL, which returns the code point in UTF8 databases."}],"related":["ascii","unicode","replace","concat"],"novel_uses":[{"body":"chr(31), the ASCII unit separator, never appears in real data, so string_agg over it builds a delimited payload that no value can corrupt, unlike a comma or tab.","sql":"SELECT string_agg(name, chr(31)) AS packed\nFROM items;"},{"body":"Files opened in Notepad want CHAR(13) plus CHAR(10); one string_agg with that separator writes correct line endings straight from the query.","sql":"SELECT STRING_AGG(line, CHAR(13) + CHAR(10)) AS win_text\nFROM log_lines;"}]},"source_url":"https://sqlly.app/sql-functions/chr-codepoint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/clock-timestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL clock_timestamp function","description":"PostgreSQL's clock_timestamp() returns the true wall clock as it advances, unlike NOW() and transaction_timestamp() which freeze at transaction start.","body":{"slug":"clock-timestamp","name":"clock_timestamp","h1":"SQL clock_timestamp function","category":"datetime","lede":"Returns the actual current time, re-read on every call, the only PostgreSQL timestamptz function that changes within a single statement.","syntax":"clock_timestamp()  |  clock_timestamp() AT TIME ZONE 'UTC'","return_type":"timestamptz","support":[{"engine_slug":"sql-server","status":"partial","note":"SYSDATETIME() is fixed per query but re-read by each statement in a batch"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"SYSDATE() is the per-call clock; NOW() is fixed per statement"},{"engine_slug":"sqlite","status":"partial","note":"'now' is stable for the whole statement and is re-read by each statement"},{"engine_slug":"oracle","status":"partial","note":"SYSTIMESTAMP is fixed per SQL statement; each PL/SQL call re-reads it"}],"gotchas":["NOW() and transaction_timestamp() freeze for the whole transaction, statement_timestamp() for one statement; only clock_timestamp() advances between rows of one query.","For timing steps inside a PL/pgSQL function, use clock_timestamp(): the whole function runs in one transaction, so NOW() returns the same value at every step.","MySQL's SYSDATE() is the same idea but is unsafe with statement-based replication; NOW() is the replication-safe choice."],"examples":[{"engine_slug":"postgresql","sql":"SELECT clock_timestamp() AS tick_one,\n       pg_sleep(0.5),\n       clock_timestamp() AS tick_two;"},{"engine_slug":"mysql","sql":"SELECT SYSDATE(6) AS tick_one, SLEEP(1), SYSDATE(6) AS tick_two;"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIME() AS tick_one;\nWAITFOR DELAY '00:00:01';\nSELECT SYSDATETIME() AS tick_two;"},{"engine_slug":"sqlite","sql":"SELECT datetime('now') AS t1, datetime('now') AS t2;  -- same value inside one statement"},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AS t1, SYSTIMESTAMP AS t2 FROM dual;  -- same value inside one statement"}],"faqs":[{"question":"Why does NOW() not change inside my loop?","answer":"PostgreSQL freezes NOW() at transaction start, and a function or DO block runs inside one transaction. clock_timestamp() advances call to call."},{"question":"What is MySQL's equivalent?","answer":"SYSDATE(): it evaluates per call, while NOW() is constant for the whole statement."}],"related":["now","transaction-timestamp","localtimestamp"],"novel_uses":[{"body":"NOW() stamps every row of a single INSERT identically, so a feed table that must sort by true arrival order needs clock_timestamp() re-read per row.","sql":"INSERT INTO feed (at)\nSELECT clock_timestamp() FROM generate_series(1, 3);"},{"body":"statement_timestamp() froze when this statement began, so the difference against clock_timestamp() is how long the query has been running so far, readable from any row.","sql":"SELECT clock_timestamp() - statement_timestamp() AS elapsed_so_far;"}]},"source_url":"https://sqlly.app/sql-functions/clock-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/coalesce","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COALESCE function","description":"COALESCE in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: return the first non-NULL argument, with type precedence and evaluation traps.","body":{"slug":"coalesce","name":"COALESCE","h1":"SQL COALESCE function","category":"conditional","lede":"Returns the first argument that is not NULL: a display value for missing data, a default, or a fallback chain such as COALESCE(mobile, work_phone, home_phone).","syntax":"COALESCE(value1, value2, ...)","return_type":"the common type of all arguments","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["All arguments must share a type. On SQL Server, the highest-precedence type wins: COALESCE(int_col, '') silently returns 0, and COALESCE(int_col, 'none') fails at run time converting 'none' to int. PostgreSQL resolves the '' literal to integer and fails at run time with invalid input syntax for type integer, even when no row reaches it. Cast to a common type.","Evaluation stops at the first non-NULL argument, but SQL Server rewrites COALESCE as a CASE expression, so a subquery argument can run twice. For an expensive lookup, compute it once in a CTE, or use ISNULL for two arguments.","An all-NULL COALESCE returns NULL: COALESCE(a, b, 0) with a final literal guarantees a non-NULL result."],"examples":[{"engine_slug":"all","sql":"SELECT COALESCE(nickname, first_name, 'Anonymous') AS display_name\nFROM users;"},{"engine_slug":"all","sql":"SELECT COALESCE(SUM(amount), 0) AS total FROM payments;"}],"faqs":[{"question":"What does COALESCE return if everything is NULL?","answer":"NULL, provided at least one argument is a typed NULL such as a column. On SQL Server, COALESCE(NULL, NULL) with only untyped literals fails with Msg 4127, so cast one of them. Add a literal as the last argument when the caller cannot handle NULL: COALESCE(a, b, 0)."},{"question":"COALESCE or ISNULL / IFNULL / NVL?","answer":"COALESCE is the SQL standard and takes any number of arguments; the others are engine dialects that take exactly two. Prefer COALESCE for portability."}],"related":["nullif","ifnull","case"],"novel_uses":[{"body":"LEFT JOIN the incoming feed and take COALESCE(new.phone, old.phone) per column: updated where the feed carries a value, preserved where it does not. One statement merges the whole record, and unmatched rows fall through intact.","sql":"SELECT COALESCE(n.phone, o.phone) AS phone,\n       COALESCE(n.address, o.address) AS address\nFROM old_customers o\nLEFT JOIN new_feed n ON n.id = o.id;"},{"body":"a.x = b.x drops NULL-NULL pairs because NULL never equals anything. COALESCE both sides to a sentinel the data cannot hold (like -1 for positive ids) and the pairs match; pick the sentinel carefully, because a real -1 would join rows that should not.","sql":"SELECT *\nFROM a JOIN b\n  ON COALESCE(a.parent_id, -1) = COALESCE(b.parent_id, -1);"}]},"source_url":"https://sqlly.app/sql-functions/coalesce","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/coalesce-index","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COALESCE index usage","description":"Wrapping an indexed column in COALESCE or ISNULL inside WHERE hides it from the index: OR IS NULL rewrites, computed-column and expression-index fixes per engine.","body":{"slug":"coalesce-index","name":"COALESCE","h1":"SQL COALESCE index usage","category":"conditional","lede":"Why COALESCE(col, default) in a WHERE clause turns index seeks into scans, and the fixes.","syntax":"WHERE COALESCE(col, 'new') = 'new' | WHERE col = 'new' OR col IS NULL","return_type":"rows","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["A function on the column makes the predicate non-sargable: the engine must evaluate COALESCE per row unless an expression index matches it exactly.","PostgreSQL fix: CREATE INDEX ON t (COALESCE(col, '')) makes the wrapped form seekable.","SQL Server fix: add a computed column AS COALESCE(col, '') and index it. MySQL 8.0.13+ supports functional indexes, written with doubled parentheses: INDEX ((COALESCE(col, ''))). SQLite and Oracle accept expression indexes directly.","The common intent behind COALESCE(col, 'new') = 'new' is col = 'new' OR col IS NULL, and a plain index on col can answer that form directly. Oracle is the exception: its B-tree indexes do not store all-NULL keys, so the IS NULL half needs a composite index such as (col, 0)."],"examples":[{"engine_slug":"postgresql","sql":"CREATE INDEX ON users (COALESCE(email, ''));"},{"engine_slug":"all","sql":"SELECT * FROM users WHERE email = 'a@b.c' OR email IS NULL;"}],"faqs":[{"question":"Why does COALESCE(col, '') = @x ignore my index?","answer":"The index is on col, not on COALESCE(col, ''); the engine must compute the expression for every row unless an expression index exists."},{"question":"What is the sargable rewrite?","answer":"Spell out what the COALESCE means. COALESCE(col, @d) = @x is col = @x when @x differs from @d, and col = @x OR col IS NULL when they are equal. Or keep the COALESCE and build an expression index that matches it exactly."},{"question":"Does this apply to other functions?","answer":"Usually: UPPER(col), CAST(col AS ...) and friends break index use the same way. A few casts are exceptions: SQL Server still seeks on CAST(datetime_col AS date), and PostgreSQL ignores a no-op cast such as text to varchar."}],"related":["coalesce","is-null","null-safe-equal","null"],"novel_uses":[{"body":"An expression index serves only the identical expression: COALESCE(email, '') in the index answers WHERE COALESCE(email, '') = ... but not a different default or an extra cast; near-misses scan.","sql":"CREATE INDEX ix_users_email_c ON users ((COALESCE(email, '')));"},{"body":"Run EXPLAIN before and after creating the index; if the plan still scans the table, the WHERE expression does not match the indexed one.","sql":"EXPLAIN SELECT * FROM users WHERE COALESCE(email, '') = 'a@b.c';"}]},"source_url":"https://sqlly.app/sql-functions/coalesce-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/collapse-spaces","corpus":"sql-functions","engine":null,"language":"en","title":"SQL collapse multiple spaces","description":"Turn runs of spaces into one space per engine: REGEXP_REPLACE where regex exists (it also takes tabs and newlines), nested REPLACE passes where it does not (spaces only).","body":{"slug":"collapse-spaces","name":"Collapsing duplicate spaces","h1":"SQL collapse multiple spaces","category":"string","lede":"Normalize whitespace: 'a    b' becomes 'a b'. Regex does it in one call; SQL Server before 2025 needs the nested-REPLACE idiom or a loop.","syntax":"REGEXP_REPLACE(s, '\\s+', ' ')  -- PostgreSQL: add 'g'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"REGEXP_REPLACE from SQL Server 2025; nested REPLACE before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Regex form: REGEXP_REPLACE(s, '\\s+', ' ') collapses tabs, newlines and space runs on Oracle and SQL Server 2025. PostgreSQL replaces only the first match unless you pass 'g' as the fourth argument. On MySQL the literal '\\s+' arrives as 's+' because the backslash is a string escape; write '[[:space:]]+' or '\\\\s+'. Use ' +' for spaces only.","The pre-2025 SQL Server idiom is repeated REPLACE(s, '  ', ' '): each pass halves the longest run, so n nested passes handle runs up to 2^n. LTRIM/RTRIM the ends separately.","Order matters when cleaning everything: turn tabs, newlines and NBSPs into spaces first, then collapse. Collapsing first leaves double spaces where a newline sat between two spaces, and deleting a newline glues its neighbours together ('a' + newline + 'b' becomes 'ab').","MySQL before 8.0 has no REGEXP_REPLACE: the nested-REPLACE idiom applies there too."],"examples":[{"engine_slug":"postgresql","sql":"SELECT REGEXP_REPLACE(note, '\\s+', ' ', 'g') AS tidy FROM notes;"},{"engine_slug":"sql-server","sql":"SELECT LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(note, '  ', ' '), '  ', ' '), '  ', ' '))) AS tidy\nFROM notes;  -- three passes handle runs up to 8"},{"engine_slug":"mysql","sql":"SELECT REGEXP_REPLACE(note, ' +', ' ') AS tidy FROM notes;"},{"engine_slug":"sqlite","sql":"SELECT trim(replace(replace(replace(trim(note), '  ', ' '), '  ', ' '), '  ', ' ')) AS tidy\nFROM notes;  -- no regexp_replace; three passes handle runs up to 8 spaces"},{"engine_slug":"oracle","sql":"SELECT TRIM(REGEXP_REPLACE(note, ' {2,}', ' ')) AS tidy FROM notes;"}],"faqs":[{"question":"Why are some double spaces still there?","answer":"Each nested REPLACE pass halves run lengths: one pass turns 8 spaces into 4, not 1. Add passes until they exceed the longest run you can produce, or use regex."},{"question":"Does '\\s+' include tabs and newlines?","answer":"Yes. PostgreSQL, MySQL 8+, Oracle and SQL Server 2025 all support the \\s class, but on MySQL the backslash must be doubled in the literal ('\\\\s+'), or use [[:space:]]. Use ' +' when spaces alone should collapse."},{"question":"How do I collapse spaces on SQL Server?","answer":"On 2025, REGEXP_REPLACE(s, ' +', ' '). Before that, the nested REPLACE(s, '  ', ' ') idiom plus LTRIM/RTRIM, or a WHILE loop for unbounded runs. Keep it in a view or function so the idiom lives once."}],"related":["remove-newlines","remove-nbsp","trim","regexp-replace"],"novel_uses":[{"body":"Normalizing runs to one space in a GROUP BY exposes the lead entries typed with double spaces, which is the pass to run before a dedupe merge.","sql":"SELECT REGEXP_REPLACE(name, ' +', ' ', 'g') AS folded, COUNT(*)\nFROM leads GROUP BY 1 HAVING COUNT(*) > 1;"},{"body":"A LIKE against two spaces measures how many rows a collapse pass would rewrite, which decides whether it runs now or in the maintenance window.","sql":"SELECT COUNT(*) FROM notes WHERE note LIKE '%  %';"}]},"source_url":"https://sqlly.app/sql-functions/collapse-spaces","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/collate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COLLATE clause","description":"COLLATE overrides string comparison for one expression or column: case sensitivity, accent handling and ordering on SQL Server, MySQL, PostgreSQL and SQLite.","body":{"slug":"collate","name":"COLLATE","h1":"SQL COLLATE clause","category":"conversion","lede":"x COLLATE utf8mb4_bin changes how x is compared right there (case-sensitive equality, custom ordering) without changing the value or the column.","syntax":"expression COLLATE collation_name","return_type":"same type as the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"built-in collations only: BINARY, NOCASE, RTRIM"},{"engine_slug":"oracle","status":"partial","note":"12.2+ supports expression COLLATE; NLSSORT is the older route"}],"gotchas":["COLLATE changes comparison semantics, not the value: 'MATT' = 'matt' is true under a case-insensitive collation (_CI on SQL Server, _ci on MySQL) and false under _CS or _bin.","PostgreSQL's default collations are already case-sensitive, so 'a' = 'A' is false without any COLLATE. Case-insensitive matching there needs a nondeterministic ICU collation, ILIKE or lower() on both sides.","Collation names never port: SQL Server's Windows collations, MySQL's utf8mb4_* and PostgreSQL's libc/ICU names are unrelated vocabularies with overlapping intent.","COLLATE inside a WHERE on an indexed column can prevent index use on MySQL and SQL Server; set the collation at column level when one rule should always apply.","SQLite ships only BINARY, NOCASE and RTRIM, and NOCASE folds ASCII letters only: 'É' and 'é' still differ. Anything else needs a collation registered by the application."],"examples":[{"engine_slug":"sql-server","sql":"SELECT name FROM users\nORDER BY name COLLATE Latin1_General_CS_AS;"},{"engine_slug":"mysql","sql":"SELECT * FROM users\nWHERE name = 'matt' COLLATE utf8mb4_bin;"},{"engine_slug":"sqlite","sql":"SELECT * FROM users ORDER BY name COLLATE NOCASE;"},{"engine_slug":"postgresql","sql":"SELECT * FROM users\nORDER BY name COLLATE \"C\";"},{"engine_slug":"oracle","sql":"SELECT * FROM users\nORDER BY NLSSORT(name, 'NLS_SORT=BINARY_CI');"}],"faqs":[{"question":"How do I make one comparison case-sensitive?","answer":"Add a case-sensitive collation to the expression: utf8mb4_bin (MySQL), Latin1_General_CS_AS (SQL Server), COLLATE BINARY (SQLite), BINARY via COLLATE or NLSSORT (Oracle). PostgreSQL is case-sensitive by default. It affects only that comparison."},{"question":"Does COLLATE work on any expression?","answer":"On any string expression: a column, a literal or a computed string. SQL Server and PostgreSQL reject it on non-string types such as int. Applying it in a predicate against an indexed column can cost you the index; prefer column-level collation for standing rules."}],"related":["binary-cast","upper","convert-charset","ascii"],"novel_uses":[{"body":"Collations carry language rules: ORDER BY name COLLATE Finnish_Swedish_CI_AS on SQL Server puts Å, Ä and Ö after Z instead of folding them in with A and O. Picking the collation per query fixes ordering for one report without touching the column.","sql":"SELECT name FROM members ORDER BY name COLLATE Finnish_Swedish_CI_AS;"},{"body":"The RTRIM collation ignores trailing spaces during comparison, so ON a.code = b.code COLLATE RTRIM matches 'AB7 ' to 'AB7' where plain BINARY collation fails. A quick fix for imports padded by another system.","sql":"SELECT a.id FROM a JOIN b ON a.code = b.code COLLATE RTRIM;"},{"body":"The default collation folds 'Matt' and 'matt' into one group. Group on the expression with a binary collation to count them separately: GROUP BY name COLLATE utf8mb4_bin.","sql":"SELECT name COLLATE utf8mb4_bin AS exact_name, COUNT(*) FROM users GROUP BY exact_name;"}]},"source_url":"https://sqlly.app/sql-functions/collate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/concat","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONCAT function","description":"Concatenate strings in SQL Server, PostgreSQL, MySQL, SQLite and Oracle with CONCAT and ||, and the NULL differences that make the same query behave differently.","body":{"slug":"concat","name":"CONCAT","h1":"SQL CONCAT function","category":"string","lede":"Joins strings into one. The trap is NULL: engines disagree on whether one NULL argument makes the whole result NULL, and the || operator can behave differently from CONCAT on the same engine.","syntax":"CONCAT(a, b, ...)  |  a || b  -- PostgreSQL, SQLite, Oracle, SQL Server 2025","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"CONCAT from 2012; the || operator from SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"CONCAT returns NULL if any argument is NULL; || means OR unless PIPES_AS_CONCAT is set"},{"engine_slug":"sqlite","status":"yes","note":"CONCAT and CONCAT_WS from SQLite 3.44; || has always existed"},{"engine_slug":"oracle","status":"yes","note":"CONCAT took exactly two arguments before 23ai; || ignores NULLs"}],"gotchas":["NULL handling differs by engine: CONCAT on SQL Server, PostgreSQL, SQLite and Oracle treats NULL as an empty string, but MySQL's CONCAT returns NULL if any argument is NULL.","The || operator is stricter than CONCAT on PostgreSQL and SQLite: NULL || 'a' is NULL there. Oracle's || ignores NULL operands, so the same expression gives 'a'.","On MySQL, || is logical OR by default: 'a' || 'b' returns 0. Use CONCAT, or set sql_mode PIPES_AS_CONCAT.","CONCAT never adds separators. CONCAT_WS(', ', a, b, c) does, and skips NULL arguments; it exists on MySQL, PostgreSQL, SQL Server 2017+ and SQLite 3.44+."],"examples":[{"engine_slug":"all","sql":"SELECT CONCAT(first_name, ' ', last_name) AS full_name\nFROM users;"},{"engine_slug":"postgresql","sql":"-- || is stricter: NULL poisons the result\nSELECT NULL || 'a' AS strict_concat;  -- NULL"},{"engine_slug":"mysql","sql":"SELECT CONCAT_WS(', ', city, region, country) AS place\nFROM addresses;"},{"engine_slug":"oracle","sql":"-- || chains; CONCAT took exactly two arguments before 23ai\nSELECT first_name || ' ' || last_name AS full_name\nFROM users;"}],"faqs":[{"question":"Does CONCAT return NULL if a value is NULL?","answer":"Depends on the engine: SQL Server, PostgreSQL, SQLite and Oracle treat NULL as empty; MySQL returns NULL for the whole call. COALESCE each argument if the query has to behave the same everywhere."},{"question":"What is the difference between CONCAT and ||?","answer":"On PostgreSQL and SQLite, NULL || x is NULL while CONCAT skips the NULL. On MySQL, || is logical OR unless PIPES_AS_CONCAT is set. Oracle's || ignores NULLs, and its CONCAT took only two arguments before 23ai. SQL Server only gained || in 2025."},{"question":"How do I concatenate with a separator?","answer":"CONCAT_WS(', ', a, b, c) on MySQL, PostgreSQL, SQL Server 2017+ and SQLite 3.44+; it skips NULL arguments instead of leaving doubled separators. Oracle has no CONCAT_WS, so write a || ', ' || b. For values from many rows, use STRING_AGG."}],"related":["nullif","string-agg","ifnull"],"novel_uses":[{"body":"CONCAT(year, '-', month) sorts 2026-10 before 2026-2 because text order is character by character. Padding the number to a fixed width first makes the key sort like the date: LPAD exists on PostgreSQL, MySQL and Oracle; SQLite uses printf('%02d', ...) and SQL Server RIGHT('0' + ..., 2).","sql":"SELECT CONCAT(order_year, '-', LPAD(CAST(order_month AS text), 2, '0')) AS month_key\nFROM sales;"},{"body":"Wrapping every field in quotes and doubling the ones inside is the CSV escape every reader understands. Doing it in the query keeps the export statement self-contained, and it needs nothing but REPLACE and CONCAT on any engine.","sql":"SELECT CONCAT('\"', REPLACE(note, '\"', '\"\"'), '\"') AS safe_cell\nFROM records;"}]},"source_url":"https://sqlly.app/sql-functions/concat","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/concat-implicit-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL concatenation and implicit casts","description":"Joining numbers and dates to strings behaves differently per engine: SQL Server errors, MySQL adds, Oracle follows NLS formats, so cast explicitly.","body":{"slug":"concat-implicit-cast","name":"Implicit casts in concatenation","h1":"SQL concatenation and implicit casts","category":"string","lede":"What happens when a number or date meets a string operator depends on the engine: a conversion error, silent arithmetic, or a session-dependent date format.","syntax":"'x' || CAST(n AS text)  -- PostgreSQL and SQLite; use CONCAT elsewhere","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server: + keeps the higher-precedence type, so 'Age: ' + 42 is a conversion error, while '5' + 1 is 6. CONCAT converts every argument to text cleanly.","MySQL and SQLite: + is arithmetic on strings; 'Total: ' + 5 is 5, because 'Total: ' casts to 0. There is no string +.","Oracle: number || string works, but dates pick up NLS_DATE_FORMAT, so the same query shows different date formats per session. TO_CHAR explicitly.","PostgreSQL: || works when one side is text ('x' || 1 is 'x1') but 1 || 2 is an error. Dates print per the DateStyle setting, so use to_char for a fixed format."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CONCAT('Order ', 42) AS ok;  -- Order 42"},{"engine_slug":"mysql","sql":"SELECT 'Total: ' + 5 AS arith, CONCAT('Total: ', 5) AS joined;\n-- 5, Total: 5"},{"engine_slug":"oracle","sql":"SELECT 'Due: ' || TO_CHAR(due_date, 'YYYY-MM-DD') AS due FROM tasks;"},{"engine_slug":"postgresql","sql":"SELECT 'Total: ' || 5 AS joined;  -- Total: 5; but 1 || 2 errors, neither side is text"},{"engine_slug":"sqlite","sql":"SELECT 'Total: ' || 5 AS joined;  -- Total: 5; || casts every value to text"}],"faqs":[{"question":"Why does my concatenation throw a conversion error?","answer":"On SQL Server, + with a number tries to convert the string side to a number (int outranks varchar). CONCAT or an explicit CAST avoids the trap."},{"question":"Why did my date concatenate as '01-AUG-26'?","answer":"That is Oracle's default NLS_DATE_FORMAT (DD-MON-RR) at work; PostgreSQL follows DateStyle instead. TO_CHAR with an explicit pattern, or CONVERT with a style on SQL Server, pins it down."},{"question":"Is there one portable way to join strings and numbers?","answer":"CAST the non-string operand explicitly, then use the engine's string joiner. Casting alone does not fix + on MySQL: 'Age: ' + CAST(42 AS CHAR) is 42, so use CONCAT there."}],"related":["concat","plus-concat","cast","to-char"],"novel_uses":[{"body":"An explicit CAST makes SQL Server render bit as 1 or 0, but + with a bit raises Msg 402, so a CASE is the readable form when a flag joins a concatenation.","sql":"SELECT 'active=' + CASE WHEN flag = 1 THEN 'Y' ELSE 'N' END FROM flags;\n-- CAST(flag AS varchar) would give 1 or 0"},{"body":"CONCAT reads a DECIMAL at its declared scale, so CONCAT(total, '') prints 1.50 for DECIMAL(8,2), while + arithmetic keeps the two decimals too (CAST(1.5 AS DECIMAL(8,2)) + 0 is 1.50), so the point is the text form, not precision.","sql":"SELECT CONCAT(total, '') AS text_total FROM payments;  -- keeps the two decimals"}]},"source_url":"https://sqlly.app/sql-functions/concat-implicit-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/concat-null-yields-null","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONCAT_NULL_YIELDS_NULL setting","description":"SQL Server's CONCAT_NULL_YIELDS_NULL decides whether NULL operands poison the + operator, a deprecated setting you should never rely on either way.","body":{"slug":"concat-null-yields-null","name":"CONCAT_NULL_YIELDS_NULL","h1":"SQL CONCAT_NULL_YIELDS_NULL setting","category":"string","lede":"Controls whether 'a' + NULL is NULL on SQL Server. It only affects the + operator; CONCAT and CONCAT_WS always skip NULLs regardless.","syntax":"SET CONCAT_NULL_YIELDS_NULL { ON | OFF }","return_type":"setting","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["The setting is deprecated. Microsoft Learn says SQL Server 2017 and later always set it ON, but on SQL Server 2022 RTM-CU28 a session SET ... OFF is still honoured, so do not rely on either behaviour. The ODBC driver switches it ON when it connects, so in practice most client sessions are ON whatever the database default says.","CONCAT and CONCAT_WS ignore the setting and always treat NULL as empty; prefer them and stop depending on the flag.","It can be set per database (ALTER DATABASE ... SET, default OFF) or per session, and the session value wins. A connection that never sets it, or a script that runs SET ... OFF, is where results start to differ.","Write NULL-safe code instead: ISNULL(col, ''), COALESCE, or CONCAT."],"examples":[{"engine_slug":"sql-server","sql":"SET CONCAT_NULL_YIELDS_NULL ON;\nSELECT 'a' + NULL AS result;  -- NULL"},{"engine_slug":"sql-server","sql":"SET CONCAT_NULL_YIELDS_NULL OFF;\nSELECT 'a' + NULL AS result;  -- a"},{"engine_slug":"sql-server","sql":"SELECT CONCAT('a', NULL) AS always_safe;  -- a"}],"faqs":[{"question":"Why does the same query return NULL in one tool and 'a' in another?","answer":"CONCAT_NULL_YIELDS_NULL differs per connection. Standard drivers turn it ON; a client that skips that, or a stored procedure or script that sets it OFF, falls back to different behaviour. Check with SELECT SESSIONPROPERTY('CONCAT_NULL_YIELDS_NULL')."},{"question":"Does CONCAT_NULL_YIELDS_NULL affect CONCAT?","answer":"No. CONCAT and CONCAT_WS always skip NULLs. The setting only governs the + operator and +=."},{"question":"Should I turn it OFF in my database?","answer":"No. It is deprecated, and Microsoft Learn states SQL Server 2017 and later always set it ON. Make the SQL NULL-safe with CONCAT, ISNULL or COALESCE instead."}],"related":["plus-concat","concat","coalesce"],"novel_uses":[{"body":"With the setting ON a long + chain returns all or nothing, so run the same statement with SET CONCAT_NULL_YIELDS_NULL OFF in a debug session: the NULL operand becomes an empty gap in the otherwise complete string.","sql":"SET CONCAT_NULL_YIELDS_NULL OFF;\nSELECT 'Order ' + ref + ' qty ' + CAST(qty AS varchar(10)) AS partial\nFROM orders WHERE id = 7;\n-- the double space (empty gap) marks the NULL operand"},{"body":"Run the target procedures with the setting OFF and compare output to the ON run: identical results on your test inputs show the output does not depend on the flag for those inputs, so include NULL inputs in the test.","sql":"SET CONCAT_NULL_YIELDS_NULL OFF;\nEXEC dbo.report_build @id = 7;  -- same output as ON for NULL and non-NULL inputs means the code is flag-safe for those inputs"}]},"source_url":"https://sqlly.app/sql-functions/concat-null-yields-null","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/concat-operator","corpus":"sql-functions","engine":null,"language":"en","title":"SQL || operator","description":"The || double-pipe operator concatenates strings in PostgreSQL, SQLite and Oracle, with per-engine NULL rules, and MySQL and SQL Server caveats.","body":{"slug":"concat-operator","name":"||","h1":"SQL || operator","category":"string","lede":"The standard SQL concatenation operator. Cleaner than CONCAT for short joins, but its NULL behaviour and availability differ per engine.","syntax":"a || b || c","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"from SQL Server 2025 and Azure SQL Database; use + or CONCAT before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"only with PIPES_AS_CONCAT in sql_mode; || means logical OR by default"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL || 'a' is NULL on PostgreSQL, SQLite and SQL Server. Oracle returns 'a': its || treats a NULL operand as an empty string, the flip side of Oracle storing '' as NULL.","In MySQL, || is logical OR unless the PIPES_AS_CONCAT flag is in sql_mode, a classic why-is-this-1-instead-of-a-string trap.","SQL Server only gained || in SQL Server 2025 (and Azure SQL Database); on 2022 and older the + operator or CONCAT is the only option.","Numbers: Oracle and SQLite turn 1 || 2 into '12'. PostgreSQL needs at least one text operand: 'x' || 1 works, 1 || 2 is an operator-does-not-exist error."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'cafe' || ' corner' AS place;  -- cafe corner"},{"engine_slug":"postgresql","sql":"SELECT NULL || 'a' AS strict_concat;  -- NULL"},{"engine_slug":"oracle","sql":"SELECT first_name || ' ' || last_name AS full_name FROM users;"},{"engine_slug":"sqlite","sql":"SELECT 'cafe' || ' corner' AS place, NULL || 'a' AS null_concat;  -- cafe corner, NULL: SQLite propagates NULL like PostgreSQL"},{"engine_slug":"mysql","sql":"SET sql_mode = 'PIPES_AS_CONCAT';\nSELECT 'a' || 'b' AS joined;  -- ab; without the flag || is logical OR"},{"engine_slug":"sql-server","sql":"SELECT 'a' || 'b' AS joined;  -- ab, from SQL Server 2025 and Azure SQL Database"}],"faqs":[{"question":"Is || the same on every database?","answer":"No. Oracle and PostgreSQL treat it as plain concatenation, MySQL needs PIPES_AS_CONCAT (else it is OR), and SQL Server only supports it from 2025 (and in Azure SQL Database). The NULL rules also differ."},{"question":"Why does 1 || 1 return 1 in MySQL?","answer":"Because MySQL reads || as logical OR: 1 || 1 is 1 (true). Add PIPES_AS_CONCAT to sql_mode, or use CONCAT, to get '11'."},{"question":"Does || handle NULL like CONCAT?","answer":"Usually not: on PostgreSQL and SQLite, NULL || 'a' is NULL while CONCAT('a', NULL) returns 'a' (SQLite's concat() needs version 3.44 or later). Oracle's || skips NULLs on both counts."}],"related":["concat","concat-ws","plus-concat"],"novel_uses":[{"body":"SQLite has no LPAD, so substr('00000' || CAST(n AS TEXT), -5) is the one-line zero-pad: glue zeros on the front, then keep the last five characters. Values with more than five digits are cut to their last five characters (123456 becomes 23456), so use it only for bounded numbers.","sql":"SELECT substr('00000' || CAST(n AS TEXT), -5) AS padded FROM t;"},{"body":"Building a string key from numeric columns needs at least one text operand on PostgreSQL, or the operator does not exist; SQLite and Oracle accept the bare numbers.","sql":"SELECT CAST(order_id AS TEXT) || '-' || line_no AS line_key FROM orders;"},{"body":"On PostgreSQL and SQLite one NULL operand NULLs the whole chain, so a NULL output proves a required piece was missing; on Oracle the NULL piece vanishes silently instead, so do not port that check.","sql":"SELECT a || '-' || b AS k FROM t;  -- NULL key on PostgreSQL and SQLite when a or b is NULL; 'x-' on Oracle"}]},"source_url":"https://sqlly.app/sql-functions/concat-operator","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/concat-ws","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONCAT_WS function","description":"CONCAT_WS joins values with a separator in SQL Server, PostgreSQL, MySQL and SQLite, and skips NULL arguments, unlike plain CONCAT on some engines.","body":{"slug":"concat-ws","name":"CONCAT_WS","h1":"SQL CONCAT_WS function","category":"string","lede":"Joins strings with a separator between each pair, collapsing the CONCAT(a, ', ', b, ', ', c) pattern into one call that drops NULL values along with their separators.","syntax":"CONCAT_WS(separator, value1, value2, ...)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"from SQL Server 2017"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"from SQLite 3.44"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["NULL values are skipped on SQL Server, PostgreSQL, MySQL and SQLite. A NULL separator returns NULL on PostgreSQL, MySQL and SQLite, but SQL Server treats it as '' and returns the values run together.","Empty strings are not skipped: CONCAT_WS(', ', 'a', '', 'c') keeps the gap, so '' and NULL behave differently.","Oracle has no CONCAT_WS, up to and including 23ai. Chain || with the separator typed out, and use CASE or NVL2 to drop a part and its separator when the value is NULL.","Numbers join using their default text format; TO_CHAR, CAST or FORMAT first when the look matters."],"examples":[{"engine_slug":"all","sql":"SELECT CONCAT_WS(' ', first_name, last_name) AS full_name\nFROM users;"},{"engine_slug":"mysql","sql":"SELECT CONCAT_WS(', ', NULL, 'Paris', 'France') AS place;  -- Paris, France"},{"engine_slug":"oracle","sql":"SELECT CONCAT(CONCAT(city, ', '), country) AS place FROM addresses;"}],"faqs":[{"question":"Does CONCAT_WS skip NULLs?","answer":"Yes, every NULL value is dropped with no stray separator, on SQL Server, PostgreSQL, MySQL and SQLite. Empty strings are kept, which is the main difference to watch for."},{"question":"Why does my result come back NULL?","answer":"The separator itself is NULL, not the values. CONCAT_WS(NULL, 'a', 'b') is NULL on PostgreSQL, MySQL and SQLite. SQL Server is the exception: it treats a NULL separator as '' and returns 'ab', and when every value is NULL it returns '' rather than NULL."},{"question":"Is CONCAT_WS in Oracle?","answer":"No. Before 23ai Oracle's CONCAT takes exactly two arguments, so multi-part joins mean nested CONCAT or || chains with the separator written out. 23ai's CONCAT accepts more arguments but still has no separator form."}],"related":["concat","concat-operator","string-agg"],"novel_uses":[{"body":"CONCAT_WS(',', id, name, city) writes one CSV row per query result, and NULL columns leave no doubled commas, so no CASE guards are needed.","sql":"SELECT CONCAT_WS(',', id, name, city) AS csv_row\nFROM users;"},{"body":"Empty strings are kept by CONCAT_WS, so wrapping an optional part in NULLIF(part, '') makes both NULL and '' disappear from the output.","sql":"SELECT CONCAT_WS(' ', first_name, NULLIF(middle_name, ''), last_name) AS display\nFROM users;"},{"body":"Pair CONCAT_WS with a CASE that returns NULL: the whole key=value element vanishes, so no dangling ampersand survives a missing parameter.","sql":"SELECT CONCAT_WS('&', 'page=1',\n       CASE WHEN q IS NULL THEN NULL ELSE CONCAT('q=', q) END) AS url\nFROM filters;"}]},"source_url":"https://sqlly.app/sql-functions/concat-ws","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/conditional-aggregation","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUM(CASE WHEN) pattern","description":"Pivot rows into columns with SUM(CASE WHEN ...) and COUNT(CASE WHEN ...): the portable pattern on all five engines, ELSE 0 versus NULL, and the FILTER shorthand.","body":{"slug":"conditional-aggregation","name":"SUM(CASE)","h1":"SQL SUM(CASE WHEN) pattern","category":"conditional","lede":"One query, several conditional totals: CASE inside an aggregate, portable everywhere.","syntax":"SUM(CASE WHEN c THEN 1 ELSE 0 END) | COUNT(CASE WHEN c THEN 1 END)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without ELSE, CASE yields NULL and aggregates skip it: that is why SUM needs ELSE 0 but COUNT(CASE WHEN c THEN 1 END) works bare.","MySQL and SQLite accept bare SUM(paid = 1) because comparisons return 1 or 0; PostgreSQL needs SUM((paid = 1)::int) or COUNT(*) FILTER (WHERE ...).","The pattern is the standard pivot: one CASE per output column, grouped by the row key.","Write the condition for the column's real type: WHEN paid THEN on a PostgreSQL or Oracle 23ai BOOLEAN, WHEN paid = 1 THEN on SQL Server BIT and MySQL or SQLite 0/1 integers."],"examples":[{"engine_slug":"all","sql":"SELECT dept, SUM(CASE WHEN paid = 1 THEN amount ELSE 0 END) AS paid_amt FROM invoices GROUP BY dept;"},{"engine_slug":"postgresql","sql":"SELECT dept, COUNT(*) FILTER (WHERE paid) AS paid_count FROM invoices GROUP BY dept;"}],"faqs":[{"question":"Why ELSE 0 in SUM but not in COUNT?","answer":"COUNT(CASE WHEN c THEN 1 END) counts only the matching rows, so NULLs dropping out is exactly right; bare SUM(CASE WHEN c THEN 1 END) returns NULL for a group with no matches, while ELSE 0 gives a clean 0."},{"question":"Is there a shorter form?","answer":"PostgreSQL and SQLite: COUNT(*) FILTER (WHERE cond). MySQL and SQLite: SUM(cond), since a comparison is 1 or 0."},{"question":"How do I pivot rows to columns?","answer":"One conditional aggregate per output column, all sharing the GROUP BY key."}],"related":["aggregate-filter","case","count","sum","iif"],"novel_uses":[{"body":"Sum price times quantity over the same CASE-guarded quantity and the result is a volume-weighted mean, the number plain AVG gets wrong when order sizes vary, since it counts every row once. The * 1.0 stops integer columns from truncating on SQL Server, PostgreSQL and SQLite.","sql":"SELECT tier, SUM(CASE WHEN channel = 'web' THEN price * qty END) * 1.0 / NULLIF(SUM(CASE WHEN channel = 'web' THEN qty END), 0) AS web_weighted FROM line_items GROUP BY tier;"},{"body":"One CASE ladder stops at the first match, so the 30-49 and 40-59 age bands cannot share a ladder; overlapping ranges need one aggregate per bucket.","sql":"SELECT COUNT(CASE WHEN age BETWEEN 30 AND 49 THEN 1 END) AS a3049, COUNT(CASE WHEN age BETWEEN 40 AND 59 THEN 1 END) AS a4059 FROM users;"}]},"source_url":"https://sqlly.app/sql-functions/conditional-aggregation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/connection-id","corpus":"sql-functions","engine":null,"language":"en","title":"SQL session ID: @@SPID and CONNECTION_ID()","description":"Get the server's id for the current connection: @@SPID on SQL Server, pg_backend_pid() on PostgreSQL, CONNECTION_ID() on MySQL, the SID from SYS_CONTEXT on Oracle.","body":{"slug":"connection-id","name":"@@SPID / CONNECTION_ID","h1":"SQL session ID: @@SPID and CONNECTION_ID()","category":"system","lede":"The session id links your connection to the server's activity views, lock listings and kill commands.","syntax":"@@SPID  |  pg_backend_pid()  |  CONNECTION_ID()  |  SYS_CONTEXT('USERENV', 'SID')","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"@@SPID; matches session_id in sys.dm_exec_sessions"},{"engine_slug":"postgresql","status":"partial","note":"pg_backend_pid(); matches pid in pg_stat_activity"},{"engine_slug":"mysql","status":"partial","note":"CONNECTION_ID(); matches ID in the process list"},{"engine_slug":"sqlite","status":"no","note":"no server, no session id"},{"engine_slug":"oracle","status":"partial","note":"SYS_CONTEXT('USERENV', 'SID'); matches SID in v$session"}],"gotchas":["Ids are reused: SQL Server hands a freed SPID to the next connection straight away, and PostgreSQL pids and MySQL connection ids come back once their counters wrap. An id identifies a live session, not a user or a request over time.","With a connection pool the id belongs to the pooled connection. Two requests from different users can run on the same id one after the other.","This is the number you pass to KILL (SQL Server, MySQL) or pg_terminate_backend (PostgreSQL); Oracle's ALTER SYSTEM KILL SESSION also needs SERIAL#. Check it twice: ending your own session is an easy mistake."],"examples":[{"engine_slug":"sql-server","sql":"SELECT session_id, login_name, status\nFROM sys.dm_exec_sessions\nWHERE session_id = @@SPID;"},{"engine_slug":"postgresql","sql":"SELECT pid, usename, state\nFROM pg_stat_activity\nWHERE pid = pg_backend_pid();"},{"engine_slug":"mysql","sql":"SELECT id, user, command\nFROM information_schema.processlist\nWHERE id = CONNECTION_ID();"},{"engine_slug":"oracle","sql":"SELECT SYS_CONTEXT('USERENV', 'SID') AS sid FROM dual;"}],"faqs":[{"question":"How do I see what other sessions are running?","answer":"SQL Server: sys.dm_exec_requests joined to sys.dm_exec_sql_text. PostgreSQL: the query column of pg_stat_activity. MySQL: SHOW PROCESSLIST or performance_schema.threads. Oracle: v$session joined to v$sql."},{"question":"Is @@SPID unique?","answer":"Only among sessions connected at the same time. After a disconnect the same number is handed to a new session."}],"related":["current-user","sleep","current-database"],"novel_uses":[{"body":"PostgreSQL's pg_blocking_pids() takes the pid from pg_stat_activity and lists the sessions holding the lock, which turns the session id into the join key of a lock post-mortem without walking pg_locks by hand.","sql":"SELECT pid, pg_blocking_pids(pid) AS blockers, wait_event_type\nFROM pg_stat_activity\nWHERE wait_event_type = 'Lock';"},{"body":"An Extended Events session can filter on sqlserver.session_id = @@SPID, which limits tracing to your own connection while tuning one query on a busy server. The filter also keeps the capture small enough to read live.","sql":"SELECT @@SPID AS my_session;  -- use it as the session_id predicate of the XEvent session"}]},"source_url":"https://sqlly.app/sql-functions/connection-id","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/consecutive-streaks","corpus":"sql-functions","engine":null,"language":"en","title":"SQL consecutive streaks with window functions","description":"The gaps-and-islands variant for streaks: current streak length, longest win streak and streak id with ROW_NUMBER minus another ROW_NUMBER.","body":{"slug":"consecutive-streaks","name":"Consecutive Streaks","h1":"SQL consecutive streaks with window functions","category":"window","lede":"Group consecutive equal states by differencing two ROW_NUMBERs: one over all rows, one over rows grouped by state. Equal differences within one state form each streak.","syntax":"ROW_NUMBER() OVER (ORDER BY d) - ROW_NUMBER() OVER (PARTITION BY state ORDER BY d) AS streak_id","return_type":"integer streak id","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Both ROW_NUMBERs must share the same row order and it must be deterministic; otherwise rows of one streak can interleave and split it.","The difference trick only groups by equality of the partition key. For streaks with a condition (days with sales > 0), first derive a 0/1 flag column and partition on it.","Current streak and longest streak are different queries: the current one is the streak containing the latest row; the longest is the largest COUNT(*) per streak id."],"examples":[{"engine_slug":"all","sql":"-- longest winning streak per player\nWITH g AS (\n  SELECT player, day, result,\n         ROW_NUMBER() OVER (PARTITION BY player ORDER BY day)\n           - ROW_NUMBER() OVER (PARTITION BY player, result ORDER BY day) AS streak\n  FROM matches\n)\nSELECT player, MAX(cnt) AS longest_win_streak\nFROM (\n  SELECT player, streak, COUNT(*) AS cnt FROM g\n  WHERE result = 'win'\n  GROUP BY player, streak\n) s\nGROUP BY player;"}],"faqs":[{"question":"Why does ROW_NUMBER minus ROW_NUMBER find streaks?","answer":"Within a run of consecutive same-state rows, both numbers advance by exactly 1, so their difference is constant for the whole run and changes when the state flips. It needs no lag comparison and no recursive CTE."},{"question":"How do I get the current streak, not the longest?","answer":"Find the latest streak id (the one containing MAX(day)), then COUNT its rows with the same result; or in a single pass, COUNT(*) OVER (PARTITION BY player, result, streak_id) and pick the row at MAX(day)."}],"related":["gaps-and-islands","row-number","lag"],"novel_uses":[{"body":"Group by the streak id and take MIN and MAX of the date: every run comes out with its own start and end, not just a count. That is the shape you want for a calendar of hot streaks or outage windows.","sql":"WITH g AS (\n  SELECT player, day, result,\n         ROW_NUMBER() OVER (PARTITION BY player ORDER BY day)\n           - ROW_NUMBER() OVER (PARTITION BY player, result ORDER BY day) AS streak\n  FROM matches\n)\nSELECT player, MIN(day) AS from_day, MAX(day) AS to_day, COUNT(*) AS games\nFROM g\nWHERE result = 'win'\nGROUP BY player, streak;"},{"body":"Count rows per streak id, then aggregate those counts: the average and the distribution of run lengths say whether wins cluster or scatter. Longest streak alone overstates typical behaviour because one freak run drags it.","sql":"WITH g AS (\n  SELECT player, result,\n         ROW_NUMBER() OVER (PARTITION BY player ORDER BY day)\n           - ROW_NUMBER() OVER (PARTITION BY player, result ORDER BY day) AS streak\n  FROM matches\n), runs AS (\n  SELECT player, streak, COUNT(*) AS len\n  FROM g\n  WHERE result = 'win'\n  GROUP BY player, streak\n)\nSELECT AVG(1.0 * len) AS avg_win_run, MAX(len) AS longest\nFROM runs;"}]},"source_url":"https://sqlly.app/sql-functions/consecutive-streaks","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/conv","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONV function","description":"MySQL's CONV converts numbers between bases 2 through 36, treating both input and output as strings: base conversion without hex-only limits.","body":{"slug":"conv","name":"CONV","h1":"SQL CONV function","category":"conversion","lede":"CONV('ff', 16, 10) is 255. It parses the input in the from-base and renders it in the to-base, all as strings, both directions.","syntax":"CONV(number_or_string, from_base, to_base)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Both the input and the output are strings: CONV('ff', 16, 10) returns the string '255'. Cast if a numeric type is required downstream.","Bases run from 2 to 36, using 0-9 and A-Z. Beyond hex, letters map upward: CONV('z', 36, 10) is 35.","Parsing stops at the first digit that is invalid for the from-base: CONV('1g', 16, 10) is '1' with no warning. CONV('g', 16, 10) is '0' too, but with no valid digit at all it warns, and an INSERT of that value fails under strict mode (error 1292). Never NULL for a non-empty input.","PostgreSQL reaches for to_hex, to_bin and casts; SQL Server uses CONVERT with binary/hex styles; CONV's general base math is MySQL-only."],"examples":[{"engine_slug":"mysql","sql":"SELECT CONV('ff', 16, 10) AS dec_;  -- 255"},{"engine_slug":"mysql","sql":"SELECT CONV(255, 10, 2) AS bin_;  -- 11111111"}],"faqs":[{"question":"Does CONV return a number or a string?","answer":"A string, which keeps the to-base output representable for bases above 10. Cast the result when arithmetic needs a numeric type."},{"question":"What bases does CONV support?","answer":"2 through 36. Digits above 9 are letters A-Z, case-insensitive on input."},{"question":"How do I convert between bases in PostgreSQL or SQL Server?","answer":"Piecewise: PostgreSQL has to_hex(), to_bin() and to_oct() for output, and bit casts such as B'11111111'::int for input; to_number() does not parse hex. SQL Server has CONVERT styles for hex on binary values. There is no general from-base parser outside MySQL."}],"related":["hex","unhex","cast"],"novel_uses":[{"body":"CONV(id, 10, 36) renders a number with digits and letters for short codes and URLs, and CONV(code, 36, 10) reads it back, all inside MySQL.","sql":"SELECT CONV(id, 10, 36) AS short_code FROM orders;  -- 123456789 becomes 21I3V9"},{"body":"CONV stops at the first invalid digit, so converting there and back catches the garbage: values that fail the round trip are not clean base 36, and an overflowing value such as 'ZZZZZZZZZZZZZ' fails the same way. An empty string returns NULL, which the comparison skips, so the query names it explicitly.","sql":"SELECT v FROM staged WHERE v = '' OR CONV(CONV(v, 36, 10), 10, 36) <> UPPER(v);"}]},"source_url":"https://sqlly.app/sql-functions/conv","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT function","description":"CONVERT in SQL Server and MySQL: opposite argument orders, SQL Server's style codes, and why PostgreSQL and Oracle CONVERT means something completely different.","body":{"slug":"convert","name":"CONVERT","h1":"SQL CONVERT function","category":"conversion","lede":"A type conversion function in SQL Server and MySQL, with opposite argument orders and different capabilities. On PostgreSQL and Oracle, CONVERT converts character-set encoding, not types.","syntax":"CONVERT(type, expression [, style])  -- SQL Server  |  CONVERT(expression, type)  -- MySQL","return_type":"the target type","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"CONVERT changes encoding, not types; use CAST or ::"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no CONVERT; use CAST"},{"engine_slug":"oracle","status":"no","note":"CONVERT converts between character sets; use CAST for types"}],"gotchas":["Argument order is opposite: SQL Server CONVERT(target, value), MySQL CONVERT(value, target). A query ported between them usually fails to parse rather than converting the wrong thing.","SQL Server's third style argument is the date-format codebook: CONVERT(varchar, d, 120) is ISO 'yyyy-mm-dd hh:mi:ss'. TRY_CONVERT adds NULL-on-failure.","PostgreSQL's and Oracle's CONVERT are character-set functions: CONVERT(bytes, 'UTF8', 'LATIN1') on PostgreSQL takes and returns bytea, and CONVERT(text, 'US7ASCII') on Oracle re-encodes a string. Type conversion there is CAST (or TO_CHAR, TO_NUMBER, TO_DATE).","MySQL's CONVERT has a second form for character sets too: CONVERT(s USING utf8mb4)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(10), order_date, 120) AS day\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT CONVERT(order_total, CHAR) AS total_text FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT TRY_CONVERT(DATE, '01/08/2026', 103) AS d;"}],"faqs":[{"question":"Is CONVERT the same in SQL Server and MySQL?","answer":"No. Argument order is reversed and the feature sets differ. SQL Server adds style codes for dates; MySQL's is closer to CAST. Use CAST for anything portable."},{"question":"What are SQL Server's CONVERT style codes?","answer":"Numbers that pick a date and time format: 101 US mm/dd/yyyy, 103 British dd/mm/yyyy, 112 yyyymmdd, 120 ODBC canonical yyyy-mm-dd hh:mi:ss, 126 ISO 8601 with a T. They only exist in SQL Server."}],"related":["cast","try-cast","to-char"],"novel_uses":[{"body":"Style 112 renders yyyymmdd, the canonical date key in SQL Server warehouses: CONVERT(char(8), order_date, 112) joins facts to a date dimension with no formatting logic in the app.","sql":"SELECT CONVERT(char(8), order_date, 112) AS date_key\nFROM orders;"},{"body":"Text encoded twice shows up as mojibake where the accented letter belongs. Casting the value to BINARY and then CONVERT(... USING utf8mb4) decodes the bytes one more time and repairs it, a one-off migration query instead of a re-import.","sql":"SELECT CONVERT(CAST(raw_text AS BINARY) USING utf8mb4) AS fixed\nFROM mojibake;"}]},"source_url":"https://sqlly.app/sql-functions/convert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert-charset","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT character set","description":"CONVERT ... USING on MySQL, CONVERT(text, dest, source) on Oracle and convert(bytea, source, dest) on PostgreSQL re-encode text between character sets.","body":{"slug":"convert-charset","name":"CONVERT (charset)","h1":"SQL CONVERT character set","category":"conversion","lede":"This CONVERT changes encoding, not type. MySQL writes USING; Oracle puts the destination set first; PostgreSQL works on bytea and puts the source first.","syntax":"CONVERT(expr USING charset)  -- MySQL  |  CONVERT(text, dest_charset [, source_charset])  -- Oracle  |  convert(bytea, src, dest)  -- PostgreSQL","return_type":"text or bytea","support":[{"engine_slug":"sql-server","status":"no","note":"no charset conversion; collations govern code pages"},{"engine_slug":"postgresql","status":"partial","note":"convert(bytea, src, dest) plus convert_to/convert_from"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"text is always Unicode (UTF-8 or UTF-16); nothing to convert"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Argument order is opposite between the two three-argument forms: Oracle's CONVERT(text, 'US7ASCII', 'AL32UTF8') is destination then source, PostgreSQL's convert(bytes, 'UTF8', 'LATIN1') is source then destination.","Characters missing from the target set are replaced, not rejected, on Oracle and MySQL: Oracle's CONVERT('café', 'US7ASCII') returns 'cafe', and MySQL substitutes '?'. Converting emoji to latin1 loses them for good. PostgreSQL refuses instead: convert_to('\uD83D\uDE00', 'LATIN1') raises a \"has no equivalent in encoding\" error.","MySQL data lives in the column's charset: CONVERT ... USING changes the value in flight, usually for a comparison or cross-table insert. Changing the column itself is ALTER TABLE ... CONVERT TO CHARACTER SET."],"examples":[{"engine_slug":"mysql","sql":"SELECT CONVERT(name USING utf8mb4) AS name\nFROM legacy_users;"},{"engine_slug":"postgresql","sql":"SELECT convert_to('café', 'LATIN1') AS latin1_bytes,\n       convert_from(convert_to('café', 'LATIN1'), 'LATIN1') AS back;"},{"engine_slug":"oracle","sql":"SELECT CONVERT('café', 'US7ASCII', 'AL32UTF8') AS ascii_only FROM dual;"}],"faqs":[{"question":"How do I change a column's charset?","answer":"ALTER TABLE t CONVERT TO CHARACTER SET utf8mb4 on MySQL. CONVERT ... USING only re-encodes the value in a query; the column definition is a separate operation."},{"question":"Is this the same CONVERT as type conversion?","answer":"No. SQL Server's CONVERT casts types; MySQL's CONVERT does both (CONVERT(x, CHAR) casts, CONVERT(x USING cs) re-encodes); PostgreSQL's and Oracle's only re-encode. The argument shape tells you which one you are reading."}],"related":["convert","collate","encode-bytea","binary-cast"],"novel_uses":[{"body":"Text stored as utf8mb4 bytes inside a latin1 column shows up as 'Ã©' instead of 'é'. Convert to latin1, recast through BINARY to keep the bytes, then convert to utf8mb4, and the accents come back intact.","sql":"UPDATE users SET name = CONVERT(CAST(CONVERT(name USING latin1) AS BINARY) USING utf8mb4) WHERE name LIKE '%Ã%';"},{"body":"Instead of one risky ALTER TABLE, INSERT ... SELECT with CONVERT(... USING utf8mb4) fills the new table in batches, each row re-encoded in flight. Bad rows surface one batch at a time and the old table stays untouched until the cutover.","sql":"INSERT INTO users_v2 (name) SELECT CONVERT(name USING utf8mb4) FROM users_old LIMIT 10000;"}]},"source_url":"https://sqlly.app/sql-functions/convert-charset","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert-style","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT date style","description":"SQL Server's CONVERT third argument picks a date format: 112 is YYYYMMDD, 120 is 'YYYY-MM-DD HH:MI:SS', 103 is dd/mm/yyyy, 101 is mm/dd/yyyy.","body":{"slug":"convert-style","name":"CONVERT date styles","h1":"SQL CONVERT date style","category":"datetime","lede":"Returns a date formatted or parsed per a style number: 112 for YYYYMMDD keys, 120 or 126 for timestamps, and no two-digit-year style in new code.","syntax":"CONVERT(varchar, GETDATE(), 120)  |  CONVERT(date, '20240115', 112)  |  CONVERT(varchar, GETDATE(), 112)","return_type":"varchar / date","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"TO_CHAR masks instead of numeric styles"},{"engine_slug":"mysql","status":"partial","note":"DATE_FORMAT masks"},{"engine_slug":"sqlite","status":"partial","note":"strftime formats"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR / TO_DATE masks"}],"gotchas":["Styles 1-7 and 10-12 are two-digit-year forms; add 100 for four digits. Style 1 is mm/dd/yy, style 101 is mm/dd/yyyy. A two-digit year follows the server cutoff (default 2049): 49 reads as 2049 and 50 as 1950.","Without a style (or with style 0), parsing follows the session DATEFORMAT and LANGUAGE settings, so the same CONVERT works locally and flips dates in production.","CAST has no style argument and always follows DATEFORMAT; once input is dd/mm or mm/dd, use CONVERT with 103 or 101 so the order is fixed in the query."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(10), GETDATE(), 112) AS date_key;  -- 20240115"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(23), GETDATE(), 120) AS odbc_ts;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(date, '15/01/2024', 103) AS parsed;  -- British dd/mm/yyyy"},{"engine_slug":"postgresql","sql":"SELECT to_char(created_at, 'YYYYMMDD') AS date_key FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%Y%m%d') AS date_key FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y%m%d', created_at) AS date_key FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'YYYYMMDD') AS date_key FROM orders;"}],"faqs":[{"question":"Which CONVERT style is safest for storage?","answer":"112 (YYYYMMDD) for date keys, 120 or 126 for timestamps. They are unambiguous regardless of server language settings."},{"question":"What is style 126?","answer":"ISO-8601 with T separator: yyyy-mm-ddThh:mi:ss, with a fraction only when it is non-zero. datetime2 keeps its full scale (.1230000 for datetime2(7)) and datetime rounds to 1/300 second (.125 becomes .127). This is the right pick for JSON and XML payloads."}],"related":["parse","date-format","date-literal"],"novel_uses":[{"body":"Styles 130 and 131 read and write dates on the Islamic calendar: CONVERT(nvarchar(40), GETDATE(), 130) renders today as a Hijri string with the Arabic month name. A varchar target shows the Arabic letters as question marks.","sql":"SELECT CONVERT(nvarchar(40), GETDATE(), 130) AS hijri;"},{"body":"Style 120 output is fixed width and zero padded, so CONVERT(varchar(19), d, 120) makes file names and batch keys whose alphabetical order matches the chronological one.","sql":"SELECT CONVERT(varchar(19), created_at, 120) AS sort_key FROM orders ORDER BY sort_key;"}]},"source_url":"https://sqlly.app/sql-functions/convert-style","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert-style-numbers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT style numbers table","description":"CONVERT's third argument for dates: styles 120, 112, 126 and 101 explained, how to pick a fixed format, and why FORMAT or DATE_FORMAT-style masks win elsewhere.","body":{"slug":"convert-style-numbers","name":"CONVERT styles","h1":"SQL CONVERT style numbers table","category":"datetime","lede":"An integer style code tells SQL Server's CONVERT how to render or parse a date: a lookup table, not a format string.","syntax":"CONVERT(varchar, date, style)  |  CONVERT(datetime, text, style)","return_type":"varchar / datetime","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":"TO_CHAR / TO_TIMESTAMP with format masks"}],"gotchas":["The styles that matter: 112 gives yyyymmdd (sorts and joins reliably), 120 gives yyyy-mm-dd hh:mi:ss (ISO-ish, ODBC canonical), 126 gives full ISO 8601 with T, 101 gives US mm/dd/yyyy.","Styles 101 to 107 and 110 to 112 add century digits to their two-digit-year counterparts: 1 is mm/dd/yy while 101 is mm/dd/yyyy. The two-digit forms are parse hazards; skip them.","When parsing, the style must match the input, not the desired output: CONVERT(datetime, '01/08/2026', 103) reads British day-first order."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(19), CAST('2026-08-01 14:30' AS datetime), 120);  -- 2026-08-01 14:30:00"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(8), CAST('2026-08-01' AS date), 112);  -- 20260801"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(DATETIME2, '2026-08-01 14:30:00', 120);"}],"faqs":[{"question":"Which style is the safe default?","answer":"120 for round-trippable text with time, 112 for compact keys, 126 for ISO 8601 interchange. Avoid the two-digit-year styles (1 to 7, 10 to 12 and 22) entirely."},{"question":"What do other engines use instead of style codes?","answer":"Format masks: PostgreSQL and Oracle TO_CHAR with 'YYYY-MM-DD', MySQL DATE_FORMAT with '%Y-%m-%d', SQLite strftime. FORMAT() in SQL Server is the .NET-mask compromise."}],"related":["convert","format-date","date-to-text","iso-8601-format"],"novel_uses":[{"body":"Style 23 renders just yyyy-mm-dd, the compact key shape for day-grain exports, with no truncation trick required.","sql":"SELECT CONVERT(varchar(10), GETDATE(), 23);  -- 2026-11-27"},{"body":"Style 114 prints only the clock part, hours through milliseconds, which saves string surgery when a date column already sits beside the time.","sql":"SELECT CONVERT(varchar(12), CAST('2026-08-01 14:30:05.120' AS datetime), 114);  -- 14:30:05:120"},{"body":"Style 106 spells dd mon yyyy, the readable shape for emails and screens; the month name follows the session language, so pin SET LANGUAGE when it matters.","sql":"SELECT CONVERT(varchar(11), GETDATE(), 106);  -- 27 Nov 2026"}]},"source_url":"https://sqlly.app/sql-functions/convert-style-numbers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert-tz","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT_TZ function","description":"CONVERT_TZ in MySQL: shift a datetime between zones by name or offset, why named zones return NULL when the time zone tables are empty, and the alternatives elsewhere.","body":{"slug":"convert-tz","name":"CONVERT_TZ","h1":"SQL CONVERT_TZ function","category":"datetime","lede":"Converts a datetime from one time zone to another, by named zone or by ±HH:MM offsets.","syntax":"CONVERT_TZ(dt, from_zone, to_zone)","return_type":"datetime","support":[{"engine_slug":"sql-server","status":"partial","note":"d AT TIME ZONE '...' chained twice"},{"engine_slug":"postgresql","status":"partial","note":"d::timestamptz AT TIME ZONE '...'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"none; use the utc or localtime date modifiers (both follow the host zone), or a fixed '+02:00' modifier that ignores DST"},{"engine_slug":"oracle","status":"partial","note":"FROM_TZ(dt, 'zone') AT TIME ZONE 'other'"}],"gotchas":["Named zones need the time zone tables loaded (mysql.time_zone_name etc.); on a fresh server they can be empty, and then CONVERT_TZ(dt, 'UTC', 'Europe/Paris') silently returns NULL while offsets like '+02:00' work.","Offsets ignore DST: converting with '+01:00' is right in winter and wrong in summer; load the zone tables and use IANA names for wall-clock correctness.","Input and output are naive datetimes. MySQL has no type that stores a zone: DATETIME is naive, and TIMESTAMP converts from the session time_zone to UTC on write and back on read without remembering the original zone."],"examples":[{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ('2026-08-01 14:30:00', 'UTC', 'Europe/Paris');  -- 2026-08-01 16:30:00 (needs tz tables)"},{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ(created_at, @@session.time_zone, '+00:00') FROM logs;"},{"engine_slug":"sql-server","sql":"SELECT d AT TIME ZONE 'UTC' AT TIME ZONE 'Central European Standard Time' FROM logs;"},{"engine_slug":"postgresql","sql":"SELECT '2026-08-01 14:30+00'::timestamptz AT TIME ZONE 'Europe/Paris';  -- 2026-08-01 16:30:00"},{"engine_slug":"oracle","sql":"SELECT FROM_TZ(TIMESTAMP '2026-08-01 14:30:00', 'UTC') AT TIME ZONE 'Europe/Paris' FROM dual;  -- 2026-08-01 16:30:00 +02:00"}],"faqs":[{"question":"Why does CONVERT_TZ return NULL?","answer":"Usually a named zone that is missing from the mysql.time_zone tables, which can be empty on a fresh server. Load them with mysql_tzinfo_to_sql, or use fixed offsets like '+02:00' and accept the DST error."},{"question":"What is the PostgreSQL equivalent?","answer":"dt AT TIME ZONE 'from' AT TIME ZONE 'to' (interpret then render), or CAST to timestamptz and render in the target zone."}],"related":["at-time-zone","session-time-zone","utc-timestamp","timestamp-with-time-zone"],"novel_uses":[{"body":"A count on mysql.time_zone tells you whether named zones can resolve at all; an empty table means every named conversion returns NULL.","sql":"SELECT COUNT(*) FROM mysql.time_zone;"},{"body":"Convert user input to UTC on the way in and store the result, so every reader shares one reference frame and indexes compare equal across writers.","sql":"INSERT INTO logs(at, msg) VALUES (CONVERT_TZ('2026-08-01 14:30:00', '+02:00', 'UTC'), 'started');"}]},"source_url":"https://sqlly.app/sql-functions/convert-tz","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/convert-using","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CONVERT ... USING (MySQL)","description":"MySQL's CONVERT(x USING charset) transcodes a string's character set (not its type), with the re-encoding rules and traps that come with it.","body":{"slug":"convert-using","name":"CONVERT ... USING","h1":"SQL CONVERT ... USING (MySQL)","category":"conversion","lede":"Converts a string between character sets: CONVERT('café' USING utf8mb4) re-encodes the text. One USING means charset; two arguments mean type.","syntax":"CONVERT(string USING charset)  |  CONVERT(value, type)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["USING converts character sets, not types: CONVERT(42, CHAR) changes type, while CONVERT(42 USING utf8mb4) turns the number into a utf8mb4 string as a side effect. The shapes look similar and do different jobs.","Unrepresentable characters become '?' silently: CONVERT('é' USING ascii) is '?' with no warning. Verify with HEX before and after converting real data.","The source charset is the string's own: inspect it with CHARSET(s) first; converting from binary reinterprets the bytes.","It is MySQL-only: PostgreSQL converts with convert_to/convert_from, SQL Server with collations and nvarchar, Oracle with CONVERT(s, dest_charset, source_charset)."],"examples":[{"engine_slug":"mysql","sql":"SELECT CONVERT('café' USING utf8mb4) AS c;"},{"engine_slug":"mysql","sql":"SELECT CONVERT(42, CHAR) AS num, CHARSET(CONVERT('x' USING utf8mb4)) AS cs;\n-- 42, utf8mb4"}],"faqs":[{"question":"Does CONVERT(x USING cs) change the data type?","answer":"For a string it changes only the character set. For a number it also changes the type: CONVERT(42 USING utf8mb4) is a string, while plain 42 is an integer. CONVERT(x, type) with two arguments is the type conversion."},{"question":"Why did my converted text lose characters?","answer":"The target charset cannot represent them, so MySQL substitutes '?' with no warning. Compare HEX output before and after, and use the round-trip inequality below to find the affected rows."},{"question":"How do I check a string's current charset?","answer":"CHARSET(s) and COLLATION(s) in MySQL report the value's charset and collation, the first step before any USING conversion."}],"related":["cast","convert","utf8mb4","charset-function"],"novel_uses":[{"body":"UTF-8 bytes stored as latin1 read as the two-character form; converting to latin1, treating the result as binary, then converting to utf8mb4 reassembles the original character.","sql":"UPDATE import_names\nSET name = CONVERT(BINARY CONVERT(name USING latin1) USING utf8mb4);  -- the standard mojibake repair"},{"body":"A round trip through the target charset is identity for representable text and changes everything else, so the inequality lists exactly the rows that would lose characters.","sql":"SELECT id FROM users WHERE name <> CONVERT(CONVERT(name USING latin1) USING utf8mb4);"}]},"source_url":"https://sqlly.app/sql-functions/convert-using","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/corr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CORR function","description":"CORR computes Pearson's r for two columns per group: PostgreSQL and Oracle support, the complete-pair filtering rule, and the manual formula for MySQL and SQL Server.","body":{"slug":"corr","name":"CORR","h1":"SQL CORR function","category":"aggregate","lede":"Returns the Pearson correlation coefficient of two numeric columns in a group.","syntax":"CORR(y, x) | CORR(y, x) OVER (...)","return_type":"numeric (-1 to 1)","support":[{"engine_slug":"sql-server","status":"no","note":"same formula with STDEVP, over complete pairs, cast to float first"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"compute manually: (AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y)*STDDEV_POP(x)) over complete pairs"},{"engine_slug":"sqlite","status":"no","note":"not built in; compute (AVG(y*x) - AVG(y)*AVG(x)) / (SQRT(AVG(y*y) - AVG(y)*AVG(y)) * SQRT(AVG(x*x) - AVG(x)*AVG(x))) over complete pairs"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Only rows where both inputs are non-NULL count; a NULL in either column drops the whole pair.","Fewer than two complete pairs returns NULL; a zero-variance column also yields NULL.","The result is between -1 and 1; it measures linear correlation only.","MySQL and SQL Server lack CORR and COVAR_*, so compute (AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y) * STDDEV_POP(x)), STDEVP on SQL Server. Filter to rows where both columns are non-NULL first, and on SQL Server cast integer columns to float, because AVG of an int column returns a truncated int."],"examples":[{"engine_slug":"postgresql","sql":"SELECT corr(height, weight) FROM people;"},{"engine_slug":"oracle","sql":"SELECT dept_id, CORR(salary, age) FROM employees GROUP BY dept_id;"}],"faqs":[{"question":"What does CORR = 0 mean?","answer":"No linear relationship detected; a strong curve can still hide behind r near 0."},{"question":"How does CORR treat NULLs?","answer":"Pairs with either value NULL are excluded entirely: it correlates complete pairs only."},{"question":"How do I compute it in MySQL?","answer":"(AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y) * STDDEV_POP(x)), with WHERE y IS NOT NULL AND x IS NOT NULL so every term uses the same rows."}],"related":["covar-pop","covar-samp","stddev-pop","regr-r2"],"novel_uses":[{"body":"PostgreSQL runs CORR as a window function, so a trailing 30-row frame shows the relationship strengthening or falling apart over time, which a single number hides.","sql":"SELECT day, corr(sessions, conversions) OVER (ORDER BY day ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS r30 FROM daily;"},{"body":"Pair CORR with REGR_COUNT so the number ships with the pair count it rests on; r = 0.9 from three pairs is noise, from three thousand it is a finding.","sql":"SELECT corr(height, weight), regr_count(height, weight) FROM people;"}]},"source_url":"https://sqlly.app/sql-functions/corr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cos","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COS function","description":"COS(x) returns the cosine of a radian angle. Ranges from -1 to 1, feeds distance and rotation formulas, and shares the radians-not-degrees trap.","body":{"slug":"cos","name":"COS","h1":"SQL COS function","category":"math","lede":"Returns the cosine of an angle expressed in radians: COS(0) is 1 and COS(PI()) is -1.","syntax":"COS(angle_radians)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Available since 3.35.0 when built with the math functions; builds without SQLITE_ENABLE_MATH_FUNCTIONS raise an error instead"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["COS itself always returns a value in [-1, 1], but COS(60 * PI() / 180) is 0.50000000000000011, not 0.5, so compare with a tolerance.","The argument is radians: COS(60) is the cosine of 60 radians, not 60 degrees. Use RADIANS() or x * PI() / 180. On SQL Server, RADIANS() of an integer returns an integer, so RADIANS(60) is 1; write RADIANS(60.0) or use x * PI() / 180.","The spherical law of cosines sums products of SIN and COS and feeds the total to ACOS. That sum can land at 1.0000000000000002 for two identical points, and ACOS then fails on PostgreSQL (\"input is out of range\") and SQL Server (error 3623), while MySQL and SQLite return NULL silently; clamp it first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT COS(0) AS one, COS(PI()) AS minus_one;  -- 1, -1"},{"engine_slug":"postgresql","sql":"SELECT COS(RADIANS(lat1 - lat2)) AS lat_cos\nFROM geo_pairs;"},{"engine_slug":"sql-server","sql":"SELECT COS(60 * PI() / 180) AS cos_60;  -- 0.5000000000000001"},{"engine_slug":"mysql","sql":"SELECT COS(0) AS one, COS(PI()) AS minus_one;  -- 1, -1"},{"engine_slug":"sqlite","sql":"SELECT cos(0) AS one, cos(pi()) AS minus_one;  -- 1.0, -1.0"},{"engine_slug":"oracle","sql":"SELECT COS(0) AS one, COS(ACOS(-1)) AS minus_one FROM dual;  -- 1, -1"}],"faqs":[{"question":"What range does COS return?","answer":"Between -1 and 1 inclusive. The function itself never leaves that range; expressions built from several COS and SIN terms can, which is why distance formulas clamp before calling ACOS."},{"question":"Why does COS(60) not give 0.5?","answer":"60 is interpreted as 60 radians. For degrees, convert: COS(60 * PI() / 180) returns about 0.5 on every engine. COS(RADIANS(60)) does too, except on SQL Server, where RADIANS of an integer is an integer; use RADIANS(60.0) there."},{"question":"How is COS used for distance?","answer":"The spherical law of cosines computes ACOS(SIN(lat1) * SIN(lat2) + COS(lat1) * COS(lat2) * COS(lon2 - lon1)) * 6371 for kilometres. Convert all angles to radians first."}],"related":["sin","tan","acos","radians"],"novel_uses":[{"body":"COS(2 * PI() * hour / 24.0) places midnight and 23:00 next to each other on a circle, so clustering and distance over hour-of-day stop treating them as opposites. Pair it with the matching SIN for the full coordinate.","sql":"SELECT hour, COS(2 * PI() * hour / 24.0) AS x, SIN(2 * PI() * hour / 24.0) AS y FROM hours;"},{"body":"x * COS(t) - y * SIN(t) rotates a point by t radians, which aligns survey or sensor coordinates to a reference frame. Radians in, one expression per axis, no procedural code.","sql":"SELECT x * COS(RADIANS(30.0)) - y * SIN(RADIANS(30.0)) AS xr FROM points;"}]},"source_url":"https://sqlly.app/sql-functions/cos","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cosh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COSH function","description":"COSH(x) is the hyperbolic cosine, (e^x + e^-x)/2, never below 1 and the shape of a hanging chain. SQL Server and MySQL lack it.","body":{"slug":"cosh","name":"COSH","h1":"SQL COSH function","category":"math","lede":"Returns the hyperbolic cosine: COSH(0) is 1 and COSH grows exponentially, always 1 or greater.","syntax":"COSH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; compute (EXP(x) + EXP(-x)) / 2.0"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 12 introduced the hyperbolic set, cosh included"},{"engine_slug":"mysql","status":"no","note":"No COSH in MySQL through 8.4; use (EXP(x) + EXP(-x)) / 2.0"},{"engine_slug":"sqlite","status":"yes","note":"Built in since 3.35 with the math functions enabled"},{"engine_slug":"oracle","status":"yes","note":"Built in on Oracle for NUMBER input"}],"gotchas":["COSH(x) >= 1 for every input: the e^x and e^-x terms cannot cancel below 1.","COSH and SINH pair up in the identity COSH(x)^2 - SINH(x)^2 = 1, the hyperbolic analogue of the Pythagorean one.","The exponential fallback for SQL Server is (EXP(x) + EXP(-x)) / 2.0; it fails above x = 709.78, where EXP itself overflows, while native COSH stays finite until about x = 710.47."],"examples":[{"engine_slug":"postgresql","sql":"SELECT COSH(0) AS one;  -- 1"},{"engine_slug":"sql-server","sql":"SELECT (EXP(1.0) + EXP(-1.0)) / 2.0 AS cosh_one;  -- 1.5430806348152437"},{"engine_slug":"oracle","sql":"SELECT COSH(x) AS catenary FROM cable_points;"},{"engine_slug":"mysql","sql":"SELECT (EXP(x) + EXP(-x)) / 2 AS cosh_x FROM cable_points;  -- no COSH in MySQL"},{"engine_slug":"sqlite","sql":"SELECT cosh(0) AS one;  -- 1.0"}],"faqs":[{"question":"What is the smallest value COSH can return?","answer":"1, at x = 0. The function is symmetric and grows exponentially away from zero in both directions."},{"question":"How do I compute COSH on SQL Server or MySQL?","answer":"(EXP(x) + EXP(-x)) / 2.0. Neither engine ships hyperbolic functions."},{"question":"Is COSH related to regular COS?","answer":"Only by name. COS oscillates between -1 and 1; COSH is a smooth exponential curve that never drops below 1."}],"related":["exp","sinh","tanh"],"novel_uses":[{"body":"A cable under uniform load hangs in a catenary, y = a * COSH(x / a): with the span parameter a from tension and weight per unit length, the query predicts sag at each point. Comparing measured sag finds stretched or overloaded spans.","sql":"SELECT a * COSH(CAST(x AS FLOAT) / a) AS predicted_sag FROM span_points;"},{"body":"COSH(1) + SINH(1) is exactly e, so ABS(COSH(1) + SINH(1) - EXP(1)) is a two-function float sanity check. Run it when porting math to a new engine or after a driver upgrade.","sql":"SELECT ABS(COSH(1) + SINH(1) - EXP(1)) AS float_check;  -- 0 or near 0"}]},"source_url":"https://sqlly.app/sql-functions/cosh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cot","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COT function","description":"COT(x) is the cotangent, 1/TAN(x). Built into SQL Server, PostgreSQL and MySQL; SQLite and Oracle need 1 / TAN(x). COT(0) errors on two engines.","body":{"slug":"cot","name":"COT","h1":"SQL COT function","category":"math","lede":"Returns the cotangent of a radian angle: COT(PI()/4) is about 1, and COT(0) is an error or Infinity because tangent is zero there.","syntax":"COT(angle_radians)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":"COT(x) is built in; COT(0) raises an invalid floating point operation"},{"engine_slug":"postgresql","status":"yes","note":"cot(x) is built in; cot(0) returns Infinity"},{"engine_slug":"mysql","status":"yes","note":"COT(x) is built in; COT(0) raises 'DOUBLE value is out of range'"},{"engine_slug":"sqlite","status":"no","note":"Not in the 3.35+ math set; 1 / TAN(x)"},{"engine_slug":"oracle","status":"no","note":"No COT; 1 / TAN(x)"}],"gotchas":["COT(0) has no finite value: SQL Server and MySQL raise an error, PostgreSQL returns Infinity.","Where it is missing, 1 / TAN(x) is the definition. Guard the zero with NULLIF: 1 / NULLIF(TAN(x), 0). Oracle raises ORA-01476 and SQLite returns NULL without it.","Arguments are radians, same as every other trig function."],"examples":[{"engine_slug":"sql-server","sql":"SELECT COT(PI()/4) AS one;  -- 1 (float-rounding aside)"},{"engine_slug":"mysql","sql":"SELECT COT(1) AS cot_one;  -- 0.6420926..."},{"engine_slug":"postgresql","sql":"SELECT COT(RADIANS(angle_deg)) AS cotangent\nFROM slopes;"},{"engine_slug":"oracle","sql":"SELECT 1 / NULLIF(TAN(1), 0) AS cot_one FROM dual;  -- .642092616"}],"faqs":[{"question":"Which engines have COT?","answer":"SQL Server, PostgreSQL and MySQL ship COT(). SQLite and Oracle do not; compute 1 / NULLIF(TAN(x), 0) there."},{"question":"What happens at COT(0)?","answer":"The cotangent of zero is undefined because TAN(0) is zero. SQL Server and MySQL raise an error; PostgreSQL returns Infinity."},{"question":"Is COT just 1/TAN?","answer":"Mathematically yes, and that identity is the portable replacement. COT(x) = COS(x) / SIN(x) is equivalent, though results can differ from COT(x) in the last bit (MySQL: COT(1) - COS(1)/SIN(1) = -1.1e-16)."}],"related":["tan","cos","division-by-zero"],"novel_uses":[{"body":"height * COT(RADIANS(elevation_deg)) is the shadow a mast casts at a given sun angle, the quantity building and solar studies need. On SQLite and Oracle, where COT is missing, write height / TAN(RADIANS(elevation_deg)).","sql":"SELECT mast_height * COT(RADIANS(sun_elev_deg)) AS shadow_m FROM sun_positions;"},{"body":"COT is run over rise: rise * COT(RADIANS(angle)) answers how far out a ramp must start to climb a given height under a max-angle rule. The reciprocal form makes ramp planning a one-column query.","sql":"SELECT rise_m * COT(RADIANS(max_angle_deg)) AS run_m FROM ramp_specs;"}]},"source_url":"https://sqlly.app/sql-functions/cot","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/count","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COUNT function","description":"How COUNT works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: COUNT(*), COUNT(column) and COUNT(DISTINCT), how NULLs are counted and common mistakes.","body":{"slug":"count","name":"COUNT","h1":"SQL COUNT function","category":"aggregate","lede":"Counts rows, or the non-null values of an expression, in a group. COUNT(*) and COUNT(column) give different answers as soon as the column holds a NULL.","syntax":"COUNT(*)  |  COUNT(expression)  |  COUNT(DISTINCT expression)","return_type":"integer (int on SQL Server, bigint on PostgreSQL, NUMBER on Oracle)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["COUNT(*) counts every row, including rows where every column is NULL; COUNT(column) counts only rows where that column is not NULL.","COUNT(DISTINCT expression) removes duplicates and NULLs before counting, so a column holding only NULLs counts as zero.","COUNT(*) FILTER (WHERE shipped) counts a subset on PostgreSQL and SQLite 3.30+. Elsewhere use COUNT(CASE WHEN shipped THEN 1 END), which counts only the rows where the CASE is not NULL.","On SQL Server COUNT returns int and errors past 2,147,483,647 rows; COUNT_BIG returns bigint."],"examples":[{"engine_slug":"all","sql":"SELECT COUNT(*) FROM orders;"},{"engine_slug":"all","sql":"SELECT COUNT(DISTINCT customer_id) AS customers\nFROM orders;"},{"engine_slug":"postgresql","sql":"SELECT COUNT(*) FILTER (WHERE shipped) AS shipped_orders\nFROM orders;"}],"faqs":[{"question":"What is the difference between COUNT(*) and COUNT(column)?","answer":"COUNT(*) counts every row in the group. COUNT(column) skips rows where column is NULL, so COUNT(email) is usually smaller than COUNT(*) on tables with missing addresses."},{"question":"Does COUNT count NULL values?","answer":"No. COUNT of an expression counts only non-null values, and COUNT(DISTINCT ...) also removes duplicates first. Only COUNT(*) ignores what is inside the rows."},{"question":"How do I count rows per group?","answer":"Add GROUP BY: SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id gives one row and one count per customer."}],"related":["sum","count-distinct","string-agg"],"novel_uses":[{"body":"COUNT(*) OVER (ORDER BY day) counts every row up to the current one, a cumulative count in one pass with no self join. The default frame is RANGE, so rows tied on the sort key share one count; add ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to count one row at a time. Window functions need MySQL 8+ or SQLite 3.25+ where those are your engines.","sql":"SELECT day,\n       COUNT(*) OVER (ORDER BY day) AS orders_so_far,\n       COUNT(*) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS one_by_one\nFROM orders;"},{"body":"Join against a calendar of periods and count the outer table's column instead of *. The join keeps one row per empty month, and COUNT(*) would count that surviving row as 1; COUNT(o.id) sees NULL and returns 0.","sql":"SELECT m.month, COUNT(o.id) AS orders\nFROM months m\nLEFT JOIN orders o ON o.month = m.month\nGROUP BY m.month;"},{"body":"ROWS BETWEEN 6 PRECEDING AND CURRENT ROW turns COUNT into a trailing seven-day window, the shape churn and incident dashboards want. Sliding offset frames on window aggregates need Oracle 12c+; SQL Server has them from 2012, MySQL 8+, and SQLite from 3.25.","sql":"SELECT day,\n       COUNT(*) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_days\nFROM daily_signups;"}]},"source_url":"https://sqlly.app/sql-functions/count","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/count-big","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server COUNT_BIG function","description":"SQL Server's COUNT is int and overflows past 2,147,483,647 rows; COUNT_BIG returns bigint and indexed views require it. Elsewhere it's 64-bit, or NUMBER on Oracle.","body":{"slug":"count-big","name":"COUNT_BIG","h1":"SQL Server COUNT_BIG function","category":"aggregate","lede":"COUNT_BIG works exactly like COUNT but returns bigint. On SQL Server that matters for huge tables and for indexed views.","syntax":"COUNT_BIG(* | [ALL | DISTINCT] expression)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"COUNT already returns bigint"},{"engine_slug":"mysql","status":"partial","note":"COUNT already returns BIGINT"},{"engine_slug":"sqlite","status":"partial","note":"COUNT already returns a 64-bit integer"},{"engine_slug":"oracle","status":"partial","note":"COUNT returns NUMBER"}],"gotchas":["COUNT(*) over more than 2,147,483,647 rows fails with an arithmetic overflow; COUNT_BIG(*) does not.","An indexed view that uses GROUP BY must include COUNT_BIG(*); COUNT(*) is not allowed there.","COUNT_BIG(col) skips NULLs and COUNT_BIG(DISTINCT col) counts distinct values, the same as COUNT."],"examples":[{"engine_slug":"sql-server","sql":"SELECT COUNT_BIG(*) AS n, SQL_VARIANT_PROPERTY(COUNT_BIG(*), 'BaseType') AS type_name\nFROM (VALUES (1), (2), (NULL)) AS t(x);  -- 3, bigint"},{"engine_slug":"sql-server","sql":"SELECT COUNT(x) AS non_null, COUNT_BIG(DISTINCT x) AS distinct_values\nFROM (VALUES (1), (1), (NULL)) AS t(x);  -- 2, 1"},{"engine_slug":"postgresql","sql":"SELECT count(*) AS n, pg_typeof(count(*)) AS t FROM generate_series(1, 3);  -- 3, bigint"},{"engine_slug":"mysql","sql":"SELECT COUNT(*) AS n FROM dual;  -- 1; the type is already BIGINT"},{"engine_slug":"sqlite","sql":"SELECT count(*) AS n, typeof(count(*)) AS t FROM (VALUES (1), (2), (3));  -- 3, integer"},{"engine_slug":"oracle","sql":"SELECT COUNT(*) AS n FROM dual;  -- 1; COUNT returns NUMBER on Oracle"}],"faqs":[{"question":"Do I need COUNT_BIG on PostgreSQL or MySQL?","answer":"No. Their COUNT already returns a 64-bit integer."},{"question":"Is COUNT_BIG slower than COUNT?","answer":"No. The counting work is the same; only the result type differs."}],"related":["count","count-distinct","integer-overflow"],"novel_uses":[{"body":"sys.dm_db_partition_stats carries a bigint row_count per partition, so summing it for the heap or clustered index answers 'how many rows' on SQL Server without touching the table, close enough for monitoring and capacity work.","sql":"SELECT SUM(row_count) AS estimated_rows\nFROM sys.dm_db_partition_stats\nWHERE object_id = OBJECT_ID('dbo.orders') AND index_id IN (0, 1);"},{"body":"pg_class.reltuples is the estimate PostgreSQL's planner uses, readable as an integer: a query that must branch on table size gets a stale but instant answer and leaves the real COUNT for when it matters. Run ANALYZE first when freshness counts; -1 means the table has never been analyzed.","sql":"SELECT reltuples::bigint AS estimated_rows\nFROM pg_class WHERE oid = 'orders'::regclass;"}]},"source_url":"https://sqlly.app/sql-functions/count-big","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/count-distinct","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COUNT(DISTINCT) function","description":"How COUNT(DISTINCT x) works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle, why it ignores NULLs, and the approximations big engines offer instead.","body":{"slug":"count-distinct","name":"COUNT(DISTINCT)","h1":"SQL COUNT(DISTINCT) function","category":"aggregate","lede":"Counts the unique non-null values of an expression in a group: distinct customers, distinct countries, distinct error codes.","syntax":"COUNT(DISTINCT expression)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL is never counted, even once: a column of NULLs counts as zero distinct values.","Exact distinct counting keeps every distinct value it has seen, so memory grows with the number of distinct values, not the number of rows.","Approximate counters trade a small error for far less memory: APPROX_COUNT_DISTINCT on SQL Server 2019+ and Oracle 12c+. PostgreSQL needs an extension such as postgresql-hll; MySQL and SQLite have none.","MySQL also accepts several expressions: COUNT(DISTINCT customer_id, product_id) counts distinct pairs."],"examples":[{"engine_slug":"all","sql":"SELECT COUNT(DISTINCT customer_id) AS paying_customers\nFROM orders;"},{"engine_slug":"sql-server","sql":"SELECT APPROX_COUNT_DISTINCT(session_id) AS approx_sessions\nFROM events;"}],"faqs":[{"question":"Does COUNT(DISTINCT) count NULL?","answer":"No. NULLs are dropped before counting. If the column holds NULLs, COUNT(DISTINCT col) is exactly one less than COUNT(DISTINCT COALESCE(col, 'unknown')), assuming 'unknown' is not already a value."},{"question":"Can I count distinct pairs, like customer and product?","answer":"MySQL takes both columns directly: COUNT(DISTINCT customer_id, product_id). PostgreSQL accepts a row value: COUNT(DISTINCT (customer_id, product_id)). Elsewhere count distinct rows of a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT customer_id, product_id FROM orders) t. Gluing the columns into one string works too, but only with a separator that cannot appear in the data."},{"question":"Why is COUNT(DISTINCT) slow?","answer":"It has to sort or hash every value to remove duplicates before counting. On SQL Server and Oracle, APPROX_COUNT_DISTINCT answers within a few percent using much less memory."}],"related":["count","string-agg","sum"],"novel_uses":[{"body":"CASE inside COUNT(DISTINCT) answers multiple distinct-user questions in one pass: COUNT(DISTINCT CASE WHEN country = 'US' THEN user_id END) counts the US users only, because non-matching rows become NULL and distinct counting drops them.","sql":"SELECT COUNT(DISTINCT CASE WHEN country = 'US' THEN user_id END) AS us_users,\n       COUNT(DISTINCT CASE WHEN plan = 'pro' THEN user_id END) AS pro_users\nFROM users;"},{"body":"COUNT(DISTINCT x) after a one-to-many join dedupes correctly but pays to push the inflated row set through the aggregate. Computing the distinct values per group in a subquery first and joining the small result keeps the expensive step over the smaller input.","sql":"WITH per_day AS (\n  SELECT day, COUNT(DISTINCT user_id) AS users\n  FROM events GROUP BY day\n)\nSELECT d.day, d.users, f.revenue\nFROM per_day d JOIN daily_revenue f ON f.day = d.day;"}]},"source_url":"https://sqlly.app/sql-functions/count-distinct","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/count-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COUNT with OVER","description":"COUNT(*) OVER and COUNT(expr) OVER: partition sizes, running counts and the per-row total that GROUP BY cannot give you.","body":{"slug":"count-over","name":"COUNT OVER","h1":"SQL COUNT with OVER","category":"window","lede":"Counts rows in the window frame or partition and attaches the number to every row: partition size, running count or grand total as needed.","syntax":"COUNT(*) OVER (PARTITION BY g) | COUNT(*) OVER (ORDER BY d) | COUNT(*) OVER ()","return_type":"integer (int on SQL Server, bigint on PostgreSQL and MySQL, integer on SQLite, NUMBER on Oracle)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["COUNT(*) OVER (ORDER BY d) is a running count: the default frame runs through the current row's last peer, so every row shows how many rows came up to it and tied rows share one count.","COUNT(expr) counts non-NULL values only, in window form too: COUNT(x) OVER () can be smaller than COUNT(*) OVER () on sparse columns.","COUNT(DISTINCT x) OVER (...) is rejected by SQL Server, PostgreSQL, MySQL and SQLite. Oracle runs it, but only without ORDER BY in the OVER clause."],"examples":[{"engine_slug":"all","sql":"SELECT department, employee_id,\n       COUNT(*) OVER (PARTITION BY department) AS dept_size\nFROM employees;"},{"engine_slug":"all","sql":"SELECT order_id, created_at,\n       COUNT(*) OVER (ORDER BY created_at) AS orders_so_far,\n       COUNT(*) OVER () AS total_orders\nFROM orders;"}],"faqs":[{"question":"How do I get the group size on every row?","answer":"COUNT(*) OVER (PARTITION BY group_col): the same number repeats on every row of the group without collapsing them, unlike GROUP BY + join."},{"question":"Why is my running COUNT the same on tied rows?","answer":"The default frame is RANGE up to CURRENT ROW, which includes peers. Tied rows share the count through the last peer; use COUNT(*) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) for strict row-by-row counting; add a unique column to the ORDER BY when the order among ties must be stable."}],"related":["aggregate-over","running-total","rows-vs-range"],"novel_uses":[{"body":"COUNT(*) OVER (PARTITION BY team) is the team size on every row, so a pool can be divided evenly: bonus pool divided by peer count. The same column doubles as a duplicate detector when the partition key should be unique.","sql":"SELECT employee_id, team, bonus_pool,\n       bonus_pool * 1.0 / NULLIF(COUNT(*) OVER (PARTITION BY team), 0) AS individual_share\nFROM team_bonus;"},{"body":"The grand count minus the running count is the number of rows still to come, a burndown column with no second query. Tied timestamps share a running count under the default frame, so add a tiebreaker when depth must be exact per row.","sql":"SELECT ticket_id, created_at,\n       COUNT(*) OVER ()\n         - COUNT(*) OVER (ORDER BY created_at, ticket_id) AS rows_after_this_one\nFROM tickets;"}]},"source_url":"https://sqlly.app/sql-functions/count-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/count-substring","corpus":"sql-functions","engine":null,"language":"en","title":"SQL count occurrences of a substring","description":"Count how many times a substring appears: the length-minus-replace trick, per engine syntax, plus overlap and case-sensitivity caveats.","body":{"slug":"count-substring","name":"Counting substring occurrences","h1":"SQL count occurrences of a substring","category":"string","lede":"Outside the regex counters (Oracle's REGEXP_COUNT, PostgreSQL 15's regexp_count and SQL Server 2025's REGEXP_COUNT), there is no substring counter; the standard trick measures the length lost when the needle is removed.","syntax":"LEN(s) - LEN(REPLACE(s, needle, ''))","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The trick: removing the needle shortens the string by count x needle-length. For single characters no division is needed; for longer needles divide by LENGTH(needle), written DIV on MySQL, where / returns a DECIMAL such as 1.0000.","Counts are non-overlapping by construction: REPLACE removes left to right, so 'aaa' counts one 'aa', not two.","Case sensitivity follows REPLACE: SQL Server's default case-insensitive collations count 'A' and 'a' alike, while MySQL's REPLACE matches exact case even under a _ci collation, as do PostgreSQL, SQLite and Oracle.","NULL poisons the math: a NULL column yields NULL, so wrap with COALESCE(s, '') when blanks should count as zero.","On SQL Server, LEN ignores trailing spaces, so a needle that is or ends in a space undercounts: LEN(s) - LEN(REPLACE(s, ' ', '')) gives 1 for 'a b  ', which holds 3 spaces. Divide DATALENGTH(s) - DATALENGTH(REPLACE(s, needle, '')) by DATALENGTH(needle) instead.","An empty needle divides by zero: SQL Server and PostgreSQL raise an error, while MySQL and SQLite return NULL; guard the divisor with NULLIF(LENGTH(needle), 0)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT LEN(note) - LEN(REPLACE(note, ',', '')) AS commas FROM notes;"},{"engine_slug":"postgresql","sql":"SELECT length(note) - length(replace(note, ',', '')) AS commas FROM notes;"},{"engine_slug":"oracle","sql":"SELECT (LENGTH(note) - LENGTH(REPLACE(note, ',', ''))) AS commas FROM notes;"},{"engine_slug":"mysql","sql":"SELECT (CHAR_LENGTH(note) - CHAR_LENGTH(REPLACE(note, ',', ''))) AS commas FROM notes;  -- REPLACE matches case exactly even under _ci collations"},{"engine_slug":"sqlite","sql":"SELECT length(note) - length(replace(note, ',', '')) AS commas FROM notes;"}],"faqs":[{"question":"How do I count occurrences of a multi-character needle?","answer":"Divide the length difference by the needle's length: (LEN(s) - LEN(REPLACE(s, 'ab', ''))) / 2 counts 'ab' pairs; on MySQL write DIV 2, since / returns a DECIMAL."},{"question":"Does this count overlapping matches?","answer":"No. REPLACE consumes left to right, so 'aaaa' with needle 'aa' counts 2. Overlap counting needs a recursive or regex-based approach."},{"question":"Is there a COUNT function for substrings?","answer":"Oracle has REGEXP_COUNT(s, pattern) and PostgreSQL 15+ has regexp_count(); both take a regex, so escape special characters in the needle. Elsewhere the length-minus-replace trick is the idiom."}],"related":["replace","length","instr","regexp-replace"],"novel_uses":[{"body":"Commas plus one is the field count, so the length-minus-replace trick flags rows with the wrong shape before a parser ever sees them.","sql":"SELECT line FROM staged WHERE LEN(line) - LEN(REPLACE(line, ',', '')) + 1 <> 12;  -- wrong field count"},{"body":"PostgreSQL 15's regexp_count with \\y word boundaries counts ab but not the ab inside abc, which the length trick cannot distinguish.","sql":"SELECT regexp_count(note, '\\yab\\y') AS whole_words FROM notes;"}]},"source_url":"https://sqlly.app/sql-functions/count-substring","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/covar-pop","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COVAR_POP function","description":"COVAR_POP computes population covariance, dividing by n: PostgreSQL and Oracle support, its role in the CORR formula, and how it differs from COVAR_SAMP.","body":{"slug":"covar-pop","name":"COVAR_POP","h1":"SQL COVAR_POP function","category":"aggregate","lede":"Population covariance of two columns: divides by n over the complete pairs.","syntax":"COVAR_POP(y, x) | COVAR_POP(y, x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"same manual formula over complete pairs, but cast integers to float first: AVG of an int column returns an int and truncates the result"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"compute manually over complete pairs: AVG(y*x) - AVG(y)*AVG(x) with WHERE y IS NOT NULL AND x IS NOT NULL"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Complete pairs only: either input NULL drops the row from the computation.","One complete pair returns 0 (divisor n), not NULL like COVAR_SAMP.","It is the building block of Pearson correlation: CORR(y,x) = COVAR_POP(y,x) / (STDDEV_POP(y) * STDDEV_POP(x)), with both standard deviations taken over the same complete pairs."],"examples":[{"engine_slug":"postgresql","sql":"SELECT covar_pop(height, weight) FROM people;"},{"engine_slug":"oracle","sql":"SELECT COVAR_POP(salary, age) FROM employees;"}],"faqs":[{"question":"COVAR_POP vs COVAR_SAMP?","answer":"Divisor n versus n-1, and the one-pair result: 0 versus NULL."},{"question":"Does MySQL have COVAR_POP?","answer":"No, but AVG(y*x) - AVG(y)*AVG(x) is exactly it over complete pairs."},{"question":"How does CORR use it?","answer":"CORR is COVAR_POP normalized by both population standard deviations."}],"related":["covar-samp","corr","stddev-pop","regr-slope"],"novel_uses":[{"body":"covar_pop(y, x) / var_pop(x) is the same least-squares slope REGR_SLOPE returns, but only over complete pairs: a row with y NULL and x present still feeds var_pop(x) and skews the slope, so filter both columns first.","sql":"SELECT covar_pop(sales, ad_spend) / var_pop(ad_spend) AS slope FROM monthly WHERE sales IS NOT NULL AND ad_spend IS NOT NULL;"},{"body":"The sign of COVAR_POP answers whether two metrics move together before any normalization; CORR only rescales that sign into a strength between -1 and 1.","sql":"SELECT sign(covar_pop(latency, payload_bytes)) AS move_together FROM requests;"}]},"source_url":"https://sqlly.app/sql-functions/covar-pop","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/covar-samp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL COVAR_SAMP function","description":"COVAR_SAMP computes sample covariance, dividing by n-1: PostgreSQL and Oracle support, complete-pair filtering, NULL for one pair, and the manual MySQL recipe.","body":{"slug":"covar-samp","name":"COVAR_SAMP","h1":"SQL COVAR_SAMP function","category":"aggregate","lede":"Sample covariance of two columns: divides by n-1 over the complete pairs.","syntax":"COVAR_SAMP(y, x) | COVAR_SAMP(y, x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"same manual route; cast integers to float, and divide by NULLIF(COUNT(*) - 1, 0) so a single pair returns NULL instead of a divide-by-zero error"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"compute manually: (SUM(y*x) - SUM(y)*SUM(x)/COUNT(*)) / (COUNT(*) - 1) over complete pairs"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Rows where either input is NULL are dropped; covariance runs on complete pairs only.","One complete pair returns NULL: the n-1 divisor needs at least two pairs.","Read the sign, not the size: covariance is in y-units times x-units, so its magnitude changes when you rescale a column. CORR divides that scale out."],"examples":[{"engine_slug":"postgresql","sql":"SELECT covar_samp(height, weight) FROM people;"},{"engine_slug":"oracle","sql":"SELECT COVAR_SAMP(salary, age) FROM employees;"}],"faqs":[{"question":"COVAR_SAMP vs COVAR_POP?","answer":"The divisor: n-1 versus n; a single pair gives NULL versus 0."},{"question":"Which engines have it?","answer":"PostgreSQL and Oracle. MySQL and SQL Server need the manual formula (SUM(y*x) - SUM(y)*SUM(x)/COUNT(*)) / (COUNT(*) - 1), run over complete pairs only."},{"question":"How is covariance used in CORR?","answer":"CORR is COVAR_POP divided by the product of the two population standard deviations."}],"related":["covar-pop","corr","stddev-samp","regr-slope"],"novel_uses":[{"body":"As a window function on PostgreSQL and Oracle, COVAR_SAMP over a rolling frame tracks how two metrics move together through regimes, not just on average.","sql":"SELECT day, covar_samp(sales, ad_spend) OVER (ORDER BY day ROWS BETWEEN 89 PRECEDING AND CURRENT ROW) FROM daily;"},{"body":"COVAR_POP reads smaller than COVAR_SAMP by the factor (n-1)/n; at 5 pairs that is 20 percent, which is why the two variants must never be mixed inside one report.","sql":"SELECT covar_samp(y, x), covar_pop(y, x) FROM pairs;"}]},"source_url":"https://sqlly.app/sql-functions/covar-samp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/crc32","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CRC32 function","description":"How CRC32 computes a 32-bit checksum in MySQL and PostgreSQL 18: unsigned integer results, collision odds for change detection, and the CHECKSUM and hash alternatives.","body":{"slug":"crc32","name":"CRC32","h1":"SQL CRC32 function","category":"string","lede":"Computes the 32-bit CRC checksum of a string, returned as an unsigned integer.","syntax":"CRC32(string)","return_type":"unsigned integer","support":[{"engine_slug":"sql-server","status":"no","note":"No CRC32; CHECKSUM and BINARY_CHECKSUM use other algorithms."},{"engine_slug":"postgresql","status":"yes","note":"crc32(bytea) and crc32c(bytea) from PostgreSQL 18; convert text with convert_to."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No CRC32 built in."},{"engine_slug":"oracle","status":"no","note":"No CRC32; ORA_HASH or STANDARD_HASH."}],"gotchas":["CRC32 detects accidental corruption, not deliberate tampering; it has no cryptographic strength.","With 2^32 possible values, collisions become likely after about 77,000 distinct inputs (the birthday bound). Treat equal CRCs as a hint and compare the actual values.","The result is an integer, so it indexes and compares cheaply; a classic use is a stored checksum column that flags changed text."],"examples":[{"engine_slug":"mysql","sql":"SELECT CRC32('hello') AS checksum;  -- 907060870"},{"engine_slug":"mysql","sql":"SELECT * FROM documents\nWHERE CRC32(body) <> stored_crc;"},{"engine_slug":"postgresql","sql":"SELECT crc32(convert_to(body, 'UTF8')) AS checksum\nFROM documents;"}],"faqs":[{"question":"Can CRC32 be used as a unique identifier?","answer":"No. Collisions are certain beyond 2^32 (about 4.3 billion) distinct inputs and likely far sooner; use it to spot likely changes and confirm with the full value."},{"question":"What is the difference between CRC32 and CHECKSUM in SQL Server?","answer":"Different algorithms: CRC32 is the standard cyclic code over one string; SQL Server's CHECKSUM hashes an expression list. Their values differ in general ('abc' gives 891568578 from CRC32 and 34400 from CHECKSUM), though both happen to return 0 for the empty string."},{"question":"Does PostgreSQL have CRC32?","answer":"From PostgreSQL 18: crc32(bytea) gives the same value as MySQL's CRC32 for the same bytes (907060870 for 'hello'), and crc32c uses the Castagnoli polynomial."}],"related":["md5","sha2","hashbytes","hex"],"novel_uses":[{"body":"CRC32(id) % 10 = 0 selects about a tenth of the rows, and the same id always lands in the same bucket because the checksum is deterministic.","sql":"SELECT * FROM users\nWHERE CRC32(CAST(id AS CHAR)) % 10 = 0;"},{"body":"Both sides compute CRC32 over the same bytes and exchange a 4-byte integer instead of full rows; only mismatches need a real comparison. Same bytes, same checksum, so column types and encodings must match.","sql":"SELECT id, CRC32(body) AS crc FROM documents;"}]},"source_url":"https://sqlly.app/sql-functions/crc32","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cube","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUP BY CUBE","description":"GROUP BY CUBE(a, b) adds subtotals for every combination of the columns plus a grand total. SQL Server, PostgreSQL and Oracle support it; MySQL and SQLite reject it.","body":{"slug":"cube","name":"CUBE","h1":"SQL GROUP BY CUBE","category":"aggregate","lede":"CUBE(region, product) groups by (region, product), (region), (product) and () in one query: the detail rows, both sets of subtotals and the grand total.","syntax":"GROUP BY CUBE(col1, col2 [, ...])","return_type":"extra subtotal rows with NULL in the rolled-up columns","support":[{"engine_slug":"sql-server","status":"yes","note":"CUBE(...), also the older WITH CUBE"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"CUBE fails with 'CUBE' is not supported; WITH ROLLUP only"},{"engine_slug":"sqlite","status":"no","note":"no CUBE or ROLLUP; UNION ALL the groupings"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["n columns produce 2^n groupings: CUBE over four columns is sixteen GROUP BYs in one pass, and the row count grows fast.","Subtotal rows show NULL in the rolled-up columns. GROUPING(col) returns 1 on those rows, which tells them apart from real NULL values.","CUBE implies no sort order. Add ORDER BY, often on GROUPING(col), to put the totals where readers expect them."],"examples":[{"engine_slug":"postgresql","sql":"SELECT region, product, SUM(n) AS total\nFROM (VALUES ('E', 'x', 1), ('E', 'y', 2), ('W', 'x', 3)) AS t(region, product, n)\nGROUP BY CUBE(region, product)\nORDER BY region NULLS LAST, product NULLS LAST;  -- 8 rows: 3 detail, 2 region totals, 2 product totals, 1 grand total"},{"engine_slug":"sql-server","sql":"SELECT region, product, SUM(n) AS total, GROUPING(region) AS g_region, GROUPING(product) AS g_product\nFROM (VALUES ('E', 'x', 1), ('E', 'y', 2), ('W', 'x', 3)) AS t(region, product, n)\nGROUP BY CUBE(region, product);"},{"engine_slug":"oracle","sql":"SELECT region, product, SUM(n) AS total\nFROM (SELECT 'E' AS region, 'x' AS product, 1 AS n FROM dual\n      UNION ALL SELECT 'E', 'y', 2 FROM dual\n      UNION ALL SELECT 'W', 'x', 3 FROM dual)\nGROUP BY CUBE(region, product)\nORDER BY region, product;"}],"faqs":[{"question":"CUBE or ROLLUP?","answer":"ROLLUP(a, b) follows a hierarchy: (a, b), (a), (). CUBE(a, b) also adds (b) on its own. Use ROLLUP for year > month style drill-downs and CUBE for cross-tab totals."},{"question":"How do I get CUBE results in MySQL?","answer":"Combine queries: GROUP BY a, b WITH ROLLUP gives (a, b), (a) and (); UNION ALL a GROUP BY b query adds the missing (b) subtotals."}],"related":["rollup","grouping-sets","grouping","grouping-id"],"novel_uses":[{"body":"GROUPING_ID(a, b) on SQL Server and Oracle packs the GROUPING bits into one integer: 0 for detail rows, then each subtotal level, up to the grand total; PostgreSQL spells it GROUPING(a, b) with several arguments. ORDER BY GROUPING_ID(a, b) puts every row of a CUBE in report order without a CASE ladder.","sql":"SELECT region, product, SUM(n) AS total, GROUPING_ID(region, product) AS lvl\nFROM (VALUES ('E', 'x', 1), ('E', 'y', 2)) AS t(region, product, n)\nGROUP BY CUBE(region, product)\nORDER BY lvl;"},{"body":"PostgreSQL accepts parenthesized elements inside CUBE, so CUBE((region, product), month) treats region and product as one unit and produces four groupings instead of eight. Hierarchies stay hierarchies instead of exploding into meaningless subtotals.","sql":"SELECT region, product, month, SUM(n)\nFROM sales\nGROUP BY CUBE((region, product), month);"},{"body":"GROUP BY () on PostgreSQL is the empty grouping: one row of totals for the whole input. It is the cheapest grand-total row to UNION ALL onto a detail query, with no duplicate aggregate expressions in a second pass.","sql":"SELECT SUM(n) AS grand_total\nFROM sales\nGROUP BY ();"}]},"source_url":"https://sqlly.app/sql-functions/cube","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cume-dist","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CUME_DIST function","description":"CUME_DIST in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: the share of partition rows at or below the current row, ties included.","body":{"slug":"cume-dist","name":"CUME_DIST","h1":"SQL CUME_DIST function","category":"window","lede":"Returns the number of partition rows with a value less than or equal to the current row, divided by the total rows in the partition, a value in (0, 1].","syntax":"CUME_DIST() OVER (PARTITION BY g ORDER BY x)","return_type":"double precision / float","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["CUME_DIST counts ties in: all peers get the same value, equal to the fraction of rows up to and including the last peer. PERCENT_RANK gives peers the rank of the first one instead.","The maximum value is always exactly 1; the minimum is greater than 0 (it is at least peers / total rows).","Without ORDER BY every row is a peer of every other row, so CUME_DIST returns 1 on PostgreSQL, MySQL and SQLite. SQL Server rejects the call: \"The function 'CUME_DIST' must have an OVER clause with ORDER BY.\""],"examples":[{"engine_slug":"all","sql":"SELECT product, price,\n       CUME_DIST() OVER (ORDER BY price) AS price_dist\nFROM products;"},{"engine_slug":"all","sql":"-- at most the most expensive quartile; tie groups stay whole\nWITH d AS (\n  SELECT p.*, CUME_DIST() OVER (ORDER BY price DESC) AS cd\n  FROM products p\n)\nSELECT * FROM d WHERE cd <= 0.25;"}],"faqs":[{"question":"How is CUME_DIST different from PERCENT_RANK?","answer":"CUME_DIST = rows at or below (including peers and the current row) / total rows, so it never returns 0 and hits exactly 1 at the top. PERCENT_RANK = (rank - 1) / (rows - 1), which starts at 0. With ties, CUME_DIST gives every peer the value through the last peer."},{"question":"Can CUME_DIST be used for percentiles?","answer":"Yes. CUME_DIST() OVER (ORDER BY x) <= 0.25 keeps at most the lowest quartile, without splitting a tie group, and the smallest x with CUME_DIST >= 0.25 is exactly PERCENTILE_DISC(0.25). That works on MySQL and SQLite, which lack PERCENTILE_DISC."}],"related":["percent-rank","percentile-disc","rank"],"novel_uses":[{"body":"CUME_DIST over prices is the share of the catalogue at or below each price point, so a product at 0.9 costs at least as much as 90% of the catalogue, itself included. Pricing teams use that number directly as a market-position metric.","sql":"SELECT product, price,\n       CUME_DIST() OVER (ORDER BY price) AS share_at_or_below\nFROM products;"},{"body":"CEIL(10 * CUME_DIST()) assigns decile numbers by value share (SQL Server spells it CEILING; CEIL is rejected there), and because tied rows share the same CUME_DIST they always land in the same bucket. NTILE cannot promise that: it buckets by position and can split a tie group.","sql":"SELECT product, price,\n       CEIL(10 * CUME_DIST() OVER (ORDER BY price)) AS price_decile\nFROM products;"}]},"source_url":"https://sqlly.app/sql-functions/cume-dist","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/cumulative-share","corpus":"sql-functions","engine":null,"language":"en","title":"SQL cumulative percent of total","description":"Running sum over grand total: Pareto curves and 'top rows are X% of everything' with one window divided by another.","body":{"slug":"cumulative-share","name":"Cumulative Share","h1":"SQL cumulative percent of total","category":"window","lede":"SUM(x) OVER (ORDER BY d) divided by SUM(x) OVER () gives each row's cumulative share (tied sort keys share one value): the Pareto distribution in two windows.","syntax":"1.0 * SUM(x) OVER (ORDER BY d) / NULLIF(SUM(x) OVER (), 0)","return_type":"numeric fraction","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Window calls cannot be nested (SUM(SUM(x) OVER ...) OVER ... is an error), but they can be combined in one expression: SUM(x) OVER (ORDER BY d) / SUM(x) OVER () is two separate windows divided.","Sorting by descending value gives the classic Pareto curve (80/20 check); ascending gives a growth curve. The denominator ignores ORDER BY because it has none.","Watch integer division and zero totals as in percent-of-total, plus peers: under the default RANGE frame, tied rows all show the cumulative share through the last of them. The tiebreaker in the example avoids that."],"examples":[{"engine_slug":"all","sql":"WITH ranked AS (\n  SELECT customer_id, spend,\n         SUM(spend) OVER (ORDER BY spend DESC, customer_id) AS cum,\n         SUM(spend) OVER () AS total\n  FROM customer_spend\n)\nSELECT customer_id, spend, cum,\n       100.0 * cum / NULLIF(total, 0) AS cum_share\nFROM ranked;"}],"faqs":[{"question":"How do I find the rows that make up 80% of revenue?","answer":"Cumulative share ordered by spend DESC, then keep rows with cum_share <= 80 (the example scales by 100) in an outer query. One boundary row may straddle 80%; include or exclude it as a business rule."},{"question":"Why does the total differ from my other report?","answer":"The denominator is the sum after WHERE. Filters applied to the query shrink it; compute the total in a separate unfiltered CTE when the base must stay fixed."}],"related":["percent-of-total","running-total","cume-dist"],"novel_uses":[{"body":"Sort ascending, take the cumulative share, and the Gini coefficient is 1 minus twice its average plus one over the row count. Zero means perfectly even shares and the result approaches 1 as one row holds everything.","sql":"WITH l AS (\n  SELECT income,\n         SUM(income) OVER (ORDER BY income ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) * 1.0 / SUM(income) OVER () AS cum_share\n  FROM households\n)\nSELECT 1 - 2 * AVG(cum_share) + 1.0 / COUNT(*) AS gini\nFROM l;"},{"body":"Rank by size descending and read the cumulative share at row five: that number, the CR5, says how much of the market the top five names control. It is the standard concentration metric in industry analysis and it adds one ROW_NUMBER to the running sum.","sql":"WITH r AS (\n  SELECT vendor, revenue,\n         ROW_NUMBER() OVER (ORDER BY revenue DESC, vendor) AS rn,\n         100.0 * SUM(revenue) OVER (ORDER BY revenue DESC, vendor ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / SUM(revenue) OVER () AS cum_pct\n  FROM market_share\n)\nSELECT MAX(cum_pct) AS cr5\nFROM r\nWHERE rn <= 5;"}]},"source_url":"https://sqlly.app/sql-functions/cumulative-share","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-database","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DB_NAME and current_database()","description":"Get the name of the database the session is using: DB_NAME() on SQL Server, current_database() on PostgreSQL, DATABASE() on MySQL, SYS_CONTEXT on Oracle.","body":{"slug":"current-database","name":"DB_NAME / current_database","h1":"SQL DB_NAME and current_database()","category":"system","lede":"Scripts that run against several databases often need to know which one they are in. Each engine has a function for it, and SQLite has none.","syntax":"DB_NAME()  |  current_database()  |  DATABASE()  |  SYS_CONTEXT('USERENV', 'DB_NAME')","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":"DB_NAME(); DB_NAME(id) names another database"},{"engine_slug":"postgresql","status":"partial","note":"current_database()"},{"engine_slug":"mysql","status":"partial","note":"DATABASE() or its synonym SCHEMA(); NULL when no default database is selected"},{"engine_slug":"sqlite","status":"no","note":"no name; PRAGMA database_list shows main and the file path"},{"engine_slug":"oracle","status":"partial","note":"SYS_CONTEXT('USERENV', 'DB_NAME') or ORA_DATABASE_NAME"}],"gotchas":["MySQL's DATABASE() is NULL until a default database is chosen with USE or in the connection settings.","In MySQL a database and a schema are the same thing, so DATABASE() and SCHEMA() agree. In SQL Server and PostgreSQL one database holds many schemas, and DB_NAME() says nothing about the schema.","Connected to an Oracle pluggable database, SYS_CONTEXT('USERENV', 'DB_NAME') returns the PDB name (FREEPDB1 on the Free image), not the container database's name."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DB_NAME() AS current_db, DB_NAME(1) AS first_db;  -- first_db is master"},{"engine_slug":"postgresql","sql":"SELECT current_database();"},{"engine_slug":"mysql","sql":"SELECT DATABASE(), SCHEMA();  -- the same name twice"},{"engine_slug":"oracle","sql":"SELECT SYS_CONTEXT('USERENV', 'DB_NAME') AS db, SYS_CONTEXT('USERENV', 'CON_NAME') AS container FROM dual;"}],"faqs":[{"question":"How do I list all databases?","answer":"SQL Server: SELECT name FROM sys.databases. PostgreSQL: SELECT datname FROM pg_database. MySQL: SHOW DATABASES. SQLite: PRAGMA database_list lists the attached files. Oracle: SELECT name FROM v$pdbs, which needs privileges on the view."},{"question":"What is the SQLite equivalent?","answer":"A SQLite connection opens a file, not a named database. SELECT file FROM pragma_database_list WHERE name = 'main' returns its path, which is empty for an in-memory database."}],"related":["current-schema","current-user","version"],"novel_uses":[{"body":"current_catalog is the SQL-standard name for the same answer on PostgreSQL: SELECT current_catalog returns exactly what current_database() does, so vendor-neutral scripts can stick to the standard form.","sql":"SELECT current_database(), current_catalog;  -- the same name twice"},{"body":"Deploy scripts that write to a central audit table can stamp the source with DB_NAME() in the SELECT, which settles which database ran the script when one schema deploys to dozens of them.","sql":"INSERT central.dbo.deploys (src_db, server_name, ran_at)\nSELECT DB_NAME(), @@SERVERNAME, SYSUTCDATETIME();"}]},"source_url":"https://sqlly.app/sql-functions/current-database","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CURRENT_DATE function","description":"Get today's date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: CURRENT_DATE, CURDATE and the CAST(GETDATE()) stand-in, with time-zone caveats.","body":{"slug":"current-date","name":"CURRENT_DATE","h1":"SQL CURRENT_DATE function","category":"datetime","lede":"Returns today's date with no time part on most engines, which makes it the usual lower bound for today's rows: WHERE created_at >= CURRENT_DATE.","syntax":"CURRENT_DATE  |  CURDATE()  -- MySQL  |  CAST(GETDATE() AS date)  -- SQL Server before 2025","return_type":"date (text on SQLite)","support":[{"engine_slug":"sql-server","status":"yes","note":"CURRENT_DATE from SQL Server 2025; CAST(GETDATE() AS date) before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"CURRENT_DATE, CURRENT_DATE() and CURDATE()"},{"engine_slug":"sqlite","status":"yes","note":"CURRENT_DATE returns UTC text 'YYYY-MM-DD'"},{"engine_slug":"oracle","status":"partial","note":"CURRENT_DATE keeps the time of day; TRUNC(SYSDATE) for midnight"}],"gotchas":["Older SQL Server has no CURRENT_DATE; SQL Server 2025 and Azure SQL added it. CAST(GETDATE() AS date) works on every version.","Oracle's CURRENT_DATE is a DATE, and Oracle DATEs carry a time: it returns the current date and time in the session time zone. Use TRUNC(CURRENT_DATE) or TRUNC(SYSDATE) for today at midnight.","SQLite's CURRENT_DATE is the UTC date. On a machine east or west of UTC it can be tomorrow or yesterday near midnight.","CURRENT_DATE uses the session time zone on PostgreSQL and MySQL, so the same instant can be different days in two sessions."],"examples":[{"engine_slug":"postgresql","sql":"-- also MySQL, SQLite and SQL Server 2025\nSELECT COUNT(*) FROM orders\nWHERE created_at >= CURRENT_DATE;"},{"engine_slug":"mysql","sql":"-- CURDATE() and CURRENT_DATE() are synonyms\nSELECT CURRENT_DATE AS today;"},{"engine_slug":"sqlite","sql":"SELECT CURRENT_DATE AS today;  -- UTC text, 'YYYY-MM-DD'"},{"engine_slug":"sql-server","sql":"SELECT CAST(GETDATE() AS date) AS today;"},{"engine_slug":"oracle","sql":"SELECT COUNT(*) FROM orders\nWHERE created_at >= TRUNC(SYSDATE);"}],"faqs":[{"question":"Does SQL Server have CURRENT_DATE?","answer":"SQL Server 2025 and Azure SQL Database do. On earlier versions, CAST(GETDATE() AS date) or CAST(SYSDATETIME() AS date) returns the date without the time."},{"question":"Why is SQLite's CURRENT_DATE a different day?","answer":"It reads UTC. Near midnight, UTC can already be tomorrow or still be yesterday where you are. date('now', 'localtime') returns the local date."},{"question":"Does Oracle's CURRENT_DATE include the time?","answer":"Yes. Oracle's DATE type always stores a time of day, and CURRENT_DATE returns the current date and time in the session time zone. TRUNC(CURRENT_DATE) gives midnight."}],"related":["now","date-trunc","extract"],"novel_uses":[{"body":"Write CURRENT_DATE into a one-row state table when a nightly job finishes and check it first. Re-running a failed job is a no-op for the rest of the day and resumes automatically the next morning, with no scheduler bookkeeping.","sql":"SELECT CASE WHEN processed_date = CURRENT_DATE THEN 1 ELSE 0 END AS already_ran\nFROM job_state\nWHERE id = 1;"},{"body":"DATE_TRUNC('month', CURRENT_DATE) is month to date and DATE_TRUNC('year', ...) is year to date, so the report never takes a date parameter and always opens correct. Oracle spells it TRUNC(SYSDATE, 'MM'); MySQL DATE_FORMAT(CURDATE(), '%Y-%m-01').","sql":"SELECT COUNT(*) FROM orders\nWHERE created_at >= DATE_TRUNC('month', CURRENT_DATE);"}]},"source_url":"https://sqlly.app/sql-functions/current-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-schema","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CURRENT_SCHEMA and SCHEMA_NAME()","description":"Find the default schema that unqualified table names resolve to: SCHEMA_NAME() on SQL Server, current_schema on PostgreSQL, DATABASE() on MySQL, SYS_CONTEXT on Oracle.","body":{"slug":"current-schema","name":"CURRENT_SCHEMA / SCHEMA_NAME","h1":"SQL CURRENT_SCHEMA and SCHEMA_NAME()","category":"system","lede":"An unqualified name such as orders is looked up in a default schema. Knowing which one explains most 'table does not exist' errors for tables that clearly exist.","syntax":"SCHEMA_NAME()  |  current_schema  |  DATABASE()  |  SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"SCHEMA_NAME() with no argument is the caller's default schema"},{"engine_slug":"postgresql","status":"yes","note":"current_schema, the first existing schema on search_path"},{"engine_slug":"mysql","status":"partial","note":"DATABASE(); a schema is a database"},{"engine_slug":"sqlite","status":"no","note":"no schemas; attached databases act as prefixes"},{"engine_slug":"oracle","status":"partial","note":"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"}],"gotchas":["PostgreSQL resolves names through search_path, and current_schema is the first schema on it that exists. current_schemas(true) shows the full path, including the implicit pg_catalog.","SQL Server has no per-session switch: the default schema belongs to the database user (usually dbo) and changes only with ALTER USER ... WITH DEFAULT_SCHEMA.","Oracle's current schema starts as the login user. ALTER SESSION SET CURRENT_SCHEMA = hr changes name resolution but not privileges."],"examples":[{"engine_slug":"postgresql","sql":"SET search_path = missing_schema, public;\nSELECT current_schema, current_schemas(false);  -- public, {public}"},{"engine_slug":"sql-server","sql":"SELECT SCHEMA_NAME() AS default_schema;  -- dbo"},{"engine_slug":"mysql","sql":"SELECT DATABASE() AS cur_schema;"},{"engine_slug":"oracle","sql":"SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS cur_schema FROM dual;"}],"faqs":[{"question":"Is a schema the same as a database?","answer":"In MySQL, yes. In SQL Server and PostgreSQL a database contains schemas. In Oracle a schema is the set of objects a user owns."},{"question":"How do I change the current schema?","answer":"PostgreSQL: SET search_path = sales, public. MySQL: USE sales. Oracle: ALTER SESSION SET CURRENT_SCHEMA = sales. SQL Server: qualify names, or change the user's default with ALTER USER ... WITH DEFAULT_SCHEMA = sales."}],"related":["current-database","current-user","identifier-quoting"],"novel_uses":[{"body":"A search_path entry that does not exist is skipped without error, so SET search_path = sales, public with a typo lands current_schema on public and unqualified CREATE TABLE quietly builds there. SELECT current_schema is the one-line check before migration DDL.","sql":"SET search_path = salse, public;\nSELECT current_schema;  -- public, not salse"},{"body":"SCHEMA_NAME(schema_id) is the join that names a table's schema from metadata: sys.tables stores only the id, and this call turns it into the dbo, sales or hr prefix your scripts assumed.","sql":"SELECT SCHEMA_NAME(schema_id) AS schema_name, name\nFROM sys.tables\nORDER BY schema_name, name;"}]},"source_url":"https://sqlly.app/sql-functions/current-schema","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-time","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CURRENT_TIME function","description":"Get the current time without the date: CURRENT_TIME on PostgreSQL, MySQL and SQLite, CURTIME() on MySQL, and the stand-ins where the keyword is missing.","body":{"slug":"current-time","name":"CURRENT_TIME","h1":"SQL CURRENT_TIME function","category":"datetime","lede":"Returns the current time of day. The standard keyword is CURRENT_TIME; SQL Server casts a timestamp to time, and Oracle, which has no TIME type, formats one as text.","syntax":"CURRENT_TIME  |  CURRENT_TIME(p)  |  CURTIME()  -- MySQL","return_type":"time (time with time zone on PostgreSQL)","support":[{"engine_slug":"sql-server","status":"partial","note":"CAST(SYSDATETIME() AS time)"},{"engine_slug":"postgresql","status":"yes","note":"returns time with time zone; LOCALTIME returns plain time"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"UTC text 'HH:MM:SS'; no precision argument"},{"engine_slug":"oracle","status":"no","note":"no TIME type; TO_CHAR(SYSDATE, 'HH24:MI:SS') gives text"}],"gotchas":["SQLite's CURRENT_TIME is UTC; time('now', 'localtime') gives the local wall clock.","PostgreSQL's CURRENT_TIME returns time with time zone, a type its own docs advise against storing. LOCALTIME returns plain time.","Precision differs: PostgreSQL takes CURRENT_TIME(3), MySQL takes CURTIME(3) or CURRENT_TIME(3), and SQLite rejects a precision argument."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CURRENT_TIME(3) AS now_time;"},{"engine_slug":"mysql","sql":"SELECT CURTIME() AS now_time;"},{"engine_slug":"sql-server","sql":"SELECT CAST(SYSDATETIME() AS time) AS now_time;"},{"engine_slug":"sqlite","sql":"SELECT CURRENT_TIME AS now_time;  -- UTC text, no precision argument"}],"faqs":[{"question":"Does SQL Server have CURRENT_TIME?","answer":"No. CAST(SYSDATETIME() AS time) or CAST(GETDATE() AS time) returns just the time of day."},{"question":"Why is SQLite's CURRENT_TIME off by hours?","answer":"It returns UTC. If you need the local wall clock, use strftime('%H:%M:%S','now','localtime')."}],"related":["now","getdate","localtimestamp"],"novel_uses":[{"body":"SQLite DDL accepts CURRENT_TIME (with CURRENT_DATE and CURRENT_TIMESTAMP) as a DEFAULT expression, one of the few function calls its table definitions allow. The value lands as 'HH:MM:SS' text at insert.","sql":"CREATE TABLE pings (at TEXT DEFAULT CURRENT_TIME);"},{"body":"Compare a TIME column against CURTIME() to answer is-it-open questions: rows whose start and end times bracket the current clock come back no matter what the date is.","sql":"SELECT * FROM shifts WHERE CURTIME() BETWEEN starts_at AND ends_at;"},{"body":"Cast the timestamp to time and the comparison stops caring about the date, so one predicate finds everything inside 09:00 to 17:00 on any day.","sql":"SELECT * FROM events WHERE CAST(happened_at AS time) BETWEEN '09:00' AND '17:00';"}]},"source_url":"https://sqlly.app/sql-functions/current-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-user","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CURRENT_USER","description":"Find out which user a session runs as: CURRENT_USER and SUSER_SNAME on SQL Server, CURRENT_USER in PostgreSQL, CURRENT_USER() in MySQL and USER in Oracle.","body":{"slug":"current-user","name":"CURRENT_USER","h1":"SQL CURRENT_USER","category":"system","lede":"CURRENT_USER is standard SQL, but what it returns differs: a database user on SQL Server, a role on PostgreSQL, an account with a host on MySQL.","syntax":"CURRENT_USER  |  SESSION_USER  |  CURRENT_USER()  -- MySQL  |  USER  -- Oracle","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":"CURRENT_USER is the database user (dbo for sysadmins); SUSER_SNAME() is the login"},{"engine_slug":"postgresql","status":"yes","note":"CURRENT_USER and SESSION_USER, written without parentheses"},{"engine_slug":"mysql","status":"yes","note":"CURRENT_USER() is the account that authenticated; USER() is what the client sent"},{"engine_slug":"sqlite","status":"no","note":"no users"},{"engine_slug":"oracle","status":"partial","note":"USER or SYS_CONTEXT('USERENV', 'CURRENT_USER'); CURRENT_USER is not valid in SQL"}],"gotchas":["SQL Server tracks two identities. CURRENT_USER returns the database user, which is dbo for every sysadmin login; SUSER_SNAME() returns the login itself, such as sa or a Windows account. Audit columns usually want the login.","In PostgreSQL CURRENT_USER and SESSION_USER are keywords, so CURRENT_USER() is a syntax error. They differ after SET ROLE, and inside a SECURITY DEFINER function CURRENT_USER is the function's owner.","MySQL's USER() is the user and host the client claimed; CURRENT_USER() is the account row that matched, which can be a wildcard-host account such as app@'%'.","Oracle rejects SELECT CURRENT_USER FROM dual with ORA-00904. Use USER, or SYS_CONTEXT('USERENV', 'SESSION_USER')."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CURRENT_USER AS db_user, SUSER_SNAME() AS login_name;  -- dbo, sa when connected as sa"},{"engine_slug":"postgresql","sql":"SELECT current_user, session_user;"},{"engine_slug":"mysql","sql":"SELECT USER(), CURRENT_USER();"},{"engine_slug":"oracle","sql":"SELECT USER, SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user FROM dual;"}],"faqs":[{"question":"How do I record who changed a row?","answer":"Use a column default or a trigger. PostgreSQL: DEFAULT CURRENT_USER. SQL Server: DEFAULT SUSER_SNAME(). Oracle: DEFAULT USER. MySQL 8.0.13+ accepts an expression default such as DEFAULT (CURRENT_USER())."},{"question":"Why does CURRENT_USER return dbo on SQL Server?","answer":"Members of sysadmin map to the dbo user in every database. Call SUSER_SNAME() or ORIGINAL_LOGIN() to see the login that actually connected."}],"related":["current-database","current-schema","connection-id"],"novel_uses":[{"body":"A PostgreSQL row security policy is evaluated as the querying role, so CURRENT_USER inside the policy expression is the caller. Inside a SECURITY DEFINER helper the policy calls, CURRENT_USER is the function owner instead, so checks written there test a different role.","sql":"CREATE POLICY p ON orders\n  USING (owner = current_user);  -- the caller, unless the check lives in a definer function"},{"body":"EXECUTE AS inside a SQL Server module rewrites CURRENT_USER for everything the module runs, so audit code inside it would stamp the impersonated user. ORIGINAL_LOGIN() is unaffected by any depth of EXECUTE AS and always returns the login that connected.","sql":"SELECT CURRENT_USER AS impersonated, ORIGINAL_LOGIN() AS connected;"}]},"source_url":"https://sqlly.app/sql-functions/current-user","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/current-utc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL current UTC timestamp","description":"Current UTC time on every engine: UTC_TIMESTAMP in MySQL, SYSUTCDATETIME in SQL Server, 'now' in SQLite, AT TIME ZONE 'UTC' elsewhere.","body":{"slug":"current-utc","name":"UTC_TIMESTAMP","h1":"SQL current UTC timestamp","category":"datetime","lede":"The current instant expressed in UTC: the timestamp shape to persist for events, logs and any cross-zone comparison.","syntax":"UTC_TIMESTAMP()  |  SYSUTCDATETIME()  |  datetime('now')","return_type":"timestamp","support":[{"engine_slug":"sql-server","status":"yes","note":"SYSUTCDATETIME() / GETUTCDATE()"},{"engine_slug":"postgresql","status":"yes","note":"now() AT TIME ZONE 'UTC'"},{"engine_slug":"mysql","status":"yes","note":"UTC_TIMESTAMP()"},{"engine_slug":"sqlite","status":"yes","note":"strftime('%Y-%m-%d %H:%M:%S', 'now')"},{"engine_slug":"oracle","status":"yes","note":"SYS_EXTRACT_UTC(SYSTIMESTAMP)"}],"gotchas":["SQLite's 'now' is UTC natively; the localtime modifier is the opt-in. Every other engine's local default needs the UTC spelling above.","Oracle's SYSDATE and SYSTIMESTAMP are the *database server's* zone, not the session's; UTC conversion is SYS_EXTRACT_UTC(SYSTIMESTAMP), and neither touches session TIME_ZONE.","MySQL's UTC_TIMESTAMP and NOW() differ by the session offset; mixing them in one table is how people get rows dated hours off: 2 hours in the future under a +02:00 session, 5 hours in the past under -05:00."],"examples":[{"engine_slug":"mysql","sql":"SELECT UTC_TIMESTAMP(), NOW();  -- differ by session offset"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%dT%H:%M:%SZ', 'now');"},{"engine_slug":"postgresql","sql":"SELECT now() AT TIME ZONE 'UTC';"},{"engine_slug":"sql-server","sql":"SELECT SYSUTCDATETIME(), GETUTCDATE();"},{"engine_slug":"oracle","sql":"SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP) FROM dual;"}],"faqs":[{"question":"Is UTC 'now' affected by DST?","answer":"Never. UTC has no offsets or transitions, which is precisely why it is the storage zone for event times."},{"question":"Why is my UTC timestamp still wrong?","answer":"Usually the data was built from a local clock with a hardcoded offset. Compute UTC inside the database with the functions above instead of string surgery in app code."}],"related":["sysutcdatetime","now","session-time-zone","unix-timestamp"],"novel_uses":[{"body":"MySQL's DATETIME has no built-in UTC behavior, so an expression default with UTC_TIMESTAMP gives UTC stamps on columns that never shift with the session.","sql":"CREATE TABLE logs (at DATETIME DEFAULT (UTC_TIMESTAMP()));"},{"body":"strftime('%s','now') returns the current second as text, no date types involved. Arithmetic and comparison against a stored INTEGER column work, but comparison against an integer literal does not (text sorts above every number), so CAST it to INTEGER first, as the example does.","sql":"SELECT CAST(strftime('%s','now') AS INTEGER) + 3600;  -- one hour from now"}]},"source_url":"https://sqlly.app/sql-functions/current-utc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datalength","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATALENGTH function","description":"DATALENGTH measures a SQL Server value's stored bytes; unlike LEN it counts trailing spaces and counts nvarchar as 2 bytes per character.","body":{"slug":"datalength","name":"DATALENGTH","h1":"SQL DATALENGTH function","category":"string","lede":"SQL Server's byte-level length: the number storage and truncation math needs, where LEN reports characters and skips trailing spaces.","syntax":"DATALENGTH(expression)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["nvarchar data counts 2 bytes per character (UTF-16): DATALENGTH(N'ab') is 4, LEN(N'ab') is 2. Since 2019, UTF-8 collations on varchar change that ratio too.","Trailing spaces count: DATALENGTH('ab ') is 3 while LEN('ab ') is 2. Leading spaces count for both.","On varchar(max) and varbinary(max) it reports the actual data size, not the declared maximum, useful for finding oversized rows.","LEN on nvarchar counts UTF-16 code units under most collations, so an emoji is 2. Supplementary-character collations (_SC, or the _140 family) count it as 1. DATALENGTH is 4 bytes either way."],"examples":[{"engine_slug":"sql-server","sql":"SELECT LEN(N'ab ') AS chars, DATALENGTH(N'ab ') AS bytes;\n-- 2, 6"},{"engine_slug":"sql-server","sql":"SELECT DATALENGTH(big_note) AS stored_bytes FROM docs\nORDER BY stored_bytes DESC;"}],"faqs":[{"question":"Why do LEN and DATALENGTH disagree?","answer":"LEN counts characters (UTF-16 code units under most collations, so an emoji is 2) and ignores trailing spaces; DATALENGTH counts stored bytes including trailing spaces, and nvarchar bytes are 2 per character. They answer different questions."},{"question":"Does DATALENGTH work on non-string types?","answer":"Yes. It returns the storage size of any expression: 4 for int, 8 for datetime, the actual bytes for blobs. It is the closest thing to sizeof in T-SQL."},{"question":"What is the cross-engine equivalent?","answer":"OCTET_LENGTH on PostgreSQL and MySQL, LENGTHB on Oracle. All three report bytes; only DATALENGTH adds the trailing-space and UTF-16 specifics."}],"related":["length","octet-length","varchar-char-semantics","emoji-length"],"novel_uses":[{"body":"SUM(DATALENGTH(col)) reports the real stored bytes, which is the number an archive-or-keep decision needs; LEN returns characters, not bytes, on nvarchar(max) and varchar(max), so it cannot answer that.","sql":"SELECT SUM(DATALENGTH(note)) / 1048576.0 AS note_mb FROM docs;"},{"body":"A zero-byte or NULL blob is the usual signature of a failed upload, and DATALENGTH is the check that sees actual storage rather than the declared type.","sql":"SELECT id FROM uploads WHERE file_blob IS NULL OR DATALENGTH(file_blob) = 0;"}]},"source_url":"https://sqlly.app/sql-functions/datalength","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-bin","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE_BIN function","description":"DATE_BIN in PostgreSQL 14: bucket timestamps into fixed grids like every 15 minutes aligned to an origin, what date_trunc cannot express.","body":{"slug":"date-bin","name":"DATE_BIN","h1":"SQL DATE_BIN function","category":"datetime","lede":"Floors a timestamp into fixed-width bins counted from an origin you choose, so buckets never reset at calendar boundaries.","syntax":"DATE_BIN(stride, source, origin)","return_type":"timestamp (timestamptz when source is timestamptz)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATE_BUCKET(MINUTE, 15, d [, origin]) on SQL Server 2022+"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["date_trunc('hour', d) resets on the clock hour; date_bin('15 minutes', d) can align to :05, :20, :35, :50 by passing an origin; that is its whole point.","The stride cannot contain months or years; those vary in length and cannot form a fixed grid.","PostgreSQL requires the origin argument; date_bin('5 minutes', now()) fails with 'function does not exist'. TIMESTAMP '2001-01-01' is the usual choice, and because that was a Monday, '7 days' bins then start on Mondays."],"examples":[{"engine_slug":"postgresql","sql":"SELECT date_bin('15 minutes', ts, TIMESTAMPTZ '2026-01-01 00:05:00+00') AS bucket, COUNT(*) FROM events GROUP BY 1;"},{"engine_slug":"postgresql","sql":"SELECT date_bin('15 minutes', TIMESTAMP '2026-08-01 10:07', TIMESTAMP '2001-01-01');  -- 2026-08-01 10:00:00"},{"engine_slug":"sql-server","sql":"SELECT DATE_BUCKET(MINUTE, 15, CAST('2026-08-01 10:07' AS datetime2));  -- 2026-08-01 10:00:00"}],"faqs":[{"question":"DATE_BIN vs date_trunc?","answer":"date_trunc snaps to calendar boundaries (day, month); date_bin snaps to a fixed repeating grid counted from an origin. For 'every 90 minutes', date_bin is one call (date_trunc has no 90-minute unit), though epoch arithmetic can do it too."},{"question":"What is the SQL Server equivalent?","answer":"DATE_BUCKET on SQL Server 2022+: DATE_BUCKET(MINUTE, 15, d, origin). Before 2022, rebuild the grid by hand: DATEADD(MINUTE, DATEDIFF(MINUTE, '2026-01-01', d) - ((DATEDIFF(MINUTE, '2026-01-01', d) % 15 + 15) % 15), '2026-01-01')."}],"related":["date-trunc","datetrunc","interval-arithmetic"],"novel_uses":[{"body":"Pass the shift start as the origin to bin an 8-hour grid that begins at 06:00, matching operating schedules instead of clock days.","sql":"SELECT date_bin('8 hours', ts, TIMESTAMPTZ '2026-01-01 06:00+00') FROM shifts;"},{"body":"Binning now() to a five-minute grid hands every dashboard instance the same stable key, so caches expire together instead of per process.","sql":"SELECT date_bin('5 minutes', now(), TIMESTAMP '2001-01-01');"},{"body":"generate_series over the bin grid, left-joined to the data, fills empty buckets with zeros, which charts need and plain GROUP BY never returns.","sql":"SELECT g, COUNT(e.id) FROM generate_series(TIMESTAMP '2026-08-01 10:00', TIMESTAMP '2026-08-01 12:00', INTERVAL '15 minutes') g LEFT JOIN events e ON date_bin('15 minutes', e.ts, TIMESTAMP '2001-01-01') = g GROUP BY g ORDER BY g;"}]},"source_url":"https://sqlly.app/sql-functions/date-bin","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-format","corpus":"sql-functions","engine":null,"language":"en","title":"MySQL DATE_FORMAT function","description":"MySQL's DATE_FORMAT with the full specifier set (%Y %m %d %H %i %s, weekday and month names) and the DATE_FORMAT equivalents in other databases.","body":{"slug":"date-format","name":"DATE_FORMAT","h1":"MySQL DATE_FORMAT function","category":"datetime","lede":"MySQL's function for rendering a date or timestamp as text, using %-prefixed specifiers from %Y (4-digit year) to %r (12-hour time). It does the job TO_CHAR does on PostgreSQL and Oracle.","syntax":"DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s')","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"FORMAT(d, 'yyyy-MM-dd') or CONVERT style codes"},{"engine_slug":"postgresql","status":"no","note":"TO_CHAR(ts, 'YYYY-MM-DD')"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"strftime('%Y-%m-%d', ts), with mostly different codes"},{"engine_slug":"oracle","status":"no","note":"TO_CHAR(d, 'YYYY-MM-DD')"}],"gotchas":["%i is minutes (not %M, which is the full month name) and %H is 24-hour hours: the two most-mistyped specifiers.","Week numbers: %U starts weeks on Sunday and %u on Monday. For ISO 8601 weeks use %v together with %x, the matching ISO year.","DATE_FORMAT(d, '%Y-%m') returns a string that sorts correctly, which is fine for grouping. Keep the original column for filtering, so an index on it can still be used."],"examples":[{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) AS orders\nFROM orders GROUP BY month;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%W %d %M %Y %r') AS pretty FROM orders;"}],"faqs":[{"question":"What is the DATE_FORMAT code for month name?","answer":"%M gives the full name (August), %b the abbreviation (Aug). Be careful: %m is the number 08, not the name."},{"question":"What is the equivalent of DATE_FORMAT in PostgreSQL?","answer":"TO_CHAR, with different codes: TO_CHAR(ts, 'YYYY-MM') for the same output as DATE_FORMAT(ts, '%Y-%m')."}],"related":["to-char","extract","now"],"novel_uses":[{"body":"DATE_FORMAT(at, '%H') buckets every timestamp into its hour slot, so grouping across weeks answers when users are actually active. Add %i for a finer grid when the hour is too coarse.","sql":"SELECT DATE_FORMAT(at, '%H') AS hour_slot, COUNT(*) AS events\nFROM events\nGROUP BY 1\nORDER BY 1;"},{"body":"%j counts January 1 as 001, so a ratio against the year's length gives percent-of-year figures for proration and quota burn-down. Pair it with %v and %x when the unit is the ISO week instead.","sql":"SELECT CURDATE() AS today,\n       DATE_FORMAT(CURDATE(), '%j') AS day_of_year;"}]},"source_url":"https://sqlly.app/sql-functions/date-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-format-codes","corpus":"sql-functions","engine":null,"language":"en","title":"SQL date format codes reference","description":"The same output in each engine's mask language: %Y-%m-%d vs YYYY-MM-DD vs yyyy-MM-dd. A cross-reference table for TO_CHAR, DATE_FORMAT, strftime and FORMAT.","body":{"slug":"date-format-codes","name":"Format codes","h1":"SQL date format codes reference","category":"datetime","lede":"Every engine has its own mask language for the same idea; this maps the common patterns between TO_CHAR, DATE_FORMAT, STRFTIME and FORMAT.","syntax":"TO_CHAR(d, 'YYYY-MM-DD')  |  DATE_FORMAT(d, '%Y-%m-%d')","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":"FORMAT 'yyyy-MM-dd' / CONVERT styles"},{"engine_slug":"postgresql","status":"yes","note":"to_char 'YYYY-MM-DD'"},{"engine_slug":"mysql","status":"yes","note":"DATE_FORMAT '%Y-%m-%d'"},{"engine_slug":"sqlite","status":"yes","note":"strftime '%Y-%m-%d'"},{"engine_slug":"oracle","status":"yes","note":"TO_CHAR 'YYYY-MM-DD'"}],"gotchas":["Year-month-day: PostgreSQL/Oracle 'YYYY-MM-DD', MySQL/SQLite '%Y-%m-%d', SQL Server FORMAT 'yyyy-MM-dd' or CONVERT style 23 (date only; style 120 adds the time and 112 drops the dashes).","Weekday and month names: to_char 'fmDay, DD fmMonth', DATE_FORMAT '%W %d %M', FORMAT 'dddd, dd MMMM'; MySQL (lc_time_names) and SQL Server (session language or culture argument) localize them. PostgreSQL prints English for plain Day and Month and needs the TM prefix (TMDay, TMMonth) for localized names. SQLite has no name codes.","Minutes are the classic trap: MySQL uses %i (its %M is the month name), SQLite uses %M, PostgreSQL and Oracle use MI (MM is the month), and SQL Server FORMAT uses mm (MM is the month)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_char(now(), 'YYYY-MM-DD HH24:MI:SS');"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d %H:%M:%S', 'now');"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm:ss');"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') FROM dual;"}],"faqs":[{"question":"Why do the mask codes differ so much?","answer":"Each vendor borrowed a different tradition: Oracle's TO_CHAR masks (PostgreSQL copied them), C's strftime percent codes (MySQL and SQLite), and .NET custom format strings (SQL Server FORMAT)."},{"question":"Is there a mask that works everywhere?","answer":"No. Even ISO 'YYYY-MM-DD' needs three spellings. Build a thin formatting helper per engine and keep the business code mask-free."}],"related":["to-char","date-format","strftime","format-date"],"novel_uses":[{"body":"The FX prefix in TO_DATE demands the text match the mask exactly, so '2026-8-1' fails against YYYY-MM-DD instead of slipping through.","sql":"SELECT TO_DATE('2026-8-1', 'fxYYYY-MM-DD') FROM dual;  -- errors: FX demands exact match"},{"body":"MySQL escapes a real percent as %%, so labels can mix the formatted time and a percent sign without the mask eating it.","sql":"SELECT DATE_FORMAT('2026-08-01 14:00:00', '%H%%');  -- 14%"}]},"source_url":"https://sqlly.app/sql-functions/date-format-codes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-from-datetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE() function","description":"Get the date out of a timestamp: DATE() on MySQL and SQLite, CAST AS date on SQL Server, ::date on PostgreSQL, TRUNC(d) on Oracle.","body":{"slug":"date-from-datetime","name":"DATE()","h1":"SQL DATE() function","category":"datetime","lede":"Returns the date component with the time removed, the standard form for grouping timestamps by day and for date-only joins.","syntax":"DATE(ts)  -- MySQL, SQLite  |  CAST(ts AS date)  -- SQL Server  |  ts::date  -- PostgreSQL  |  TRUNC(d)  -- Oracle","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"CAST(ts AS date); no DATE() function"},{"engine_slug":"postgresql","status":"yes","note":"date(ts) works as function-style cast syntax; ts::date is the usual spelling"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"TRUNC(d); Oracle's DATE type already holds a time"}],"gotchas":["Oracle's DATE type has a time inside: TRUNC(d) is not cosmetic, it is what makes equality comparisons hit midnight matches.","On a timestamptz, PostgreSQL's ::date uses the session time zone, so the same instant can fall on different dates in different sessions.","Filtering on DATE(created_at) = '2024-01-15' blocks a plain index on most engines; created_at >= '2024-01-15' AND created_at < '2024-01-16' keeps it. SQL Server is an exception: CAST(col AS date) stays seekable."],"examples":[{"engine_slug":"mysql","sql":"SELECT DATE(created_at) AS day, COUNT(*) FROM orders GROUP BY day;"},{"engine_slug":"postgresql","sql":"SELECT created_at::date AS day, COUNT(*) FROM orders GROUP BY 1;"},{"engine_slug":"sql-server","sql":"SELECT CAST(created_at AS date) AS day, COUNT(*) FROM orders GROUP BY CAST(created_at AS date);"},{"engine_slug":"oracle","sql":"SELECT TRUNC(created_at) AS day, COUNT(*) FROM orders GROUP BY TRUNC(created_at);"},{"engine_slug":"sqlite","sql":"SELECT date(created_at) AS day, COUNT(*) FROM orders GROUP BY date(created_at);"}],"faqs":[{"question":"Is DATE() the same as CAST AS date?","answer":"Same result, engine spelling differs. MySQL and SQLite call it DATE(); SQL Server casts; PostgreSQL casts (date_trunc('day', ts) keeps the timestamp type instead). SQLite's DATE() returns 'YYYY-MM-DD' text."},{"question":"Why is my date-equality join missing rows?","answer":"The column still has a time: 2024-01-15 09:30 is not equal to 2024-01-15. Compare DATE(ts) = DATE(d2) on MySQL and SQLite, CAST(ts AS date) = CAST(d2 AS date) on SQL Server, ts::date = d2::date on PostgreSQL, or use half-open ranges."}],"related":["time-from-datetime","date-trunc","cast"],"novel_uses":[{"body":"A STORED generated column on DATE(created_at) materializes the day once and takes an index, so day-level joins and filters stop recomputing the cast.","sql":"ALTER TABLE orders ADD day_key DATE AS (DATE(created_at)) STORED;\nCREATE INDEX ix_orders_day ON orders (day_key);"},{"body":"On a timestamptz column, AT TIME ZONE 'UTC' before the cast fixes the calendar day: (created_at AT TIME ZONE 'UTC')::date never drifts when a session in another zone runs the same query. On a plain timestamp column, skip the pin: created_at::date is already session-independent, and AT TIME ZONE would turn the value into timestamptz and bring the drift back.","sql":"SELECT (created_at AT TIME ZONE 'UTC')::date AS utc_day FROM events;"}]},"source_url":"https://sqlly.app/sql-functions/date-from-datetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-integer-arithmetic","corpus":"sql-functions","engine":null,"language":"en","title":"SQL date plus integer arithmetic","description":"Oracle and PostgreSQL let you add a bare integer to a date as whole days: where that works, where it silently does math you did not mean, and the safe spellings.","body":{"slug":"date-integer-arithmetic","name":"DATE + N","h1":"SQL date plus integer arithmetic","category":"datetime","lede":"In Oracle and PostgreSQL, date + integer adds exactly that many days; the other engines reject or misread it.","syntax":"date + n  |  date - n  |  date + n/24","return_type":"date / timestamp","support":[{"engine_slug":"sql-server","status":"partial","note":"datetime + 7 adds days; date + 7 is an error; use DATEADD(DAY, n, d)"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"'2026-01-01' + 5 is numeric addition, use DATE_ADD"},{"engine_slug":"sqlite","status":"no","note":"needs modifiers: date(d, '+5 days')"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL is the trap: '2026-08-01' + 7 converts the string to the number 2026 and returns 2033, and DATE '2026-08-01' + 7 returns the number 20260808. Use DATE_ADD or + INTERVAL 7 DAY there.","Fractions scale by day in Oracle: d + 1/24 is one hour later, d + 7/1440 is seven minutes. PostgreSQL needs intervals for that: d + INTERVAL '7 minutes'.","PostgreSQL's date + int returns a date; timestamp + int is rejected; cast or use intervals to avoid confusion."],"examples":[{"engine_slug":"oracle","sql":"SELECT SYSDATE + 7 FROM dual;  -- one week out"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-08-01' + 7;  -- 2026-08-08"},{"engine_slug":"oracle","sql":"SELECT SYSDATE + 3/24 FROM dual;  -- three hours out"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(DAY, 7, CAST('2026-08-01' AS date));  -- 2026-08-08"}],"faqs":[{"question":"Is date + 7 portable?","answer":"No. It is right on Oracle and PostgreSQL, a type error on SQL Server date columns (datetime accepts it), and a silent numeric add in MySQL and SQLite. Portable code spells out DATEADD, INTERVAL or modifiers per engine."},{"question":"How do I add hours on PostgreSQL?","answer":"Not with an integer: ts + INTERVAL '3 hours'. date + int is days-only."}],"related":["dateadd","adddate","interval-arithmetic","interval-literal"],"novel_uses":[{"body":"Subtract a fixed anchor date to store a date as one integer and add the anchor back to reconstruct it. The keys sort chronologically and diff in one subtraction.","sql":"SELECT DATE '2026-08-01' - DATE '2000-01-01';  -- days since the anchor"},{"body":"PostgreSQL's ISODOW numbers Monday 1 through Sunday 7, so subtracting ISODOW minus one lands on the week's Monday with no CASE table.","sql":"SELECT CURRENT_DATE - (EXTRACT(ISODOW FROM CURRENT_DATE)::int - 1);"}]},"source_url":"https://sqlly.app/sql-functions/date-integer-arithmetic","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-literal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL date literal","description":"Typed date literals like DATE '2024-01-15' and TIMESTAMP '2024-01-15 09:30:00': standard syntax that works on PostgreSQL, MySQL and Oracle but not on SQL Server.","body":{"slug":"date-literal","name":"DATE / TIMESTAMP literals","h1":"SQL date literal","category":"datetime","lede":"Returns a typed date value straight from SQL text. DATE '...' and TIMESTAMP '...' skip the implicit string-to-date conversion, but the text inside still follows the engine's date rules: on PostgreSQL, DATE '01/02/2024' reads as January 2 under DateStyle MDY and February 1 under DMY, so write ISO YYYY-MM-DD.","syntax":"DATE '2024-01-15'  |  TIMESTAMP '2024-01-15 09:30:00'  |  {d '2024-01-15'}  -- ODBC escape, SQL Server","return_type":"date / timestamp","support":[{"engine_slug":"sql-server","status":"partial","note":"no typed DATE literal; ODBC escapes or unambiguous strings"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"plain text strings serve as dates; no typed literal"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server rejects DATE '2024-01-15'. For the legacy datetime type even '2024-01-02' reads as February 1 under SET DATEFORMAT dmy; 'YYYYMMDD' and 'YYYY-MM-DDThh:mm:ss' parse the same under every setting.","Oracle's DATE literal still carries the midnight time; TIMESTAMP '...' is the literal that keeps sub-second fields.","MySQL accepts both the standard typed literal and ODBC escapes like {d '2024-01-15'}. SQLite has no typed literal at all: a bare SELECT DATE '2024-01-15' fails with no such column: DATE, while inside a WHERE clause or with an alias the same text is a syntax error near the string. Dates are plain text."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM orders\nWHERE created_at >= DATE '2024-01-01';"},{"engine_slug":"oracle","sql":"SELECT * FROM orders\nWHERE created_at >= TIMESTAMP '2024-01-01 00:00:00';"},{"engine_slug":"sql-server","sql":"SELECT * FROM orders\nWHERE created_at >= '20240101';"},{"engine_slug":"mysql","sql":"SELECT * FROM orders\nWHERE created_at >= DATE '2024-01-01';"}],"faqs":[{"question":"Why does SQL Server prefer 20240101 over dashes?","answer":"Language and DATEFORMAT settings make 01-02-2024 ambiguous: it flips between January 2 and February 1. YYYYMMDD parses the same under every setting, for every date type."},{"question":"Are date literals portable?","answer":"DATE 'YYYY-MM-DD' works on PostgreSQL, MySQL and Oracle; SQL Server and SQLite need string or ODBC-escape stand-ins."}],"related":["cast","convert-style","to-date"],"novel_uses":[{"body":"PostgreSQL accepts 'infinity' and '-infinity' as date and timestamp values, so open-ended validity ranges store a real sentinel that sorts last and compares correctly.","sql":"SELECT * FROM subscriptions WHERE canceled_at = TIMESTAMP 'infinity';"},{"body":"The {d ...} escape has siblings: {ts '2024-01-01 09:30:00'} carries a time and works on SQL Server and MySQL, typed and setting-proof like the date escape.","sql":"SELECT * FROM orders WHERE created_at >= {ts '2024-01-01 00:00:00'};"},{"body":"'today', 'yesterday', 'tomorrow' and 'epoch' all read as typed values, handy in ad-hoc queries. They convert when the statement text is parsed, so a long-lived prepared statement keeps the day it was parsed with.","sql":"SELECT TIMESTAMP 'today', TIMESTAMP 'yesterday', TIMESTAMP 'tomorrow', TIMESTAMP 'epoch';"}]},"source_url":"https://sqlly.app/sql-functions/date-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-literal-ansi","corpus":"sql-functions","engine":null,"language":"en","title":"ANSI SQL DATE literal","description":"The ANSI typed literal DATE '2026-08-01': supported by PostgreSQL, MySQL and Oracle, its format rules, and what SQL Server and SQLite use instead.","body":{"slug":"date-literal-ansi","name":"DATE literal","h1":"ANSI SQL DATE literal","category":"datetime","lede":"DATE 'YYYY-MM-DD' builds a date constant without TO_DATE, CAST or implicit string parsing ambiguity.","syntax":"DATE 'YYYY-MM-DD'","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"no typed literal; { d '2026-08-01' } or CAST('2026-08-01' AS date)"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no typed literals; date('2026-08-01')"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Write the text as year-month-day. All three accept DATE '2026-8-1' without padding. MySQL and Oracle reject anything else, including '08/01/2026' and a time part (DATE '2026-08-01 10:00' raises error 1525 and ORA-01861). PostgreSQL reads '08/01/2026' by its DateStyle and silently drops a time part.","Time zones never enter it: it is a bare date. TIMESTAMP '2026-08-01 12:00:00' is the parallel form for datetimes, with engine-specific zone rules.","SQLite has no typed literals: SELECT DATE '2026-08-01' fails with 'no such column: DATE'. Use date('2026-08-01') or the bare ISO string."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM orders WHERE ordered_on >= DATE '2026-08-01';"},{"engine_slug":"oracle","sql":"SELECT * FROM orders WHERE ordered_on >= DATE '2026-08-01';"},{"engine_slug":"mysql","sql":"SELECT DATE '2026-08-01' + INTERVAL 7 DAY;"},{"engine_slug":"sql-server","sql":"SELECT CAST('2026-08-01' AS date);"}],"faqs":[{"question":"Why prefer DATE '2026-08-01' over a bare string?","answer":"Session settings cannot reinterpret it. On Oracle a bare '2026-08-01' is parsed with NLS_DATE_FORMAT and fails under the default DD-MON-RR mask; DATE '2026-08-01' always means August 1. PostgreSQL reads ISO strings the same way under every DateStyle, so there the literal mostly documents the type."},{"question":"Does SQL Server support it?","answer":"No. SELECT DATE '2026-08-01' fails with Invalid column name 'DATE'. Use the ODBC escape { d '2026-08-01' } (returns datetime) or CAST('2026-08-01' AS date) (returns date)."}],"related":["to-date","cast","current-date","interval-literal"],"novel_uses":[{"body":"Keep the column side of the predicate untouched and put the typed literal on the constant side, so range scans and partition pruning survive.","sql":"SELECT * FROM orders WHERE ordered_on >= DATE '2026-08-01' AND ordered_on < DATE '2026-08-02';"},{"body":"PostgreSQL reads an offset inside the typed literal, so test data can pin exact instants that compare identically on every server; the displayed clock still follows the session TimeZone.","sql":"SELECT TIMESTAMPTZ '2026-08-01 12:00:00+02:00';"}]},"source_url":"https://sqlly.app/sql-functions/date-literal-ansi","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-literal-typed","corpus":"sql-functions","engine":null,"language":"en","title":"SQL typed date literals","description":"The typed-literal form DATE '2026-01-31', TIMESTAMP '...' and TIME '...': which engines accept the standard spelling, and what to write where it does not parse.","body":{"slug":"date-literal-typed","name":"Date literals","h1":"SQL typed date literals","category":"conversion","lede":"DATE '2026-01-31' is a date, not a string to be converted. The standard spelling is immune to session language settings, where it is supported at all.","syntax":"DATE 'yyyy-mm-dd'  |  TIMESTAMP 'yyyy-mm-dd hh:mm:ss'  |  TIME 'hh:mm:ss'","return_type":"date, timestamp or time","support":[{"engine_slug":"sql-server","status":"no","note":"no DATE literal; CONVERT or CAST a string, or the ODBC escape { d '2026-01-31' }"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no typed literals; ISO-8601 text compares correctly by itself"},{"engine_slug":"oracle","status":"yes","note":"DATE and TIMESTAMP literals; Oracle's DATE also holds a time of day"}],"gotchas":["SQL Server rejects DATE '...' (it reads DATE as a column name). Use CAST('2026-01-31' AS date), or the ODBC escape { d '2026-01-31' }, which SQL Server itself parses and which returns datetime.","On Oracle the literal must be ISO yyyy-mm-dd whatever NLS_DATE_FORMAT says, while a bare string is read through NLS_DATE_FORMAT. On PostgreSQL DATE '...' parses its string under DateStyle exactly like a bare string (DATE '31/01/2026' works only with DateStyle DMY), so write ISO yyyy-mm-dd, which every DateStyle reads the same. On SQL Server a string cast to datetime depends on DATEFORMAT and the session language, while CAST('2026-01-31' AS date) does not.","On Oracle, DATE '2026-01-31' means midnight, and DATE columns often carry a time. WHERE order_date = DATE '2026-01-31' misses every row stamped after 00:00:00; use a half-open range."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM orders\nWHERE order_date >= DATE '2026-01-01';"},{"engine_slug":"oracle","sql":"SELECT * FROM orders\nWHERE order_date >= DATE '2026-01-01';"},{"engine_slug":"mysql","sql":"SELECT TIMESTAMP '2026-01-31 10:00:00' AS ts;"}],"faqs":[{"question":"Why prefer DATE '...' over a quoted string?","answer":"It states the type, so the value is a date from the start instead of text the engine has to coerce. On Oracle it also fixes the format, because a bare string is converted through NLS_DATE_FORMAT. On PostgreSQL and MySQL the literal parses its string just as a cast would, so what keeps results stable across sessions there is writing ISO yyyy-mm-dd."},{"question":"Does SQLite need the literal?","answer":"No. SQLite stores dates as ISO-8601 text (or julian day numbers), so '2026-01-31' compared against a date column is already correct and index-friendly."}],"related":["cast","to-date","current-date","str-to-date"],"novel_uses":[{"body":"A bare '2026-01-31' inside VALUES types the derived column as text on PostgreSQL, so a later join to a date column fails with operator does not exist: date = text. Writing DATE '2026-01-31' pins the column as a real date from the start.","sql":"SELECT t.d, o.total FROM (VALUES (DATE '2026-01-31'), (DATE '2026-02-01')) AS t(d) JOIN orders o ON o.order_date = t.d;"},{"body":"Cast the timestamp to its clock part first: CAST(clock_in AS TIME) < TIME '06:00:00' finds early starts no matter which date they happened on. Comparing the timestamp directly does not work, because PostgreSQL rejects timestamp < time and MySQL turns the TIME into today's datetime. Handy for shift and SLA checks where the date is noise.","sql":"SELECT name FROM shifts WHERE CAST(clock_in AS TIME) < TIME '06:00:00';"}]},"source_url":"https://sqlly.app/sql-functions/date-literal-typed","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-minus-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL date minus date","description":"Subtracting two dates: whole days on PostgreSQL and Oracle, boundary-counting DATEDIFF or string coercion elsewhere, with the pitfalls of each.","body":{"slug":"date-minus-date","name":"DATE - DATE","h1":"SQL date minus date","category":"datetime","lede":"Plain date subtraction gives an integer day count where it is supported, the cleanest way to answer 'how many days apart'.","syntax":"date1 - date2","return_type":"integer (days)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(DAY, a, b); counts midnight boundaries"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"DATEDIFF(a, b); genuinely whole days here"},{"engine_slug":"sqlite","status":"partial","note":"JULIANDAY(a) - JULIANDAY(b)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server's DATEDIFF(DAY, '2026-07-31 23:00', '2026-08-01 01:00') is 1 (one midnight crossed), even though only two hours elapsed.","Oracle DATE - DATE returns a NUMBER with a fraction if times are present; wrap in TRUNC or CAST for whole days.","MySQL's minus sign does not count days: DATE '2026-08-01' - DATE '2026-07-01' returns 100 (20260801 - 20260701). Use DATEDIFF there, and JULIANDAY on SQLite; the plain string form is numeric on SQLite too but returns 0 for '2026-08-01' - '2026-07-01' (it subtracts the year numbers)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT DATE '2026-08-01' - DATE '2026-07-01';  -- 31"},{"engine_slug":"oracle","sql":"SELECT TRUNC(DATE '2026-08-01') - TRUNC(DATE '2026-07-01') FROM dual;  -- 31"},{"engine_slug":"mysql","sql":"SELECT DATEDIFF('2026-08-01', '2026-07-01');  -- 31 (days only)"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(DAY, '2026-07-01', '2026-08-01');  -- 31"},{"engine_slug":"sqlite","sql":"SELECT CAST(julianday('2026-08-01') - julianday('2026-07-01') AS INTEGER);  -- 31"}],"faqs":[{"question":"Is date - date the same as DATEDIFF?","answer":"On PostgreSQL and Oracle yes, in days. On SQL Server DATEDIFF counts boundaries, so hours around midnight change the answer, and date - date is an operand type error."},{"question":"How do I get business days between dates?","answer":"None of the engines do it natively: count weekdays with a recursive CTE, a calendar table, or generate_series + EXTRACT(ISODOW) filters on PostgreSQL."}],"related":["datediff","timestamp-difference","julianday","days-in-month"],"novel_uses":[{"body":"Integer-divide the day count from a known Monday for a stable week number that works as a join and partition key. PostgreSQL truncates the division; Oracle needs TRUNC or FLOOR around it.","sql":"SELECT (DATE '2026-08-15' - DATE '2026-01-05') / 7;  -- 31 (partial week floors)"},{"body":"On Oracle DATE columns the difference is a NUMBER of days, so AVG and SUM treat it like any measure and feed reports without casts.","sql":"SELECT AVG(shipped - ordered) AS avg_cycle_days FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/date-minus-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-part","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE_PART function","description":"PostgreSQL's date_part('field', ts) is the legacy spelling of EXTRACT: same fields, function-style call, kept for compatibility with old code.","body":{"slug":"date-part","name":"DATE_PART","h1":"SQL DATE_PART function","category":"datetime","lede":"Returns one date field as double precision from a two-argument call: date_part('year', ts) gives the same value as EXTRACT(year FROM ts).","syntax":"DATE_PART('year', ts)  |  DATE_PART('dow', d)  |  EXTRACT(year FROM ts)  -- standard equivalent","return_type":"double precision","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(year, ts) is the same idea, different argument order"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"EXTRACT or the YEAR / MONTH shorthands"},{"engine_slug":"sqlite","status":"partial","note":"strftime formats"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT"}],"gotchas":["date_part returns double precision; since PostgreSQL 14, EXTRACT returns numeric. The two can differ in the last digits of fractional fields such as epoch and julian.","The field is a text argument, so it can come from a parameter or column: date_part($1, ts) works where EXTRACT needs the field written into the SQL.","It accepts the same fields as EXTRACT (dow, isodow, doy, epoch, isoyear); only the call shape and return type differ."],"examples":[{"engine_slug":"postgresql","sql":"SELECT date_part('year', created_at) AS yr FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT date_part('isodow', d) AS weekday FROM events;"},{"engine_slug":"postgresql","sql":"SELECT CAST(date_part('hour', ts) AS int) AS hr FROM events;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(year, created_at) AS yr FROM orders;"},{"engine_slug":"mysql","sql":"SELECT EXTRACT(year FROM created_at) AS yr, MONTH(created_at) AS mon FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%Y', created_at) AS INTEGER) AS yr FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(year FROM created_at) AS yr FROM orders;"}],"faqs":[{"question":"Should I use date_part or EXTRACT?","answer":"EXTRACT. It is the standard, works on MySQL and Oracle too, and returns exact numeric on PostgreSQL 14+. date_part is useful when the field name is a parameter."},{"question":"Why is date_part a double?","answer":"Fields like epoch and second carry fractions, and date_part predates the numeric return type EXTRACT got in PostgreSQL 14. Cast when you need integers."}],"related":["extract","extract-epoch","date-trunc"],"novel_uses":[{"body":"date_part('decade', d) is the year divided by ten, so 1994 gives 199 and multiplying back by ten yields the 1990s bucket label.","sql":"SELECT date_part('decade', d) * 10 AS decade FROM events;"},{"body":"date_part('epoch', interval '12:30') totals a span as 45000, the quick route from a clock-shaped interval to a number for arithmetic or APIs.","sql":"SELECT date_part('epoch', interval '12:30') AS secs;"}]},"source_url":"https://sqlly.app/sql-functions/date-part","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-sub","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE_SUB function","description":"DATE_SUB and SUBDATE in MySQL: subtract days or an INTERVAL, and the negative-DATEADD, minus-interval and modifier equivalents elsewhere.","body":{"slug":"date-sub","name":"DATE_SUB / SUBDATE","h1":"SQL DATE_SUB function","category":"datetime","lede":"Subtracts an INTERVAL from a date or datetime. SUBDATE is its alias and also accepts a bare number of days.","syntax":"DATE_SUB(date, INTERVAL n unit)  |  SUBDATE(date, days)","return_type":"date / datetime","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(day, -7, d); pass a negative number"},{"engine_slug":"postgresql","status":"partial","note":"d - INTERVAL '7 days'"},{"engine_slug":"mysql","status":"partial","note":null},{"engine_slug":"sqlite","status":"yes","note":"date(d, '-7 days')"},{"engine_slug":"oracle","status":"partial","note":"d - 7 or d - INTERVAL '7' DAY"}],"gotchas":["Every engine that lacks DATE_SUB subtracts with a negative: DATEADD(day, -7, d) on SQL Server, d - 7 on Oracle, date(d, '-7 days') on SQLite.","On PostgreSQL, date - integer also subtracts days: DATE '2026-08-10' - 7 gives DATE '2026-08-03'.","SUBDATE with a bare number means days only; wrap units in INTERVAL."],"examples":[{"engine_slug":"mysql","sql":"SELECT DATE_SUB('2026-08-01', INTERVAL 7 DAY);  -- 2026-07-25"},{"engine_slug":"mysql","sql":"SELECT SUBDATE('2026-08-01', 7);  -- 2026-07-25"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(DAY, -7, '2026-08-01');"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-08-01' - INTERVAL '7 days';  -- 2026-07-25 00:00:00"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-01', '-7 days');  -- 2026-07-25"},{"engine_slug":"oracle","sql":"SELECT DATE '2026-08-01' - 7 FROM dual;  -- 2026-07-25"}],"faqs":[{"question":"How do I subtract days in SQL Server?","answer":"There is no DATE_SUB; call DATEADD with a negative value: DATEADD(DAY, -7, d)."},{"question":"Does DATE_SUB handle months?","answer":"Yes, DATE_SUB('2026-03-31', INTERVAL 1 MONTH) gives 2026-02-28, clamping to the month's last day."}],"related":["dateadd","adddate","datediff","date-trunc"],"novel_uses":[{"body":"Subtract the day-of-month minus one days to land on the 1st. The INTERVAL count accepts expressions, so no variable or subquery is needed.","sql":"SELECT DATE_SUB('2026-08-15', INTERVAL DAYOFMONTH('2026-08-15') - 1 DAY);  -- 2026-08-01"},{"body":"WEEKDAY numbers Monday as 0, so subtracting it returns the week's Monday and stays correct on a Monday. Reuse the expression for rolling Monday-to-Sunday report windows.","sql":"SELECT DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY);  -- Monday of this week"},{"body":"Deleting old rows in LIMIT-bounded passes keeps each transaction short and replication lag low, with DATE_SUB fixing the cutoff once per pass.","sql":"DELETE FROM events WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY) LIMIT 1000;"}]},"source_url":"https://sqlly.app/sql-functions/date-sub","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-to-text","corpus":"sql-functions","engine":null,"language":"en","title":"SQL cast date to string","description":"Turning a date into text on each engine: CAST AS CHAR, ::text, TO_CHAR, CONVERT styles and strftime, and which output format each gives you.","body":{"slug":"date-to-text","name":"Date to text","h1":"SQL cast date to string","category":"datetime","lede":"Every engine can stringify a date, but the default shape differs wildly (ISO here, locale there), so pick the explicit formatter when it matters.","syntax":"CAST(d AS varchar)  |  d::text  |  TO_CHAR(d, fmt)  (MySQL: CAST(d AS CHAR))","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":"CONVERT(varchar, d, style) or FORMAT"},{"engine_slug":"postgresql","status":"yes","note":"d::text (DateStyle-shaped) or to_char"},{"engine_slug":"mysql","status":"yes","note":"CAST(d AS CHAR): ISO 'YYYY-MM-DD' for DATE, 'YYYY-MM-DD hh:mm:ss' for DATETIME"},{"engine_slug":"sqlite","status":"yes","note":"values are already text; strftime for other shapes"},{"engine_slug":"oracle","status":"yes","note":"TO_CHAR(d, fmt); NLS_DATE_FORMAT if implicit"}],"gotchas":["Implicit conversion inherits session settings: PostgreSQL's ::text output changes with DateStyle, Oracle's bare conversion with NLS_DATE_FORMAT. Never build keys or comparisons on implicit shapes.","ISO output is safe everywhere when asked for explicitly: to_char(d, 'YYYY-MM-DD'), CONVERT(varchar(10), d, 120), DATE_FORMAT(d, '%Y-%m-%d'), strftime('%Y-%m-%d', d).","SQLite already stores dates as text: 'casting' is a no-op; the work is in strftime masks or keeping the format ISO in the first place."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_char(order_date, 'YYYY-MM-DD') FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(10), order_date, 120) FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(order_date, 'YYYY-MM-DD') FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(order_date, '%Y-%m-%d') FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d', order_date) FROM orders;"}],"faqs":[{"question":"Why does my date column print differently on two servers?","answer":"Session settings: PostgreSQL DateStyle and Oracle NLS_DATE_FORMAT alter implicit output, and SQL Server language changes only the month names in datetime's default style 0 (a date stays ISO). Explicit format masks make output environment-proof."},{"question":"What is the MySQL default shape?","answer":"CAST(datetime AS CHAR) gives 'YYYY-MM-DD hh:mm:ss' whatever the session (DATETIME only; TIMESTAMP shifts with time_zone). Compare SQL Server, where CAST(datetime AS varchar) gives 'Aug  1 2026  2:30PM' (style 0, month name in the session language) while CAST(date AS varchar) gives ISO."}],"related":["cast","convert-style","strftime","date-format-codes"],"novel_uses":[{"body":"PostgreSQL and Oracle pad names and numbers to fixed widths; the FM prefix suppresses the filler, giving labels that line up without post-processing.","sql":"SELECT to_char(DATE '2026-08-01', 'FMDay, FMDD FMMonth');  -- Saturday, 1 August"},{"body":"Oracle's 'J' mask renders a date as its Julian day number, a compact sortable integer for keys and diffs without date subtraction.","sql":"SELECT TO_CHAR(DATE '2026-08-01', 'J') FROM dual;  -- days since 4712 BC"}]},"source_url":"https://sqlly.app/sql-functions/date-to-text","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/date-trunc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE_TRUNC function","description":"Floor a timestamp to day, week or month: DATE_TRUNC in PostgreSQL, DATETRUNC on SQL Server 2022, and the DATEFROMPARTS, DATE_FORMAT, date() and TRUNC stand-ins.","body":{"slug":"date-trunc","name":"DATE_TRUNC","h1":"SQL DATE_TRUNC function","category":"datetime","lede":"Rounds a timestamp down to the start of a day, week, month or year. It is how time series get grouped into one bucket per period.","syntax":"DATE_TRUNC('month', ts)  -- PostgreSQL  |  DATETRUNC(month, ts)  -- SQL Server 2022","return_type":"timestamp / date","support":[{"engine_slug":"sql-server","status":"partial","note":"DATETRUNC from SQL Server 2022; DATEFROMPARTS before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"no DATE_TRUNC; DATE_FORMAT(d, '%Y-%m-01') or arithmetic"},{"engine_slug":"sqlite","status":"partial","note":"date(ts, 'start of month') or strftime('%Y-%m-01', ts)"},{"engine_slug":"oracle","status":"partial","note":"TRUNC(date, 'MM'); 'IW' for ISO weeks, 'YYYY' for years"}],"gotchas":["Week starts differ: PostgreSQL's DATE_TRUNC('week', ts) starts on Monday (ISO). SQL Server's DATETRUNC(week, d) follows SET DATEFIRST, Sunday under us_english; DATETRUNC(iso_week, d) starts Monday.","The pre-2022 SQL Server idiom rebuilds the date: DATEFROMPARTS(YEAR(d), MONTH(d), 1).","MySQL and SQLite get there by formatting: DATE_FORMAT(d, '%Y-%m-01') on MySQL returns a string, and SQLite's date(ts, 'start of month') returns text like every SQLite date.","On PostgreSQL, DATE_TRUNC on a date returns a timestamp (with time zone); cast back with ::date when you want a date."],"examples":[{"engine_slug":"postgresql","sql":"SELECT DATE_TRUNC('month', created_at) AS month,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY 1 ORDER BY 1;"},{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(month, created_at) AS month, COUNT(*) AS orders\nFROM orders\nGROUP BY DATETRUNC(month, created_at);"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%Y-%m-01') AS month, COUNT(*) AS orders\nFROM orders GROUP BY month;"},{"engine_slug":"sqlite","sql":"SELECT date(created_at, 'start of month') AS month,\n       COUNT(*) AS orders\nFROM orders GROUP BY month;"},{"engine_slug":"oracle","sql":"SELECT TRUNC(created_at, 'MM') AS month, COUNT(*) AS orders\nFROM orders\nGROUP BY TRUNC(created_at, 'MM');"}],"faqs":[{"question":"Does SQL Server have DATE_TRUNC?","answer":"SQL Server 2022 added DATETRUNC(month, d). Before that, rebuild the date: DATEFROMPARTS(YEAR(d), MONTH(d), 1) for months, or DATEADD(month, DATEDIFF(month, 0, d), 0), which also works for other units."},{"question":"Why does DATE_TRUNC('week') start on Monday?","answer":"PostgreSQL uses ISO weeks, which start on Monday. SQL Server's DATETRUNC(week) follows DATEFIRST, so the same query can bucket differently per session language. Use DATETRUNC(iso_week, d) or SET DATEFIRST 1 to match PostgreSQL."}],"related":["extract","current-date","to-char"],"novel_uses":[{"body":"DATE_TRUNC has no quarter-hour, but dividing the epoch by 900 seconds, flooring and converting back works for any bucket width: 900 for 15 minutes, 3600 for hours. MySQL's version is FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(ts) / 900) * 900).","sql":"SELECT TO_TIMESTAMP(FLOOR(EXTRACT(epoch FROM ts) / 900) * 900) AS quarter_hour,\n       COUNT(*) AS events\nFROM events\nGROUP BY 1\nORDER BY 1;"},{"body":"Facts arrive at odd timestamps while reference tables hold one row per day. Truncating the event time to the same boundary turns both sides into comparable keys, and the join does the rest. The truncation on the event side blocks an index-only lookup there, so pre-compute the bucket column when the table is huge.","sql":"SELECT e.at, r.rate\nFROM events e\nJOIN daily_rates r ON DATE_TRUNC('day', e.at) = r.day;"}]},"source_url":"https://sqlly.app/sql-functions/date-trunc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dateadd","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATEADD function","description":"Add days, months or years to a date in SQL Server (DATEADD), MySQL (DATE_ADD), PostgreSQL (interval), SQLite (modifiers) and Oracle (+ n / ADD_MONTHS).","body":{"slug":"dateadd","name":"DATEADD / DATE_ADD","h1":"SQL DATEADD function","category":"datetime","lede":"Shifts a date or timestamp by an interval. SQL Server and MySQL have a function with unit names; PostgreSQL, SQLite and Oracle add intervals or modifiers instead.","syntax":"DATEADD(month, 1, d)  -- SQL Server  |  DATE_ADD(d, INTERVAL 1 MONTH)  -- MySQL  |  d + INTERVAL '1 month'","return_type":"date / timestamp","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"no DATEADD; date + interval '1 month'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no DATEADD; modifiers such as date(d, '+1 month')"},{"engine_slug":"oracle","status":"partial","note":"date + n adds days; ADD_MONTHS for months; INTERVAL literals for the rest"}],"gotchas":["Adding one month to January 31: SQL Server, MySQL and PostgreSQL clamp to February 28 (29 in a leap year). SQLite normalizes the impossible February 31 to March 3 unless you add the 'floor' modifier (3.46+).","Oracle has two behaviours. ADD_MONTHS(DATE '2026-01-31', 1) clamps to February 28, and ADD_MONTHS from a month's last day lands on the target's last day, so February 28 plus one month is March 31. DATE '2026-01-31' + INTERVAL '1' MONTH raises ORA-01839 instead.","Oracle adds days with plain +: d + 1 is tomorrow and d + 1/24 is an hour later.","SQLite chains modifiers left to right: date(created_at, 'start of month', '+1 month', '-1 day') is the last day of the month."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(day, 30, order_date) AS due_date\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD(order_date, INTERVAL 30 DAY) AS due_date FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT order_date + INTERVAL '30 days' AS due_date FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT date(order_date, '+30 days') AS due_date FROM orders;"},{"engine_slug":"oracle","sql":"SELECT order_date + 30 AS due_date,\n       ADD_MONTHS(order_date, 1) AS next_month\nFROM orders;"}],"faqs":[{"question":"What happens when I add a month to January 31?","answer":"SQL Server, MySQL, PostgreSQL and Oracle's ADD_MONTHS clamp to the last day of February. Oracle's + INTERVAL '1' MONTH raises ORA-01839 instead, and SQLite returns March 3 (or March 2 in a leap year) unless you add the 'floor' modifier."},{"question":"How do I add hours to a timestamp?","answer":"SQL Server: DATEADD(hour, 3, ts). MySQL: DATE_ADD(ts, INTERVAL 3 HOUR). PostgreSQL: ts + INTERVAL '3 hours'. SQLite: datetime(ts, '+3 hours'). Oracle: ts + INTERVAL '3' HOUR, or d + 3/24 for a DATE."}],"related":["datediff","date-trunc","months-between"],"novel_uses":[{"body":"Adding a month to a clamped date walks off the month end: January 31 plus one month is February 28, plus one more is March 28, and billing has quietly moved off the 31st for good. Compute every due date from the original anchor in one step; PostgreSQL's make_interval(months => n) does it cleanly.","sql":"SELECT anchor + make_interval(months => n) AS due_date\nFROM billing_schedule;"},{"body":"Trading and hospitality days rarely run midnight to midnight. Shift the timestamp back by the offset, truncate to the date, shift forward again, and events after 5 PM group into the business day they belong to.","sql":"SELECT DATEADD(hour, 5, CAST(DATEADD(hour, -5, ts) AS date)) AS biz_day\nFROM trades;"}]},"source_url":"https://sqlly.app/sql-functions/dateadd","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dateadd-truncation-trick","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATEADD DATEDIFF truncation trick","description":"The pre-2022 SQL Server truncation idiom DATEADD(DAY, DATEDIFF(DAY, 0, d), 0): why it works, its overflow edge, and why DATETRUNC replaced it.","body":{"slug":"dateadd-truncation-trick","name":"DATEADD/DATEDIFF trick","h1":"SQL DATEADD DATEDIFF truncation trick","category":"datetime","lede":"Counts units from a base date and re-adds them, flooring the timestamp: the classic SQL Server truncation before DATETRUNC existed.","syntax":"DATEADD(unit, DATEDIFF(unit, 0, date), 0)","return_type":"datetime","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["It works because 0 is SQL Server's epoch date 1900-01-01: DATEDIFF counts midnights since then, DATEADD walks them back; the remainder is discarded, i.e. truncation.","The month form DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) truncates to the month; QUARTER and YEAR work the same way.","The result is always datetime, because the 0 is read as a datetime, so a datetime2 input is rounded to datetime's precision before truncation: 2026-08-15 14:59:59.9999999 becomes 15:00 under the HOUR form, where DATETRUNC(HOUR, ...) gives 14:00. datetime2 values before 1753 fail with error 242. Small units overflow: DATEDIFF(SECOND, 0, GETDATE()) exceeds int and fails with error 535.","The WEEK form ignores DATEFIRST and returns Mondays (1900-01-01 was a Monday), but DATEDIFF(WEEK) counts Sunday boundaries, so a Sunday rounds forward: 2026-08-02 becomes 2026-08-03."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(DAY, DATEDIFF(DAY, 0, order_date), 0) AS day_only FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, order_date), 0) AS month_start FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(DAY, order_date) FROM orders;  -- 2022+ spelling"}],"faqs":[{"question":"Why does the trick use 0 instead of '1900-01-01'?","answer":"0 casts to the datetime epoch automatically; it is shorter and avoids string parsing. Same value, same result."},{"question":"Should I keep using it in new code?","answer":"On SQL Server 2022+ use DATETRUNC: clearer, and it handles week starts via DATEFIRST without off-by-one corrections."}],"related":["dateadd","datediff","datetrunc","trunc-date"],"novel_uses":[{"body":"Divide the minute count by the slot width before re-adding, and the epoch trick floors to any minute multiple for datetimes from 1900-01-01 on, with no DATETRUNC. For earlier values integer division truncates toward zero, so the slot rounds forward. DATEDIFF(MINUTE) stays in int range only until about 5983-01-24, so later dates fail with error 535.","sql":"SELECT DATEADD(MINUTE, (DATEDIFF(MINUTE, 0, order_date) / 5) * 5, 0) FROM orders;"},{"body":"The divided count itself is a stable integer key for datetimes from 1900-01-01 on: group or join on it directly and skip datetime comparisons entirely.","sql":"SELECT DATEDIFF(MINUTE, 0, order_date) / 5 AS slot, COUNT(*) FROM orders GROUP BY DATEDIFF(MINUTE, 0, order_date) / 5;"}]},"source_url":"https://sqlly.app/sql-functions/dateadd-truncation-trick","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datediff","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATEDIFF function","description":"Date difference in SQL: DATEDIFF unit traps on SQL Server, day-only DATEDIFF in MySQL, date subtraction in PostgreSQL, SQLite and Oracle.","body":{"slug":"datediff","name":"DATEDIFF","h1":"SQL DATEDIFF function","category":"datetime","lede":"Returns the amount of time between two dates. The name is shared by SQL Server and MySQL but the semantics are completely different, and the other engines subtract instead.","syntax":"DATEDIFF(day, start, end)  -- SQL Server  |  DATEDIFF(end, start)  -- MySQL, days","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"no DATEDIFF; date - date gives days, age() gives years, months and days"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no DATEDIFF; julianday(end) - julianday(start) gives days"},{"engine_slug":"oracle","status":"partial","note":"date - date gives days as a number; MONTHS_BETWEEN for months"}],"gotchas":["SQL Server's DATEDIFF counts unit boundaries crossed, not elapsed time: DATEDIFF(year, '2025-12-31', '2026-01-01') is 1.","MySQL's DATEDIFF only does whole days; TIMESTAMPDIFF(month, a, b) is the unit-aware version.","Argument order differs: SQL Server is (unit, start, end); MySQL is (end, start). Subtraction on PostgreSQL, SQLite and Oracle is end - start.","On PostgreSQL, date - date is an integer number of days, but timestamp - timestamp is an interval such as '2 days 03:00:00'. Use EXTRACT(epoch FROM b - a) for seconds."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(day, order_date, ship_date) AS days_to_ship\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATEDIFF(ship_date, order_date) AS days_to_ship FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT ship_date - order_date AS days_to_ship FROM orders;"},{"engine_slug":"oracle","sql":"SELECT ship_date - order_date AS days_to_ship FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT julianday(ship_date) - julianday(order_date) AS days_to_ship\nFROM orders;"}],"faqs":[{"question":"Why does DATEDIFF(year, ...) say 1 for December 31 to January 1?","answer":"SQL Server counts boundaries crossed, not elapsed time. One year boundary lies between the two dates, so the answer is 1. For elapsed time, take DATEDIFF in a smaller unit (days, or seconds) and divide."},{"question":"How do I get the difference in months?","answer":"SQL Server: DATEDIFF(month, a, b). MySQL: TIMESTAMPDIFF(month, a, b). PostgreSQL: date_part('year', age(b, a)) * 12 + date_part('month', age(b, a)). Oracle: MONTHS_BETWEEN(b, a)."}],"related":["dateadd","months-between","now"],"novel_uses":[{"body":"DATEDIFF(year, dob, today) counts New Year boundaries, so a baby born on December 31 is 1 year old on January 1. Subtract one when this year's birthday has not happened yet; MySQL's TIMESTAMPDIFF(year, dob, CURDATE()) already does the whole calculation.","sql":"SELECT name,\n       DATEDIFF(year, dob, CAST(GETDATE() AS date))\n       - CASE WHEN DATEADD(year, DATEDIFF(year, dob, CAST(GETDATE() AS date)), dob)\n                   > CAST(GETDATE() AS date) THEN 1 ELSE 0 END AS age\nFROM people;"},{"body":"Flag each day whose gap from the previous login is more than one, running-sum the flags, and every consecutive run shares a streak number; counting each run's rows and taking the max gives the longest streak. DATEDIFF does the classification, the window sum does the grouping.","sql":"WITH days AS (\n  SELECT user_id, login_day,\n         LAG(login_day) OVER (PARTITION BY user_id ORDER BY login_day) AS prev_day\n  FROM (SELECT DISTINCT user_id, CAST(login_at AS date) AS login_day FROM logins) d\n), flagged AS (\n  SELECT user_id, login_day,\n         SUM(CASE WHEN DATEDIFF(day, prev_day, login_day) = 1 THEN 0 ELSE 1 END)\n             OVER (PARTITION BY user_id ORDER BY login_day) AS streak_no\n  FROM days\n)\nSELECT user_id, MAX(streak_len) AS longest_streak\nFROM (\n  SELECT user_id, streak_no, COUNT(*) AS streak_len\n  FROM flagged GROUP BY user_id, streak_no\n) s\nGROUP BY user_id;"}]},"source_url":"https://sqlly.app/sql-functions/datediff","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datediff-big","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATEDIFF_BIG function","description":"DATEDIFF_BIG in SQL Server: the same boundary-counting semantics as DATEDIFF but returning bigint, so millisecond diffs on long spans do not overflow.","body":{"slug":"datediff-big","name":"DATEDIFF_BIG","h1":"SQL DATEDIFF_BIG function","category":"datetime","lede":"Counts unit boundaries between two datetimes like DATEDIFF, but returns a bigint for every unit, so microsecond and nanosecond spans no longer overflow.","syntax":"DATEDIFF_BIG(unit, startdate, enddate)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(EPOCH FROM b - a) never overflows"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"partial","note":"JULIANDAY differences are floats"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["DATEDIFF(MILLISECOND, ...) overflows int beyond about 24.8 days of span; DATEDIFF_BIG handles 292 million years of milliseconds.","It keeps DATEDIFF's semantics exactly: it counts boundaries, not elapsed units. DATEDIFF_BIG(YEAR, '2025-12-31', '2026-01-01') is still 1.","A bigint holds about 292 years of nanoseconds, so the inputs limit precision more than the result does: datetime stores 1/300-second ticks, and nanosecond diffs only mean something on datetime2, which resolves 100 nanoseconds at most (datetime2(9) is rejected)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEDIFF_BIG(MILLISECOND, '2026-01-01', '2026-03-01');  -- 5097600000"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF_BIG(NANOSECOND, started, finished) FROM traces;"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(EPOCH FROM TIMESTAMP '2026-03-01' - TIMESTAMP '2026-01-01');  -- 5097600"},{"engine_slug":"sqlite","sql":"SELECT julianday('2026-03-01') - julianday('2026-01-01');  -- 59.0"}],"faqs":[{"question":"When do I actually need DATEDIFF_BIG?","answer":"When the unit is small and the span is large: milliseconds beyond about 24.8 days, microseconds beyond about 35 minutes, nanoseconds beyond about 2.1 seconds. Plain DATEDIFF fails there with error 535 instead of wrapping."},{"question":"Which SQL Server version added it?","answer":"SQL Server 2016. On older versions, diff in a coarser unit and scale it: DATEDIFF(SECOND, a, b) * CAST(1000 AS bigint) for approximate milliseconds."}],"related":["datediff","timestampdiff","extract-epoch"],"novel_uses":[{"body":"The DATEADD/DATEDIFF truncation trick overflows int when the unit is SECOND and the base is 0, because 1900 sits about 4.0 billion seconds away. DATEDIFF_BIG fixes the diff, but DATEADD's number argument is still int, so count in MINUTE instead: minutes since 1900 stay under the int limit for about four thousand years, and the same shape builds 15-minute buckets.","sql":"SELECT DATEADD(MINUTE, (DATEDIFF_BIG(MINUTE, 0, SYSDATETIME()) / 15) * 15, 0);"},{"body":"Short spans diff fine in int; the overflow usually arrives when you total thousands of them, because SUM returns int for int input. Cast each diff to bigint before summing.","sql":"SELECT SUM(CAST(DATEDIFF(SECOND, started, ended) AS bigint)) FROM jobs;"}]},"source_url":"https://sqlly.app/sql-functions/datediff-big","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datefirst","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SET DATEFIRST","description":"SET DATEFIRST in SQL Server: it renumbers weekdays for DATEPART(WEEKDAY) and DATETRUNC(WEEK), breaking comparisons written for a different first day.","body":{"slug":"datefirst","name":"SET DATEFIRST","h1":"SQL SET DATEFIRST","category":"datetime","lede":"A session setting declaring the first day of the week; it silently renumbers DATEPART(WEEKDAY) and re-anchors week truncation.","syntax":"SET DATEFIRST n  -- 1 = Monday ... 7 = Sunday","return_type":"session setting","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(ISODOW) is always Monday=1; DOW is Sunday=0"},{"engine_slug":"mysql","status":"partial","note":"DAYOFWEEK is ODBC Sunday=1; WEEKDAY is Monday=0"},{"engine_slug":"sqlite","status":"partial","note":"strftime %w is always Sunday=0"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'D') follows NLS_TERRITORY"}],"gotchas":["us_english defaults to 7 (Sunday first) while British and most European language settings use 1, so DATEPART(WEEKDAY, d) = 1 means Sunday on one login and Monday on another.","DATETRUNC(WEEK, d) also anchors on DATEFIRST: the same query can truncate to any of the seven weekdays depending on the connection (Sunday under us_english, Monday under SET DATEFIRST 1).","Everywhere else the functions just differ by name instead of by session: PostgreSQL's ISODOW (Mon=1) vs DOW (Sun=0), MySQL's DAYOFWEEK (Sun=1) vs WEEKDAY (Mon=0)."],"examples":[{"engine_slug":"sql-server","sql":"SET DATEFIRST 1; SELECT DATEPART(WEEKDAY, '2026-08-01');  -- 6 (Saturday, Monday=1)"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(ISODOW FROM DATE '2026-08-01');  -- 6"},{"engine_slug":"mysql","sql":"SELECT WEEKDAY('2026-08-01');  -- 5 (Monday=0)"},{"engine_slug":"sqlite","sql":"SELECT strftime('%w', '2026-08-01');  -- 6 (Sunday=0)"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(DATE '2026-08-01', 'D') FROM dual;  -- 7 with NLS_TERRITORY=AMERICA, 6 with GERMANY"}],"faqs":[{"question":"How do I write week-start code that survives DATEFIRST?","answer":"Normalize with @@DATEFIRST: (DATEPART(WEEKDAY, d) + @@DATEFIRST - 2) % 7 + 1 is Monday = 1 under every setting. DATEADD(DAY, 1 - that value, CAST(d AS date)) is then the ISO Monday of d's week."},{"question":"What is the portable weekday number?","answer":"There is none. Pick ISO (Monday = 1) and convert per engine: EXTRACT(ISODOW) on PostgreSQL, WEEKDAY(d) + 1 in MySQL, strftime('%u') on SQLite 3.44+, and the @@DATEFIRST formula above on SQL Server."}],"related":["day-of-week","dayname","datename","week-numbers"],"novel_uses":[{"body":"A SET DATEFIRST inside a stored procedure reverts when the procedure exits, so reporting procs can pin Monday-first without polluting the caller's session.","sql":"CREATE PROCEDURE iso_report AS BEGIN SET DATEFIRST 1; SELECT DATEPART(WEEKDAY, GETDATE()) AS iso_dow; END;"},{"body":"DATENAME(WEEKDAY, d) returns Saturday whatever DATEFIRST says, so weekend filters built on names are immune to the setting, though not to SET LANGUAGE.","sql":"SELECT DATENAME(WEEKDAY, '2026-08-01');  -- Saturday under any DATEFIRST"}]},"source_url":"https://sqlly.app/sql-functions/datefirst","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dateformat-bucket","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATE_FORMAT bucketing","description":"Bucketing dates in MySQL with DATE_FORMAT masks like '%Y-%m-01': it returns strings, not dates. The trap and the CAST/STR_TO_DATE fix.","body":{"slug":"dateformat-bucket","name":"DATE_FORMAT bucketing","h1":"SQL DATE_FORMAT bucketing","category":"datetime","lede":"Formatting the day away with DATE_FORMAT is MySQL's idiom for month and day buckets, at the cost of returning text.","syntax":"DATE_FORMAT(date, '%Y-%m-01')","return_type":"varchar","support":[{"engine_slug":"sql-server","status":"partial","note":"FORMAT(d, 'yyyy-MM-01') or DATETRUNC"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'YYYY-MM-01') or date_trunc"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y-%m-01', d)"},{"engine_slug":"oracle","status":"partial","note":"TRUNC(d, 'MM') keeps it a date"}],"gotchas":["The output is a string: GROUP BY DATE_FORMAT(d, '%Y-%m') sorts lexicographically (fine for ISO), but comparing it with a date literal raises ERROR 1525 in MySQL. Use the '%Y-%m-01' form and wrap it with STR_TO_DATE(key, '%Y-%m-%d') or CAST(key AS DATE): a bare '%Y-%m' key parses to NULL with those.","On a plain index over the column, wrapping it in the WHERE clause turns the range seek into a full index scan; keep predicates raw (d >= '2026-08-01') and bucket only in SELECT/GROUP BY.","Oracle's TRUNC(d, 'MM') and PostgreSQL's date_trunc return real dates, so the bucket still compares and joins as a date."],"examples":[{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) FROM orders GROUP BY month;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(order_date, '%Y-%m-01') AS month_start FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m', order_date) AS month FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(CAST('2026-08-15' AS date), 'yyyy-MM-01');  -- 2026-08-01"},{"engine_slug":"postgresql","sql":"SELECT to_char(DATE '2026-08-15', 'YYYY-MM-01');  -- 2026-08-01"},{"engine_slug":"oracle","sql":"SELECT TRUNC(order_date, 'MM') AS month, COUNT(*) FROM orders GROUP BY TRUNC(order_date, 'MM');"}],"faqs":[{"question":"Why '%Y-%m-01' instead of '%Y-%m'?","answer":"Both group identically; the '-01' form produces a value you can feed to STR_TO_DATE or CAST back to a real date, which makes joins to a dates table possible."},{"question":"Is DATE_FORMAT bucketing index-friendly?","answer":"Not on a plain index over the column: the wrapped predicate becomes a full index scan. A functional index on the same expression, ((DATE_FORMAT(order_date, '%Y-%m'))), lets the wrapped predicate use a ref lookup. Without that index, filter with d >= start AND d < end and use DATE_FORMAT only for output."}],"related":["date-format","strftime-bucket","datetrunc","date-trunc"],"novel_uses":[{"body":"GROUP_CONCAT can emit the CASE-per-month SQL for a pivot, so report columns follow the data instead of a hand-written month list. It stops at group_concat_max_len (1024 bytes by default): run SET SESSION group_concat_max_len = 1000000; first, because 47 months overflow it and the generated SELECT fails.","sql":"SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(CASE WHEN DATE_FORMAT(order_date, ''%Y-%m'') = ''', m, ''' THEN total END) AS `', m, '`')) FROM (SELECT DISTINCT DATE_FORMAT(order_date, '%Y-%m') AS m FROM orders) t;"},{"body":"Appending an a or b marker for the month's halves gives fortnightly period keys that still sort correctly as text.","sql":"SELECT CONCAT(DATE_FORMAT('2026-08-20', '%Y-%m'), CASE WHEN DAY('2026-08-20') <= 15 THEN '-a' ELSE '-b' END);  -- 2026-08-b"}]},"source_url":"https://sqlly.app/sql-functions/dateformat-bucket","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datefromparts","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATEFROMPARTS function","description":"Build a date from year, month and day: DATEFROMPARTS on SQL Server, make_date on PostgreSQL, and the TO_DATE string tricks on the other engines.","body":{"slug":"datefromparts","name":"DATEFROMPARTS","h1":"SQL DATEFROMPARTS function","category":"datetime","lede":"Returns a date from three integers. SQL Server has DATEFROMPARTS; PostgreSQL has make_date; MySQL has no month-and-day constructor (MAKEDATE takes day-of-year), so MySQL, SQLite and Oracle rebuild from strings.","syntax":"DATEFROMPARTS(year, month, day)  -- SQL Server  |  MAKE_DATE(year, month, day)  -- PostgreSQL","return_type":"date","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"make_date(year, month, day)"},{"engine_slug":"mysql","status":"partial","note":"no direct form; MAKEDATE uses day-of-year, or STR_TO_DATE"},{"engine_slug":"sqlite","status":"partial","note":"build a string and pass it to date()"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE(year || '-' || month || '-' || day, 'YYYY-MM-DD')"}],"gotchas":["Invalid parts such as February 30 raise an error on SQL Server, PostgreSQL and Oracle. SQLite rolls date('2024-02-30') over to 2024-03-01 without complaint, and MySQL's STR_TO_DATE returns NULL.","MySQL's MAKEDATE is not month-and-day: it takes day-of-year, so MAKEDATE(2024, 61) is March 1, not January 61.","DATEFROMPARTS returns NULL when any argument is NULL, so a missing month in the source data becomes a missing date rather than an error."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEFROMPARTS(2024, 2, 29) AS leap_day;"},{"engine_slug":"postgresql","sql":"SELECT make_date(2024, 2, 29) AS leap_day;"},{"engine_slug":"oracle","sql":"SELECT TO_DATE('2024-02-29', 'YYYY-MM-DD') AS leap_day FROM dual;"},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('2024-02-29', '%Y-%m-%d') AS leap_day;"},{"engine_slug":"sqlite","sql":"SELECT date(printf('%04d-%02d-%02d', 2024, 2, 29)) AS leap_day;"}],"faqs":[{"question":"What happens with an invalid date like February 30?","answer":"SQL Server, PostgreSQL and Oracle raise an error. MySQL's STR_TO_DATE returns NULL in a SELECT (and errors inside an INSERT under strict mode); SQLite silently moves it to March 1."},{"question":"Is DATEFROMPARTS the same as make_date?","answer":"Yes for integer inputs: same arguments, same date, same error for an invalid date, same NULL for a NULL argument. Decimals part ways: SQL Server quietly truncates 2024.9 to 2024, while make_date rejects numeric arguments. PostgreSQL spells it make_date; MySQL, SQLite and Oracle have no equivalent and need string building."}],"related":["make-date","makedate","date-literal"],"novel_uses":[{"body":"DATEFROMPARTS(YEAR(d), MONTH(d), 1) turns any timestamp into its first-of-month date: a sortable, joinable month key that beats '2024-03' text everywhere ordering matters.","sql":"SELECT DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1) AS month_key FROM orders;"},{"body":"Feed MAKEDATE the year and day-of-year, then MONTH() and DAY() read the real month and day back out: the reverse trip of building one.","sql":"SELECT MAKEDATE(2024, 61) AS d, MONTH(MAKEDATE(2024, 61)) AS m, DAY(MAKEDATE(2024, 61)) AS dom;"},{"body":"make_date takes int arguments and EXTRACT returns numeric (double before version 14), so the casts are not decoration: without ::int the call fails to resolve.","sql":"SELECT make_date(EXTRACT(year FROM now())::int, EXTRACT(month FROM now())::int, 1) AS month_start;"}]},"source_url":"https://sqlly.app/sql-functions/datefromparts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datename","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATENAME function","description":"SQL Server's DATENAME returns a date part as text (month and weekday names, or numbers as strings), the word-producing sibling of DATEPART.","body":{"slug":"datename","name":"DATENAME","h1":"SQL DATENAME function","category":"datetime","lede":"Returns the named part of a date as text: DATENAME(month, d) gives 'January' where DATEPART(month, d) gives 1.","syntax":"DATENAME(month, d)  |  DATENAME(weekday, d)  |  DATENAME(year, d)  -- text, not int","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"TO_CHAR with Month / Day masks"},{"engine_slug":"mysql","status":"partial","note":"MONTHNAME and DAYNAME for the word parts"},{"engine_slug":"sqlite","status":"no","note":"strftime formats; no names"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR"}],"gotchas":["Everything comes back as nvarchar: DATENAME(day, d) is '5', which sorts after '10' as text. Arithmetic and comparisons against ints convert it implicitly (DATENAME(day, d) + 1 is 6), but an explicit CAST(DATENAME(day, d) AS int) says what you mean. Use DATEPART for numbers.","Month and weekday names follow the session LANGUAGE setting; the same query returns Spanish or German words elsewhere.","For week numbers DATENAME returns the text of DATEPART(week)'s convention, not ISO. Use DATENAME(iso_week) explicitly."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATENAME(month, created_at) AS mon FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATENAME(weekday, GETDATE()) AS today_name;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(month, GETDATE()) AS mon_num;  -- int"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(created_at, 'FMMonth') AS mon FROM orders;"},{"engine_slug":"mysql","sql":"SELECT MONTHNAME(created_at) AS mon, DAYNAME(created_at) AS weekday FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'Month') AS mon, TO_CHAR(created_at, 'Day') AS weekday FROM orders;"}],"faqs":[{"question":"DATENAME or DATEPART?","answer":"DATENAME for display words, DATEPART for numbers you filter, sort or group on. ORDER BY DATENAME(month, d) puts April first and January fifth."},{"question":"Does DATENAME respect SET LANGUAGE?","answer":"Yes. Month and weekday names come out in the session language, so reports can localize but filters on English names can silently fail."}],"related":["convert-style","monthname","dayname"],"novel_uses":[{"body":"DATEPART(weekday) numbers shift when a session runs SET DATEFIRST, but DATENAME(weekday) always returns the true day name, so the words never move with the setting.","sql":"SELECT DATENAME(weekday, created_at) AS dow_name FROM orders;"},{"body":"DATENAME(year, d) plus DATENAME(month, d) spells '2024-March' with no casts and no CLR call, a fast label for file names where FORMAT() would crawl.","sql":"SELECT DATENAME(year, created_at) + '-' + DATENAME(month, created_at) AS file_part FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/datename","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datestyle","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DateStyle parameter","description":"PostgreSQL's DateStyle: it picks ISO, Postgres, SQL or German output and the MDY/DMY day-month order for ambiguous literal parsing.","body":{"slug":"datestyle","name":"DateStyle","h1":"SQL DateStyle parameter","category":"datetime","lede":"A session GUC controlling timestamp output style and, for non-ISO input, the month/day order when parsing ambiguous date literals.","syntax":"SET datestyle = 'ISO, MDY'","return_type":"session GUC","support":[{"engine_slug":"sql-server","status":"partial","note":"SET DATEFORMAT / SET LANGUAGE for the parsing side"},{"engine_slug":"postgresql","status":"yes","note":"this GUC: 'ISO, DMY' and friends"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"NLS_DATE_FORMAT + NLS_DATE_LANGUAGE"}],"gotchas":["With ISO output the second component (MDY/DMY) is ignored for display; ISO is always YYYY-MM-DD. It still governs how '04/05/2026' is read: MDY says April 5, DMY says May 4.","The other styles (German, SQL, Postgres) change output to a fixed alternate text format; code that concatenates or compares now()::text output breaks when the GUC differs between sessions.","Never parse ambiguous slash dates; use DATE '2026-08-01' typed literals or unambiguous YYYY-MM-DD strings, and leave DateStyle at ISO. On SQL Server a datetime written yyyy-mm-dd still follows SET DATEFORMAT (under dmy, '2026-05-04' reads as 5 April), so write '2026-05-04T00:00:00' there."],"examples":[{"engine_slug":"postgresql","sql":"SET datestyle = 'ISO, DMY';  SELECT '04/05/2026'::date;  -- 2026-05-04"},{"engine_slug":"postgresql","sql":"SHOW datestyle;  -- check before relying on implicit parsing"},{"engine_slug":"sql-server","sql":"SET DATEFORMAT dmy;  SELECT CAST('04/05/2026' AS datetime);  -- 4 May 2026, not April 5"},{"engine_slug":"oracle","sql":"ALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YYYY';  SELECT TO_DATE('04/05/2026') FROM dual;  -- 4 May 2026, not April 5"}],"faqs":[{"question":"Does DateStyle affect to_char?","answer":"No: to_char always applies its own mask. DateStyle shapes implicit casts and default output only, which is exactly where the surprises live."},{"question":"How is this different from SQL Server's SET DATEFORMAT?","answer":"Same parsing role (day/month order for ambiguous literals); DateStyle additionally switches the output format family, which DATEFORMAT never does."}],"related":["date-literal","nls-date-format","date-to-text","to-date"],"novel_uses":[{"body":"SET LOCAL reverts the setting at transaction end, so one pooled connection can parse DMY input for a single load without leaking the choice.","sql":"BEGIN; SET LOCAL datestyle = 'ISO, DMY'; SELECT '04/05/2026'::date; COMMIT;  -- 2026-05-04"},{"body":"pg_settings reports which source set DateStyle, separating a postgresql.conf default from someone's stray SET in seconds.","sql":"SELECT setting, source FROM pg_settings WHERE name = 'DateStyle';"}]},"source_url":"https://sqlly.app/sql-functions/datestyle","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datetime-modifiers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SQLite datetime modifiers","description":"SQLite's datetime/date modifiers: chainable terms like 'start of month', '+1 day' and 'weekday 0' that do arithmetic, truncation and time-zone shifts.","body":{"slug":"datetime-modifiers","name":"datetime() modifiers","h1":"SQL SQLite datetime modifiers","category":"datetime","lede":"Modifiers are extra string arguments to date(), datetime() and strftime(), applied left to right to shift and truncate the value.","syntax":"datetime(t, modifier1, modifier2, ...)","return_type":"text (formatted timestamp)","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Modifiers apply in order: date(d, 'start of month', '+1 month', '-1 day') is the month's last day; reordering changes the result.","'start of month' zeroes the time too. 'weekday N' (0 = Sunday ... 6 = Saturday) moves forward to the next date with that weekday and leaves the date alone if it already matches: date('2026-08-02', 'weekday 0') stays 2026-08-02.","'localtime' and 'utc' convert using the OS time zone; inside SQLite there is no per-session zone, so results shift with the machine's clock settings.","Unrecognised modifiers return NULL with no error, as do out-of-range arguments such as 'weekday 7' or '+1 quarter'; out-of-range input fields such as month 13 also return NULL, while day overflow from arithmetic is normalised."],"examples":[{"engine_slug":"sqlite","sql":"SELECT date('2026-08-01', 'start of month');  -- 2026-08-01"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-01', 'start of month', '-1 day');  -- 2026-07-31"},{"engine_slug":"sqlite","sql":"SELECT datetime('2026-08-01 10:00', '+7 days', 'weekday 1');  -- 2026-08-10 10:00:00"}],"faqs":[{"question":"How do I truncate to the month in SQLite?","answer":"date(d, 'start of month'). For the year use 'start of year'; there is no quarter modifier; derive it with month arithmetic."},{"question":"Can modifiers add months across month ends?","answer":"Not by default: date('2026-01-31', '+1 month') builds 2026-02-31 and normalizes it to 2026-03-03. SQLite added the 'floor' modifier for this: date('2026-01-31', '+1 month', 'floor') is 2026-02-28."}],"related":["date-trunc","datetrunc","strftime-bucket","date-from-datetime"],"novel_uses":[{"body":"Tables that keep epoch integers become queryable as dates by attaching the 'unixepoch' modifier, which must come first, right after the value; further modifiers can truncate or shift from there in the same call.","sql":"SELECT datetime(epoch_ts, 'unixepoch', 'start of day') FROM metrics;"},{"body":"Drop to the month start and let 'weekday 1' roll forward. Because the modifier leaves a matching date alone, months that begin on a Monday keep day 1.","sql":"SELECT date('2026-08-15', 'start of month', 'weekday 1');  -- 2026-08-03"},{"body":"Back up six days, then step to the next Monday: the pair returns the Monday of the input's ISO week, including when the input is a Sunday or a Monday.","sql":"SELECT date('2026-08-05', '-6 days', 'weekday 1');  -- 2026-08-03"}]},"source_url":"https://sqlly.app/sql-functions/datetime-modifiers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datetimefromparts","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATETIMEFROMPARTS function","description":"Assemble a full timestamp from seven integers: DATETIMEFROMPARTS on SQL Server, make_timestamp on PostgreSQL, string building on the rest.","body":{"slug":"datetimefromparts","name":"DATETIMEFROMPARTS","h1":"SQL DATETIMEFROMPARTS function","category":"datetime","lede":"Returns a date plus time from year, month, day, hour, minute, seconds and milliseconds. SQL Server's DATETIMEFROMPARTS takes all seven and returns datetime.","syntax":"DATETIMEFROMPARTS(y, m, d, hh, mi, ss, ms)  -- SQL Server  |  MAKE_TIMESTAMP(y, m, d, hh, mi, ss)  -- PostgreSQL","return_type":"datetime / timestamp","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"make_timestamp()"},{"engine_slug":"mysql","status":"partial","note":"TIMESTAMP(date, MAKETIME(hh, mi, ss)), or STR_TO_DATE"},{"engine_slug":"sqlite","status":"partial","note":"printf a string into datetime()"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE of a composed string"}],"gotchas":["The seventh argument is milliseconds (500 is half a second), but datetime stores fractions in 1/300-second steps: 2 ms reads back as .003, 5 ms as .007, 9 ms as .010, and 999 ms rolls over to the next whole second. DATETIME2FROMPARTS gives exact fractions.","make_timestamp takes seconds as a double, so 59.5 is valid there; SQL Server keeps fractions in the separate seventh argument instead.","SQL Server errors on out-of-range parts. PostgreSQL errors on hour 25, minute 60 and February 30, but it rolls hour 24 and second 60 over instead: make_timestamp(2024, 1, 15, 24, 0, 0) is 2024-01-16 00:00:00. The string-building routes do not raise: SQLite turns hour 25 into NULL and day 30 of February into March 1."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATETIMEFROMPARTS(2024, 1, 15, 9, 30, 0, 0) AS meeting;"},{"engine_slug":"postgresql","sql":"SELECT make_timestamp(2024, 1, 15, 9, 30, 0) AS meeting;"},{"engine_slug":"sqlite","sql":"SELECT datetime(printf('%04d-%02d-%02d %02d:%02d:%02d', 2024, 1, 15, 9, 30, 0)) AS meeting;"},{"engine_slug":"mysql","sql":"SELECT TIMESTAMP('2024-01-15', MAKETIME(9, 30, 0)) AS meeting;"},{"engine_slug":"oracle","sql":"SELECT TO_DATE('2024-01-15 09:30:00', 'YYYY-MM-DD HH24:MI:SS') AS meeting FROM dual;"}],"faqs":[{"question":"Why seven arguments on SQL Server but six on PostgreSQL?","answer":"SQL Server's seventh is milliseconds. PostgreSQL folds fractions into its double-precision seconds argument."},{"question":"Is there DATETIME2FROMPARTS?","answer":"Yes. It takes eight arguments: the seventh is the fraction and the eighth its number of digits, so DATETIME2FROMPARTS(2024, 1, 15, 9, 30, 0, 5, 1) is 09:30:00.5."}],"related":["datefromparts","timefromparts","make-date"],"novel_uses":[{"body":"PostgreSQL adds a date and a time into a timestamp in one expression, so make_date(...) + make_time(...) replaces the six-argument constructor when the parts live in different columns.","sql":"SELECT make_date(2024, 1, 15) + make_time(9, 30, 0) AS meeting;"},{"body":"Reassembling a timestamp from its own parts is a truncation tool: divide the minutes by 15 and multiply back, and 09:37 lands on the 09:30 slot with no DATE_BUCKET in sight.","sql":"DECLARE @t datetime2 = '2024-01-15T09:37:00';\nSELECT DATETIMEFROMPARTS(YEAR(@t), MONTH(@t), DAY(@t), DATEPART(hour, @t), DATEPART(minute, @t) / 15 * 15, 0, 0) AS slot;"},{"body":"SQLite's string route returns NULL instead of raising, so running the printf output through datetime() is a cheap parts check: month 13 comes back NULL, not a rolled-over date.","sql":"SELECT printf('%04d-%02d-%02d', 2024, 13, 1) AS candidate,\n       datetime(printf('%04d-%02d-%02d', 2024, 13, 1)) AS verdict;"}]},"source_url":"https://sqlly.app/sql-functions/datetimefromparts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datetimeoffset","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATETIMEOFFSET type","description":"SQL Server's datetimeoffset(n): a datetime2 plus a ±HH:MM offset carried with every value. Insertion, comparison and the missing-zone-name caveat.","body":{"slug":"datetimeoffset","name":"DATETIMEOFFSET","h1":"SQL DATETIMEOFFSET type","category":"datetime","lede":"A 100 ns timestamp whose ±14:00 offset travels with the value, so comparisons happen in UTC space while display keeps the original offset.","syntax":"CAST('2026-08-01 14:30:00 +02:00' AS DATETIMEOFFSET)","return_type":"datetimeoffset(n)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"timestamptz, instant-correct but discards the stored offset"},{"engine_slug":"mysql","status":"no","note":"no aware type"},{"engine_slug":"sqlite","status":"no","note":"none"},{"engine_slug":"oracle","status":"partial","note":"TIMESTAMP WITH TIME ZONE: offsets and named zones"}],"gotchas":["Comparisons normalize to UTC: '2026-08-01 14:30+02:00' equals '2026-08-01 12:30+00:00'; two rows can display differently and still be the same instant.","The offset is not a zone: +02:00 says nothing about DST next month. Keep the IANA/Windows zone name in a second column if you need to reinterpret wall times later.","Precision runs to 100 ns (default 7). Assigning a datetime or datetime2 attaches +00:00 whatever the server's zone, so CAST(GETDATE() AS datetimeoffset) labels local wall time as UTC. SYSDATETIMEOFFSET() carries the real offset."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST('2026-08-01 14:30:00 +02:00' AS DATETIMEOFFSET);"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIMEOFFSET() AT TIME ZONE 'UTC';  -- renders in UTC, instant unchanged"},{"engine_slug":"postgresql","sql":"SELECT '2026-08-01 14:30+02'::timestamptz;  -- offset normalized on display"},{"engine_slug":"oracle","sql":"SELECT FROM_TZ(TIMESTAMP '2026-08-01 14:30:00', '+02:00') FROM dual;  -- 2026-08-01 14:30:00 +02:00"}],"faqs":[{"question":"datetimeoffset vs timestamptz?","answer":"Both compare as instants. datetimeoffset remembers the offset it was given; PostgreSQL's timestamptz re-renders in the session zone and forgets the original. Preserve-the-offset reporting favours datetimeoffset."},{"question":"How do I strip the offset?","answer":"CAST(d AS datetime2) drops the offset without converting; use SWITCHOFFSET or AT TIME ZONE first if you need a specific zone's wall time."}],"related":["at-time-zone","switchoffset","sysutcdatetime","timestamp-with-time-zone"],"novel_uses":[{"body":"DATEPART(TZ) returns the stored offset in minutes: the direct answer when a report must print the original zone beside the value.","sql":"SELECT DATEPART(TZ, CAST('2026-08-01 14:30 +02:00' AS datetimeoffset));  -- 120"},{"body":"datetimeoffset(0) drops fractional seconds and saves two bytes per value over the default, a free win when whole seconds are the domain.","sql":"CREATE TABLE stamps (at datetimeoffset(0) NOT NULL);"}]},"source_url":"https://sqlly.app/sql-functions/datetimeoffset","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/datetrunc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DATETRUNC function","description":"DATETRUNC in SQL Server 2022: floor a datetime to year, quarter, month, week, day or smaller, like PostgreSQL's date_trunc except that week starts follow SET DATEFIRST.","body":{"slug":"datetrunc","name":"DATETRUNC","h1":"SQL DATETRUNC function","category":"datetime","lede":"Floors a date/time to the start of the named unit, the native answer to SQL Server's pre-2022 DATEADD/DATEDIFF truncation trick.","syntax":"DATETRUNC(datepart, date)","return_type":"same type as input (date stays date; datetime2(n) stays datetime2(n))","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"date_trunc('day', d); same capability, different name"},{"engine_slug":"mysql","status":"partial","note":"DATE(d) for days, DATE_FORMAT(d, '%Y-%m-01') for months; no native truncate"},{"engine_slug":"sqlite","status":"partial","note":"strftime + date(); see the bucketing page"},{"engine_slug":"oracle","status":"partial","note":"TRUNC(d, 'DD')"}],"gotchas":["Requires SQL Server 2022 or Azure SQL; on older instances the DATEADD(DAY, DATEDIFF(DAY, 0, d), 0) idiom is the standard substitute.","DATETRUNC(week, d) starts weeks on the day set by SET DATEFIRST (default Sunday), so it does not match ISO Monday weeks unless you change DATEFIRST or compute by hand.","The result keeps the input type: a datetime2(3) comes back as datetime2(3), and a string literal becomes datetime2(7). A date input rejects units below DAY: DATETRUNC(HOUR, a date) raises error 9810."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(MONTH, '2026-08-15 14:30');  -- 2026-08-01 00:00:00.0000000"},{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(WEEK, order_date) AS week_start, COUNT(*) FROM orders GROUP BY DATETRUNC(WEEK, order_date);"},{"engine_slug":"postgresql","sql":"SELECT date_trunc('day', TIMESTAMP '2026-08-15 14:30');"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT('2026-08-15 14:30', '%Y-%m-01');  -- 2026-08-01"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-01', '2026-08-15 14:30');  -- 2026-08-01"},{"engine_slug":"oracle","sql":"SELECT TRUNC(DATE '2026-08-15', 'MM') FROM dual;  -- 2026-08-01"}],"faqs":[{"question":"How do I truncate on SQL Server 2019?","answer":"The idiom: DATEADD(DAY, DATEDIFF(DAY, 0, d), 0) for days, DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) for months. Or upgrade: DATETRUNC replaces all of it."},{"question":"Is DATETRUNC the same as PostgreSQL's date_trunc?","answer":"Same idea, different spelling: SQL Server takes bare datepart keywords ('MONTH'), PostgreSQL takes quoted strings ('month') and also offers date_bin for fixed grids."}],"related":["date-trunc","dateadd-truncation-trick","trunc-date","date-bin"],"novel_uses":[{"body":"Truncating to millisecond strips the last digits timers add, so values captured within the same millisecond compare equal.","sql":"SELECT DATETRUNC(MILLISECOND, SYSDATETIME());"},{"body":"Truncate to the month and add one: the pair produces the first of next month for expiry and reporting windows without string building.","sql":"SELECT DATEADD(MONTH, 1, DATETRUNC(MONTH, '2026-08-15'));  -- 2026-09-01"},{"body":"Wrapping both join sides in DATETRUNC turns a same-week cohort match into an equality join.","sql":"SELECT a.customer_id FROM visits a JOIN visits b ON DATETRUNC(WEEK, a.at) = DATETRUNC(WEEK, b.at);"}]},"source_url":"https://sqlly.app/sql-functions/datetrunc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/day","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DAY function","description":"Get the day of month 1-31: DAY() on SQL Server and MySQL, EXTRACT(day FROM d) on PostgreSQL and Oracle, strftime('%d', d) on SQLite.","body":{"slug":"day","name":"DAY","h1":"SQL DAY function","category":"datetime","lede":"Returns the day-of-month number from a date, useful for month-end logic like flagging entries on or after the 15th.","syntax":"DAY(d)  |  EXTRACT(day FROM d)  |  strftime('%d', d)  -- SQLite, zero-padded text","return_type":"integer on MySQL and SQL Server; numeric on PostgreSQL; text on SQLite","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(day FROM d)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%d', d) returns text"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT(day FROM d); there is no DAY() function"}],"gotchas":["DAY is day of month, not day of week or day of year; those are DATEPART(weekday) and DATEPART(dayofyear) on SQL Server.","SQLite's %d is zero-padded text: '01' through '31'. Arithmetic coerces it, but CAST to INTEGER before comparing it with a number: text always sorts after an integer, so strftime('%d', d) <= 15 is always false.","MySQL accepts DAY(), DAYOFMONTH() and the ANSI EXTRACT, all identical; older scripts use DAYOFMONTH."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(day FROM created_at) AS dom FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DAY(created_at) AS dom FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%d', created_at) AS INTEGER) AS dom FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DAY(created_at) AS dom FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(day FROM created_at) AS dom FROM orders;"}],"faqs":[{"question":"What is the difference between DAY and DAYOFYEAR?","answer":"DAY returns 1-31 within the month; DAYOFYEAR returns 1-366 within the year. MySQL even spells them DAYOFMONTH and DAYOFYEAR to keep it clear."},{"question":"Does Oracle have DAY()?","answer":"No. SELECT DAY(SYSDATE) FROM dual raises ORA-00904. Use EXTRACT(day FROM d), or TO_CHAR(d, 'DD') for zero-padded text."}],"related":["extract","dayofyear","day-of-week"],"novel_uses":[{"body":"A row is the last of its month when DAY(d) equals DAY(EOMONTH(d)), which is how SQL Server closes month-end batches without a calendar table.","sql":"SELECT CASE WHEN DAY(d) = DAY(EOMONTH(d)) THEN 1 ELSE 0 END AS is_month_end FROM t;"},{"body":"Thresholds on the day number cut each month into cycles: entries on or before the 15th bill in the first half, the rest in the second, with no boundary dates to maintain.","sql":"SELECT CASE WHEN DAY(invoice_date) <= 15 THEN 1 ELSE 2 END AS cycle\nFROM invoices;"}]},"source_url":"https://sqlly.app/sql-functions/day","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/day-of-week","corpus":"sql-functions","engine":null,"language":"en","title":"SQL day of week function","description":"Get the weekday of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle, and why every engine numbers the days differently (0 = Sunday, 1 = Monday, or ISO).","body":{"slug":"day-of-week","name":"Day of week","h1":"SQL day of week function","category":"datetime","lede":"Returns which weekday a date falls on. No two engines agree on the function or the numbering: 0 or 1 for Sunday, 1 for Monday, or whatever a session setting says.","syntax":"EXTRACT(dow FROM d)  -- PostgreSQL  |  DAYOFWEEK(d)  -- MySQL  |  DATEPART(weekday, d)","return_type":"integer 0-6 or 1-7, engine-dependent","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(weekday, d), first day set by DATEFIRST"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(dow) is 0=Sunday; EXTRACT(isodow) is 1=Monday"},{"engine_slug":"mysql","status":"partial","note":"DAYOFWEEK is 1=Sunday; WEEKDAY is 0=Monday"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%w', d), 0=Sunday, as text; '%u' (1=Monday) from 3.44"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'D') follows NLS_TERRITORY; TO_CHAR(d, 'DY') gives the name"}],"gotchas":["PostgreSQL gives you both conventions: dow (0 = Sunday) and isodow (1 = Monday). Pick isodow for business-week logic.","MySQL's DAYOFWEEK (1 = Sunday) and WEEKDAY (0 = Monday) number the same day differently: Monday is 2 in one and 0 in the other.","Oracle's TO_CHAR(d, 'D') follows the session's NLS_TERRITORY, so the same query returns different numbers in different countries. Comparing names with an explicit language is stable: TO_CHAR(d, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH').","SQL Server's DATEPART(weekday) depends on SET DATEFIRST, which changes with the login's language. (DATEPART(weekday, d) + @@DATEFIRST - 2) % 7 + 1 gives 1 = Monday under any setting."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(isodow FROM created_at) AS weekday FROM orders;"},{"engine_slug":"mysql","sql":"SELECT WEEKDAY(created_at) AS weekday FROM orders;  -- 0 = Monday"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(WEEKDAY, created_at) AS weekday FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%w', created_at) AS weekday FROM orders;  -- '0' = Sunday"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') AS weekday\nFROM orders;  -- MON, TUE, ..."}],"faqs":[{"question":"Why do engines number weekdays differently?","answer":"The US convention starts the week on Sunday and ISO 8601 starts it on Monday, and engines picked different ones. PostgreSQL has dow (0=Sunday) and isodow (1=Monday); MySQL has two functions with different bases; SQL Server follows DATEFIRST; Oracle follows NLS_TERRITORY. Check the convention before filtering."},{"question":"How do I filter for weekends only?","answer":"PostgreSQL: EXTRACT(isodow FROM d) IN (6, 7). MySQL: WEEKDAY(d) >= 5. SQL Server: DATEPART(WEEKDAY, d) IN (1, 7) with the us_english DATEFIRST of 7. SQLite: strftime('%w', d) IN ('0', '6'). Oracle: TO_CHAR(d, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') IN ('SAT', 'SUN')."}],"related":["extract","date-trunc","to-char"],"novel_uses":[{"body":"Add the deadline, then shift Saturday and Sunday forward to Monday with a CASE on the weekday number. PostgreSQL's isodow makes this readable because it numbers Monday 1 through Sunday 7; the other engines' conventions need the same idea with their own numbers.","sql":"SELECT due_on + CASE EXTRACT(isodow FROM due_on)\n         WHEN 6 THEN 2\n         WHEN 7 THEN 1\n         ELSE 0 END AS biz_due\nFROM tasks;"},{"body":"Grouping by ISO week number and day of week lays rows out exactly like a contribution graph, with no client-side reshaping. The week number must be the ISO one, or early January lands in the wrong cells.","sql":"SELECT EXTRACT(week FROM at) AS wk,\n       EXTRACT(isodow FROM at) AS dow,\n       COUNT(*) AS commits\nFROM commits\nGROUP BY 1, 2\nORDER BY 1, 2;"}]},"source_url":"https://sqlly.app/sql-functions/day-of-week","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dayname","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DAYNAME function","description":"Get the weekday as a word: DAYNAME() on MySQL, DATENAME(weekday) on SQL Server, TO_CHAR(d, 'Day') on PostgreSQL and Oracle; none on SQLite.","body":{"slug":"dayname","name":"DAYNAME","h1":"SQL DAYNAME function","category":"datetime","lede":"Returns the weekday name in the session language, which sidesteps the engines' disagreement over whether Sunday is day 0, 1 or 7.","syntax":"DAYNAME(d)  -- MySQL  |  DATENAME(weekday, d)  -- SQL Server  |  TO_CHAR(d, 'Day')  -- PostgreSQL, Oracle","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"DATENAME(weekday, d)"},{"engine_slug":"postgresql","status":"partial","note":"TO_CHAR(d, 'FMDay') trims padding"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no weekday-name format; CASE over strftime('%w')"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'Day') follows NLS settings"}],"gotchas":["PostgreSQL and Oracle pad to nine characters: TO_CHAR(d, 'Day') returns 'Monday   '. FMDay trims it on both.","Language follows the session: SQL Server's LANGUAGE and Oracle's NLS_DATE_LANGUAGE change the words, so never filter on the English spelling.","Weekday names do not sort or join well; keep the underlying dow or isodow number for logic and format for display."],"examples":[{"engine_slug":"mysql","sql":"SELECT DAYNAME(created_at) AS weekday FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATENAME(weekday, created_at) AS weekday FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(created_at, 'FMDay') AS weekday FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'Day') AS weekday FROM orders;"}],"faqs":[{"question":"Why does TO_CHAR(d, 'Day') add spaces?","answer":"PostgreSQL and Oracle pad weekday names to nine characters. Prefix the format with FM (FMDay) or RTRIM the result."},{"question":"How do I filter for weekends by name?","answer":"Do not compare names: use EXTRACT(isodow) IN (6, 7) on PostgreSQL, WEEKDAY(d) >= 5 on MySQL; name checks are for display only."}],"related":["day-of-week","monthname","datename"],"novel_uses":[{"body":"SET lc_time_names = 'de_DE' and DAYNAME answers in German, a per-session lever with no NLS machinery that reverts with the session.","sql":"SET lc_time_names = 'de_DE';\nSELECT DAYNAME(DATE '2026-11-27') AS weekday;  -- Freitag"},{"body":"The 'Dy' mask abbreviates (Mon, Tue) and FM trims the padding, so TO_CHAR(d, 'FMDy') gives compact weekday labels on PostgreSQL and Oracle.","sql":"SELECT TO_CHAR(d, 'FMDy') AS dow FROM events;"}]},"source_url":"https://sqlly.app/sql-functions/dayname","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dayofyear","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DAYOFYEAR function","description":"Get the day number 1-366: DAYOFYEAR() on MySQL, DATEPART(dayofyear) on SQL Server, EXTRACT(doy) on PostgreSQL, strftime('%j') on SQLite.","body":{"slug":"dayofyear","name":"DAYOFYEAR","h1":"SQL DAYOFYEAR function","category":"datetime","lede":"Returns the ordinal day within the year, handy for seasonal comparisons inside one year. Across years the numbers drift in leap years: April 10 is day 100 in 2023 and day 101 in 2024.","syntax":"DATEPART(dayofyear, d)  -- SQL Server  |  EXTRACT(doy FROM d)  -- PostgreSQL  |  DAYOFYEAR(d)  -- MySQL","return_type":"integer on SQL Server and MySQL; numeric on PostgreSQL; text on SQLite","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(dayofyear, d)"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(doy FROM d)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%j', d) returns zero-padded text"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'DDD') returns text"}],"gotchas":["Leap years shift day numbers after February: day 60 is February 29 in 2024 and March 1 in 2023. Align years by date, not day number, when the range crosses February.","PostgreSQL spells it doy inside EXTRACT; the word dayofyear works on SQL Server and MySQL only.","SQLite and Oracle return zero-padded text ('DDD', '%j'); CAST to a number before arithmetic."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(doy FROM created_at) AS doy FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(DAYOFYEAR, created_at) AS doy FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DAYOFYEAR(created_at) AS doy FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%j', created_at) AS doy FROM orders;  -- zero-padded text"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'DDD') AS doy FROM orders;"}],"faqs":[{"question":"What is the difference between DAY and DAYOFYEAR?","answer":"DAY is 1-31 within the month; DAYOFYEAR is 1-366 within the year. MySQL's DAYOFMONTH and DAYOFYEAR names make the split explicit."},{"question":"How do I convert a day-of-year back to a date?","answer":"MySQL: MAKEDATE(year, doy). SQL Server: DATEADD(day, doy - 1, DATEFROMPARTS(year, 1, 1)). Oracle: TO_DATE(year || LPAD(doy, 3, '0'), 'YYYYDDD')."}],"related":["makedate","day","week"],"novel_uses":[{"body":"DAYOFYEAR(CONCAT(YEAR(NOW()), '-12-31')) returns the year's own length, so dividing gives a leap-correct percent-of-year with no lookup table.","sql":"SELECT ROUND(100.0 * DAYOFYEAR(NOW()) / DAYOFYEAR(CONCAT(YEAR(NOW()), '-12-31')), 1) AS pct_of_year;"},{"body":"PARTITION BY YEAR and ORDER BY DAYOFYEAR in a window SUM builds the year-to-date running total per row, and the ordering survives February 29 because it is day based.","sql":"SELECT d, val,\n       SUM(val) OVER (PARTITION BY YEAR(d) ORDER BY DAYOFYEAR(d)) AS ytd\nFROM stats;"}]},"source_url":"https://sqlly.app/sql-functions/dayofyear","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/days-in-month","corpus":"sql-functions","engine":null,"language":"en","title":"SQL days in month per engine","description":"How many days a month has, computed per engine: EOMONTH, LAST_DAY, date_trunc, strftime and modifier one-liners with a note on leap years.","body":{"slug":"days-in-month","name":"Days in month","h1":"SQL days in month per engine","category":"datetime","lede":"A per-engine recipe for the length of a month: build the month's last day, then read its day number.","syntax":"DAY(EOMONTH(d))  |  DAY(LAST_DAY(d))  |  EXTRACT(DAY FROM ...)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DAY(EOMONTH(d))"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(DAY FROM (date_trunc('month', d) + INTERVAL '1 month -1 day'))"},{"engine_slug":"mysql","status":"partial","note":"DAY(LAST_DAY(d))"},{"engine_slug":"sqlite","status":"partial","note":"CAST(strftime('%d', date(d, 'start of month', '+1 month', '-1 day')) AS INTEGER)"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT(DAY FROM LAST_DAY(d))"}],"gotchas":["February is the only variable: the recipes return 29 for Feb 2028 and 28 for Feb 2026 automatically; never hard-code 28/29 switches.","On SQLite the '+1 month' then '-1 day' chain lands on the month end safely even from the 31st, because it walks from the month's first day.","None of the engines has a named function for this; the one-liners are the idiom, and LAST_DAY/EOMONTH are the shared half of it."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DAY(EOMONTH('2026-02-15'));  -- 28"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(DAY FROM LAST_DAY(DATE '2028-02-15')) FROM dual;  -- 29"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%d', date('2026-02-15', 'start of month', '+1 month', '-1 day')) AS INTEGER);  -- 28"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(DAY FROM (date_trunc('month', DATE '2026-02-15') + INTERVAL '1 month -1 day'));  -- 28"},{"engine_slug":"mysql","sql":"SELECT DAY(LAST_DAY('2026-02-15'));  -- 28"}],"faqs":[{"question":"What is the shortest portable version?","answer":"There is none. Every recipe has the same shape (build the month's last day, read its day number), so keep your engine's one-liner rather than a CASE table of month lengths."},{"question":"How do I get days in a quarter or year?","answer":"Subtract period starts instead of reading DAY(): on PostgreSQL (date_trunc('quarter', d) + INTERVAL '3 months')::date - date_trunc('quarter', d)::date is 92 for Q3; on SQL Server 2022+ DATEDIFF(DAY, DATETRUNC(QUARTER, d), DATEADD(QUARTER, 1, DATETRUNC(QUARTER, d)))."}],"related":["last-day","eomonth","date-trunc","datetime-modifiers"],"novel_uses":[{"body":"Weight a flat monthly rate by days used over the month's real length, so a full month always bills the full rate whatever its length; on a 100.00 rate, 14 days bill 50.00 in February 2026 but 45.16 in August 2026.","sql":"SELECT monthly_fee * TIMESTAMPDIFF(DAY, moved_in, moved_out) / DAY(LAST_DAY(moved_in)) FROM stays;"},{"body":"Build February 1 for a year and read its last day: 29 means leap, 28 means not, with no year arithmetic of your own.","sql":"SELECT DAY(LAST_DAY(CONCAT(YEAR('2028-05-01'), '-02-01'))) = 29 AS is_leap;"}]},"source_url":"https://sqlly.app/sql-functions/days-in-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/decimal-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CAST to DECIMAL","description":"Casting to DECIMAL(p, s): rounding at the target scale, overflow when precision is too small, and why division operands need the cast before the division, not after.","body":{"slug":"decimal-cast","name":"CAST AS DECIMAL","h1":"SQL CAST to DECIMAL","category":"conversion","lede":"CAST(price AS DECIMAL(10, 2)) fixes a value at two fraction digits in exact decimal arithmetic. It rounds at the scale and fails or clips when the integer part does not fit.","syntax":"CAST(expression AS DECIMAL(precision, scale))","return_type":"decimal","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"accepted but only sets NUMERIC affinity; no precision, scale or rounding"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Casting rounds to the target scale: 2.345 becomes 2.35. A float source can surprise you: the double nearest 1.005 is slightly below it, so CAST(1.005e0 AS DECIMAL(10,2)) is 1.00 on SQL Server, while PostgreSQL and MySQL return 1.01.","DECIMAL(p, s) leaves room for at most p - s integer digits. CAST(12345 AS DECIMAL(4,2)) is an overflow error on SQL Server, PostgreSQL and Oracle, and 99.99 with a warning on MySQL.","Integer division happens before the cast: CAST(a / b AS DECIMAL(10,4)) keeps the already-truncated quotient on SQL Server, PostgreSQL and SQLite. Cast an operand instead: CAST(a AS DECIMAL(12,4)) / b. SQLite's DECIMAL cast leaves an integer an integer, so use CAST(a AS REAL) / b there. MySQL's / never truncates.","SQLite has no fixed-point type. CAST(2.345 AS DECIMAL(10,2)) returns 2.345 unchanged; use ROUND(x, 2) when you need the scale applied."],"examples":[{"engine_slug":"all","sql":"SELECT CAST(price AS DECIMAL(10, 2)) AS money\nFROM items;"},{"engine_slug":"sql-server","sql":"SELECT CAST(a AS DECIMAL(12, 4)) / b AS ratio\nFROM rates;"},{"engine_slug":"sqlite","sql":"SELECT CAST(2.5 AS NUMERIC) AS n;  -- 2.5, affinity only"}],"faqs":[{"question":"DECIMAL or NUMERIC?","answer":"The same type. Both spellings are in the SQL standard, and every engine here treats them as equivalent. Use whichever your dialect's docs lead with, and always give a precision and scale: without them SQL Server and MySQL use scale 0, so CAST(2.5 AS NUMERIC) is 3 there, while PostgreSQL keeps 2.5."},{"question":"Why did my division lose the decimals?","answer":"Two integer operands divide as integers on SQL Server, PostgreSQL and SQLite, so 7 / 2 is 3. Cast one operand to DECIMAL before dividing; casting the result is too late. On SQLite, CAST(7 AS DECIMAL(12,4)) is still the integer 7, so cast to REAL there. MySQL's 7 / 2 is already 3.5000, and DIV is its integer division."}],"related":["cast","cast-truncation","signed-unsigned","numeric-trunc"],"novel_uses":[{"body":"Recasting both sides to DECIMAL(20,6) replaces exact float equality with equality at six decimals, so totals that differ by one ulp match. PostgreSQL, MySQL, SQL Server and Oracle round at the target scale; SQLite's NUMERIC cast keeps the double as is, so use ROUND(x, 6) there.","sql":"SELECT a FROM balances WHERE CAST(a AS DECIMAL(20,6)) = CAST(b AS DECIMAL(20,6));"},{"body":"SQL Server computes AVG over an int column as an int, so 10 and 11 average to 10. Cast the operand, not the result: AVG(CAST(qty AS DECIMAL(12,2))) keeps the fraction.","sql":"SELECT AVG(CAST(qty AS DECIMAL(12,2))) AS avg_qty FROM order_lines;"}]},"source_url":"https://sqlly.app/sql-functions/decimal-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/decimal-literals","corpus":"sql-functions","engine":null,"language":"en","title":"SQL numeric literals","description":"0.1 in a query is an exact decimal on four engines and a binary float on SQLite. Adding an exponent (0.1e0) makes a float only on SQL Server and MySQL.","body":{"slug":"decimal-literals","name":"numeric literals","h1":"SQL numeric literals","category":"math","lede":"How the engines type bare literals like 0.1, 1.5e0 and 42: exact decimal on four engines, IEEE REAL on SQLite, and what each does with exponent notation.","syntax":"SELECT 0.1  |  SELECT 42  |  SELECT 1.5e0","return_type":"numeric or REAL","support":[{"engine_slug":"sql-server","status":"yes","note":"0.1 is exact DECIMAL; 1.5e0 is FLOAT"},{"engine_slug":"postgresql","status":"yes","note":"0.1 and 1.5e0 are both numeric; a float needs a cast such as 0.1::float8 or float8 '0.1'"},{"engine_slug":"mysql","status":"yes","note":"0.1 is exact DECIMAL; 1.5e0 is DOUBLE"},{"engine_slug":"sqlite","status":"no","note":"Every literal with a point or exponent is an IEEE REAL; there is no decimal literal type"},{"engine_slug":"oracle","status":"yes","note":"0.1 and 1.5e0 are both NUMBER; the d or f suffix (0.1d, 0.1f) makes BINARY_DOUBLE or BINARY_FLOAT"}],"gotchas":["SQLite's 0.1 is a REAL, so 0.1 + 0.2 holds 0.30000000000000004 there: the shell prints 0.3, but 0.1 + 0.2 = 0.3 is false. The other four engines compute an exact 0.3.","The exponent changes the type only on SQL Server and MySQL: 0.1 is decimal but 0.1e0 is float. PostgreSQL and Oracle keep 0.1e0 exact, so code that relies on e0 to force a float silently stays decimal there.","Integer literals stay integers, so 7 / 2 is 3 on SQL Server, PostgreSQL and SQLite. MySQL and Oracle return 3.5 for the same expression."],"examples":[{"engine_slug":"all","sql":"SELECT 0.1 + 0.2 AS literal_sum;  -- 0.3; on SQLite a REAL 0.30000000000000004 printed as 0.3"},{"engine_slug":"sqlite","sql":"SELECT 0.1 + 0.2 = 0.3 AS eq;  -- 0 (false): both sides are REAL"},{"engine_slug":"postgresql","sql":"SELECT pg_typeof(0.1) AS a, pg_typeof(0.1e0) AS b, pg_typeof(0.1::float8) AS c;  -- numeric, numeric, double precision"},{"engine_slug":"oracle","sql":"SELECT 0.1 + 0.2 AS exact_number FROM dual;  -- 0.3: both literals are NUMBER; 0.1d would be BINARY_DOUBLE"}],"faqs":[{"question":"Is the literal 0.1 exact in SQL?","answer":"On SQL Server, PostgreSQL, MySQL and Oracle yes: it is a decimal value. On SQLite no: 0.1 becomes an IEEE REAL, the nearest binary fraction, so 0.1 + 0.2 = 0.3 is false there."},{"question":"How do I force a literal to be a float?","answer":"It depends on the engine. On SQL Server and MySQL, add an exponent: 0.1e0. PostgreSQL needs a cast (0.1::float8) and Oracle a suffix (0.1d). SQLite literals are already floats; there is no way to make them exact, so compute in integers instead."},{"question":"Why does my literal division truncate?","answer":"Because both operands are integer literals, and SQL Server, PostgreSQL and SQLite truncate integer division: 7 / 2 is 3. Write 7 / 2.0; the point makes it a decimal literal and the division returns 3.5. MySQL and Oracle return 3.5 either way."}],"related":["numeric-vs-float","integer-division","cast-to-int","double-precision"],"novel_uses":[{"body":"MySQL hands 0.1 to the client as DECIMAL and 0.1e0 as DOUBLE, so the literal form decides the .NET or ODBC type a report column gets. Pick one form per report to keep client code stable.","sql":"SELECT 0.1e0 AS as_double, 0.1 AS as_decimal;"},{"body":"The numeric product adds its operands' scales, so total * 1.00 on a NUMERIC(10, 2) column renders four decimals (12.5000), not two. Addition keeps the larger scale, so total + 0.00 renders exactly two decimals in a SELECT list. It is display formatting, not a data change.","sql":"SELECT total + 0.00 AS total_2dp FROM invoices;"}]},"source_url":"https://sqlly.app/sql-functions/decimal-literals","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/decimal-overflow","corpus":"sql-functions","engine":null,"language":"en","title":"SQL decimal overflow","description":"NUMERIC(p, s) rounds extra decimals but rejects too many integer digits on SQL Server, PostgreSQL and Oracle. MySQL's CAST clamps to 999.99 instead.","body":{"slug":"decimal-overflow","name":"DECIMAL overflow","h1":"SQL decimal overflow","category":"math","lede":"Describes what happens when a value exceeds a decimal column's declared precision or scale: errors versus silent rounding, per engine.","syntax":"NUMERIC(5, 2)  |  INSERT ... VALUES (1234.567)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":"Error: 'Arithmetic overflow error converting numeric to data type numeric' when p is exceeded; scale overflow rounds on storage"},{"engine_slug":"postgresql","status":"yes","note":"Error 'numeric field overflow' when integer digits exceed p - s; excess scale digits round to the declared scale"},{"engine_slug":"mysql","status":"yes","note":"Excess scale rounds; excess integer digits clamp to the largest value (CAST(12345.6 AS DECIMAL(5,2)) is 999.99 with a warning), and an INSERT in strict mode fails instead"},{"engine_slug":"sqlite","status":"no","note":"No decimal type: NUMERIC affinity stores numeric-looking values as INTEGER or REAL (non-numeric text stays TEXT) and ignores the (5, 2), so there is nothing to overflow"},{"engine_slug":"oracle","status":"yes","note":"NUMBER(p, s) raises ORA-01438 when the value is larger than the precision allows"}],"gotchas":["Two different failures hide here: integer-digit overflow (too many digits before the point: an error on SQL Server, PostgreSQL and Oracle, a clamp on MySQL) and scale overflow (too many after: rounded on SQL Server, PostgreSQL and MySQL). SQLite declares no precision or scale, so it accepts both.","PostgreSQL's unsuffixed numeric has no declared precision, so only its built-in ceiling applies: 131072 digits before the decimal point, past which it raises 'value overflows numeric format'. Declared limits apply only when you write NUMERIC(p, s).","Arithmetic widens the result type rather than overflowing: on SQL Server NUMERIC(5,2) * NUMERIC(5,2) is NUMERIC(11,4), so 999.99 * 999.99 = 999980.0001 fits. The overflow comes when you store that into a NUMERIC(5,2) column."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(1234.567 AS NUMERIC(6, 2)) AS fits;  -- 1234.57\nSELECT CAST(1234.567 AS NUMERIC(5, 2)) AS overflow;  -- Msg 8115, arithmetic overflow"},{"engine_slug":"mysql","sql":"SELECT CAST(1234.567 AS DECIMAL(6, 2)) AS rounded, CAST(12345.6 AS DECIMAL(5, 2)) AS clamped;  -- 1234.57, 999.99"},{"engine_slug":"postgresql","sql":"SELECT 12345.6::NUMERIC(5, 2) AS boom;  -- ERROR: numeric field overflow"},{"engine_slug":"oracle","sql":"SELECT CAST(1234.567 AS NUMBER(6, 2)) AS fits FROM dual;  -- 1234.57\nSELECT CAST(1234.567 AS NUMBER(5, 2)) AS boom FROM dual;  -- ORA-01438"}],"faqs":[{"question":"What is the difference between precision and scale overflow?","answer":"Precision is total digits, scale is digits after the point. Too many integer digits errors on SQL Server, PostgreSQL and Oracle and clamps (CAST) or errors (strict INSERT) on MySQL. Too many decimals just round on every engine that declares a scale (SQL Server, PostgreSQL, MySQL, Oracle); SQLite ignores the scale and keeps them."},{"question":"Does plain NUMERIC ever overflow in PostgreSQL?","answer":"Not in practice. NUMERIC without (p, s) grows as needed, up to 131072 digits before the decimal point. The 'numeric field overflow' error appears only for declared NUMERIC(p, s) columns and casts."},{"question":"Why does MySQL round instead of erroring?","answer":"MySQL's traditional behaviour is to fit the value to the type: round the scale and clamp the integer part, with a warning. In the default strict mode an INSERT or UPDATE that would clamp fails instead; CAST in a SELECT still clamps."}],"related":["numeric-precision-scale","integer-overflow","numeric-vs-float","cast"],"novel_uses":[{"body":"value IS NOT NULL AND TRY_CAST(value AS NUMERIC(5, 2)) IS NULL lists exactly the rows an INSERT would reject, before the batch runs. SQL Server answers with NULL instead of a message, so the sweep never aborts.","sql":"SELECT * FROM staged WHERE value IS NOT NULL AND TRY_CAST(value AS NUMERIC(5, 2)) IS NULL;"},{"body":"MAX(ABS(value)) over the staged rows gives the largest magnitude the column must hold; its integer digits plus the scale you choose give the precision to declare. On a text column, cast with TRY_CAST first, since ABS fails on non-numeric text. Sizing from observed maxima beats guessing NUMERIC(18, 6) and hoping.","sql":"SELECT MAX(ABS(value)) AS max_abs, COUNT(*) AS row_count FROM staged;"}]},"source_url":"https://sqlly.app/sql-functions/decimal-overflow","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/decode","corpus":"sql-functions","engine":null,"language":"en","title":"Oracle DECODE function","description":"Oracle's DECODE: value-pair matching inside a query, how it treats two NULLs as equal where CASE does not, and what to use on other engines.","body":{"slug":"decode","name":"DECODE","h1":"Oracle DECODE function","category":"conditional","lede":"Oracle's compact value matcher: DECODE(status, 'A', 'Active', 'I', 'Inactive', 'Unknown') checks the search values in order and returns the paired result, or the default. It is Oracle-only.","syntax":"DECODE(expr, search1, result1 [, search2, result2 ...] [, default])","return_type":"type of the first result","support":[{"engine_slug":"sql-server","status":"no","note":"no DECODE; use CASE"},{"engine_slug":"postgresql","status":"no","note":"no DECODE; use CASE"},{"engine_slug":"mysql","status":"no","note":"no DECODE in MySQL 8; the 5.7 DECODE() was an unrelated decryption function, now removed"},{"engine_slug":"sqlite","status":"no","note":"no DECODE; use CASE or IIF"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["DECODE treats two NULLs as equal, so a NULL search value matches a NULL input. A simple CASE x WHEN NULL never matches; you need a searched CASE with WHEN x IS NULL.","The result type follows the first result: if it is a number, a later result like 'x' raises ORA-01722 on the rows that return it; if it is NULL, the result is VARCHAR2.","MySQL 5.7 had a DECODE() that decrypted strings made by ENCODE(). It was removed in MySQL 8.0, and it never did what Oracle's does; port Oracle DECODE to CASE."],"examples":[{"engine_slug":"oracle","sql":"SELECT DECODE(status, 'A', 'Active', 'I', 'Inactive', 'Unknown') AS label\nFROM accounts;"},{"engine_slug":"oracle","sql":"-- NULL matching, which CASE cannot express with =\nSELECT DECODE(manager_id, NULL, 'No manager', 'Has manager') AS flag\nFROM employees;"}],"faqs":[{"question":"Is DECODE available outside Oracle?","answer":"Not as a conditional. SQL Server, MySQL 8 and SQLite have no DECODE. PostgreSQL's decode(text, format) turns base64 or hex text into bytes, which is unrelated. CASE is the portable replacement."},{"question":"How does DECODE handle NULL?","answer":"Unlike CASE, DECODE considers two NULLs equal: DECODE(col, NULL, 'missing', 'present') works, where CASE WHEN col = NULL never matches. Use IS NULL in CASE instead."}],"related":["case","coalesce","iif"],"novel_uses":[{"body":"Before Oracle 11g added the PIVOT clause, crosstabs were a dozen SUM(DECODE(month, 1, amount)) columns. The shape is still worth recognizing in older code, and it ports to CASE where DECODE is not available.","sql":"SELECT dept,\n       SUM(DECODE(month_no, 1, amount)) AS jan,\n       SUM(DECODE(month_no, 2, amount)) AS feb\nFROM budgets\nGROUP BY dept;"},{"body":"SIGN collapses a difference to -1, 0 or 1 and DECODE maps each to a label: over, under or on target in one expression. DECODE's NULL-equals-NULL quirk routes a NULL difference to the default branch instead of erroring.","sql":"SELECT account,\n       DECODE(SIGN(actual - budget), 1, 'over', -1, 'under', 'on target') AS status\nFROM budgets;"}]},"source_url":"https://sqlly.app/sql-functions/decode","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dedupe-rows","corpus":"sql-functions","engine":null,"language":"en","title":"SQL deduplicate with window functions","description":"Remove duplicates but keep the freshest row: ROW_NUMBER over the business key ordered by recency, then delete where rn > 1 or select where rn = 1 to keep the survivors.","body":{"slug":"dedupe-rows","name":"Deduplicate Rows","h1":"SQL deduplicate with window functions","category":"window","lede":"Number rows per duplicate key with ROW_NUMBER and keep rn = 1 (or delete rn > 1), deduplication that plain DISTINCT cannot express, deterministic only when the ORDER BY ends in a unique tiebreaker.","syntax":"WITH d AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY key1, key2 ORDER BY updated_at DESC) AS rn FROM t)\nSELECT * FROM d WHERE rn = 1","return_type":"one row per key","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+; delete with WITH ... DELETE t FROM t JOIN cte"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; delete with WITH ... DELETE FROM t WHERE id IN (SELECT id FROM cte ...)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["DISTINCT removes full-row duplicates only. When duplicates differ in timestamps or status, DISTINCT keeps them all; ROW_NUMBER lets you choose the survivor.","Deletion syntax differs per engine: SQL Server deletes straight from the CTE; PostgreSQL uses DELETE ... USING the CTE; MySQL needs a multi-table DELETE t FROM t JOIN cte; SQLite (no multi-table DELETE) and Oracle use WHERE id IN (subquery), Oracle often with ROWID as the key.","The ORDER BY decides the survivor; updated_at DESC keeps the newest but ties again make it nondeterministic without an id tiebreaker."],"examples":[{"engine_slug":"sql-server","sql":"-- delete stale duplicates\nWITH d AS (\n  SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn\n  FROM contacts\n)\nDELETE FROM d WHERE rn > 1;"},{"engine_slug":"postgresql","sql":"WITH d AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn\n  FROM contacts\n)\nDELETE FROM contacts c USING d WHERE c.id = d.id AND d.rn > 1;"},{"engine_slug":"mysql","sql":"WITH d AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn\n  FROM contacts\n)\nDELETE c FROM contacts c JOIN d ON c.id = d.id WHERE d.rn > 1;"},{"engine_slug":"sqlite","sql":"WITH d AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn\n  FROM contacts\n)\nDELETE FROM contacts WHERE id IN (SELECT id FROM d WHERE rn > 1);"},{"engine_slug":"oracle","sql":"DELETE FROM contacts\nWHERE ROWID IN (\n  SELECT rid FROM (\n    SELECT ROWID AS rid,\n           ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn\n    FROM contacts\n  ) WHERE rn > 1\n);"}],"faqs":[{"question":"Why not just SELECT DISTINCT?","answer":"DISTINCT collapses only identical rows and picks no survivor. Duplicates usually differ (two updated_at values), so you need a rule; that rule is the ROW_NUMBER's ORDER BY."},{"question":"How do I dedupe without deleting anything?","answer":"The same CTE with WHERE rn = 1 in a view or report keeps the raw table intact, the safer default when you are not sure which rows are 'real' duplicates."}],"related":["row-number","top-n-per-group","count-distinct"],"novel_uses":[{"body":"Put a CASE on NULL columns ahead of updated_at in the ORDER BY and the row that actually has the data wins, not just the newest one. Recency and completeness disagree constantly in contact tables.","sql":"WITH d AS (\n  SELECT *, ROW_NUMBER() OVER (PARTITION BY email\n    ORDER BY CASE WHEN phone IS NOT NULL THEN 0 ELSE 1 END, updated_at DESC) AS rn\n  FROM contacts\n)\nSELECT * FROM d\nWHERE rn = 1;"},{"body":"Run the same ROW_NUMBER and report the losers instead of deleting them: one row per duplicated key with its extra-copy count. The audit tells you whether the ORDER BY rule would keep the row your users consider real.","sql":"WITH d AS (\n  SELECT email, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn\n  FROM contacts\n)\nSELECT email, SUM(CASE WHEN rn > 1 THEN 1 ELSE 0 END) AS extra_copies\nFROM d\nGROUP BY email\nHAVING SUM(CASE WHEN rn > 1 THEN 1 ELSE 0 END) > 0;"},{"body":"Partition on lower(trim(email)) and case or whitespace differences stop hiding duplicates. Normalize in the PARTITION BY, keep the raw column for output, and the same query reports and deletes against the canonical key.","sql":"WITH d AS (\n  SELECT *, ROW_NUMBER() OVER (PARTITION BY LOWER(TRIM(email))\n    ORDER BY updated_at DESC) AS rn\n  FROM contacts\n)\nSELECT * FROM d\nWHERE rn = 1;"}]},"source_url":"https://sqlly.app/sql-functions/dedupe-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/degrees","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DEGREES function","description":"DEGREES(x) converts radians to degrees by multiplying by 180/pi. Oracle lacks it, and SQL Server returns an INT for INT input: DEGREES(1) is 57.","body":{"slug":"degrees","name":"DEGREES","h1":"SQL DEGREES function","category":"math","lede":"Converts an angle from radians to degrees: DEGREES(PI()) is 180 and DEGREES(PI()/2) is 90.","syntax":"DEGREES(angle_radians)","return_type":"double; SQL Server returns the input's type","support":[{"engine_slug":"sql-server","status":"yes","note":"Returns the input's type: DEGREES(1) is 57, DEGREES(1.0) is 57.295779513082322865"},{"engine_slug":"postgresql","status":"yes","note":"degrees(double precision) only; numeric input is cast to double"},{"engine_slug":"mysql","status":"yes","note":"MySQL ships DEGREES() in core"},{"engine_slug":"sqlite","status":"yes","note":"Part of the 3.35+ math function set"},{"engine_slug":"oracle","status":"no","note":"No DEGREES; use x * 180 / ACOS(-1)"}],"gotchas":["It is pure arithmetic: DEGREES(x) is x * 180 / PI(). On Oracle write x * 180 / ACOS(-1), since Oracle has neither DEGREES nor PI().","Trig functions stay radian-only on every engine; DEGREES is for display and for converting results like ASIN(0.5) into 30.","On SQL Server, DEGREES of an integer stays an integer and truncates: DEGREES(1) is 57, not 57.2958. Pass 1.0 or a float. Elsewhere small float noise appears instead: DEGREES(ASIN(0.5)) is 30.000000000000004 on PostgreSQL, MySQL and SQL Server, but 29.999999999999996 on the macOS build of SQLite, because the last digits come from the platform math library."],"examples":[{"engine_slug":"postgresql","sql":"SELECT DEGREES(PI()) AS straight_angle;  -- 180"},{"engine_slug":"postgresql","sql":"SELECT DEGREES(ASIN(0.5)) AS thirty_degrees;  -- 30.000000000000004"},{"engine_slug":"sql-server","sql":"SELECT DEGREES(1) AS int_in, DEGREES(1.0) AS dec_in;  -- 57, 57.295779513082322865"},{"engine_slug":"mysql","sql":"SELECT DEGREES(PI()) AS straight_angle;  -- 180"},{"engine_slug":"sqlite","sql":"SELECT degrees(pi()) AS straight_angle;  -- 180.0"},{"engine_slug":"oracle","sql":"SELECT ASIN(0.5) * 180 / ACOS(-1) AS degrees FROM dual;"}],"faqs":[{"question":"What is the formula behind DEGREES?","answer":"x * 180 / PI(). On Oracle, which has neither function, write x * 180 / ACOS(-1)."},{"question":"Why does Oracle have no DEGREES?","answer":"It never shipped one, and it has no PI() either. Multiply manually: angle * 180 / ACOS(-1)."},{"question":"Does DEGREES make SIN accept degrees?","answer":"No. DEGREES converts radians to degrees, the opposite direction of what SIN needs. Convert degrees to radians with RADIANS() before calling trig functions. On SQL Server write 30.0 rather than 30, because RADIANS(30) on an integer returns the integer 0 and SIN of that is 0."}],"related":["radians","pi","sin","asin"],"novel_uses":[{"body":"CAST(FLOOR((DEGREES(bearing) + 382.5) / 45.0) AS INT) % 8 numbers the eight compass sectors, offset so north centers its bucket, and a CASE turns the number into N, NE, E and friends. The cast to INT is what lets the % run on PostgreSQL, where % has no double precision operator; it does accept integer and numeric.","sql":"SELECT CAST(FLOOR((DEGREES(bearing) + 382.5) / 45.0) AS INT) % 8 AS sector FROM fixes;"},{"body":"The shortest angle between two headings is ABS(DEGREES(a) - DEGREES(b)), flipped to 360 minus itself when it passes 180. Alert checks over stored radian columns need this to notice that 350 and 10 degrees are 20 apart, not 340.","sql":"SELECT CASE WHEN d > 180 THEN 360 - d ELSE d END AS sep FROM (SELECT ABS(DEGREES(h1) - DEGREES(h2)) AS d FROM headings) t;"}]},"source_url":"https://sqlly.app/sql-functions/degrees","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dense-rank","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DENSE_RANK function","description":"DENSE_RANK in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: contiguous ranks for tied rows, versus RANK and ROW_NUMBER, with grouping uses.","body":{"slug":"dense-rank","name":"DENSE_RANK","h1":"SQL DENSE_RANK function","category":"window","lede":"Ranks rows within a partition like RANK, but never skips numbers after a tie: 1, 2, 2, 3. It also numbers the distinct values of a column without a GROUP BY.","syntax":"DENSE_RANK() OVER (PARTITION BY g ORDER BY x)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Because the numbers never skip, DENSE_RANK() OVER (ORDER BY category) gives each distinct category its own number, 1, 2, 3..., and MAX of it is the number of distinct categories.","On MySQL before 8.0 and SQLite before 3.25 there is no DENSE_RANK; user variables or a DISTINCT + COUNT subquery emulate it.","Like all window functions, it cannot be used in WHERE. Compute it in a CTE and filter outside: WHERE dr <= 3 keeps every row in the top three distinct scores, ties included."],"examples":[{"engine_slug":"all","sql":"SELECT name, points,\n       DENSE_RANK() OVER (ORDER BY points DESC) AS position\nFROM players;"},{"engine_slug":"all","sql":"SELECT category,\n       DENSE_RANK() OVER (ORDER BY category) AS category_no\nFROM products;"}],"faqs":[{"question":"When should I use DENSE_RANK instead of RANK?","answer":"When the gaps hurt: leaderboards that publish 1, 2, 2, 3 rather than 1, 2, 2, 4, or numbering distinct values without a GROUP BY."},{"question":"Does DENSE_RANK work on MySQL 5.7?","answer":"No. Window functions arrived in MySQL 8.0. On 5.7, a correlated subquery does it: (SELECT COUNT(DISTINCT p2.points) FROM players p2 WHERE p2.points >= p.points)."}],"related":["rank","row-number","ntile"],"novel_uses":[{"body":"DENSE_RANK() OVER (ORDER BY category) assigns small sequential integers to categories, which is exactly what a star-schema key is. The same expression inside INSERT ... SELECT populates the dimension table without a merge.","sql":"INSERT INTO dim_category (category_key, category)\nSELECT DISTINCT (DENSE_RANK() OVER (ORDER BY category))::int, category\nFROM staging;"},{"body":"For one row per day, date minus dense rank of that date is constant while days are consecutive. Grouping by that value gives every streak an id, and counting its rows sizes it. The date arithmetic differs per engine; PostgreSQL subtracts an integer from a date directly.","sql":"SELECT player, MIN(day) AS started, COUNT(*) AS streak_len\nFROM (\n  SELECT player, day,\n         day - (DENSE_RANK() OVER (PARTITION BY player ORDER BY day))::int AS grp\n  FROM (SELECT DISTINCT player, day::date AS day FROM logins) d\n) s\nGROUP BY player, grp;"}]},"source_url":"https://sqlly.app/sql-functions/dense-rank","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/deterministic-window-order","corpus":"sql-functions","engine":null,"language":"en","title":"SQL deterministic window ordering","description":"Ties inside OVER (ORDER BY ...) make ROW_NUMBER and running totals unstable: why, and the unique-tiebreaker habit that fixes it.","body":{"slug":"deterministic-window-order","name":"Deterministic Window Order","h1":"SQL deterministic window ordering","category":"window","lede":"A window ORDER BY that does not uniquely identify rows leaves tie order to the engine, so numbers and running sums can change between runs.","syntax":"ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC, id)","return_type":"stable per-row values","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Any unique column (primary key, id) appended as the last ORDER BY key makes the order total; without one, equal-key rows can permute and flip dedupes, top-N cuts and deltas.","RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST and default-frame (RANGE) aggregates give tied rows identical values, so they are stable without tiebreakers. ROW_NUMBER, NTILE, LAG/LEAD, FIRST_VALUE/LAST_VALUE and ROWS frames are the ones that wobble.","Tie order follows the plan: a parallel scan, a new index or a different row count can change it, so a query that passes on a small test table can number rows differently in production."],"examples":[{"engine_slug":"all","sql":"-- order_id breaks the tie: without it, equal amounts may swap numbers\nSELECT customer_id, order_id, amount,\n       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, order_id) AS rn\nFROM orders;"}],"faqs":[{"question":"Do I need a tiebreaker if I use RANK?","answer":"Not for stability: tied rows legitimately share a rank. But if the query then filters RANK() = 1 you can get several rows; that is the tie speaking, not nondeterminism."},{"question":"Why did my running total change between environments?","answer":"The frame is ROWS and the ORDER BY has ties, so tied rows accumulated in a different order and the partial sums changed. Add a unique tiebreaker to the ORDER BY. (The default RANGE frame does not have this problem: tied rows all get the same total.)"}],"related":["row-number","running-total","window-nulls-order"],"novel_uses":[{"body":"The appended tiebreaker decides which tied row wins, so pick one that means something: created_at DESC, order_id keeps the newer order on top instead of rewarding insertion luck. Any unique column stops the wobble; a meaningful one stops arguments.","sql":"SELECT order_id, customer_id, amount,\n       ROW_NUMBER() OVER (PARTITION BY customer_id\n         ORDER BY amount DESC, created_at DESC, order_id) AS rn\nFROM orders;"},{"body":"Partition by time of day and order by date, and LAG compares 9am today with 9am yesterday rather than with the previous raw row. The partition key is the alignment; ORDER BY day needs no tiebreaker only because each slot has one row per day, so add one if a slot can repeat a day.","sql":"SELECT day, slot, sales,\n       sales - LAG(sales) OVER (PARTITION BY slot ORDER BY day) AS vs_same_slot\nFROM hourly_sales;"}]},"source_url":"https://sqlly.app/sql-functions/deterministic-window-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/difference","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DIFFERENCE function","description":"SQL Server's DIFFERENCE scores how alike two strings sound, 0 to 4, by comparing their SOUNDEX codes, quick fuzzy matching in one call.","body":{"slug":"difference","name":"DIFFERENCE","h1":"SQL DIFFERENCE function","category":"string","lede":"Returns an integer 0 (nothing alike) through 4 (same SOUNDEX code). Cheap phonetic similarity for grouping typos of names.","syntax":"DIFFERENCE(string1, string2)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"difference() in the fuzzystrmatch extension, same 0-4 scale"},{"engine_slug":"mysql","status":"no","note":"no DIFFERENCE; compare SOUNDEX codes directly"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":"no DIFFERENCE; UTL_MATCH scores edit distance or Jaro-Winkler"}],"gotchas":["The score is not a position-by-position count of the four SOUNDEX characters: GREEN (G650) and KATHERINE (K365) share no position and still score 2. 4 means identical codes, not identical words.","It inherits every SOUNDEX weakness: the first letter is kept literally, so DIFFERENCE('Catherine', 'Katherine') is only 3, plus English bias and unrelated short names that collide.","Returns NULL if either input is NULL, but an empty string is not NULL: DIFFERENCE('', '') is 4 and DIFFERENCE('', 'Smith') is 2, so filter blanks first. It is a scalar call: for fuzzy joins over big tables it scans, with no index help.","Other engines: PostgreSQL's fuzzystrmatch extension has difference() on the same scale, plus levenshtein(); MySQL has no DIFFERENCE, so compare SOUNDEX codes directly."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DIFFERENCE('Smith', 'Smyth') AS sim;  -- 4"},{"engine_slug":"sql-server","sql":"SELECT DIFFERENCE('Green', 'Hill') AS sim;  -- 1 (G650 vs H400)"},{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;\nSELECT difference('Smith', 'Smyth') AS sim;  -- 4"}],"faqs":[{"question":"What does DIFFERENCE = 4 mean?","answer":"The two inputs have identical SOUNDEX codes; they sound alike by that algorithm. It says nothing about spelling or meaning."},{"question":"Can I use DIFFERENCE in a JOIN?","answer":"Technically yes, but every pair is scored at runtime with no index support: fine on small sets, painful on large ones. Precompute SOUNDEX codes into indexed columns instead."},{"question":"What is the MySQL equivalent?","answer":"None built in. Compare SOUNDEX(a) = SOUNDEX(b) for the same signal, or implement Levenshtein in a function for distance-based matching."}],"related":["soundex","string-sort","case-insensitive-collation"],"novel_uses":[{"body":"DIFFERENCE of 3 or 4 between two different rows lists the name pairs worth a human look, one query instead of a fuzzy-matching framework.","sql":"SELECT a.name, b.name FROM users a JOIN users b\n  ON a.id < b.id AND DIFFERENCE(a.last_name, b.last_name) >= 3;"},{"body":"ORDER BY DIFFERENCE(input, name) DESC with TOP returns the closest-sounding matches for a merge or autocomplete shortlist, no extension needed on SQL Server.","sql":"SELECT TOP (10) name FROM users ORDER BY DIFFERENCE('Katherine', name) DESC;"}]},"source_url":"https://sqlly.app/sql-functions/difference","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/difference-from-previous","corpus":"sql-functions","engine":null,"language":"en","title":"SQL difference from the previous row","description":"LAG-based deltas: day-over-day change, delta from the prior event and the first-row NULL, with the pattern that works on every window-capable engine.","body":{"slug":"difference-from-previous","name":"Difference From Previous Row","h1":"SQL difference from the previous row","category":"window","lede":"Subtract LAG's value from the current row to get the change since the previous row: day-over-day revenue, time between events, price moves.","syntax":"x - LAG(x) OVER (ORDER BY d) | x - LAG(x, 1, x) OVER (PARTITION BY g ORDER BY d)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The first row's difference is NULL because LAG has nothing to return; wrap in COALESCE if the report needs 0, but consider whether a fake zero belongs in the metric.","Ordering must be unique for stable deltas: ORDER BY day can reorder tied days and produce a meaningless delta. Add a tiebreaker column.","Against a fixed baseline (change since the first day) subtract FIRST_VALUE(x) OVER (PARTITION BY g ORDER BY d) instead of LAG."],"examples":[{"engine_slug":"all","sql":"SELECT day, closes,\n       closes - LAG(closes) OVER (ORDER BY day) AS day_change\nFROM stock_days;"},{"engine_slug":"all","sql":"-- per-store delta; LAG defaults to the row's own sales, so the first row's delta is 0\nSELECT store_id, day, sales,\n       sales - LAG(sales, 1, sales) OVER (PARTITION BY store_id ORDER BY day) AS delta\nFROM store_sales;"}],"faqs":[{"question":"How do I get the difference in days between rows?","answer":"LAG the date column, then use each engine's date arithmetic. PostgreSQL and Oracle subtract DATE values directly and return days. SQL Server rejects date - date ('Operand data type date is invalid for subtract operator'), so write DATEDIFF(day, LAG(d) OVER (...), d) for a column d. MySQL's date - date subtracts YYYYMMDD numbers (2024-02-01 minus 2024-01-31 is 70), so use DATEDIFF(d, LAG(d) OVER (...)). SQLite needs julianday(d) - julianday(LAG(d) OVER (...))."},{"question":"Why is my difference NULL on every first row?","answer":"LAG returns the default (NULL unless you pass a third argument) when there is no previous row in the partition. Pass LAG(x, 1, x) for a zero difference: LAG(x, 1, 0) makes the first-row difference equal x itself, because the default is subtracted too. Or handle NULLs in the report layer."}],"related":["lag","period-over-period","running-total"],"novel_uses":[{"body":"Subtracting LAG of the id from the id exposes holes: a gap above 1 means rows are missing, which is how you audit auto-increment health or spot deleted records. NULL on the first row is expected, not a gap.","sql":"SELECT id,\n       id - LAG(id) OVER (ORDER BY id) AS gap_to_previous\nFROM events;"},{"body":"Apply the delta twice and the column becomes acceleration: a steady trend has a near-zero second difference while a sudden jump lights up. It is the cheapest anomaly flag that ignores slow drift.","sql":"SELECT day, sales,\n       sales - 2 * LAG(sales) OVER (ORDER BY day)\n         + LAG(sales, 2) OVER (ORDER BY day) AS accel\nFROM daily_sales;"},{"body":"On PostgreSQL, EXTRACT(EPOCH FROM ts - LAG(ts) OVER (ORDER BY ts)) gives inter-arrival seconds, the input for arrival rates and timeout alerts. Each engine spells date subtraction differently, so build this column once in a CTE and reuse it.","sql":"SELECT event_id, ts,\n       EXTRACT(EPOCH FROM ts - LAG(ts) OVER (ORDER BY ts)) AS seconds_since_previous\nFROM events;"}]},"source_url":"https://sqlly.app/sql-functions/difference-from-previous","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/distinct-aggregates","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DISTINCT aggregates","description":"COUNT(DISTINCT x), SUM(DISTINCT x) and AVG(DISTINCT x) dedupe before aggregating: engine support, multi-column DISTINCT counts and SQLite's one-argument rule.","body":{"slug":"distinct-aggregates","name":"DISTINCT","h1":"SQL DISTINCT aggregates","category":"aggregate","lede":"Aggregates that drop duplicate values before counting, summing or averaging.","syntax":"COUNT(DISTINCT x) | AVG(DISTINCT x) | GROUP_CONCAT(DISTINCT x)","return_type":"numeric or string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["AVG(DISTINCT x) divides by the number of unique values, not rows, almost never what you want; dedupe upstream instead.","Counting distinct pairs: MySQL accepts COUNT(DISTINCT a, b) and skips any pair containing a NULL; PostgreSQL needs the row form COUNT(DISTINCT (a, b)); SQL Server, Oracle and SQLite need a subquery or a concatenated key.","SQLite allows DISTINCT only on one-argument aggregates, so GROUP_CONCAT(DISTINCT x, ';') is a parse error. PostgreSQL requires ORDER BY expressions in a DISTINCT aggregate to appear in its argument list; MySQL's GROUP_CONCAT(DISTINCT a ORDER BY b) is allowed. SQL Server's STRING_AGG rejects DISTINCT, so dedupe in a subquery first.","Exact DISTINCT counting is memory-hungry at scale; that is what APPROX_COUNT_DISTINCT trades accuracy against."],"examples":[{"engine_slug":"all","sql":"SELECT COUNT(DISTINCT customer_id) FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT COUNT(DISTINCT (order_id, product_id)) FROM line_items;"},{"engine_slug":"mysql","sql":"SELECT GROUP_CONCAT(DISTINCT tag ORDER BY tag) FROM posts;"}],"faqs":[{"question":"Can I use DISTINCT across two columns?","answer":"MySQL: COUNT(DISTINCT a, b) counts distinct pairs; PostgreSQL: COUNT(DISTINCT (a, b)); SQL Server, Oracle and SQLite: SELECT COUNT(*) FROM (SELECT DISTINCT a, b FROM t) d. The answers differ when a column holds NULL: MySQL skips any pair containing one, while the PostgreSQL row form and the subquery count those pairs too."},{"question":"Is SUM(DISTINCT) ever useful?","answer":"Rarely: it sums each value once. If you meant deduplicated rows, you usually want a subquery or a join instead."},{"question":"Why is COUNT(DISTINCT) slow on big tables?","answer":"It must build the full distinct set; an index on the column helps, or APPROX_COUNT_DISTINCT (SQL Server, Oracle) when a few percent of error is fine."}],"related":["count-distinct","approx-count-distinct","group-concat","aggregate-nulls"],"novel_uses":[{"body":"COUNT(DISTINCT CASE WHEN country = 'US' THEN user_id END) pivots distinct users per group in one pass, and non-matching rows drop out because the CASE yields NULL.","sql":"SELECT plan, COUNT(DISTINCT CASE WHEN country = 'US' THEN user_id END) AS us_users FROM subscriptions GROUP BY plan;"},{"body":"DISTINCT accepts any expression: COUNT(DISTINCT date_trunc('day', at)) counts active days per user in PostgreSQL, no derived table needed.","sql":"SELECT user_id, COUNT(DISTINCT date_trunc('day', at)) AS active_days FROM events GROUP BY user_id;"}]},"source_url":"https://sqlly.app/sql-functions/distinct-aggregates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/distinct-from","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IS DISTINCT FROM operator","description":"IS DISTINCT FROM compares values treating NULL as a real value: SQL Server 2022, PostgreSQL and SQLite support, MySQL's <=>, Oracle recipes and change-detection uses.","body":{"slug":"distinct-from","name":"IS DISTINCT FROM","h1":"SQL IS DISTINCT FROM operator","category":"conditional","lede":"Equality that treats two NULLs as equal instead of unknown.","syntax":"a IS DISTINCT FROM b | a IS NOT DISTINCT FROM b","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"MySQL has no IS DISTINCT FROM; use <=>"},{"engine_slug":"sqlite","status":"yes","note":"IS DISTINCT FROM since SQLite 3.39; IS / IS NOT always worked"},{"engine_slug":"oracle","status":"partial","note":"not in 23ai; use DECODE(a, b, 1, 0) = 1 or SYS_OP_MAP_NONNULL"}],"gotchas":["Two NULLs are NOT DISTINCT (equal), so a IS NOT DISTINCT FROM b is the NULL-safe =.","IS DISTINCT FROM never returns UNKNOWN: it is two-valued, which makes NOT of it behave intuitively.","Oracle's DECODE treats two NULLs as equal, unlike CASE, which makes DECODE(a, b, 1, 0) = 1 the local recipe.","SQLite's IS and IS NOT have been the null-safe comparison for years (any operands since 3.6.19); the IS DISTINCT FROM spelling arrived in 3.39."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE a IS DISTINCT FROM b;"},{"engine_slug":"sql-server","sql":"SELECT * FROM t WHERE a IS NOT DISTINCT FROM b;"},{"engine_slug":"sqlite","sql":"SELECT * FROM t WHERE a IS NOT b;"},{"engine_slug":"oracle","sql":"SELECT * FROM t WHERE DECODE(a, b, 1, 0) = 1;"}],"faqs":[{"question":"Is NULL IS NOT DISTINCT FROM NULL true?","answer":"Yes. That is the feature: null-safe equality where two unknowns count as the same."},{"question":"What is MySQL's equivalent?","answer":"<=>: NULL <=> NULL is 1, unlike NULL = NULL."},{"question":"How about Oracle?","answer":"DECODE(a, b, 1, 0) = 1, or the undocumented SYS_OP_MAP_NONNULL on both sides."}],"related":["null-safe-equal","three-valued-logic","is-null","null-safe-join","decode"],"novel_uses":[{"body":"A PostgreSQL trigger WHEN clause comparing OLD with NEW via IS DISTINCT FROM skips no-op updates, so audit tables fill with real changes only.","sql":"CREATE FUNCTION log_status_change() RETURNS trigger LANGUAGE plpgsql AS $$\nBEGIN\n  INSERT INTO audit(account_id, at) VALUES (NEW.id, now());\n  RETURN NULL;\nEND $$;\n\nCREATE TRIGGER t_a AFTER UPDATE ON accounts FOR EACH ROW\nWHEN (OLD.status IS DISTINCT FROM NEW.status)\nEXECUTE FUNCTION log_status_change();"},{"body":"Comparing payloads with IS DISTINCT FROM queues only genuine differences when two systems sync, NULLs included.","sql":"SELECT a.id FROM src a JOIN dst b ON a.id = b.id WHERE a.payload IS DISTINCT FROM b.payload;"}]},"source_url":"https://sqlly.app/sql-functions/distinct-from","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/distinct-in-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DISTINCT inside window aggregates","description":"COUNT(DISTINCT x) OVER and friends: Oracle runs it (without ORDER BY), the other four engines refuse it, with the portable workarounds.","body":{"slug":"distinct-in-window","name":"DISTINCT in Window Aggregates","h1":"SQL DISTINCT inside window aggregates","category":"window","lede":"DISTINCT inside a windowed aggregate works only on Oracle, and only over a whole partition; everywhere else it is an error and needs a rewrite.","syntax":"COUNT(DISTINCT x) OVER (PARTITION BY g) | COUNT(DISTINCT x) OVER ()","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"no","note":"'Use of DISTINCT is not allowed with the OVER clause'"},{"engine_slug":"postgresql","status":"no","note":"'DISTINCT is not implemented for window functions'"},{"engine_slug":"mysql","status":"no","note":"'doesn't yet support <window function>(DISTINCT ..)'"},{"engine_slug":"sqlite","status":"no","note":"'DISTINCT is not supported for window functions'"},{"engine_slug":"oracle","status":"yes","note":"supported with PARTITION BY only; ORDER BY in the OVER raises ORA-30487"}],"gotchas":["To keep every detail row, use two DENSE_RANKs: DENSE_RANK() OVER (PARTITION BY g ORDER BY x) + DENSE_RANK() OVER (PARTITION BY g ORDER BY x DESC) - 1 is the distinct count of x per partition, provided x has no NULLs.","The other route is to deduplicate (g, x) pairs in a CTE and window-count those, as in the first example; it is simple but returns one row per pair, not per detail row.","SUM(DISTINCT x) and AVG(DISTINCT x) follow the same matrix. They add each distinct value once, so two different orders of 50.00 count as one 50.00, rarely the intended number."],"examples":[{"engine_slug":"all","sql":"-- portable: distinct the pairs, then window\nWITH pairs AS (\n  SELECT DISTINCT customer_id, product_id FROM orders\n)\nSELECT customer_id, product_id,\n       COUNT(product_id) OVER (PARTITION BY customer_id) AS products_bought\nFROM pairs;"},{"engine_slug":"oracle","sql":"SELECT customer_id, product_id,\n       COUNT(DISTINCT product_id) OVER (PARTITION BY customer_id) AS products_bought\nFROM orders;"}],"faqs":[{"question":"Which engines allow COUNT(DISTINCT) OVER?","answer":"Only Oracle, and only with PARTITION BY (no ORDER BY, so no running distinct count). SQL Server, PostgreSQL, MySQL and SQLite all reject it with an error rather than returning a wrong count."},{"question":"What is the simplest emulation that keeps every row?","answer":"The double DENSE_RANK: DENSE_RANK() OVER (PARTITION BY g ORDER BY x) + DENSE_RANK() OVER (PARTITION BY g ORDER BY x DESC) - 1. It runs on all five engines. If x can be NULL, NULL counts as one extra value, so subtract 1 for partitions that contain a NULL."}],"related":["count-over","count-distinct","aggregate-over"],"novel_uses":[{"body":"Mark each value's first occurrence with ROW_NUMBER inside a (key, value) partition, then run a conditional running SUM over those flags: the column is the number of distinct products seen so far. No engine needs COUNT(DISTINCT) for this, which is lucky because only Oracle has it.","sql":"WITH marks AS (\n  SELECT customer_id, order_day, product_id,\n         ROW_NUMBER() OVER (PARTITION BY customer_id, product_id ORDER BY order_day) AS nth_buy\n  FROM orders\n)\nSELECT customer_id, order_day,\n       SUM(CASE WHEN nth_buy = 1 THEN 1 ELSE 0 END)\n         OVER (PARTITION BY customer_id ORDER BY order_day) AS products_so_far\nFROM marks;"},{"body":"Distinct products divided by total line items is the variety ratio, and one minus it is the repeat rate: how much of the buying is restocking rather than exploring. Join the count from the pairs CTE back to the line-item total per customer and divide.","sql":"WITH pairs AS (\n  SELECT DISTINCT customer_id, product_id FROM orders\n),\nvariety AS (\n  SELECT customer_id, COUNT(*) AS distinct_products FROM pairs GROUP BY customer_id\n),\nitems AS (\n  SELECT customer_id, COUNT(*) AS line_items FROM orders GROUP BY customer_id\n)\nSELECT v.customer_id, v.distinct_products, i.line_items,\n       1 - 1.0 * v.distinct_products / i.line_items AS repeat_rate\nFROM variety v\nJOIN items i ON i.customer_id = v.customer_id;"}]},"source_url":"https://sqlly.app/sql-functions/distinct-in-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/division-by-zero","corpus":"sql-functions","engine":null,"language":"en","title":"SQL division by zero","description":"Divide by zero and SQL Server, PostgreSQL and Oracle raise an error while MySQL and SQLite return NULL. x / NULLIF(y, 0) is the portable guard.","body":{"slug":"division-by-zero","name":"1 / 0","h1":"SQL division by zero","category":"math","lede":"What each engine does with x / 0: three of the five throw an error that aborts the query, two return NULL, so the same query can fail or silently empty a column.","syntax":"1 / 0  |  x / NULLIF(y, 0)  -- the portable guard","return_type":"error or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":"Msg 8134, Divide by zero error encountered. The statement fails; later statements in the batch still run unless XACT_ABORT is on or TRY/CATCH redirects"},{"engine_slug":"postgresql","status":"yes","note":"ERROR: division by zero; the whole statement fails"},{"engine_slug":"mysql","status":"yes","note":"SELECT returns NULL with a warning; with the default strict mode plus ERROR_FOR_DIVISION_BY_ZERO, INSERT and UPDATE fail instead"},{"engine_slug":"sqlite","status":"yes","note":"Returns NULL: any x / 0 or x % 0 is NULL"},{"engine_slug":"oracle","status":"yes","note":"ORA-01476: divisor is equal to zero for NUMBER; BINARY_DOUBLE division returns Inf (1d / 0d)"}],"gotchas":["The portable guard is NULLIF: x / NULLIF(y, 0) turns the fatal divisor into NULL, which then propagates as a NULL result instead of an error.","MySQL's NULL is a warning, not silence: SHOW WARNINGS reveals 'Division by 0'. MySQL 8's default sql_mode includes STRICT_TRANS_TABLES and ERROR_FOR_DIVISION_BY_ZERO, so INSERTs and UPDATEs that hit it fail.","Float division mostly follows the same rule: 1::float8 / 0 raises an error on PostgreSQL and 1e0 / 0 on SQL Server. Oracle is the exception: BINARY_DOUBLE 1d / 0d returns Inf."],"examples":[{"engine_slug":"all","sql":"SELECT 1 / NULLIF(0, 0) AS safe_div;  -- NULL, no error"},{"engine_slug":"postgresql","sql":"SELECT revenue / NULLIF(days_active, 0) AS rev_per_day\nFROM accounts;"},{"engine_slug":"mysql","sql":"SELECT 1 / 0 AS div_by_zero;  -- NULL, plus a warning"},{"engine_slug":"oracle","sql":"SELECT 1 / 0 AS boom FROM dual;  -- ORA-01476: divisor is equal to zero"}],"faqs":[{"question":"Does SQL return Infinity when dividing by zero?","answer":"Almost never. SQL Server, PostgreSQL and Oracle NUMBER raise an error; MySQL and SQLite return NULL. The one exception is Oracle BINARY_DOUBLE, where 1d / 0d returns Inf."},{"question":"How do I avoid division-by-zero errors portably?","answer":"Wrap the divisor in NULLIF: x / NULLIF(y, 0). The zero becomes NULL, the result becomes NULL, and the query survives on every engine. Pair with COALESCE for a 0 default."},{"question":"Why does my MySQL division return NULL silently?","answer":"In a SELECT, MySQL treats x / 0 as NULL with a warning, easy to miss in a big result set. The default strict mode with ERROR_FOR_DIVISION_BY_ZERO only turns it into an error for INSERT and UPDATE."}],"related":["mod-zero","nullif","infinity","arithmetic-operators"],"novel_uses":[{"body":"COALESCE(x / NULLIF(y, 0), -1) distinguishes a config error from a genuine zero rate on dashboards: NULL renders as a gap, the sentinel as a value the alert can catch. Pick the convention once and document it.","sql":"SELECT COALESCE(rev / NULLIF(days_active, 0), -1) AS rev_per_day FROM accounts;"},{"body":"AVG(rev / NULLIF(days, 0)) skips the guarded rows; AVG(COALESCE(rev / NULLIF(days, 0), 0)) counts them as zeros. When revenue is never NULL, every NULL came from the guard, so the gap between the two averages comes from those guarded rows.","sql":"SELECT AVG(rev / NULLIF(days_active, 0)) AS avg_over_valid, AVG(COALESCE(rev / NULLIF(days_active, 0), 0)) AS avg_with_zeros FROM accounts;"}]},"source_url":"https://sqlly.app/sql-functions/division-by-zero","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/division-scale","corpus":"sql-functions","engine":null,"language":"en","title":"SQL division result scale","description":"How many decimal places x / y returns is engine policy: MySQL adds 4 to the dividend's scale, SQL Server keeps at least 6, PostgreSQL at least 16 significant digits.","body":{"slug":"division-scale","name":"division scale","h1":"SQL division result scale","category":"math","lede":"Covers how many decimal digits a division produces on each engine, the reason 1.0 / 3 is 0.33333, 0.333333 or 0.33333333333333333333 depending on the database.","syntax":"1 / 2.0  |  1.0 / 3  |  7 / 2","return_type":"numeric / float","support":[{"engine_slug":"sql-server","status":"yes","note":"Decimal division scale: max(6, s1 + p2 + 1), at least 6 decimal places"},{"engine_slug":"postgresql","status":"yes","note":"Numeric division keeps at least 16 significant digits, not a fixed scale: 1.0::numeric / 3 gives 0.33333333333333333333 (20 decimal places)"},{"engine_slug":"mysql","status":"yes","note":"div_precision_increment (default 4) digits added to the dividend's scale: 1 / 3 is 0.3333, 1.0 / 3 is 0.33333"},{"engine_slug":"sqlite","status":"no","note":"No scale concept: integer / integer truncates (1 / 3 is 0); a REAL operand gives an IEEE double (1.0 / 3 is 0.333333333333333)"},{"engine_slug":"oracle","status":"yes","note":"NUMBER division keeps up to 38 significant digits: 1 / 3 is .333333333333333333333333333333333333333"}],"gotchas":["On SQL Server, 1.0 / 3 gives 0.333333 (six digits); on PostgreSQL, 0.33333333333333333333 (twenty); on MySQL, 0.33333 (dividend scale 1 plus 4).","Rounding happens at the engine's chosen scale, so comparisons against a literal can fail on one engine and pass on another; round both sides explicitly.","The scale rule also caps precision: SQL Server decimal division keeps at most 38 total digits, so huge precisions lose decimal places silently."],"examples":[{"engine_slug":"mysql","sql":"SELECT 1 / 3 AS int_dividend, 1.0 / 3 AS one_decimal;  -- 0.3333, 0.33333"},{"engine_slug":"sql-server","sql":"SELECT CAST(1.0 AS DECIMAL(10, 1)) / 3 AS sql_server_scale;  -- 0.333333"},{"engine_slug":"postgresql","sql":"SELECT 1.0::numeric / 3 AS pg_scale;  -- 0.33333333333333333333"},{"engine_slug":"oracle","sql":"SELECT 1 / 3 AS full_precision FROM dual;  -- .3333333333333333... up to 38 significant digits"}],"faqs":[{"question":"Why does 1.0 / 3 give a different number of digits per engine?","answer":"Each engine has a scale policy: SQL Server mandates at least 6 decimal places, MySQL adds div_precision_increment (default 4) to the dividend's scale, PostgreSQL keeps at least 16 significant digits, Oracle computes to 38 digits."},{"question":"How do I control the scale of a division?","answer":"CAST the dividend to the scale you want, and ROUND the result: ROUND(CAST(x AS DECIMAL(18, 4)) / y, 2). On SQLite, CAST(1 AS DECIMAL(18, 4)) stays the integer 1, so ROUND(CAST(1 AS DECIMAL(18, 4)) / 3, 2) returns 0.0; use CAST(x AS REAL) there, which gives 0.33. Relying on engine defaults invites cross-environment drift."},{"question":"Why did my decimal division lose precision?","answer":"SQL Server caps decimal results at 38 total digits; with very large input precisions, decimal places are the first thing cut. Reduce the operands' declared precision or cast to the needed scale."}],"related":["numeric-precision-scale","integer-division","numeric-vs-float","round"],"novel_uses":[{"body":"On SQL Server, AVG over an INT column returns INT and silently truncates the mean. AVG(qty * 1.0) promotes before averaging; PostgreSQL and MySQL return a decimal from the same call.","sql":"SELECT AVG(qty * 1.0) AS exact_avg FROM orders;"},{"body":"A query that returns 0.333333 on SQL Server and 0.33333333333333333333 on PostgreSQL fails naive comparisons. Round both sides to a fixed scale in the test harness so only real differences fail.","sql":"SELECT ROUND(CAST(1.0 AS DECIMAL(18, 9)) / 3, 6) AS normalized;"}]},"source_url":"https://sqlly.app/sql-functions/division-scale","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/double-precision","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DOUBLE PRECISION","description":"The 8-byte IEEE 754 double: 15-17 significant digits and a ceiling near 1.8e308. SQL Server's FLOAT is one; Oracle's DOUBLE PRECISION is not.","body":{"slug":"double-precision","name":"DOUBLE PRECISION","h1":"SQL DOUBLE PRECISION","category":"math","lede":"Explains the binary double format behind FLOAT/REAL/DOUBLE PRECISION: its digit budget, its special values, and which engines map which names onto it.","syntax":"DOUBLE PRECISION  |  FLOAT  |  BINARY_DOUBLE  -- Oracle","return_type":"8-byte IEEE 754 float","support":[{"engine_slug":"sql-server","status":"yes","note":"FLOAT in T-SQL defaults to FLOAT(53), a full IEEE double; REAL is the 4-byte single"},{"engine_slug":"postgresql","status":"yes","note":"double precision (float8) is the 8-byte IEEE double; real (float4) is single"},{"engine_slug":"mysql","status":"yes","note":"DOUBLE and FLOAT are distinct 8- and 4-byte IEEE types"},{"engine_slug":"sqlite","status":"yes","note":"REAL is the only floating type: an 8-byte IEEE double"},{"engine_slug":"oracle","status":"yes","note":"BINARY_DOUBLE is the IEEE double; DOUBLE PRECISION is FLOAT(126), a decimal NUMBER subtype"}],"gotchas":["15 to 17 significant digits, 0.1-style decimals never exact, values past 1.7976931348623157e308 overflow. Everything about float arithmetic follows from those three facts.","Names mislead: Oracle's DOUBLE PRECISION is a decimal NUMBER (FLOAT(126)), not IEEE, unless you declare BINARY_DOUBLE. SQL Server's FLOAT is already a double, and MySQL's FLOAT is the 4-byte single.","IEEE doubles define NaN and Infinity, but engine storage decides whether you can keep them: PostgreSQL and Oracle binary types yes, SQLite keeps Inf and turns NaN into NULL, SQL Server and MySQL never."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 0.1e0 + 0.2e0 AS binary_sum;  -- 0.30000000000000004 (e-notation is FLOAT)"},{"engine_slug":"postgresql","sql":"SELECT 0.1::float8 + 0.2::float8 AS binary_sum;  -- 0.30000000000000004"},{"engine_slug":"oracle","sql":"SELECT CAST(1.5 AS BINARY_DOUBLE) AS true_double FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT CAST(1e308 AS FLOAT) * 10 AS overflow_attempt;  -- Msg 8115 arithmetic overflow, not Inf"},{"engine_slug":"mysql","sql":"SELECT 0.1e0 + 0.2e0 AS binary_sum;  -- 0.30000000000000004"},{"engine_slug":"sqlite","sql":"SELECT printf('%!.17g', 0.1 + 0.2) AS binary_sum;  -- 0.30000000000000004; the shell shows 0.3 for REAL"}],"faqs":[{"question":"How many digits can a DOUBLE hold?","answer":"About 15 to 17 significant decimal digits (IEEE 754 binary64). Past that, digits are lost: 1234567890123456789 stored as a double comes back with trailing digits changed."},{"question":"Is SQL Server's FLOAT a single or double?","answer":"A double: FLOAT defaults to FLOAT(53), the full 8-byte IEEE binary64. REAL is the 4-byte single precision type."},{"question":"Why does Oracle's DOUBLE PRECISION not support NaN?","answer":"Oracle implements DOUBLE PRECISION as FLOAT(126), a subtype of its decimal NUMBER, which has no IEEE special values. Declare BINARY_DOUBLE to get true IEEE semantics including NaN and Infinity."}],"related":["numeric-vs-float","nan-infinity","float-equality","integer-overflow"],"novel_uses":[{"body":"REAL carries about 7 significant digits, more than any temperature or vibration sensor resolves. Each value takes 4 bytes instead of 8, but on PostgreSQL row alignment decides the table size: one real beside a timestamptz saves nothing, while two real columns beside it cut a 200,000-row table from 10.4 MB to 8.9 MB.","sql":"CREATE TABLE probes (ts timestamptz, temp_c real, humidity real);"},{"body":"Oracle NUMBER arithmetic is software; BINARY_DOUBLE uses the hardware float unit. Casting operands inside a large scientific aggregate pays for itself quickly, and the result is a normal float for the client.","sql":"SELECT AVG(CAST(reading AS BINARY_DOUBLE)) AS fast_avg FROM readings;"}]},"source_url":"https://sqlly.app/sql-functions/double-precision","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/dump","corpus":"sql-functions","engine":null,"language":"en","title":"SQL DUMP function","description":"Oracle's DUMP exposes a value's internal type code and bytes, the quickest way to settle encoding, whitespace and invisible-character questions.","body":{"slug":"dump","name":"DUMP","h1":"SQL DUMP function","category":"string","lede":"Shows exactly how a value is stored: datatype code, byte length, and each byte. Run it when two strings look equal and fail to match.","syntax":"DUMP(value [, return_format [, start_position [, length]]])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Output shape, in a UTF-8 (AL32UTF8) database: Typ=96 Len=5: 99,97,102,195,169. A CHAR value (literals are type 96; a VARCHAR2 column shows Typ=1), five bytes, the UTF-8 bytes of 'café' with é as two bytes.","return_format picks the base: 10 decimal (default), 16 hex, 8 octal, 17 prints printable bytes as characters and the rest in hex (its output format is not guaranteed); DUMP(s, 16) for hex inspection.","It reveals invisible characters: trailing spaces (32), NBSPs (194,160 in a UTF-8 database, 160 in a single-byte one), zero-width joiners and CR characters (13) all appear as their byte values.","Oracle-only. Elsewhere: PostgreSQL's encode(convert_to(s, 'utf8'), 'hex'), MySQL's HEX, SQL Server's CONVERT to varbinary."],"examples":[{"engine_slug":"oracle","sql":"SELECT DUMP('café') FROM dual;\n-- Typ=96 Len=5: 99,97,102,195,169"},{"engine_slug":"oracle","sql":"SELECT DUMP(note, 16) FROM notes WHERE id = 1;  -- hex bytes"}],"faqs":[{"question":"Why do two strings that look equal fail to match?","answer":"DUMP shows the difference: trailing spaces, NBSP (194,160 in UTF-8, 160 in single-byte charsets), combining accents or different encodings. The byte list is the evidence."},{"question":"What does Typ=96 mean?","answer":"The internal datatype code: 96 is CHAR (string literals are CHAR), 1 is VARCHAR2, 2 is NUMBER, 12 is DATE. It confirms what the column actually stores versus what the client renders."},{"question":"How do I get hex output from DUMP?","answer":"Pass 16 as the return format: DUMP(s, 16). 10 is decimal, 8 octal, 17 prints printable characters."}],"related":["ascii","rawtohex","charset-function","remove-nbsp"],"novel_uses":[{"body":"DUMP of a bind variable shows the bytes and type that reached the server, which settles why a query works in SQL*Plus but fails in the app, down to padding and encoding.","sql":"SELECT DUMP(:note, 16) FROM dual;  -- the bytes the driver bound"},{"body":"The Typ code in DUMP output is the internal datatype code, Typ 96 for CHAR and 1 for VARCHAR2, so one DISTINCT over DUMP confirms a column's datatype without reading its DDL.","sql":"SELECT DISTINCT SUBSTR(DUMP(note), 1, 6) AS type_code FROM notes;"}]},"source_url":"https://sqlly.app/sql-functions/dump","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/editdist3","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EDITDIST3 function","description":"How SQLite's editdist3 computes weighted edit distance via the spellfix1 extension: loading it, the default costs of 100 and 150, cost tables, and the PostgreSQL twin.","body":{"slug":"editdist3","name":"EDITDIST3","h1":"SQL EDITDIST3 function","category":"string","lede":"SQLite's weighted edit distance, provided by the spellfix1 extension. It works on UTF-8 characters, not bytes.","syntax":"editdist3(str1, str2)  |  editdist3(str1, str2, lang_id)  |  editdist3('cost_table')","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"EDIT_DISTANCE in SQL Server 2025, a preview feature."},{"engine_slug":"postgresql","status":"partial","note":"levenshtein from fuzzystrmatch."},{"engine_slug":"mysql","status":"no","note":"No built-in edit distance."},{"engine_slug":"sqlite","status":"yes","note":"Only after loading the spellfix1 extension."},{"engine_slug":"oracle","status":"partial","note":"UTL_MATCH.EDIT_DISTANCE."}],"gotchas":["spellfix1 is not compiled into standard SQLite builds or the sqlite3 shell. Build ext/misc/spellfix.c as a loadable extension and load it; editdist3 then becomes available.","Default costs are 100 per insertion or deletion and 150 per substitution, so editdist3('kitten', 'sitting') is 400, not 3. Scale thresholds accordingly.","Custom costs come from a table with columns iLang, cFrom, cTo and iCost, loaded with SELECT editdist3('my_costs'). Rows can price multi-character changes such as 'ss' to 'ß'."],"examples":[{"engine_slug":"sqlite","sql":"SELECT editdist3('kitten', 'sitting') AS distance;  -- 400"},{"engine_slug":"sqlite","sql":"SELECT name FROM users\nWHERE editdist3(lower(name), 'jon') <= 200;"},{"engine_slug":"postgresql","sql":"SELECT levenshtein('kitten', 'sitting') AS distance;  -- 3"},{"engine_slug":"sql-server","sql":"SELECT EDIT_DISTANCE('kitten', 'sitting') AS distance;  -- 3"},{"engine_slug":"oracle","sql":"SELECT UTL_MATCH.EDIT_DISTANCE('kitten', 'sitting') AS distance\nFROM dual;  -- 3"}],"faqs":[{"question":"Why is editdist3 not found in my SQLite?","answer":"It comes from the spellfix1 extension, which ships as source only. Compile ext/misc/spellfix.c, then load it with .load ./spellfix in a shell built with extension loading (the Apple /usr/bin/sqlite3 has no .load) or with load_extension() from your application."},{"question":"How does editdist3 relate to Levenshtein distance?","answer":"It is a weighted edit distance. With the defaults a substitution costs 150 against 100 for an insertion or deletion, so its ranking can differ from plain Levenshtein; a cost table can set all three to the same value."},{"question":"Does editdist3 distinguish case?","answer":"Yes. Unless the cost table says otherwise, 'A' to 'a' is an ordinary substitution. Fold case with lower() first."}],"related":["levenshtein","soundex","similarity","difference"],"novel_uses":[{"body":"The three-argument form selects the cost matrix by langid, so German transcriptions and English names can carry different weights in the same database.","sql":"SELECT editdist3(name, 'mueller', 1) AS d\nFROM people;"},{"body":"Rows in the cost table set what each change costs. cFrom is the text the user typed, so a row (0, 's', 'a', 50) prices a typed 's' where the word has an 'a' at 50, below the default 150 substitution, and ranks the likely typo first. Load the table once per connection before the first call.","sql":"INSERT INTO key_costs VALUES (0, 's', 'a', 50);\nSELECT editdist3('keybosrd', 'keyboard') AS typo_distance;  -- 50, or 150 without the row"}]},"source_url":"https://sqlly.app/sql-functions/editdist3","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/elt","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ELT function","description":"How ELT(n, s1, s2, ...) returns the nth string from a list in MySQL: 1-based indexing, NULL and out-of-range behaviour, and CASE-based equivalents in other engines.","body":{"slug":"elt","name":"ELT","h1":"SQL ELT function","category":"string","lede":"Returns the nth element of the string list that follows, counting from 1.","syntax":"ELT(n, str1, str2, ...)","return_type":"string or NULL","support":[{"engine_slug":"sql-server","status":"partial","note":"CHOOSE(n, ...) does the same job for whole-number indexes; the FAQ below covers where it differs."},{"engine_slug":"postgresql","status":"no","note":"Use a CASE expression or (ARRAY['a', 'b'])[n]."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"Use a CASE expression."},{"engine_slug":"oracle","status":"no","note":"Use a CASE expression or DECODE."}],"gotchas":["ELT is 1-based: ELT(1, 'a', 'b') is 'a'. An index of 0, a negative index or one past the last argument returns NULL, not an error.","It is the mirror of FIELD: FIELD('b', 'a', 'b', 'c') gives the index 2, ELT(2, 'a', 'b', 'c') gives the value 'b'.","Because a bad index quietly returns NULL, wrap with COALESCE when a default label matters."],"examples":[{"engine_slug":"mysql","sql":"SELECT ELT(2, 'small', 'medium', 'large') AS label;  -- medium"},{"engine_slug":"mysql","sql":"SELECT id, ELT(priority, 'low', 'normal', 'high') AS label\nFROM tasks;"},{"engine_slug":"sql-server","sql":"SELECT CHOOSE(2, 'small', 'medium', 'large') AS label;  -- medium"}],"faqs":[{"question":"Is ELT the same as CHOOSE in SQL Server?","answer":"Yes for whole-number indexes: both take a 1-based index, return that element, and return NULL when the index is out of range. They differ on fractional indexes (MySQL rounds, SQL Server truncates) and on mixed argument types (SQL Server picks the highest-precedence type and can fail)."},{"question":"What happens if the index is out of range?","answer":"You get NULL. ELT(0, 'a') and ELT(5, 'a') are both NULL, which suits mapping codes to labels when every code is known."}],"related":["field","case","find-in-set","concat-ws"],"novel_uses":[{"body":"INTERVAL(score, 49, 89) returns 0, 1 or 2 using greater-than-or-equal comparisons, and ELT shifts that to a label: anything under 49 is low, 49 up to 89 is mid, 89 and up is top.","sql":"SELECT score, ELT(INTERVAL(score, 49, 89) + 1, 'low', 'mid', 'top') AS band\nFROM results;"},{"body":"ELT(id % 3 + 1, 'A', 'B', 'C') assigns every row with a non-negative id to a bucket deterministically, so the same id always lands in the same group and no extra table is needed.","sql":"SELECT id, ELT(id % 3 + 1, 'A', 'B', 'C') AS cohort\nFROM users;"},{"body":"WEEKDAY() counts from 0 on Monday, so ELT(WEEKDAY(d) + 1, ...) turns a date into its weekday name without DATE_FORMAT and its locale-dependent codes.","sql":"SELECT d, ELT(WEEKDAY(d) + 1, 'Monday', 'Tuesday', 'Wednesday', 'Thursday',\n              'Friday', 'Saturday', 'Sunday') AS day_name\nFROM schedule;"}]},"source_url":"https://sqlly.app/sql-functions/elt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/emoji-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL emoji and string length","description":"An emoji is one character to people and two code units or four bytes to your database: length, storage and comparison rules per engine.","body":{"slug":"emoji-length","name":"Emoji and string length","h1":"SQL emoji and string length","category":"string","lede":"Emoji break the characters-equal-bytes assumption everywhere: lengths differ by function, storage needs utf8mb4 or nvarchar, and some engines split them in half.","syntax":"SELECT LENGTH('\uD83D\uDE00')  -- 1, 2 or 4 depending on engine and function","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server: LEN(N'\uD83D\uDE00') is 2 (UTF-16 code units) and DATALENGTH is 4 bytes, unless the collation is supplementary-aware (_SC or _140), where LEN is 1. Storage needs nvarchar, or varchar with a UTF-8 collation (2019+).","MySQL: needs utf8mb4 (utf8mb3 rejects the insert), then CHAR_LENGTH('\uD83D\uDE00') is 1 and LENGTH is 4 bytes.","PostgreSQL: length('\uD83D\uDE00') is 1 and octet_length is 4. SQLite: length('\uD83D\uDE00') is 1.","Oracle: in an AL32UTF8 VARCHAR2, LENGTH is 1, LENGTH2 is 2 (UTF-16 units) and LENGTHB is 4. NVARCHAR2 data stores UTF-16, so LENGTH there is 2."],"examples":[{"engine_slug":"sql-server","sql":"SELECT LEN(N'\uD83D\uDE00') AS units, DATALENGTH(N'\uD83D\uDE00') AS bytes;\n-- 2, 4"},{"engine_slug":"postgresql","sql":"SELECT length('\uD83D\uDE00') AS chars, octet_length('\uD83D\uDE00') AS bytes;\n-- 1, 4"},{"engine_slug":"oracle","sql":"SELECT LENGTH('\uD83D\uDE00') AS chars, LENGTH2('\uD83D\uDE00') AS units, LENGTHB('\uD83D\uDE00') AS bytes FROM dual;\n-- 1, 2, 4 in an AL32UTF8 database"},{"engine_slug":"mysql","sql":"SELECT CHAR_LENGTH('\uD83D\uDE00') AS chars, LENGTH('\uD83D\uDE00') AS bytes;  -- 1, 4 in utf8mb4"},{"engine_slug":"sqlite","sql":"SELECT length('\uD83D\uDE00') AS chars, length(CAST('\uD83D\uDE00' AS BLOB)) AS bytes;  -- 1, 4"}],"faqs":[{"question":"Why does my emoji insert fail?","answer":"The column or connection is not 4-byte capable. MySQL utf8mb3 rejects the insert in strict mode (error 1366) and stores ? otherwise. SQL Server varchar without a UTF-8 collation does not fail: it silently stores one ? per surrogate half. Move to utf8mb4 or nvarchar end to end."},{"question":"Why is LEN of an emoji 2?","answer":"SQL Server's LEN counts UTF-16 code units, and an emoji is a surrogate pair. A supplementary-character collation makes it count 1: a name ending _SC (for example Latin1_General_100_CI_AS_SC) or a version-140 collation such as Japanese_Bushu_Kakusu_140_CI_AI_WS_VSS, as PostgreSQL, MySQL's CHAR_LENGTH and SQLite already do."},{"question":"Can a string function split an emoji in half?","answer":"Yes: SQL Server's SUBSTRING under a non-SC collation returns a lone high surrogate (DATALENGTH 2, UNICODE 55357). Oracle's SUBSTR on NVARCHAR2 is not verified here."}],"related":["length","utf8mb4","varchar-char-semantics","octet-length"],"novel_uses":[{"body":"A thumbs-up with a skin-tone modifier is two code points, so length() reports 2 for what the user sees as one glyph; byte or code-point limits both undercount displays, which is why the app layer owns real width math.","sql":"SELECT length('\uD83D\uDC4D\uD83C\uDFFB') AS code_points;  -- 2 on PostgreSQL and SQLite, CHAR_LENGTH on MySQL: emoji plus skin-tone modifier"},{"body":"CHAR_LENGTH counts code points in MySQL, which matches what people expect a character counter to do, so a WHERE on CHAR_LENGTH(text) > 280 mirrors a UI limit on the server side.","sql":"SELECT id FROM replies WHERE CHAR_LENGTH(text) > 280;"}]},"source_url":"https://sqlly.app/sql-functions/emoji-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/empty-string-check","corpus":"sql-functions","engine":null,"language":"en","title":"SQL check for empty or blank strings","description":"Test for empty or whitespace-only strings per engine: NULL vs '', TRIM for blanks, and the Oracle collapse where '' already is NULL.","body":{"slug":"empty-string-check","name":"Checking for empty strings","h1":"SQL check for empty or blank strings","category":"string","lede":"Three different questions hide in is this empty: NULL, '', and whitespace-only. Each engine answers them with slightly different tools.","syntax":"col IS NULL OR col = ''  |  NULLIF(TRIM(col), '') IS NULL","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL and '' are different on all engines except Oracle: col = '' never matches NULL, so a complete empty test needs both conditions, or NULLIF(TRIM(col), '') IS NULL for blanks too.","Whitespace-only values need TRIM first; tabs and newlines need a character-set trim or a regex test such as col ~ '^\\s*$' (PostgreSQL) or REGEXP_LIKE(col, '^[[:space:]]*$') (MySQL, Oracle; MySQL would read '\\s' in a literal as a plain s).","SQL Server's LEN ignores trailing spaces, so LEN('  ') is 0, but LEN('  x') counts leading spaces, so length tests are asymmetric.","Oracle collapses the whole question: '' is NULL, so col IS NULL finds empty and blank-and-trimmed values alike."],"examples":[{"engine_slug":"sql-server","sql":"SELECT * FROM t WHERE col IS NULL OR col = '';"},{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE NULLIF(TRIM(col), '') IS NULL;"},{"engine_slug":"oracle","sql":"SELECT * FROM t WHERE col IS NULL;  -- covers '' and NULL"},{"engine_slug":"mysql","sql":"SELECT * FROM t WHERE col IS NULL OR col = '';  -- MySQL keeps '' and NULL distinct"},{"engine_slug":"sqlite","sql":"SELECT * FROM t WHERE col IS NULL OR col = '';  -- '' is a real value, not NULL"}],"faqs":[{"question":"Why does col = '' miss rows?","answer":"Those rows hold NULL, and NULL = anything is unknown. Use (col IS NULL OR col = ''), or the blank-inclusive NULLIF(TRIM(col), '') IS NULL."},{"question":"How do I catch whitespace-only values?","answer":"Trim first: NULLIF(TRIM(col), '') IS NULL catches '', '   ' and NULL in one test, with a character-set or regex trim if tabs and newlines count as blank."},{"question":"What is different on Oracle?","answer":"The empty string is NULL, so col IS NULL alone covers '' too, and TRIM('') also yields NULL. Tests ported from other engines over-count on Oracle."}],"related":["empty-string-null","trim","nullif","coalesce"],"novel_uses":[{"body":"A generated column on NULLIF(TRIM(col), '') IS NULL evaluates the three-way test once and can be indexed, on PostgreSQL 12+ and MySQL generated columns alike.","sql":"ALTER TABLE docs ADD COLUMN is_blank boolean GENERATED ALWAYS AS (NULLIF(TRIM(note), '') IS NULL) STORED;"},{"body":"SQL Server's LEN ignores trailing spaces, so a value of spaces has LEN 0 and also compares equal to ''; LEN(col) = 0 alone catches '' and space-only values in one WHERE. Tabs still have a length, so they need a character trim.","sql":"SELECT * FROM t WHERE col IS NOT NULL AND LEN(col) = 0;"}]},"source_url":"https://sqlly.app/sql-functions/empty-string-check","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/empty-string-null","corpus":"sql-functions","engine":null,"language":"en","title":"SQL empty string vs NULL","description":"Oracle treats '' and NULL as the same value, the single most consequential string difference between engines, breaking checks that pass everywhere else.","body":{"slug":"empty-string-null","name":"Empty string vs NULL","h1":"SQL empty string vs NULL","category":"string","lede":"On Oracle, an empty string IS NULL: comparisons, defaults, concatenation and indexes all behave differently than on every other major engine.","syntax":"'' IS NULL  -- TRUE on Oracle, FALSE everywhere else","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"'' and NULL are indistinguishable in Oracle SQL"}],"gotchas":["SELECT CASE WHEN '' IS NULL THEN 'null' ELSE 'empty' END FROM dual gives 'null' on Oracle; there is no empty string value in Oracle SQL.","Comparisons written elsewhere break: WHERE status = '' matches nothing, and COALESCE(status, '') returns NULL, not ''.","Concatenation absorbs it: 'a' || '' is 'a' on Oracle, PostgreSQL and SQLite, but MySQL reads || as logical OR (returns 0 under its default sql_mode) and SQL Server has no || operator (use + or CONCAT). On Oracle a column set to '' is stored as NULL, which fails NOT NULL constraints.","Migrations: NULLIF(col, '') and empty-string defaults need Oracle-specific rewrites, usually col IS NULL checks."],"examples":[{"engine_slug":"oracle","sql":"SELECT CASE WHEN '' IS NULL THEN 'null' ELSE 'empty' END AS verdict FROM dual;\n-- null"},{"engine_slug":"postgresql","sql":"SELECT '' IS NULL AS verdict;  -- false"},{"engine_slug":"oracle","sql":"SELECT COUNT(*) FROM t WHERE note IS NULL;\n-- counts both true NULLs and '' values"}],"faqs":[{"question":"Why does Oracle say '' IS NULL?","answer":"A historical decision: Oracle SQL has no distinct empty-string value. It is documented behaviour, not a bug, and every Oracle string check must account for it."},{"question":"How do I check for an empty value on Oracle?","answer":"col IS NULL: it covers both true NULLs and values written as ''. The col = '' test never matches anything on Oracle."},{"question":"Do other engines ever blur '' and NULL?","answer":"No: PostgreSQL, MySQL, SQL Server and SQLite all keep them distinct. Only Oracle collapses them."}],"related":["empty-string-check","coalesce","nullif","trim"],"novel_uses":[{"body":"Oracle's || only skips a NULL operand of the outer chain, so ' (' || nickname || ')' still prints ' ()' when nickname is NULL; wrapping the whole fragment in a CASE with an ELSE '' branch is the fix. Without the ELSE, a NULL nickname turns the whole display NULL on PostgreSQL, SQLite and MySQL, and MySQL reads || as logical OR while SQL Server has no || operator, so use CONCAT there.","sql":"SELECT name || CASE WHEN nickname IS NOT NULL THEN ' (' || nickname || ')' ELSE '' END AS display\nFROM users;"},{"body":"After moving to Oracle, WHERE col IS NULL also counts the values that arrived as empty strings, so the count measures how much data silently changed from empty to NULL.","sql":"SELECT COUNT(*) FROM t WHERE col IS NULL;  -- on Oracle this includes values that were '' before the move"}]},"source_url":"https://sqlly.app/sql-functions/empty-string-null","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/empty-string-null-oracle","corpus":"sql-functions","engine":null,"language":"en","title":"Oracle empty string vs NULL","description":"In Oracle a zero-length VARCHAR2 IS NULL: writes, comparisons and indexes behave differently from PostgreSQL, MySQL, SQL Server and SQLite. Portable patterns inside.","body":{"slug":"empty-string-null-oracle","name":"NULL","h1":"Oracle empty string vs NULL","category":"conditional","lede":"The one engine where '' and NULL are the same value, and how to write around it.","syntax":"x IS NULL | '' IS NULL","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"a zero-length VARCHAR2 IS NULL"}],"gotchas":["Oracle: '' IS NULL is TRUE, so NVL(col, '') is a no-op and CONCAT(col, '') can still be NULL.","PostgreSQL, MySQL, SQL Server and SQLite all keep '' and NULL distinct; code that works on Oracle may mis-handle empties elsewhere and vice versa.","Fixed-length CHAR columns pad with spaces, so a single space stored in CHAR(5) is a real value, not NULL: a second kind of 'empty-looking' row.","WHERE col = '' never matches in Oracle, because it is col = NULL; write WHERE col IS NULL. If 'known to be empty' and 'unknown' must stay apart, store that in a separate flag column."],"examples":[{"engine_slug":"oracle","sql":"SELECT CASE WHEN '' IS NULL THEN 'yes' ELSE 'no' END AS empty_is_null FROM dual;"},{"engine_slug":"postgresql","sql":"SELECT CASE WHEN '' IS NULL THEN 'yes' ELSE 'no' END AS empty_is_null;"}],"faqs":[{"question":"Is an empty string NULL in SQL?","answer":"In Oracle yes; in PostgreSQL, MySQL, SQL Server and SQLite no. They are distinct values."},{"question":"Why does my Oracle INSERT store NULL?","answer":"You inserted ''; Oracle converts zero-length VARCHAR2 values to NULL."},{"question":"How do I represent 'no value yet' portably?","answer":"Use NULL and IS NULL checks everywhere. Code that needs a distinct 'empty' value cannot rely on '' if Oracle is a target."}],"related":["null","is-null","nvl","concat","null-unique"],"novel_uses":[{"body":"Oracle reads a NULL operand of || as empty, so optional address parts join without COALESCE; the same expression yields NULL on PostgreSQL and SQLite, MySQL parses || as logical OR unless PIPES_AS_CONCAT is set, and SQL Server 2022 rejects || outright (its + operator yields NULL instead).","sql":"SELECT street || ' ' || unit || ' ' || city FROM addresses;"},{"body":"Because '' IS NULL, a NOT NULL check rejects empty strings on Oracle but waves them through on PostgreSQL, MySQL, SQL Server and SQLite; porting away from Oracle can silently loosen the rule. SQLite accepts the CHECK only inside CREATE TABLE, not through ALTER TABLE.","sql":"ALTER TABLE tasks ADD CHECK (note IS NOT NULL);"}]},"source_url":"https://sqlly.app/sql-functions/empty-string-null-oracle","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/encode-bytea","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ENCODE and DECODE (bytea)","description":"PostgreSQL's ENCODE and DECODE turn bytea into hex, base64 or escaped text and back; unrelated to Oracle's DECODE conditional or MySQL's removed DECODE encryption.","body":{"slug":"encode-bytea","name":"ENCODE / DECODE","h1":"SQL ENCODE and DECODE (bytea)","category":"conversion","lede":"encode(bytes, 'base64') turns a bytea into printable text and decode(text, 'base64') turns it back. Formats are hex, base64 and escape.","syntax":"encode(bytea, format)  |  decode(text, format)","return_type":"text or bytea","support":[{"engine_slug":"sql-server","status":"no","note":"CONVERT styles 1 and 2 for hex; BASE64_ENCODE/BASE64_DECODE on SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"TO_BASE64/FROM_BASE64 and HEX/UNHEX cover the formats"},{"engine_slug":"sqlite","status":"no","note":"hex() and unhex() (3.41+); base64() only in the sqlite3 shell"},{"engine_slug":"oracle","status":"no","note":"UTL_ENCODE and RAWTOHEX/HEXTORAW; Oracle's DECODE is a conditional"}],"gotchas":["Do not confuse this decode with Oracle's DECODE (a CASE-like conditional) or MySQL's old DECODE encryption function, removed in 8.0: this pair only changes how bytes are written as text.","encode takes bytea and returns text; decode takes text and returns bytea. To encode a string, cast it first ('SQL'::bytea) or use convert_to(text, 'UTF8') to pick the encoding.","The formats are hex, base64 and escape. PostgreSQL's base64 is the standard alphabet with = padding and a line break every 76 characters, so URL-safe tokens need translate() afterwards."],"examples":[{"engine_slug":"postgresql","sql":"SELECT encode('SQL'::bytea, 'base64') AS b64;"},{"engine_slug":"postgresql","sql":"SELECT decode('U1FM', 'base64') AS bytes;"},{"engine_slug":"postgresql","sql":"SELECT convert_from(decode('53514C', 'hex'), 'UTF8') AS text_out;"}],"faqs":[{"question":"Which PostgreSQL DECODE is which?","answer":"decode(text, format) converts hex/base64 text to bytea. Oracle's DECODE is a conditional expression. Same name, unrelated jobs: a recurring porting trap."},{"question":"How do I decode into readable text?","answer":"Chain it: convert_from(decode(hex_text, 'hex'), 'UTF8'). decode alone stops at bytes; convert_from applies the character encoding."}],"related":["unhex","hex","base64","decode"],"novel_uses":[{"body":"encode(payload, 'escape') leaves most bytes as they are, writes zero bytes and bytes with the high bit set as octal \\nnn escapes and doubles backslashes, so a quick SELECT reveals what a binary column actually holds. It also makes LIKE searches on text markers easy: encode it, then match the result.","sql":"SELECT encode(payload, 'escape') AS dump FROM hooks WHERE encode(payload, 'escape') LIKE '%timeout%';"},{"body":"decode(stored, 'hex') returns bytea, and bytea equality ignores the case difference that breaks 'AB12' versus 'ab12' string compares. Hash the input with digest() from the pgcrypto extension (or the built-in sha256()) and compare the two bytea values directly.","sql":"SELECT id FROM api_keys WHERE decode(secret_hash, 'hex') = digest(?, 'sha256');"},{"body":"PostgreSQL's base64 output breaks every 76 characters, which corrupts a data URI. Strip the newlines with chr(10) and the result drops straight into an img src for small thumbnails.","sql":"SELECT 'data:image/png;base64,' || replace(encode(thumb, 'base64'), chr(10), '') AS uri FROM icons;"}]},"source_url":"https://sqlly.app/sql-functions/encode-bytea","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/eomonth","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EOMONTH function","description":"EOMONTH in SQL Server: the last day of a month with an optional month offset, alongside LAST_DAY and modifier tricks in the other engines.","body":{"slug":"eomonth","name":"EOMONTH","h1":"SQL EOMONTH function","category":"datetime","lede":"Returns the last day of the month containing the input, shifted by a whole number of months if asked.","syntax":"EOMONTH(date [, months_to_add])","return_type":"date","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"(date_trunc('month', d) + INTERVAL '1 month -1 day')::date"},{"engine_slug":"mysql","status":"partial","note":"LAST_DAY(d)"},{"engine_slug":"sqlite","status":"partial","note":"date(d, 'start of month', '+1 month', '-1 day')"},{"engine_slug":"oracle","status":"partial","note":"LAST_DAY(d)"}],"gotchas":["The second argument is months, not days: EOMONTH('2026-08-15', -1) is July 31, 2026, the tidy way to get prior month-end for balances.","EOMONTH returns the date type, with no time part even for datetime input; DATEADD(DAY, 1, EOMONTH(d)) is the first of the next month.","It needs SQL Server 2012 or later. MySQL's LAST_DAY dates back to 4.1 and Oracle's is older still; neither takes a month offset."],"examples":[{"engine_slug":"sql-server","sql":"SELECT EOMONTH('2026-08-15');  -- 2026-08-31"},{"engine_slug":"sql-server","sql":"SELECT EOMONTH('2026-08-15', -1);  -- 2026-07-31"},{"engine_slug":"postgresql","sql":"SELECT (date_trunc('month', DATE '2026-08-15') + INTERVAL '1 month -1 day')::date;"},{"engine_slug":"mysql","sql":"SELECT LAST_DAY('2026-08-15');  -- 2026-08-31"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-15', 'start of month', '+1 month', '-1 day');  -- 2026-08-31"},{"engine_slug":"oracle","sql":"SELECT LAST_DAY(DATE '2026-08-15') FROM dual;  -- 2026-08-31"}],"faqs":[{"question":"EOMONTH vs LAST_DAY?","answer":"They answer the same question; LAST_DAY exists in MySQL and Oracle, EOMONTH in SQL Server. The offset argument is EOMONTH's extra; LAST_DAY callers add DATE_ADD themselves."},{"question":"How do I get the last *weekday* of the month?","answer":"No function does it. Step back from EOMONTH: subtract 1 day when it falls on a Saturday and 2 on a Sunday, testing DATEPART(WEEKDAY, ...) with SET DATEFIRST in mind."}],"related":["last-day","days-in-month","datetrunc","add-months"],"novel_uses":[{"body":"Filter on less-than one day past EOMONTH so every datetime on the last day matches and index seeks survive, instead of midnight-or-end-of-day guesses.","sql":"SELECT * FROM orders WHERE order_date >= '2026-08-01' AND order_date < DATEADD(DAY, 1, EOMONTH('2026-08-01'));"},{"body":"EOMONTH with an offset projects each signup to its anniversary month end, a grouping that lines up renewals even when signup days differ.","sql":"SELECT EOMONTH(signup_date, 12) AS renewal_window FROM subs;"}]},"source_url":"https://sqlly.app/sql-functions/eomonth","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/error-message","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ERROR_MESSAGE and SQLERRM","description":"Read the error text and number inside an error handler: ERROR_MESSAGE() in SQL Server TRY/CATCH, SQLERRM in PostgreSQL and Oracle, GET DIAGNOSTICS in MySQL.","body":{"slug":"error-message","name":"ERROR_MESSAGE","h1":"SQL ERROR_MESSAGE and SQLERRM","category":"system","lede":"Error handlers need to know what failed. Each engine exposes the message and code inside its handler, under different names.","syntax":"ERROR_MESSAGE(), ERROR_NUMBER()  |  SQLERRM, SQLSTATE  |  SQLERRM, SQLCODE  |  GET DIAGNOSTICS CONDITION 1","return_type":"text (the message), integer or text (the code)","support":[{"engine_slug":"sql-server","status":"yes","note":"ERROR_MESSAGE, ERROR_NUMBER, ERROR_LINE and friends inside BEGIN CATCH"},{"engine_slug":"postgresql","status":"partial","note":"SQLERRM and SQLSTATE in a PL/pgSQL EXCEPTION block"},{"engine_slug":"mysql","status":"partial","note":"GET DIAGNOSTICS CONDITION 1 @msg = MESSAGE_TEXT, also inside handlers"},{"engine_slug":"sqlite","status":"no","note":"no procedural error handling in SQL"},{"engine_slug":"oracle","status":"partial","note":"SQLERRM and SQLCODE in a PL/SQL EXCEPTION block"}],"gotchas":["ERROR_MESSAGE() and the other ERROR_ functions return NULL outside a CATCH block.","TRY/CATCH does not catch compile errors in the same batch, such as a misspelled column, or errors of severity 20 and above that end the connection.","Oracle's SQLERRM includes the code ('ORA-01476: divisor is equal to zero'); PostgreSQL's SQLERRM is the bare message and SQLSTATE holds the five-character code, such as 22012."],"examples":[{"engine_slug":"sql-server","sql":"BEGIN TRY\n  SELECT 1 / 0;\nEND TRY\nBEGIN CATCH\n  SELECT ERROR_NUMBER() AS num, ERROR_MESSAGE() AS msg;  -- 8134, Divide by zero error encountered.\nEND CATCH;"},{"engine_slug":"postgresql","sql":"DO $$\nBEGIN\n  PERFORM 1 / 0;\nEXCEPTION WHEN OTHERS THEN\n  RAISE NOTICE '% %', SQLSTATE, SQLERRM;  -- 22012 division by zero\nEND $$;"},{"engine_slug":"oracle","sql":"DECLARE\n  n NUMBER;\nBEGIN\n  n := 1 / 0;\nEXCEPTION WHEN OTHERS THEN\n  DBMS_OUTPUT.PUT_LINE(SQLCODE || ' ' || SQLERRM);  -- -1476 ORA-01476: divisor is equal to zero\nEND;\n/"},{"engine_slug":"mysql","sql":"SELECT 1 FROM no_such_table;\nGET DIAGNOSTICS CONDITION 1 @code = MYSQL_ERRNO, @msg = MESSAGE_TEXT;\nSELECT @code, @msg;  -- 1146 and the message"}],"faqs":[{"question":"How do I re-raise the error after logging it?","answer":"THROW; inside the CATCH block on SQL Server, RAISE; in PL/pgSQL and PL/SQL, RESIGNAL in a MySQL handler."},{"question":"Does CATCH roll back the transaction?","answer":"No. Check XACT_STATE() in the CATCH block: -1 means the transaction is doomed and must be rolled back; 1 means it can still commit."}],"related":["row-count","division-by-zero","try-cast"],"novel_uses":[{"body":"Message text is localized to the session language and drifts between builds, so retry logic should match ERROR_NUMBER() against the stable codes: 1205 for a deadlock victim, 1222 for a lock timeout under SET LOCK_TIMEOUT. A client command timeout (SqlException.Number -2 in .NET) never reaches CATCH, because the client cancels the batch, so retry that one in application code.","sql":"BEGIN CATCH\n  IF ERROR_NUMBER() IN (1205, 1222) SELECT 'retry' AS action;\nEND CATCH;"},{"body":"SQLERRM in a PostgreSQL handler names the error but not the call path that produced it. GET STACKED DIAGNOSTICS with PG_EXCEPTION_CONTEXT inside the EXCEPTION block prints the stack at the point of the error, which finds the function three calls down in one run. PG_CONTEXT there reports the handler's own line instead.","sql":"DO $$\nDECLARE ctx text;\nBEGIN\n  PERFORM 1 / 0;\nEXCEPTION WHEN OTHERS THEN\n  GET STACKED DIAGNOSTICS ctx = PG_EXCEPTION_CONTEXT;\n  RAISE NOTICE '%', ctx;\nEND $$;"},{"body":"Once an exception unwinds to an outer PL/SQL block, SQLCODE and SQLERRM say what failed but not where. DBMS_UTILITY.FORMAT_ERROR_BACKTRACE in the handler prints the original line number, which turns a log walk into a one-line answer.","sql":"BEGIN\n  NULL;\nEXCEPTION WHEN OTHERS THEN\n  DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);\nEND;\n/"}]},"source_url":"https://sqlly.app/sql-functions/error-message","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/every","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EVERY function","description":"EVERY in PostgreSQL and Oracle 23ai: true when all rows pass, NULL rows skipped, and the MIN(condition) and SUM = COUNT recipes for MySQL and SQLite.","body":{"slug":"every","name":"EVERY","h1":"SQL EVERY function","category":"aggregate","lede":"The standard SQL aggregate that returns true only if every row in the group is true.","syntax":"EVERY(boolean) | EVERY(boolean) FILTER (WHERE ...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"no EVERY(); use MIN(CASE WHEN status = 'paid' THEN 1 WHEN status <> 'paid' THEN 0 END), which skips NULLs like EVERY"},{"engine_slug":"postgresql","status":"yes","note":"synonym of bool_and"},{"engine_slug":"mysql","status":"no","note":"no EVERY(); use MIN(status = 'paid') or SUM(status = 'paid') = COUNT(status)"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"23ai+, over the BOOLEAN type"}],"gotchas":["NULLs are skipped: EVERY ignores NULL rows entirely and only true non-NULL rows keep the result true.","Empty and all-NULL groups return NULL, not false.","The SQL standard also defines ANY and SOME aggregates, but PostgreSQL rejects them as aggregate names because x = ANY(...) already means something else."],"examples":[{"engine_slug":"postgresql","sql":"SELECT category_id, every(price > 0) AS prices_ok FROM products GROUP BY category_id;"},{"engine_slug":"mysql","sql":"SELECT category_id, SUM(price > 0) = COUNT(price) AS prices_ok FROM products GROUP BY category_id;"},{"engine_slug":"oracle","sql":"SELECT status, EVERY(verified) FROM accounts GROUP BY status;"}],"faqs":[{"question":"Is EVERY the same as BOOL_AND?","answer":"Yes, in PostgreSQL they are synonyms. EVERY is the SQL standard name; Oracle 23ai has EVERY and BOOLEAN_AND_AGG."},{"question":"Does EVERY count NULL rows?","answer":"No. NULLs are skipped, so a group of one true row and five NULLs is still true."},{"question":"What replaces EVERY in MySQL?","answer":"MIN(condition), or SUM(condition) = COUNT(col): both return 1 only when every non-NULL row satisfies the condition. COUNT(*) would count NULL rows and break the match."}],"related":["bool-and","bool-or","any","min","aggregate-nulls"],"novel_uses":[{"body":"HAVING every(passed) keeps only build ids whose smoke tests all passed, turning a table of test rows into the go or no-go list in one statement.","sql":"SELECT build_id FROM smoke_tests GROUP BY build_id HAVING every(passed);"},{"body":"every(check_ok) OVER (PARTITION BY run_id) lets a report show each check beside the run's overall verdict without collapsing the detail rows.","sql":"SELECT run_id, check_name, every(check_ok) OVER (PARTITION BY run_id) AS run_ok FROM results;"}]},"source_url":"https://sqlly.app/sql-functions/every","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/exists","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EXISTS operator","description":"EXISTS(subquery) returns true when the subquery produces any row: correlation, why SELECT * inside is fine, NULL-immunity versus IN, and engine behaviour.","body":{"slug":"exists","name":"EXISTS","h1":"SQL EXISTS operator","category":"conditional","lede":"True when the subquery returns at least one row, regardless of what those rows contain.","syntax":"EXISTS (SELECT 1 FROM t WHERE ...) | NOT EXISTS (...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The inner SELECT list is ignored: SELECT 1, SELECT * and SELECT NULL all behave the same; pick the one your team reads best.","EXISTS is two-valued: TRUE or FALSE, never UNKNOWN, so it composes with NOT cleanly where IN does not.","Correlated EXISTS stops scanning the subquery at the first match for each outer row."],"examples":[{"engine_slug":"all","sql":"SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);"},{"engine_slug":"postgresql","sql":"SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_catalog.pg_tables);"}],"faqs":[{"question":"Why SELECT 1 inside EXISTS?","answer":"The column list is never read; 1 just says 'row count only'. SELECT * is equally correct."},{"question":"EXISTS vs IN for subqueries?","answer":"Correlated logic reads naturally as EXISTS, it is NULL-immune, and planners turn both into joins in most cases."},{"question":"Can EXISTS return NULL?","answer":"No: TRUE or FALSE only, which is why NOT EXISTS sidesteps the NOT IN trap."}],"related":["not-exists","in","not-in","three-valued-logic"],"novel_uses":[{"body":"PostgreSQL returns SELECT EXISTS(...) as a true/false boolean column and MySQL and SQLite as 1 or 0; SQL Server and Oracle wrap the same subquery in CASE WHEN EXISTS.","sql":"SELECT c.id, EXISTS(SELECT 1 FROM orders o WHERE o.customer_id = c.id) AS has_orders FROM customers c;"},{"body":"Two ranges overlap when each starts before the other ends; as a correlated EXISTS it is a semi-join the planner can index.","sql":"SELECT a.id FROM bookings a WHERE EXISTS (SELECT 1 FROM bookings b WHERE b.id <> a.id AND b.starts < a.ends AND b.ends > a.starts);"}]},"source_url":"https://sqlly.app/sql-functions/exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/exp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EXP function","description":"EXP(x) raises e (about 2.718) to the power x and undoes LN. Per-engine overflow points, from EXP(291) on Oracle NUMBER to Inf on SQLite.","body":{"slug":"exp","name":"EXP","h1":"SQL EXP function","category":"math","lede":"Returns e raised to the given power: EXP(1) is about 2.71828 and EXP(0) is exactly 1.","syntax":"EXP(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"In the math function set added in 3.35.0; a build without SQLITE_ENABLE_MATH_FUNCTIONS raises 'no such function: exp'"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Integer input still returns a fraction: EXP(1) is 2.718281828459045 as a double on most engines. PostgreSQL returns numeric for numeric input (exp(1.0)) and Oracle returns NUMBER.","EXP(709) is near the top of a double. Past about 709.78, SQL Server, PostgreSQL and MySQL raise an overflow error and SQLite returns Inf. Oracle NUMBER overflows far sooner: EXP(291) raises ORA-01426.","EXP of a large negative input underflows. PostgreSQL raises 'value out of range: underflow' below about -745 (EXP(-746) fails), while SQL Server, MySQL and SQLite return 0.","EXP and LN undo each other only approximately in floats: on SQL Server EXP(LOG(10)) returns 10.000000000000002."],"examples":[{"engine_slug":"all","sql":"SELECT EXP(0) AS one, EXP(1) AS e;  -- 1, 2.71828..."},{"engine_slug":"postgresql","sql":"SELECT SUM(amount * EXP(-rate * years)) AS present_value\nFROM cash_flows;"},{"engine_slug":"sql-server","sql":"SELECT EXP(LOG(10)) AS back_to_ten;  -- 10.000000000000002"},{"engine_slug":"oracle","sql":"SELECT EXP(0) AS one, EXP(1) AS e FROM dual;  -- 1, 2.71828..."}],"faqs":[{"question":"Why does EXP overflow?","answer":"EXP(709) is about 8e307, close to the double maximum near 1.8e308. EXP(710) cannot be stored: SQL Server, PostgreSQL and MySQL raise an error, SQLite hands back Inf. Oracle NUMBER caps near 1e126, so EXP(291) already fails there; EXP of a BINARY_DOUBLE returns Inf."},{"question":"Is EXP the opposite of LN?","answer":"Mathematically yes: LN(EXP(x)) is x and EXP(LN(x)) is x for positive x. In floating point the round trip can be off in the last digits."},{"question":"What is EXP(0)?","answer":"Exactly 1. e to the power zero is 1 on every engine, returned as a float 1.0."}],"related":["ln","log","power"],"novel_uses":[{"body":"EXP(-decay * age_days) builds a smooth decay weight, so a weighted average leans on recent rows without a window function. Pick the decay so EXP(-decay * 30) is the weight you want a month-old row to carry.","sql":"SELECT SUM(value * EXP(-0.01 * age_days)) / SUM(EXP(-0.01 * age_days)) AS decayed_avg FROM metrics;"},{"body":"EXP(score) divided by its sum converts raw scores into shares that total 100. Subtract the maximum first: EXP overflows once its input passes about 709, so one score of 800 fails the whole query on SQL Server, PostgreSQL and MySQL, and SQLite quietly returns 0 for the other rows and NULL for that one. The shift cancels in the ratio, so the shares match the unshifted form.","sql":"WITH m AS (SELECT name, score - MAX(score) OVER () AS d FROM candidates), k AS (SELECT name, EXP(CASE WHEN d < -700 THEN -700 ELSE d END) AS w FROM m) SELECT name, w / SUM(w) OVER () * 100 AS share_pct FROM k;"}]},"source_url":"https://sqlly.app/sql-functions/exp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/exponent-operator","corpus":"sql-functions","engine":null,"language":"en","title":"SQL exponentiation operator","description":"Only PostgreSQL uses ^ for power. SQL Server and MySQL read ^ as bitwise XOR, and Oracle's ** works only in PL/SQL. Portable code calls POWER.","body":{"slug":"exponent-operator","name":"^","h1":"SQL exponentiation operator","category":"math","lede":"The caret raises to a power on PostgreSQL only. On SQL Server and MySQL ^ is bitwise XOR, SQLite has no ^, and Oracle SQL has no power operator at all.","syntax":"base ^ exponent  -- PostgreSQL  |  base ** exponent  -- Oracle PL/SQL only  |  POWER(base, exponent)  -- everywhere (SQLite needs its math functions built in)","return_type":"double / numeric","support":[{"engine_slug":"sql-server","status":"no","note":"^ is the bitwise XOR operator, not power"},{"engine_slug":"postgresql","status":"yes","note":"^ is exponentiation for both double precision and numeric; 2.0 ^ 2 stays numeric"},{"engine_slug":"mysql","status":"no","note":"^ is the bitwise XOR operator, not power"},{"engine_slug":"sqlite","status":"no","note":"There is no ^ operator at all in SQLite"},{"engine_slug":"oracle","status":"no","note":"No operator in SQL: SELECT 2 ** 10 FROM dual raises ORA-00936. ** exists only in PL/SQL; use POWER in queries"}],"gotchas":["Migrating T-SQL or MySQL code to PostgreSQL can silently turn 2 ^ 3 from an XOR (1) into a power (8); both are legal, both return a number.","PostgreSQL ^ breaks math convention twice: unary minus binds tighter, so -2 ^ 2 is 4, and ^ associates left to right, so 2 ^ 3 ^ 2 is 64, not 512.","Oracle's ** is a PL/SQL operator. Inside a SQL statement it is a syntax error, so code copied from a PL/SQL block into a query must switch to POWER."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 2 ^ 10 AS power_result;  -- 1024"},{"engine_slug":"postgresql","sql":"SELECT -2 ^ 2 AS neg_first, 2 ^ 3 ^ 2 AS left_assoc;  -- 4, 64"},{"engine_slug":"sql-server","sql":"SELECT 2 ^ 3 AS xor_result;  -- 1, not 8"},{"engine_slug":"all","sql":"SELECT POWER(2, 10) AS portable_power;"}],"faqs":[{"question":"Does ^ mean power in SQL?","answer":"Only on PostgreSQL. In SQL Server and MySQL it is bitwise XOR, and SQLite has no ^ at all. Use POWER() when the query must run on more than one engine."},{"question":"What is the Oracle exponentiation operator?","answer":"In SQL there is none: SELECT 2 ** 10 FROM dual fails with ORA-00936. ** works in PL/SQL expressions only. Use POWER(2, 10) in queries."},{"question":"Why is -2 ^ 2 equal to 4 in PostgreSQL?","answer":"Unary minus binds tighter than ^ in PostgreSQL, so it parses as (-2) ^ 2. Write -(2 ^ 2) when you mean -4. ^ is also left-associative: 2 ^ 3 ^ 2 is (2 ^ 3) ^ 2 = 64."}],"related":["power","bitand","operator-precedence"],"novel_uses":[{"body":"On SQL Server and MySQL, flags_a ^ flags_b is a mask of exactly the bits that differ between two permission sets. One operator answers what changed between two snapshots.","sql":"SELECT permissions_old ^ permissions_new AS changed_bits FROM user_history;"},{"body":"On SQL Server and MySQL, flags ^ 4 flips the bit worth 4 (the third bit, counting from 1) whatever it was, where AND and OR can only clear or set. It is the toggle you want when the update must not read the row first. On PostgreSQL ^ is power, so the same UPDATE silently stores 625 for flags = 5.","sql":"UPDATE user_settings SET flags = flags ^ 4 WHERE user_id = 42;"}]},"source_url":"https://sqlly.app/sql-functions/exponent-operator","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/extract","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EXTRACT function","description":"Get the year, month, day or hour from a timestamp: EXTRACT on PostgreSQL, MySQL and Oracle, DATEPART on SQL Server, strftime on SQLite.","body":{"slug":"extract","name":"EXTRACT / DATEPART","h1":"SQL EXTRACT function","category":"datetime","lede":"Returns one field of a date or timestamp as a number: the year of an order, the hour of a login. EXTRACT is the standard form; SQL Server and SQLite use their own functions.","syntax":"EXTRACT(year FROM ts)  |  DATEPART(year, ts)  -- SQL Server","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(year, ts) or YEAR(ts); no EXTRACT"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"EXTRACT, plus YEAR(), MONTH(), DAY() shorthands"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y', ts) returns text; CAST it"},{"engine_slug":"oracle","status":"yes","note":"EXTRACT only; Oracle has no YEAR() or MONTH() function"}],"gotchas":["SQLite's strftime returns text: strftime('%Y', ts) = 2026 compares text with a number and is false. CAST the result to INTEGER first.","Week numbers: EXTRACT(week) on PostgreSQL is the ISO week, matching SQL Server's DATEPART(iso_week). SQL Server's DATEPART(week) counts from January 1 and follows DATEFIRST, so the two disagree near year boundaries.","SQL Server and MySQL also have YEAR(d), MONTH(d) and DAY(d) shorthands. Oracle does not: YEAR(SYSDATE) fails with ORA-00904.","On Oracle, EXTRACT(hour FROM ...) only works on TIMESTAMP values, not DATE; cast first or use TO_CHAR(d, 'HH24')."],"examples":[{"engine_slug":"postgresql","sql":"-- same on MySQL and Oracle\nSELECT EXTRACT(year FROM created_at) AS yr FROM orders;"},{"engine_slug":"mysql","sql":"SELECT EXTRACT(year FROM created_at) AS yr FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(year, created_at) AS yr FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%Y', created_at) AS INTEGER) AS yr FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(year FROM created_at) AS yr FROM orders;"}],"faqs":[{"question":"What is the difference between EXTRACT and DATEPART?","answer":"EXTRACT is the SQL standard (PostgreSQL, MySQL, Oracle); DATEPART is SQL Server's spelling with comma syntax. They cover the same parts, though week numbering differs as described above."},{"question":"Does SQLite have EXTRACT?","answer":"No. strftime('%Y', ts) is the stand-in, and it returns text. CAST the result to INTEGER before comparing or doing arithmetic."}],"related":["date-trunc","day-of-week","current-date"],"novel_uses":[{"body":"EXTRACT(epoch FROM x) reduces any timestamp to a plain number, which is what modulo bucketing, quick diffs and chart libraries want. PostgreSQL's timestamp minus timestamp gives an interval instead, so the epoch form is the shortcut there; SQLite uses strftime('%s', ts) and MySQL UNIX_TIMESTAMP(ts).","sql":"SELECT EXTRACT(epoch FROM at) AS unix_seconds\nFROM events;"},{"body":"EXTRACT(year FROM signed_at) * 100 + EXTRACT(month FROM signed_at) builds the classic YYYYMM cohort key with pure integer math, sortable and joinable without format functions. Cast the result when you want a clean int column; EXTRACT returns numerics on PostgreSQL.","sql":"SELECT (EXTRACT(year FROM signed_at) * 100 + EXTRACT(month FROM signed_at))::int AS cohort,\n       COUNT(*) AS signups\nFROM users\nGROUP BY 1\nORDER BY 1;"}]},"source_url":"https://sqlly.app/sql-functions/extract","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/extract-epoch","corpus":"sql-functions","engine":null,"language":"en","title":"SQL EXTRACT epoch function","description":"EXTRACT(epoch FROM ts) returns seconds since 1970 on PostgreSQL, and works on intervals too, where it totals the span in seconds.","body":{"slug":"extract-epoch","name":"EXTRACT(epoch)","h1":"SQL EXTRACT epoch function","category":"datetime","lede":"Returns a timestamp as seconds since 1970-01-01, or an interval as its total length in seconds.","syntax":"EXTRACT(epoch FROM ts)  |  EXTRACT(epoch FROM interval '1 day')  -- 86400","return_type":"numeric (double precision before PostgreSQL 14)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF_BIG(second, '1970-01-01', ts)"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"UNIX_TIMESTAMP(ts)"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%s', ts)"},{"engine_slug":"oracle","status":"partial","note":"date subtraction times 86400"}],"gotchas":["A timestamp without time zone is counted as if it were UTC, whatever the session zone; a timestamptz gives the true instant. Storing local wall time in a plain timestamp therefore shifts every epoch by your UTC offset.","On intervals, months and years are fixed lengths: EXTRACT(epoch FROM interval '1 month') is 2,592,000 (30 days) and '1 year' is 365.25 days.","The return is numeric (double precision before PostgreSQL 14). Casting to bigint rounds to the nearest second rather than truncating (1705320000.7 becomes 1705320001), so use FLOOR(EXTRACT(epoch FROM ts))::bigint when you need the whole second."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(epoch FROM created_at)::bigint AS epoch FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(epoch FROM SUM(end_ts - start_ts)) AS total_seconds FROM shifts;"},{"engine_slug":"mysql","sql":"SELECT UNIX_TIMESTAMP(created_at) AS epoch FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF_BIG(SECOND, '1970-01-01', SYSUTCDATETIME()) AS now_epoch;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%s', created_at) AS epoch FROM orders;"},{"engine_slug":"oracle","sql":"SELECT (SYSDATE - DATE '1970-01-01') * 86400 AS now_epoch FROM dual;"}],"faqs":[{"question":"What is the difference between EXTRACT(epoch) and UNIX_TIMESTAMP?","answer":"Spelling and engine: PostgreSQL uses EXTRACT(epoch FROM ts), MySQL uses UNIX_TIMESTAMP(ts). Both count seconds since 1970, but a MySQL DATETIME is read in the session time_zone while a PostgreSQL timestamp is always read as UTC, so they agree only when the MySQL session is UTC. A MySQL TIMESTAMP column is stored as UTC and agrees either way."},{"question":"Why does one month give 30 days?","answer":"An interval has no start date, so PostgreSQL converts a month to 30 days and a year to 365.25 days. For an exact span, subtract two real timestamps and extract the epoch from that."}],"related":["unix-timestamp","date-part","from-unixtime"],"novel_uses":[{"body":"Filters that convert the column with EXTRACT(epoch FROM ts) lose the index. Convert the bound value instead: created_at >= to_timestamp($1) compares timestamptz directly when created_at is timestamptz. On a plain timestamp column the bound is first converted with the session time_zone, so the result changes with the zone.","sql":"SELECT COUNT(*) FROM orders WHERE created_at >= to_timestamp($1);"},{"body":"EXTRACT(epoch FROM now() + interval '30 days')::bigint computes a token or cache expiry as plain seconds, on the clock the database and the client both count from.","sql":"SELECT EXTRACT(epoch FROM now() + interval '30 days')::bigint AS expires_at;"}]},"source_url":"https://sqlly.app/sql-functions/extract-epoch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/factorial","corpus":"sql-functions","engine":null,"language":"en","title":"SQL factorial","description":"PostgreSQL has factorial(n); its old 5! and !!5 operators were removed in 14. The other four engines need a recursive CTE or a log-sum trick.","body":{"slug":"factorial","name":"FACTORIAL","h1":"SQL factorial","category":"math","lede":"Computes n!, the product of 1 through n: factorial(5) is 120 on PostgreSQL, and a recursive CTE builds the same product on the other engines.","syntax":"factorial(n)  -- PostgreSQL  |  recursive CTE elsewhere","return_type":"integer / numeric","support":[{"engine_slug":"sql-server","status":"no","note":"No built-in; use a recursive CTE"},{"engine_slug":"postgresql","status":"yes","note":"factorial(bigint) returns numeric; the postfix 5! and prefix !!5 operators were removed in PostgreSQL 14"},{"engine_slug":"mysql","status":"no","note":"No factorial function; a recursive CTE works on MySQL 8.0+"},{"engine_slug":"sqlite","status":"no","note":"No built-in; recursive CTE on 3.8.3+"},{"engine_slug":"oracle","status":"no","note":"No built-in; recursive subquery factoring gives the running product"}],"gotchas":["Factorials explode: 21! already exceeds a 64-bit integer. PostgreSQL's factorial() returns numeric, so it stays exact; a hand-rolled CTE on BIGINT raises an overflow error at 21 on PostgreSQL, SQL Server and MySQL; SQLite silently turns the product into a REAL.","The portable pattern is a recursive CTE multiplying a running product, capped with an explicit n to avoid runaway recursion. SQL Server omits the RECURSIVE keyword, while PostgreSQL, MySQL and SQLite require it.","For combinatorics in bulk, LN-based sums are safer: summing LN(1)..LN(n) avoids overflow, then EXP the total, which gives an approximate float rather than an exact integer. SQL Server has no LN; use LOG there."],"examples":[{"engine_slug":"postgresql","sql":"SELECT factorial(5) AS f5, factorial(20) AS f20;  -- 120, 2432902008176640000"},{"engine_slug":"sqlite","sql":"WITH RECURSIVE f(n, fact) AS (\n  SELECT 1, 1\n  UNION ALL\n  SELECT n + 1, fact * (n + 1) FROM f WHERE n < 20\n)\nSELECT fact FROM f WHERE n = 20;  -- 2432902008176640000"}],"faqs":[{"question":"Does SQL have a FACTORIAL function?","answer":"PostgreSQL does: factorial(5) is 120. It dropped the 5! and !!5 operator forms in version 14, so old queries using them need rewriting. SQL Server, MySQL, SQLite and Oracle have nothing built in; use a recursive CTE with a running product."},{"question":"How large can a factorial be in SQL?","answer":"20! fits in a 64-bit integer (about 2.4e18); 21! does not. PostgreSQL's factorial() returns numeric and handles far larger n; on SQL Server a DECIMAL(38,0) CTE stays exact through 33!, and MySQL DECIMAL(65,0) is exact through at least 30!; SQLite has no exact decimal type, so sum logarithms there."},{"question":"Is a recursive factorial slow?","answer":"For small n it is a handful of rows and fine. For per-row combinatorics over big tables, precompute the values or use the log-sum approach instead of recursing per row."}],"related":["power","gcd","arithmetic-operators"],"novel_uses":[{"body":"Build n choose k by multiplying the falling product (n-k+1) through n and dividing by 1 through k as you go, so intermediates stay small. Three separate factorials overflow a BIGINT past n = 20.","sql":"SELECT 5.0 * 4 * 3 / (1 * 2 * 3) AS c_5_3;  -- 10, no factorial(5) needed"},{"body":"A recursive CTE summing 1/n! terms approximates e to about 15 significant digits in 18 terms. Drop RECURSIVE on SQL Server. It is a self-contained way to test an engine's float pipeline against a known answer.","sql":"WITH RECURSIVE t(n, term) AS (SELECT 1, 1.0e0 UNION ALL SELECT n + 1, term / n FROM t WHERE n < 18) SELECT SUM(term) AS e_approx FROM t;"}]},"source_url":"https://sqlly.app/sql-functions/factorial","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/field","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FIELD function","description":"How FIELD(str, s1, s2, ...) returns a value's position in a candidate list in MySQL, the classic ORDER BY FIELD trick for custom sort orders, and alternatives.","body":{"slug":"field","name":"FIELD","h1":"SQL FIELD function","category":"string","lede":"Returns the index of the first argument within the remaining arguments, which lets you sort rows in a chosen order.","syntax":"FIELD(str, str1, str2, ...)  |  ORDER BY FIELD(column, 'b', 'a', 'c')","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No FIELD; use CASE WHEN col = 'b' THEN 1 ... END in ORDER BY."},{"engine_slug":"postgresql","status":"partial","note":"array_position(ARRAY['b', 'a', 'c'], col) returns the same position, but NULL rather than 0 when nothing matches, and an ORDER BY on it puts those rows last. Wrap it in COALESCE(..., 0) to match FIELD."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No FIELD; use a CASE expression."},{"engine_slug":"oracle","status":"no","note":"No FIELD; use DECODE or a CASE expression in ORDER BY."}],"gotchas":["FIELD returns 0 when nothing matches, so in ascending order values missing from the list sort ahead of every listed value.","A NULL first argument also returns 0, not NULL, because NULL equals nothing in the list. COALESCE around FIELD therefore never fires.","Comparisons follow the collation, so with MySQL's case-insensitive default FIELD('A', 'a') is 1."],"examples":[{"engine_slug":"mysql","sql":"SELECT FIELD('b', 'a', 'b', 'c') AS idx;  -- 2"},{"engine_slug":"mysql","sql":"SELECT id, status FROM tickets\nORDER BY FIELD(status, 'open', 'pending', 'closed');"},{"engine_slug":"postgresql","sql":"SELECT array_position(ARRAY['open', 'pending', 'closed'], status) AS bucket\nFROM tickets;"}],"faqs":[{"question":"How do I sort rows in a custom order in MySQL?","answer":"ORDER BY FIELD(status, 'open', 'pending', 'closed'). Values outside the list get 0 and sort first; to push them to the end, sort by FIELD(status, ...) = 0 first, then by FIELD(status, ...)."},{"question":"What does FIELD return when nothing matches?","answer":"Zero, including when the searched value is NULL. FIELD never returns NULL, so test for 0 rather than wrapping it in COALESCE."}],"related":["elt","find-in-set","case","substring-index"],"novel_uses":[{"body":"FIELD maps each label to its list position, which is exactly what moving a varchar column to a tinyint needs in MySQL. Unlisted labels become 0, so decide where they belong before running it.","sql":"UPDATE tasks\nSET priority = FIELD(label, 'low', 'normal', 'high');"},{"body":"Grouping by FIELD(status, 'open', 'pending', 'closed') gives one bucket per listed value and throws every other status, NULL included, into bucket 0 together, a quick rollup when only the listed values matter.","sql":"SELECT FIELD(status, 'open', 'pending', 'closed') AS bucket, COUNT(*) AS n\nFROM tickets\nGROUP BY bucket;"},{"body":"CHECK (FIELD(status, ...) > 0) rejects anything outside the list. A NULL status also fails the check, because FIELD(NULL, ...) is 0. NOT NULL does not change which rows pass; it only changes the error (1048 instead of 3819), so add it for the schema's own sake.","sql":"ALTER TABLE tickets ADD CONSTRAINT status_ok\n  CHECK (FIELD(status, 'open', 'pending', 'closed') > 0);"}]},"source_url":"https://sqlly.app/sql-functions/field","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/filter-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FILTER clause with window aggregates","description":"FILTER (WHERE ...) on window aggregates: the standard conditional form, native on PostgreSQL, SQLite 3.30+ and recent Oracle; written as CASE on SQL Server and MySQL.","body":{"slug":"filter-over","name":"FILTER with OVER","h1":"SQL FILTER clause with window aggregates","category":"window","lede":"FILTER (WHERE condition) restricts which rows the aggregate sees, inside or outside a window: conditional sums and counts without CASE nesting.","syntax":"COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep)","return_type":"conditional aggregate","support":[{"engine_slug":"sql-server","status":"no","note":"not supported, including SQL Server 2025; use CASE inside the aggregate"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 9.4+"},{"engine_slug":"mysql","status":"no","note":"not supported; use CASE inside the aggregate"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.30+; rejected on built-in (non-aggregate) window functions like ROW_NUMBER"},{"engine_slug":"oracle","status":"yes","note":"Oracle AI Database 26ai, release update 23.26.1+; CASE on 23ai and earlier"}],"gotchas":["FILTER is only valid on aggregate functions: SQLite says 'FILTER clause may only be used with aggregate window functions' for ROW_NUMBER, LAG and the rest, and PostgreSQL rejects them too.","The portable equivalent is the CASE aggregate: COUNT(*) FILTER (WHERE status = 'won') becomes SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END), and SUM(x) FILTER (WHERE c) becomes SUM(CASE WHEN c THEN x END).","Keep the ELSE off when translating SUM(x) FILTER: with no matching rows FILTER returns NULL, and SUM(CASE WHEN c THEN x END) also returns NULL, while ELSE 0 would return 0."],"examples":[{"engine_slug":"postgresql","sql":"SELECT rep, deal_id, amount,\n       COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep) AS wins,\n       SUM(amount) FILTER (WHERE status = 'open') OVER (PARTITION BY rep) AS open_amount\nFROM deals;"},{"engine_slug":"sql-server","sql":"SELECT rep, deal_id,\n       SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END) OVER (PARTITION BY rep) AS wins\nFROM deals;"},{"engine_slug":"sqlite","sql":"-- 3.30+ for FILTER, on aggregates only\nSELECT rep, deal_id,\n       COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep) AS wins,\n       SUM(amount) FILTER (WHERE status = 'open') OVER (PARTITION BY rep) AS open_amount\nFROM deals;"},{"engine_slug":"oracle","sql":"-- FILTER on aggregates from 26ai (23.26.1); CASE inside the aggregate before that\nSELECT rep, deal_id,\n       COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep) AS wins\nFROM deals;"}],"faqs":[{"question":"Is FILTER faster than CASE inside the aggregate?","answer":"On PostgreSQL both spellings plan to the same WindowAgg and ran within a few percent of each other on a million rows, so the choice is readability. Use FILTER where it exists."},{"question":"Can FILTER be used without OVER?","answer":"Yes, it works on plain aggregates too (COUNT(*) FILTER (WHERE ...) in a GROUP BY query), which is exactly how the window form composes."}],"related":["sum-over","aggregate-over","window-clause"],"novel_uses":[{"body":"Divide a filtered running count by the plain running count over the same frame and each row carries the conversion rate of its recent window. The FILTER spelling beats nested CASEs once you count more than one condition.","sql":"SELECT rep, deal_day,\n       COUNT(*) FILTER (WHERE status = 'won')\n         OVER (ORDER BY deal_day, deal_id ROWS BETWEEN 9 PRECEDING AND CURRENT ROW) * 1.0\n         / COUNT(*) OVER (ORDER BY deal_day, deal_id ROWS BETWEEN 9 PRECEDING AND CURRENT ROW) AS win_rate10\nFROM deals ORDER BY deal_day, deal_id;"},{"body":"Count converted signups and total signups with two window counts over the same order and the running rate builds itself day by day. The filtered count skips signups with a NULL conversion date, but it still counts a conversion that happens after the row's signup day, so the rate is the share of signups seen so far that ever converted, not the conversion rate as of that day.","sql":"SELECT signup_day, user_id,\n       COUNT(*) FILTER (WHERE converted_day IS NOT NULL) OVER (ORDER BY signup_day)\n         * 1.0 / COUNT(*) OVER (ORDER BY signup_day) AS ever_conv_rate\nFROM signups;"}]},"source_url":"https://sqlly.app/sql-functions/filter-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/find-in-set","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FIND_IN_SET function","description":"How FIND_IN_SET searches a comma-separated string in MySQL: 1-based index results, why spaces and commas break it, and the STRING_SPLIT and array alternatives.","body":{"slug":"find-in-set","name":"FIND_IN_SET","h1":"SQL FIND_IN_SET function","category":"string","lede":"Returns the 1-based position of a value inside a comma-separated string, or 0 when the value is not in the list.","syntax":"FIND_IN_SET(value, comma_separated_list)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No FIND_IN_SET; split with STRING_SPLIT and compare rows."},{"engine_slug":"postgresql","status":"no","note":"No FIND_IN_SET; array_position(string_to_array(list, ','), value)."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No FIND_IN_SET; INSTR(',' || list || ',', ',' || value || ',')."},{"engine_slug":"oracle","status":"no","note":"No FIND_IN_SET; the same INSTR trick with delimiters added."}],"gotchas":["The list is one string with no quoting or trimming: 'red' is not found in 'blue, red' because that element is ' red'.","A search value that contains a comma never matches: FIND_IN_SET('a,b', 'a,b') is 0. Returns NULL when either argument is NULL. Matching follows the collation: FIND_IN_SET('RED', 'blue,red') is 2 under utf8mb4_0900_ai_ci and 0 under utf8mb4_bin. Trailing spaces count, so 'red' is not found in 'blue,red '.","Filtering with WHERE FIND_IN_SET(5, tag_ids) cannot use an index on tag_ids, so it scans the table. A child table and a join scale; comma lists do not."],"examples":[{"engine_slug":"mysql","sql":"SELECT FIND_IN_SET('red', 'blue,red,green') AS pos;  -- 2"},{"engine_slug":"mysql","sql":"SELECT * FROM roles\nWHERE FIND_IN_SET('admin', permissions) > 0;"}],"faqs":[{"question":"What is the difference between FIND_IN_SET and LIKE?","answer":"FIND_IN_SET matches a whole element of a comma list, so it finds 'red' but not inside 'bordered'. LIKE '%red%' would match 'bordered' too."},{"question":"Should I store comma-separated lists to use with FIND_IN_SET?","answer":"Usually not. It defeats indexes and foreign keys. Use a child table and a join; keep FIND_IN_SET for legacy data and SET columns."}],"related":["string-split","substring-index","elt","field"],"novel_uses":[{"body":"ORDER BY FIND_IN_SET(size, 'S,M,L,XL') sorts by the position in the chart instead of alphabetically. Sizes missing from the chart return 0 and sort first, which makes gaps easy to spot.","sql":"SELECT * FROM products\nORDER BY FIND_IN_SET(size, 'S,M,L,XL'), name;"},{"body":"FIND_IN_SET returns the position and ELT turns the position into a label, so a stored CSV value becomes display text in one expression without a CASE chain.","sql":"SELECT ELT(FIND_IN_SET(role, 'admin,editor,viewer'),\n           'Administrator', 'Editor', 'Viewer') AS label\nFROM members;"},{"body":"A MySQL SET column reads as its comma-separated form, so FIND_IN_SET is the documented way to ask whether one member is present.","sql":"SELECT * FROM user_perms\nWHERE FIND_IN_SET('read', perms) > 0;"}]},"source_url":"https://sqlly.app/sql-functions/find-in-set","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/first-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FIRST_VALUE function","description":"FIRST_VALUE in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: compare every row against the group's first, with default-frame caveats.","body":{"slug":"first-value","name":"FIRST_VALUE","h1":"SQL FIRST_VALUE function","category":"window","lede":"Returns an expression from the first row of the window frame, so every row can be compared with a baseline, such as each price next to the opening price.","syntax":"FIRST_VALUE(expression) OVER (PARTITION BY g ORDER BY x)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is fine for FIRST_VALUE with a plain ORDER BY, but be explicit when the frame is custom.","FIRST_VALUE is window-only: to return only the first row per group, use ROW_NUMBER() = 1 instead.","If the first row's value is NULL, FIRST_VALUE returns NULL. NULLS LAST in the ORDER BY (PostgreSQL, Oracle, SQLite 3.30+) or a CASE sort key on SQL Server and MySQL moves those rows out of first place; Oracle and SQL Server 2022+ also accept FIRST_VALUE(x) IGNORE NULLS."],"examples":[{"engine_slug":"all","sql":"SELECT day, price,\n       FIRST_VALUE(price) OVER (ORDER BY day) AS open_price\nFROM prices;"},{"engine_slug":"all","sql":"SELECT region, city, sales,\n       sales - FIRST_VALUE(sales) OVER (PARTITION BY region ORDER BY sales DESC) AS vs_leader\nFROM regional_sales;"}],"faqs":[{"question":"How is FIRST_VALUE different from MIN?","answer":"MIN returns the smallest value; FIRST_VALUE returns the value from the first row of the frame. FIRST_VALUE(price) OVER (ORDER BY day) is the earliest price, which is only the minimum if prices never fell. FIRST_VALUE can return one column from the row chosen by another."},{"question":"How do I get the first row per group, not just its value?","answer":"ROW_NUMBER() OVER (PARTITION BY g ORDER BY x) = 1 in a CTE. FIRST_VALUE attaches values to all rows; it does not reduce them."}],"related":["last-value","lag","row-number"],"novel_uses":[{"body":"First observation carried forward: FIRST_VALUE(reading IGNORE NULLS) over a frame from the partition start fills every NULL with the most recent real reading, the standard repair for spotty sensor feeds. IGNORE NULLS exists on Oracle and SQL Server 2022+; elsewhere a correlated subquery or an application-side fill does it.","sql":"SELECT device, at,\n       FIRST_VALUE(reading IGNORE NULLS) OVER (\n         PARTITION BY device ORDER BY at\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS filled\nFROM readings;"},{"body":"Partition by the truncated day and order by time, and every row of that day carries its opening event. Subtracting the two gives seconds-since-open per event in one scan, no join back to a daily aggregate.","sql":"SELECT at,\n       EXTRACT(epoch FROM at - FIRST_VALUE(at) OVER (\n         PARTITION BY DATE_TRUNC('day', at) ORDER BY at)) AS secs_into_day\nFROM events;"}]},"source_url":"https://sqlly.app/sql-functions/first-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/float-equality","corpus":"sql-functions","engine":null,"language":"en","title":"SQL float equality","description":"Comparing floats with = fails on accumulated error: 0.1 + 0.2 <> 0.3 in binary. Compare within a tolerance, or keep exact types for exact values.","body":{"slug":"float-equality","name":"float equality","h1":"SQL float equality","category":"math","lede":"Why = is unreliable on float columns and the portable fixes: ABS(a - b) < epsilon, or storing exact decimals for values that must compare equal.","syntax":"ABS(a - b) < 1e-9  |  a = b  -- exact types only","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":"Same rule; DECIMAL columns compare exactly, FLOAT does not"},{"engine_slug":"postgresql","status":"yes","note":"= on double precision compares exact binary values; a real (float4) column never equals the literal 0.1, because the literal is numeric and the float4 widens to 0.10000000149011612"},{"engine_slug":"mysql","status":"yes","note":"Same; DECIMAL compares exactly"},{"engine_slug":"sqlite","status":"yes","note":"REAL compares by value; INTEGER cents sidestep the problem"},{"engine_slug":"oracle","status":"yes","note":"NUMBER compares exactly; BINARY_FLOAT/BINARY_DOUBLE do not"}],"gotchas":["The failure is representational, not engine-specific: 0.1 and 0.2 have no exact binary form, so their float sum is the neighbour of 0.3 rather than 0.3.","Pick the tolerance relative to the magnitude: ABS(a - b) < 1e-9 suits values near 1, but near 1e12 adjacent doubles are about 1e-4 apart, so use ABS(a - b) <= 1e-9 * ABS(b).","Single-precision columns are the worst case: on PostgreSQL WHERE real_col = 0.1 matches nothing, because the stored float4 widens to 0.10000000149011612, which is not 0.1. MySQL FLOAT columns behave the same way."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ABS((0.1::float8 + 0.2::float8) - 0.3::float8) < 1e-9 AS close_enough;  -- true"},{"engine_slug":"mysql","sql":"SELECT * FROM measurements\nWHERE ABS(reading - 0.1) < 0.000001;"},{"engine_slug":"postgresql","sql":"SELECT 0.1::float4 = 0.1 AS f4, 0.1::float8 = 0.1 AS f8;  -- false, true"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN ABS(CAST(0.1 AS FLOAT) + CAST(0.2 AS FLOAT) - CAST(0.3 AS FLOAT)) < 1e-9 THEN 1 ELSE 0 END AS close_enough;  -- 1"},{"engine_slug":"sqlite","sql":"SELECT ABS(0.1 + 0.2 - 0.3) < 1e-9 AS close_enough;  -- 1"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN 0.1 + 0.2 = 0.3 THEN 1 ELSE 0 END AS exact FROM dual;  -- 1: NUMBER compares exactly"}],"faqs":[{"question":"Why does my WHERE x = 0.1 not match?","answer":"Either the column is single precision (REAL/float4, MySQL FLOAT), whose 0.1 differs from the double the literal becomes, or the value was computed and carries rounding error. Compare with a tolerance: ABS(x - 0.1) < 1e-6 for single precision."},{"question":"How should I compare floats in SQL?","answer":"Within a tolerance scaled to your data: ABS(a - b) < epsilon. For currency and counts, avoid the problem entirely by using NUMERIC/DECIMAL columns, which compare exactly."},{"question":"Do joins on float keys work?","answer":"They match only values that compare equal under =, so computed floats routinely fail to join. Join on rounded keys (CAST to a fixed scale) or exact integer keys instead."}],"related":["numeric-vs-float","double-precision","nan-check","cast"],"novel_uses":[{"body":"ABS(SUM(parts) - control) < 0.005 turns float tolerance into a reconciliation check: the books pass when parts sum to the control total within half a cent. Wider tolerances hide missing rows; tighter ones false-alarm on float dust.","sql":"SELECT ABS(SUM(amount) - 1000.00) < 0.005 AS books_ok FROM entries;"},{"body":"-0.0 equals 0 in every comparison but formats as -0 in some clients and exports. One UPDATE with WHERE x = 0 rewrites both zeros to a single stored form, since IEEE equality catches the negative zero too.","sql":"UPDATE readings SET value = 0 WHERE value = 0;"}]},"source_url":"https://sqlly.app/sql-functions/float-equality","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/floor","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FLOOR function","description":"Round down with SQL FLOOR in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: negative numbers, integer division and FLOOR versus ROUND and TRUNC.","body":{"slug":"floor","name":"FLOOR","h1":"SQL FLOOR function","category":"math","lede":"Returns the largest integer not greater than the input. FLOOR(-2.5) is -3, not -2: rounding down means toward negative infinity, which is where most off-by-one bugs come from.","syntax":"FLOOR(number)","return_type":"integer / numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"math functions from SQLite 3.35+, enabled in standard builds"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["FLOOR rounds toward negative infinity: FLOOR(-2.5) is -3. To drop the decimals toward zero, use TRUNC (or CAST to an integer type).","Integer division happens first and truncates toward zero on SQL Server, PostgreSQL and SQLite: -7/2 is -3, so FLOOR(-7/2) is -3, not the -4 that FLOOR(-3.5) gives. Write FLOOR(-7 / 2.0). MySQL's / returns a decimal (7/2 is 3.5); DIV is its integer division.","The result keeps the input's type on SQL Server and PostgreSQL: FLOOR(2.5) is a numeric 2, FLOOR of a float is a float. SQLite returns a real for real input; MySQL returns an integer for exact numeric input."],"examples":[{"engine_slug":"all","sql":"SELECT FLOOR(2.9) AS down;   -- 2"},{"engine_slug":"all","sql":"SELECT FLOOR(-2.1) AS down;  -- -3"}],"faqs":[{"question":"What is FLOOR of a negative number?","answer":"The next lower integer: FLOOR(-2.1) is -3. It rounds toward negative infinity, unlike TRUNC which rounds toward zero."},{"question":"How do I get whole pages from a row count?","answer":"That is a ceiling, not a floor: CEIL(total * 1.0 / page_size). The * 1.0 avoids integer division on SQL Server, PostgreSQL and SQLite, which would otherwise round down before CEIL runs."}],"related":["ceil","round","mod"],"novel_uses":[{"body":"FLOOR(EXTRACT(hour FROM at) / 4) * 4 collapses 24 hours into six four-hour segments (0, 4, 8, 12, 16, 20), the day-parting buckets ad schedules compare against. Extract the hour your engine's way and the arithmetic is identical.","sql":"SELECT FLOOR(EXTRACT(hour FROM at) / 4) * 4 AS day_part,\n       COUNT(*) AS events\nFROM events\nGROUP BY 1\nORDER BY 1;"},{"body":"Equal-width bins are useless when sizes span orders of magnitude. FLOOR(LOG(b, size)) puts values into doubling buckets (1, 2, 4, 8 and so on), which is how file-size and latency histograms are usually built. MySQL spells it LOG(b, x); SQL Server reverses the arguments to LOG(x, b).","sql":"SELECT FLOOR(LOG(2, size_bytes)) AS magnitude, COUNT(*) AS files\nFROM uploads\nGROUP BY 1;"}]},"source_url":"https://sqlly.app/sql-functions/floor","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/for-xml","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FOR XML clause","description":"SQL Server's FOR XML clause turns a result set into one XML document, with PATH mode to shape it. Oracle and PostgreSQL build XML with XMLElement and XMLAgg instead.","body":{"slug":"for-xml","name":"FOR XML","h1":"SQL FOR XML clause","category":"string","lede":"SELECT id, total FROM orders FOR XML PATH('order'), ROOT('orders') returns <orders><order><id>1</id><total>5</total></order>...</orders>.","syntax":"SELECT ... FOR XML [RAW | AUTO | EXPLICIT | PATH('name')] [, ROOT('name')]","return_type":"XML","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"xmlelement / xmlattributes / xmlagg functions"},{"engine_slug":"mysql","status":"no","note":"no XML generation"},{"engine_slug":"sqlite","status":"no","note":"no XML generation"},{"engine_slug":"oracle","status":"partial","note":"XMLElement, XMLForest, XMLAgg"}],"gotchas":["PATH mode shapes output through column aliases: '@id' becomes an attribute, '*' becomes the element's text, 'customer/name' nests elements. A nested FOR XML PATH subquery needs , TYPE to stay XML instead of escaped text.","The pre-2017 string-aggregation idiom, STUFF((SELECT ',' + name ... FOR XML PATH('')), 1, 1, ''), escapes & and < unless you add , TYPE and read .value('.', 'nvarchar(max)'). On SQL Server 2017+ use STRING_AGG.","Oracle composes with XMLElement, XMLForest and XMLAgg; PostgreSQL has the lowercase xmlelement/xmlattributes/xmlagg set. Function-style on both, not a clause."],"examples":[{"engine_slug":"sql-server","sql":"SELECT id, total\nFROM orders\nFOR XML PATH('order'), ROOT('orders');"},{"engine_slug":"sql-server","sql":"SELECT id AS '@id', total AS '*'\nFROM orders FOR XML PATH;"},{"engine_slug":"postgresql","sql":"SELECT xmlelement(name order,\n  xmlattributes(id AS id), total) AS doc\nFROM orders;"},{"engine_slug":"oracle","sql":"SELECT XMLELEMENT(\"order\", XMLATTRIBUTES(id AS \"id\"), total) AS doc\nFROM orders;"}],"faqs":[{"question":"How do I get JSON instead?","answer":"FOR JSON PATH on SQL Server, JSON_ARRAYAGG with JSON_OBJECT on MySQL and Oracle, json_agg with json_build_object on PostgreSQL, json_group_array with json_object on SQLite."},{"question":"Why is my FOR XML output truncated?","answer":"Usually the data is intact and the client is cutting it. A top-level FOR XML without TYPE reaches the client as a series of 2,033-character rows, so code that reads only the first row gets a fragment; wrap it as (SELECT ... FOR XML PATH, TYPE) or cast it to nvarchar(max) to get one value. SSMS also caps what it displays, so click the XML cell to open the full document."}],"related":["xmltable","xmlquery","xml-value","json-agg"],"novel_uses":[{"body":"RAW and AUTO modes emit columns as attributes by default; appending ELEMENTS nests each column as a child element instead. PATH already emits elements, so there it only matters as ELEMENTS XSINIL, which keeps NULL columns as xsi:nil=\"true\" elements instead of dropping them.","sql":"SELECT id, total FROM orders FOR XML RAW('order'), ELEMENTS, ROOT('orders');"},{"body":"FOR XML AUTO, BINARY BASE64 encodes varbinary columns as base64 inside the document, so a result set carries images or files without a second channel.","sql":"SELECT thumb FROM icons FOR XML AUTO, BINARY BASE64;"}]},"source_url":"https://sqlly.app/sql-functions/for-xml","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/format","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FORMAT function","description":"SQL Server's FORMAT turns numbers and dates into strings with .NET format strings and a culture: flexible, readable, and slow on big row counts.","body":{"slug":"format","name":"FORMAT","h1":"SQL FORMAT function","category":"string","lede":"Formats a value as text using .NET numeric and date format strings, with an optional culture. The most expressive formatter in SQL, and the slowest.","syntax":"FORMAT(value, format_string [, culture])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"partial","note":"MySQL's FORMAT(x, d) is a different function: it groups digits"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["FORMAT is .NET under the hood and can be an order of magnitude slower than CONVERT or CAST. Keep it off large result sets and WHERE clauses.","Common styles: 'N2' thousands plus two decimals, 'C' currency, 'P' percent, 'd' short date. Culture argument: FORMAT(1234.5, 'N2', 'de-de') gives 1.234,50.","Error handling is lopsided: a single-letter standard specifier that does not fit the value's type (FORMAT(1.5, 'D') or FORMAT(date, 'C')) quietly returns NULL, while an unrecognised pattern is read as literal or custom text (FORMAT(1234.5, 'bogus') returns bogus), and passing a varchar as the value fails with Msg 8116.","MySQL's FORMAT is not this function: it rounds and groups a number with thousands separators. See number-format."],"examples":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(1234.5, 'N2', 'en-us') AS money;  -- 1,234.50"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS iso_day;"},{"engine_slug":"mysql","sql":"SELECT FORMAT(1234.5, 2) AS grouped;  -- 1,234.50"}],"faqs":[{"question":"Why is FORMAT so slow?","answer":"It calls into the .NET formatting layer per row, while CONVERT/CAST are native. On thousands of rows the difference is measurable. Format in the query only for final display."},{"question":"Is FORMAT available outside SQL Server?","answer":"As a culture-aware formatter, no. MySQL's FORMAT groups digits only; PostgreSQL uses TO_CHAR; SQLite has printf, with format() as an alias since 3.38.0; there FORMAT(1234.5, 'N2') does not error and returns 1234.5. The .NET style strings are SQL Server specific."},{"question":"How do I format a date as ISO with FORMAT?","answer":"FORMAT(d, 'yyyy-MM-dd', 'en-US'). Pass the culture: without it FORMAT uses the session language, and a culture with a non-Gregorian calendar changes the date itself: FORMAT(d, 'yyyy-MM-dd', 'ar-SA') returns a Hijri date like 1447-07-16. CONVERT(char(10), d, 23) is the cheaper ISO route."}],"related":["convert","number-format","to-char"],"novel_uses":[{"body":"Custom .NET digit placeholders zero-pad and fix scale in one call: FORMAT(1234.5, '00000.00') gives 01234.50, which the common style strings never show.","sql":"SELECT FORMAT(1234.5, '00000.00') AS fixed;  -- 01234.50"},{"body":"Quoted text inside a custom format string is emitted as-is, so FORMAT(42, '0\" pcs\"') builds a display label without a concatenation.","sql":"SELECT FORMAT(42, '0\" pcs\"') AS label;  -- 42 pcs"},{"body":"With a culture argument FORMAT spells out date parts in that language, which CONVERT cannot do: FORMAT(GETDATE(), 'dddd', 'el-GR') returns the Greek weekday name.","sql":"SELECT FORMAT(GETDATE(), 'dddd', 'el-GR') AS weekday;"}]},"source_url":"https://sqlly.app/sql-functions/format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/format-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FORMAT date function","description":"FORMAT in SQL Server: .NET format strings and an optional culture argument like 'de-DE' for dates, flexible and convenient, with a real performance cost.","body":{"slug":"format-date","name":"FORMAT","h1":"SQL FORMAT date function","category":"datetime","lede":"Formats a date with .NET custom format strings and optional culture: the closest SQL Server gets to TO_CHAR's expressiveness.","syntax":"FORMAT(date, 'format' [, culture])","return_type":"nvarchar","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'YYYY-MM-DD'); masks, not .NET codes"},{"engine_slug":"mysql","status":"partial","note":"DATE_FORMAT(d, '%Y-%m-%d')"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y-%m-%d', d); numeric codes only, no %a or %b name codes"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'YYYY-MM-DD', 'NLS_DATE_LANGUAGE=...')"}],"gotchas":["FORMAT calls into the .NET runtime for every row and is far slower than CONVERT; on large result sets, use CONVERT with a style number.","Codes are .NET custom strings: 'yyyy-MM-dd HH:mm:ss'. Capital M is month and lowercase m is minute; HH is 24-hour and hh is 12-hour.","The culture argument changes names and order: FORMAT(d, 'D', 'de-DE') gives German long dates, something Oracle's TO_CHAR needs NLS parameters for."],"examples":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(GETDATE(), 'yyyy-MM-dd');"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(CAST('2026-08-01' AS date), 'dddd, dd MMMM yyyy', 'de-DE');  -- Samstag, 01 August 2026"},{"engine_slug":"postgresql","sql":"SELECT to_char(DATE '2026-08-01', 'FMDay, DD FMMonth YYYY');  -- Saturday, 01 August 2026"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT('2026-08-01', '%W, %d %M %Y');  -- Saturday, 01 August 2026"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(DATE '2026-08-01', 'FMDay, DD FMMonth YYYY', 'NLS_DATE_LANGUAGE=ENGLISH') FROM dual;  -- Saturday, 01 August 2026"}],"faqs":[{"question":"Is FORMAT slow enough to matter?","answer":"Yes on sets: in a 300,000-row run on SQL Server 2022 Developer, FORMAT used about 9x the CPU of CONVERT for the same output (955 ms vs 108 ms). Use it for one-off presentation, not for GROUP BY or large exports."},{"question":"What is the difference between 'MM' and 'mm'?","answer":"In .NET masks, 'MM' is two-digit month, 'mm' is minutes (the reverse intuition of many C formats). 'dd' is day, 'dddd' the day name."}],"related":["convert-style","date-format-codes","date-to-text","lc-time-names"],"novel_uses":[{"body":"The .NET 'O' specifier emits full ISO 8601 with offset and precision in one character, no mask to maintain or get wrong.","sql":"SELECT FORMAT(SYSDATETIMEOFFSET(), 'O');"},{"body":"Six f characters print the microseconds datetime2 carries, for log lines that must show sub-millisecond gaps.","sql":"SELECT FORMAT(SYSDATETIME(), 'yyyy-MM-dd HH:mm:ss.ffffff');"},{"body":"Letters that are not .NET codes pass through (yyyy Q gives 2026 Q), but some letters are codes: F is fractional seconds, so yyyy FY gives 2026 Y. Quote fixed text like fiscal-year labels inside the mask.","sql":"SELECT FORMAT(CAST('2026-08-01' AS date), 'yyyy ''FY''');  -- 2026 FY"}]},"source_url":"https://sqlly.app/sql-functions/format-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/format-numbers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FORMAT number formatting","description":"How FORMAT differs across engines in SQL Server, MySQL and PostgreSQL: .NET format strings, decimal rounding, locale separators and the printf-style PG version.","body":{"slug":"format-numbers","name":"FORMAT","h1":"SQL FORMAT number formatting","category":"string","lede":"Formats values as display text. SQL Server and MySQL format numbers; PostgreSQL and SQLite use the name for printf-style composition.","syntax":"FORMAT(value, format [, culture])  |  MySQL: FORMAT(number, decimals [, locale])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"format() is printf-style text composition; TO_CHAR formats numbers."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"format() (3.38+) is an alias of printf; printf('%,d', n) adds thousands separators."},{"engine_slug":"oracle","status":"partial","note":"No FORMAT; TO_CHAR(value, '9G999D99') formats numbers."}],"gotchas":["SQL Server's FORMAT takes .NET format strings ('N2' for grouped decimals, 'C' for currency, 'yyyy-MM-dd' for dates) and runs through the CLR, so it is much slower than CONVERT on large result sets.","MySQL's FORMAT(number, 2) rounds and inserts thousands separators, producing '1,234.50'. A DECIMAL midpoint rounds away from zero (FORMAT(2.5, 0) gives '3'), but a DOUBLE midpoint does not (CAST(2.5 AS DOUBLE) gives '2', and 0.125 gives '0.12'), so cast to DECIMAL first when that matters. The result is text, so sorting or comparing it gives string order.","PostgreSQL's format('%s ...', args) never formats numbers with separators; for that use TO_CHAR(value, 'FM9,999,999.00'). The pattern needs enough 9s for the largest value: with 'FM9,999.00', 10000 renders as '#,###.##'."],"examples":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(total, 'N2') AS total_fmt\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT FORMAT(1234.5, 2) AS price_fmt;  -- 1,234.50"},{"engine_slug":"postgresql","sql":"SELECT format('%s sold %s units', product, units) AS line\nFROM sales;"},{"engine_slug":"sqlite","sql":"SELECT format('%,d', 1234567) AS grouped;  -- 1,234,567"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(1234.5, '9G999D99') AS price_fmt\nFROM dual;  -- 1,234.50"}],"faqs":[{"question":"Why does ORDER BY FORMAT(...) sort wrong?","answer":"FORMAT returns a string, so '10,000.00' sorts before '9,999.00' ('1' comes before '9'). Order by the numeric column and format only in the SELECT list."},{"question":"Is FORMAT the same function in every engine?","answer":"No. SQL Server and MySQL format numbers for display; PostgreSQL's format() and SQLite's format() compose strings printf-style. Oracle has no FORMAT."},{"question":"What should I use for locale-aware currency?","answer":"MySQL accepts a locale: FORMAT(x, 2, 'de_DE') gives '1.234,50'. SQL Server takes a culture: FORMAT(x, 'C', 'de-DE'). PostgreSQL's TO_CHAR uses the L, D and G codes, which follow lc_monetary and lc_numeric."}],"related":["to-char","printf","strftime","cast"],"novel_uses":[{"body":"FORMAT(id, '000000') is the .NET custom numeric format for fixed digits: 123 becomes 000123. It suits invoice and member numbers that must render at a fixed width.","sql":"SELECT FORMAT(id, '000000') AS invoice_no FROM invoices;"},{"body":"PostgreSQL's format accepts %1$s style positional specifiers, so one argument can appear twice without being passed twice or concatenated by hand.","sql":"SELECT format('%1$s and %1$s again', 'tick') AS label;"},{"body":"A width with the - flag pads the value to a fixed number of characters, which builds aligned plain-text columns straight from PostgreSQL's format.","sql":"SELECT format('%-12s| %s', name, note) FROM items;"}]},"source_url":"https://sqlly.app/sql-functions/format-numbers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/formatmessage","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FORMATMESSAGE function","description":"SQL Server's FORMATMESSAGE builds strings from a template with %s and %d placeholders: sprintf inside T-SQL, for messages and dynamic SQL.","body":{"slug":"formatmessage","name":"FORMATMESSAGE","h1":"SQL FORMATMESSAGE function","category":"string","lede":"Substitutes arguments into a message template the way RAISERROR does, returning the string instead of raising an error.","syntax":"FORMATMESSAGE('template %s %d', arg1, arg2)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"format-string styles need SQL Server 2016+"},{"engine_slug":"postgresql","status":"partial","note":"format() covers the same ground"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"partial","note":"printf()/format()"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Passing a template string with placeholders needs SQL Server 2016+; older builds only format messages by sys.messages message_id.","Placeholders mirror RAISERROR: %s string, %d integer, %i signed, %% for a literal percent sign.","PostgreSQL's format() is the portable twin: format('%s bought %s items', name, n), with %I and %L for safe identifiers and literals.","Missing arguments print as (null): FORMATMESSAGE('%s has %s', 'A') returns 'A has (null)'. Types must match the placeholder or the substitution misfires."],"examples":[{"engine_slug":"sql-server","sql":"SELECT FORMATMESSAGE('Order %s has %d items', 'A-100', 3) AS msg;  -- Order A-100 has 3 items"},{"engine_slug":"postgresql","sql":"SELECT format('Order %s has %s items', 'A-100', 3) AS msg;"},{"engine_slug":"sqlite","sql":"SELECT printf('Order %s has %d items', 'A-100', 3) AS msg;  -- Order A-100 has 3 items"}],"faqs":[{"question":"Is FORMATMESSAGE the same as RAISERROR?","answer":"Same placeholder engine, different effect: RAISERROR raises an error, FORMATMESSAGE just returns the formatted string, which you can use in variables and queries."},{"question":"What is the PostgreSQL equivalent of FORMATMESSAGE?","answer":"format(): format('%s = %s', k, v) with %s, %I and %L placeholders. SQLite's printf()/format() is a closer sprintf with %d and %f."},{"question":"Why does my output contain (null)?","answer":"A placeholder had no matching argument, or the argument was NULL. Count placeholders against arguments, and write a literal percent sign as %%."}],"related":["format","printf","plus-concat"],"novel_uses":[{"body":"THROW takes no placeholder formatting, so build the text with FORMATMESSAGE first and raise that; you keep THROW's abort semantics and get sprintf-style messages.","sql":"DECLARE @order varchar(20) = 'A-100', @err varchar(50) = 'timeout';\nDECLARE @msg nvarchar(2048) = FORMATMESSAGE('Order %s failed: %s', @order, @err);\nTHROW 50001, @msg, 1;"},{"body":"Calling FORMATMESSAGE with a message_id pulls the sys.messages row for the session's language, so sp_addmessage rows in several languages give localized messages with no app-side catalog, provided each localized row uses positional placeholders such as %1!; a %s placeholder in a non-English row fails with a formatting error.","sql":"DECLARE @user varchar(20) = 'Ann';\nSELECT FORMATMESSAGE(50010, @user) AS msg;  -- sys.messages text in the session language"}]},"source_url":"https://sqlly.app/sql-functions/formatmessage","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/fractional-powers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL POWER with fractional exponents","description":"POWER(-8, 1.0/3.0) has no real answer: four engines raise an error and SQLite returns NULL. The sign-preserving rewrite works on all five.","body":{"slug":"fractional-powers","name":"POWER fractional","h1":"SQL POWER with fractional exponents","category":"math","lede":"Covers what happens when the base is negative and the exponent is not a whole number: an error on SQL Server, PostgreSQL, MySQL and Oracle NUMBER, NULL on SQLite.","syntax":"POWER(-8, 1.0/3.0)","return_type":"base type on SQL Server, numeric on PostgreSQL, float elsewhere / NULL","support":[{"engine_slug":"sql-server","status":"partial","note":"Raises 'An invalid floating point operation occurred'"},{"engine_slug":"postgresql","status":"partial","note":"Raises 'a negative number raised to a non-integer power yields a complex result' for double and numeric"},{"engine_slug":"mysql","status":"partial","note":"Raises 'DOUBLE value is out of range in pow(...)'"},{"engine_slug":"sqlite","status":"partial","note":"NULL, with no error"},{"engine_slug":"oracle","status":"partial","note":"NUMBER input raises ORA-01428; BINARY_DOUBLE input returns NaN"}],"gotchas":["The failure is mathematical, not a bug: a negative base with a non-integer exponent has only complex roots, and C's pow() returns NaN for it, which each engine turns into an error or NULL.","For odd roots the fix is sign-aware: SIGN(x) * POWER(ABS(x), 1e0/3) returns -2 for x = -8. On SQL Server, pass a float x, or POWER returns an INT and truncates the root.","Negative bases with whole-number exponents are fine: POWER(-2, 3) is -8 on every engine."],"examples":[{"engine_slug":"sqlite","sql":"SELECT POWER(-8, 1.0/3.0) AS r;  -- NULL"},{"engine_slug":"postgresql","sql":"SELECT POWER(-8::float8, 1.0/3.0) AS r;  -- ERROR: ... yields a complex result"},{"engine_slug":"oracle","sql":"SELECT POWER(-8d, 1/3) AS nan_result FROM dual;  -- NaN: BINARY_DOUBLE input; NUMBER input would raise ORA-01428"},{"engine_slug":"all","sql":"SELECT SIGN(-8) * POWER(ABS(-8e0), 1e0/3) AS cube_root;  -- -2"}],"faqs":[{"question":"Why does POWER(-8, 1.0/3.0) return NULL or error?","answer":"A negative base with a non-integer exponent has no real result. SQLite returns NULL; SQL Server, PostgreSQL, MySQL and Oracle (NUMBER input) raise an error. Oracle BINARY_DOUBLE input returns NaN."},{"question":"How do I take a cube root of a negative number?","answer":"Use the sign trick: SIGN(x) * POWER(ABS(x), 1e0/3), or CBRT() on PostgreSQL, which is defined for negative input. The 1e0 keeps the exponent a full-precision double on MySQL and SQL Server."},{"question":"Does POWER(-2, 3) work?","answer":"Yes, the exponent is a whole number, so the sign is carried directly: POWER(-2, 3) is -8 on all engines. Only fractional exponents on negative bases fail."}],"related":["power","cbrt","nan-infinity"],"novel_uses":[{"body":"POWER(x, 1.0/4) is a fourth root on any engine with POWER, a gentler flattening of heavy-tailed values than a log. Cast float input first on SQL Server so POWER does not return the input's type.","sql":"SELECT POWER(625.0e0, 1.0/4) AS fourth_root;  -- 5"},{"body":"POWER(votes, 0.6) grows slower than the raw count, so one heavy hitter cannot swamp a blended ranking. The exponent is a tunable middle ground between raw counts and a full log.","sql":"SELECT title, POWER(CAST(votes AS float), 0.6) * freshness AS blended_rank FROM stories ORDER BY 2 DESC;"}]},"source_url":"https://sqlly.app/sql-functions/fractional-powers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/frame-boundary-shorthand","corpus":"sql-functions","engine":null,"language":"en","title":"SQL frame shorthand syntax","description":"The single-boundary frame form (ROWS n PRECEDING with no BETWEEN) and the end boundary it silently assumes.","body":{"slug":"frame-boundary-shorthand","name":"Frame Shorthand","h1":"SQL frame shorthand syntax","category":"window","lede":"Writing just a start boundary (ROWS UNBOUNDED PRECEDING) omits BETWEEN, and the frame then ends at CURRENT ROW by definition.","syntax":"ROWS n PRECEDING | RANGE UNBOUNDED PRECEDING | -- same as:\nROWS BETWEEN n PRECEDING AND CURRENT ROW | RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW","return_type":"frame specification","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The implied end is always CURRENT ROW; you cannot shorten a frame that ends in FOLLOWING or UNBOUNDED FOLLOWING; those need BETWEEN.","The shorthand reads cleanly but hides the peer semantics: RANGE UNBOUNDED PRECEDING still includes the current row's peers under RANGE rules.","The shorthand is common for running totals (ROWS UNBOUNDED PRECEDING); for anything else, the BETWEEN form tells the reader where the frame ends."],"examples":[{"engine_slug":"all","sql":"SELECT day, amount,\n       SUM(amount) OVER (ORDER BY day ROWS 6 PRECEDING) AS trailing7\nFROM daily_sales;"}],"faqs":[{"question":"Is ROWS 6 PRECEDING the same as ROWS BETWEEN 6 PRECEDING AND CURRENT ROW?","answer":"Yes, exactly. The BETWEEN form is just spelled out; the shorthand always assumes AND CURRENT ROW."},{"question":"Why write the long form at all?","answer":"Readers and linters can see the end boundary is deliberate, and ports to engines or ORMs that rewrite SQL do not depend on the implicit rule."}],"related":["rows-frame","frame-current-row","window-default-frame"],"novel_uses":[{"body":"Writing RANGE UNBOUNDED PRECEDING as the shorthand says the peers-included running total is intentional, which is exactly what a reviewer needs to see when they spot no ROWS keyword. Same result as the default frame, explicit intent.","sql":"SELECT day, amount,\n       SUM(amount) OVER (ORDER BY day RANGE UNBOUNDED PRECEDING) AS running_with_peers\nFROM daily_sales;"},{"body":"Pair the shorthand for the running column with a BETWEEN frame for the sliding column and the two behaviours sit next to each other visibly. Queries that mix frames silently are where the wrong-window bugs live.","sql":"SELECT day, amount,\n       SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS running_total,\n       AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7\nFROM daily_sales;"}]},"source_url":"https://sqlly.app/sql-functions/frame-boundary-shorthand","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/frame-current-row","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CURRENT ROW frame boundary","description":"CURRENT ROW in a frame means the exact row with ROWS but the row plus all its peers with RANGE, the subtlest frame boundary in SQL.","body":{"slug":"frame-current-row","name":"CURRENT ROW Boundary","h1":"SQL CURRENT ROW frame boundary","category":"window","lede":"As a frame boundary, CURRENT ROW is positional under ROWS and peer-inclusive under RANGE and GROUPS, which is where identical queries diverge. GROUPS is supported on PostgreSQL and SQLite only; SQL Server and MySQL reject it.","syntax":"ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW","return_type":"frame boundary","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["With duplicate ORDER BY values, RANGE ... CURRENT ROW includes every peer, so running sums jump by the whole tie group; ROWS ... CURRENT ROW walks row by row.","For CURRENT ROW, this single word is the whole difference; the default (implicit) frame uses RANGE semantics, which is where most surprises originate.","CURRENT ROW works as both the start and the end boundary; as a start it means 'this row onward' (under RANGE, all its peers, earlier ones included)."],"examples":[{"engine_slug":"all","sql":"-- tied days: RANGE version includes both rows' amounts at once\nSELECT day, amount,\n       SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS by_row,\n       SUM(amount) OVER (ORDER BY day RANGE UNBOUNDED PRECEDING) AS by_peer\nFROM t;"}],"faqs":[{"question":"Why does my running total skip ties one moment and include them the next?","answer":"Someone changed ROWS to RANGE (or removed it, falling back to the default RANGE). Under RANGE, CURRENT ROW carries the current row's peers with it. If the query did not change, the tie order is the cause: ROWS orders only by the ORDER BY key, so tied rows can swap when the physical order changes (PostgreSQL, SQLite and MySQL swapped their running totals in testing; SQL Server did not). Add a unique tiebreaker to the OVER ORDER BY to pin it."},{"question":"Which CURRENT ROW should I use for dedupes and top-N?","answer":"Neither directly: ranking uses partitions, not frames. For running aggregates over unique-ordered rows, prefer ROWS plus a tiebreaker."}],"related":["rows-vs-range","window-default-frame","range-frame"],"novel_uses":[{"body":"RANGE between CURRENT ROW and CURRENT ROW is exactly the current row and its peers, so COUNT over it reports how many rows share this value. Duplicate detection and peer-aware ranks both start from this number.","sql":"SELECT player, score,\n       COUNT(*) OVER (ORDER BY score RANGE BETWEEN CURRENT ROW AND CURRENT ROW) AS tied_players\nFROM leaderboard;"},{"body":"Divide the group total by the peer count and every row of the group gets its fair slice of a figure they produced together. The peer count is the honest denominator when the rows genuinely happened at the same key.","sql":"SELECT claim_id, day, amount,\n       SUM(amount) OVER (ORDER BY day RANGE BETWEEN CURRENT ROW AND CURRENT ROW) * 1.0\n         / NULLIF(COUNT(*) OVER (ORDER BY day RANGE BETWEEN CURRENT ROW AND CURRENT ROW), 0) AS even_split\nFROM claims;"}]},"source_url":"https://sqlly.app/sql-functions/frame-current-row","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/from-base64","corpus":"sql-functions","engine":null,"language":"en","title":"SQL base64 decoding","description":"Decode base64 back to bytes: FROM_BASE64 on MySQL (NULL on bad input), PostgreSQL's decode(..., 'base64'), plus the cast back to text.","body":{"slug":"from-base64","name":"FROM_BASE64 / decode","h1":"SQL base64 decoding","category":"string","lede":"The inverse of base64 encoding: bytes out. Whether those bytes are text depends on the encoding that was encoded in the first place.","syntax":"FROM_BASE64(b64)  |  decode(b64, 'base64')","return_type":"binary","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"decode(b64, 'base64') returns bytea"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["MySQL's FROM_BASE64 returns NULL on invalid base64 instead of erroring. Silent NULLs can hide truncated payloads.","PostgreSQL's decode returns bytea; convert_from(bytes, 'utf8') turns it back into text.","Both MySQL and PostgreSQL skip spaces, tabs and newlines, so MIME-wrapped input decodes unchanged. Other invalid characters fail: NULL on MySQL, an error on PostgreSQL. PostgreSQL also ignores text after the first '=', so check the padding yourself.","Round-trip encoding matters: base64 of UTF-8 bytes decodes to those bytes; interpreting them as latin1 changes accented text."],"examples":[{"engine_slug":"mysql","sql":"SELECT FROM_BASE64('YWI=') AS s;  -- ab"},{"engine_slug":"postgresql","sql":"SELECT convert_from(decode('YWI=', 'base64'), 'utf8') AS s;  -- ab"}],"faqs":[{"question":"Why does FROM_BASE64 return NULL?","answer":"MySQL returns NULL when the input is not valid base64: wrong padding, stray characters, or a truncated payload. Validate or clean the source string."},{"question":"How do I get text instead of bytes?","answer":"PostgreSQL: convert_from(decode(x, 'base64'), 'utf8'). MySQL: FROM_BASE64 returns a binary string, so convert it with CONVERT(FROM_BASE64(x) USING utf8mb4). Until then CHAR_LENGTH counts bytes ('é' is 2) and comparisons are case-sensitive."},{"question":"Is decoding base64 safe in SQL?","answer":"It is reversible encoding, not security. Decoded content is still data: treat it like any other string and keep parameterized queries for execution paths."}],"related":["to-base64","unhex","hex"],"novel_uses":[{"body":"Decode the part after Basic, then split on the colon: the first piece is the username, which turns a raw API log line into an account name during debugging.","sql":"SELECT SUBSTRING_INDEX(FROM_BASE64(SUBSTRING_INDEX(header, ' ', -1)), ':', 1) AS user\nFROM api_log WHERE header LIKE 'Basic %';"},{"body":"MySQL's FROM_BASE64 returns NULL for bad padding instead of erroring, so FROM_BASE64(payload) IS NULL lists corrupt rows cheaply; on PostgreSQL the same data raises, so the trick is MySQL-specific.","sql":"SELECT id FROM staging WHERE FROM_BASE64(payload) IS NULL;  -- broken padding, stray characters, or a NULL payload"}]},"source_url":"https://sqlly.app/sql-functions/from-base64","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/from-tz","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FROM_TZ function","description":"Oracle's FROM_TZ attaches a named time zone to a zone-less timestamp, producing TIMESTAMP WITH TIME ZONE, the input side of zone conversions.","body":{"slug":"from-tz","name":"FROM_TZ","h1":"SQL FROM_TZ function","category":"datetime","lede":"Returns a TIMESTAMP WITH TIME ZONE built from a plain timestamp plus a zone name or offset, letting session-independent conversions follow.","syntax":"FROM_TZ(ts, 'UTC')  |  FROM_TZ(ts, 'Europe/London')  |  FROM_TZ(ts, '-05:00')","return_type":"TIMESTAMP WITH TIME ZONE","support":[{"engine_slug":"sql-server","status":"yes","note":"TODATETIMEOFFSET / AT TIME ZONE"},{"engine_slug":"postgresql","status":"yes","note":"ts AT TIME ZONE 'zone'"},{"engine_slug":"mysql","status":"partial","note":"TIMESTAMP is stored as UTC and shown in the session zone; CONVERT_TZ(dt, from_zone, to_zone) handles named zones and needs the time-zone tables loaded"},{"engine_slug":"sqlite","status":"no","note":"no zone-aware type"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["A region name like 'America/New_York' applies whichever offset was in force on that date, DST included; a fixed '-05:00' never changes.","An unknown region raises ORA-01882: either a typo, or a zone newer than the server's time-zone file version.","On Oracle, FROM_TZ is not the same as ts AT TIME ZONE zone: a plain TIMESTAMP is read in the session zone first, so 09:30 can come back as 14:30 UTC. PostgreSQL and SQL Server read a naive value in the named zone, so there the two forms agree."],"examples":[{"engine_slug":"oracle","sql":"SELECT FROM_TZ(TIMESTAMP '2024-01-15 09:30:00', 'UTC') AS utc_ts FROM dual;"},{"engine_slug":"oracle","sql":"SELECT FROM_TZ(ts, 'Europe/London') AT TIME ZONE 'UTC' AS utc_ts\nFROM events;"},{"engine_slug":"postgresql","sql":"SELECT '2024-01-15 09:30:00'::timestamp AT TIME ZONE 'UTC';"},{"engine_slug":"sql-server","sql":"SELECT CAST('2024-01-15 09:30' AS datetime2) AT TIME ZONE 'UTC' AS tagged;"}],"faqs":[{"question":"What is the difference between FROM_TZ and CAST?","answer":"CAST to TIMESTAMP WITH TIME ZONE assumes the session zone; FROM_TZ names the zone explicitly, which is reproducible across sessions."},{"question":"Why ORA-01882 on a correct-looking zone?","answer":"The server's time-zone file does not list it. Check the name against V$TIMEZONE_NAMES and the file version in V$TIMEZONE_FILE."}],"related":["todatetimeoffset","session-timezone","systimestamp"],"novel_uses":[{"body":"An unknown region raises ORA-01882 on the spot, so probing a user-supplied zone name with FROM_TZ before you store it catches typos and stale zone files in one call.","sql":"SELECT FROM_TZ(TIMESTAMP '2024-01-15 09:30:00', :user_zone) AS probed FROM dual;"},{"body":"Tag the column with its real named zone: FROM_TZ(log_ts, 'America/New_York') compared with a UTC window start applies the offset in force on each row's date, where a hard-coded '-05:00' is an hour off for every daylight-time row.","sql":"SELECT COUNT(*) FROM logs\nWHERE FROM_TZ(log_ts, 'America/New_York') >= FROM_TZ(TIMESTAMP '2024-07-01 00:00:00', 'UTC');"}]},"source_url":"https://sqlly.app/sql-functions/from-tz","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/from-unixtime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL FROM_UNIXTIME function","description":"Turn Unix epoch seconds into a timestamp: FROM_UNIXTIME on MySQL, to_timestamp on PostgreSQL, datetime(ts,'unixepoch') on SQLite, arithmetic elsewhere.","body":{"slug":"from-unixtime","name":"FROM_UNIXTIME","h1":"SQL FROM_UNIXTIME function","category":"datetime","lede":"Converts seconds since 1970-01-01 UTC into a date-time value in the session zone. MySQL native, one idiomatic form per other engine.","syntax":"FROM_UNIXTIME(1700000000)  -- MySQL  |  TO_TIMESTAMP(1700000000)  -- PostgreSQL  |  datetime(1700000000, 'unixepoch')  -- SQLite","return_type":"DATETIME on MySQL (DATETIME(n) for fractional input, VARCHAR when a format is given)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(second, @ts, '1970-01-01'); int-only, so it overflows after 2038-01-19"},{"engine_slug":"postgresql","status":"partial","note":"to_timestamp(ts)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"datetime(ts, 'unixepoch')"},{"engine_slug":"oracle","status":"partial","note":"DATE '1970-01-01' + ts / 86400"}],"gotchas":["SQLite needs the 'unixepoch' modifier: without it a number is read as a Julian day, and datetime(1700000000) returns NULL because that day is out of range.","Epoch seconds are UTC by definition; MySQL's FROM_UNIXTIME renders them in the session time_zone, so two sessions can show different wall times.","JavaScript-style 13-digit millisecond epochs need division: to_timestamp(ms / 1000.0), else you land tens of thousands of years out. SQL Server's DATEADD takes an int, so split large values into days and seconds."],"examples":[{"engine_slug":"mysql","sql":"SELECT FROM_UNIXTIME(1700000000) AS created;"},{"engine_slug":"postgresql","sql":"SELECT to_timestamp(1700000000) AT TIME ZONE 'UTC' AS created;"},{"engine_slug":"sqlite","sql":"SELECT datetime(1700000000, 'unixepoch') AS created;"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(SECOND, 1700000000, '1970-01-01') AS created;"},{"engine_slug":"oracle","sql":"SELECT DATE '1970-01-01' + 1700000000 / 86400 AS created FROM dual;"}],"faqs":[{"question":"Why is my result off by hours?","answer":"Epoch seconds are UTC. MySQL and PostgreSQL render the value in the session zone; AT TIME ZONE 'UTC' pins the display on PostgreSQL; on MySQL use CONVERT_TZ(FROM_UNIXTIME(ts), @@session.time_zone, '+00:00')."},{"question":"How do I handle millisecond epochs?","answer":"Divide by 1000 first: to_timestamp(ms / 1000.0) on PostgreSQL, FROM_UNIXTIME(ms / 1000) on MySQL. MySQL's / returns a decimal, so the milliseconds survive as a fraction."}],"related":["unix-timestamp","sqlite-datetime","sqlite-modifiers"],"novel_uses":[{"body":"Floor the seconds before converting: FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(created_at) / 3600) * 3600) lands every row on its hour, with no DATE_FORMAT and no truncation function.","sql":"SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(created_at) / 3600) * 3600) AS hour_bucket FROM orders;"},{"body":"SQL Server's DATEADD takes a signed int, so negative seconds reach back to about 1901 before the range ends. On MySQL, FROM_UNIXTIME returns NULL for any negative input, so build pre-1970 values with DATE_ADD('1970-01-01 00:00:00', INTERVAL n SECOND) instead. The MySQL range ends at 3001-01-18 23:59:59 (32536771199), so 2038 is not a limit there.","sql":"SELECT DATE_ADD('1970-01-01 00:00:00', INTERVAL -1000000000 SECOND) AS pre_epoch;  -- lands in 1938"}]},"source_url":"https://sqlly.app/sql-functions/from-unixtime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/gaps-and-islands","corpus":"sql-functions","engine":null,"language":"en","title":"SQL gaps and islands","description":"Grouping overlapping ranges and finding the holes: an island-start flag, a running SUM for island ids and LEAD for the gaps, on any window-capable engine.","body":{"slug":"gaps-and-islands","name":"Gaps and Islands","h1":"SQL gaps and islands","category":"window","lede":"Finds runs of overlapping rows ('islands') and the gaps between them: a row starts a new island when it begins after every earlier row has ended, and a row that merely touches an earlier one (starts on the day it ends) stays in the same island.","syntax":"CASE WHEN d <= MAX(d_end) OVER (ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) THEN 0 ELSE 1 END AS island_start","return_type":"island boundaries","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Sum the island-start flag runningly to assign an island id: SUM(flag) OVER (ORDER BY d); rows sharing an id belong to the same island. Forgetting the running SUM is a common bug.","Compare against the largest end so far, not just the previous row's end: a long booking can cover several later ones. MAX(end_day) OVER (ORDER BY start_day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) handles that; LAG(end_day) does not.","This is the range-flavoured sibling of the streak pattern: streaks group equal values, gaps-and-islands groups overlapping ranges."],"examples":[{"engine_slug":"all","sql":"-- merge overlapping reservations into booked ranges\nWITH flags AS (\n  SELECT room_id, start_day, end_day,\n         CASE WHEN start_day <= MAX(end_day) OVER (\n                PARTITION BY room_id ORDER BY start_day, end_day\n                ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n              THEN 0 ELSE 1 END AS is_start\n  FROM bookings\n), islands AS (\n  SELECT f.*, SUM(is_start) OVER (PARTITION BY room_id ORDER BY start_day, end_day\n                              ROWS UNBOUNDED PRECEDING) AS island_id\n  FROM flags f\n)\nSELECT room_id, MIN(start_day) AS from_day, MAX(end_day) AS to_day\nFROM islands\nGROUP BY room_id, island_id;"},{"engine_slug":"all","sql":"-- the gaps between merged islands: where the next island starts after this one ends\nWITH flags AS (\n  SELECT room_id, start_day, end_day,\n         CASE WHEN start_day <= MAX(end_day) OVER (\n                PARTITION BY room_id ORDER BY start_day, end_day\n                ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n              THEN 0 ELSE 1 END AS is_start\n  FROM bookings\n), islands AS (\n  SELECT f.*, SUM(is_start) OVER (PARTITION BY room_id ORDER BY start_day, end_day\n                              ROWS UNBOUNDED PRECEDING) AS island_id\n  FROM flags f\n), merged AS (\n  SELECT room_id, MIN(start_day) AS from_day, MAX(end_day) AS to_day\n  FROM islands\n  GROUP BY room_id, island_id\n), n AS (\n  SELECT room_id, to_day,\n         LEAD(from_day) OVER (PARTITION BY room_id ORDER BY from_day) AS next_from\n  FROM merged\n)\nSELECT room_id, to_day AS gap_from, next_from AS gap_to\nFROM n\nWHERE next_from > to_day;"}],"faqs":[{"question":"How do I find the gaps instead of the islands?","answer":"LEAD on the start column: a gap exists where the next row's start is beyond the current end. That check is only safe on merged islands or non-overlapping rows; with nested bookings, run it over the islands query's output."},{"question":"Why do my islands merge everything into one group?","answer":"The running SUM is the usual cause: without it the id is just the 0/1 flag, so every island start shares id 1 and every continuation row shares id 0, which merges separate islands. The flag is never all zeros, because the first row of each partition is always flagged 1 (MAX over an empty frame is NULL). Touching rows are merged on purpose, so check the flag and the running SUM as separate steps."}],"related":["consecutive-streaks","lag","lead"],"novel_uses":[{"body":"Flag a row 1 when it sits more than 30 minutes after the previous event, then run a running SUM over the flag: every row gets a session number. This is the standard clickstream session builder, and the timeout is just a constant in the CASE. PostgreSQL interval spelling shown; adjust the literal per engine.","sql":"WITH gaps AS (\n  SELECT user_id, ts,\n         CASE WHEN ts - LAG(ts) OVER (PARTITION BY user_id ORDER BY ts)\n                   > INTERVAL '30 minutes' THEN 1 ELSE 0 END AS new_session\n  FROM events\n)\nSELECT user_id, ts,\n       SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no\nFROM gaps;"},{"body":"Subtract ROW_NUMBER from the id and consecutive ids share a constant, so MIN and MAX per group list the intact runs. What lies between one run's max and the next run's min is exactly the missing records.","sql":"WITH g AS (\n  SELECT id, id - ROW_NUMBER() OVER (ORDER BY id) AS island\n  FROM shipments\n)\nSELECT MIN(id) AS from_id, MAX(id) AS to_id\nFROM g\nGROUP BY island\nORDER BY from_id;"}]},"source_url":"https://sqlly.app/sql-functions/gaps-and-islands","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/gcd","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GCD function","description":"gcd(a, b) is the largest integer dividing both, a PostgreSQL 13+ builtin and nowhere else among the five; the Euclidean algorithm is the portable fallback.","body":{"slug":"gcd","name":"GCD","h1":"SQL GCD function","category":"math","lede":"Returns the greatest common divisor of two integers: gcd(12, 18) is 6, computed with the Euclidean algorithm where it is not built in.","syntax":"GCD(a, b)","return_type":"integer / bigint","support":[{"engine_slug":"sql-server","status":"no","note":"No built-in; recursive CTE or a T-SQL function implementing the Euclidean algorithm"},{"engine_slug":"postgresql","status":"yes","note":"Built in since PostgreSQL 13; gcd(0, 0) is 0"},{"engine_slug":"mysql","status":"no","note":"No GCD; a recursive CTE (MySQL 8.0+) runs the Euclidean algorithm"},{"engine_slug":"sqlite","status":"no","note":"No built-in; recursive CTE"},{"engine_slug":"oracle","status":"no","note":"No built-in; recursive subquery factoring runs the Euclidean loop"}],"gotchas":["gcd(0, 0) is defined as 0 on PostgreSQL; gcd(x, 0) is x.","PostgreSQL also accepts numeric: gcd(12.0, 18.0) is 6.0, and gcd(1.5, 0.5) is 0.5, so fractional inputs are not truncated first.","The Euclidean fallback is three lines: r = a % b, then loop with (b, r) until r is 0; a recursive CTE expresses it with a running modulo."],"examples":[{"engine_slug":"postgresql","sql":"SELECT GCD(12, 18) AS six;  -- 6"},{"engine_slug":"postgresql","sql":"SELECT GCD(width, height) AS aspect_step\nFROM media_assets;"},{"engine_slug":"sqlite","sql":"WITH RECURSIVE g(a, b) AS (\n  SELECT 48, 18\n  UNION ALL\n  SELECT b, a % b FROM g WHERE b <> 0\n)\nSELECT a FROM g WHERE b = 0;  -- 6"}],"faqs":[{"question":"Which engines have a GCD function?","answer":"PostgreSQL 13 and later. SQL Server, MySQL, SQLite and Oracle have none; implement the Euclidean algorithm as a recursive CTE or a stored function."},{"question":"What is gcd(0, 0)?","answer":"0, by the convention PostgreSQL adopts: every integer divides zero, and the greatest common divisor of the all-zero pair is defined as zero."},{"question":"Why is GCD useful in SQL?","answer":"Aspect ratios, shard sizing and periodic scheduling: gcd(width, height) gives the largest unit both dimensions share, so ratios reduce cleanly."}],"related":["lcm","modulo-operator","factorial"],"novel_uses":[{"body":"num / gcd and den / gcd put rational pairs like gear ratios in canonical form, so (12, 18) and (8, 12) compare equal after reduction. Compare the reduced pairs, not the raw columns.","sql":"SELECT 12 / gcd(12, 18) AS num, 18 / gcd(12, 18) AS den;  -- 2, 3 on PostgreSQL 13+"},{"body":"A hash probe sequence visits every slot only when the stride and table size are coprime: gcd(stride, bucket_count) = 1. Check it once at config load and bad sharding setups fail fast. PostgreSQL 13+ has gcd; elsewhere compute it in a CTE.","sql":"SELECT * FROM shard_config WHERE gcd(stride, bucket_count) <> 1;"}]},"source_url":"https://sqlly.app/sql-functions/gcd","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/gen-random-uuid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GEN_RANDOM_UUID function","description":"PostgreSQL's built-in gen_random_uuid (13+) makes version 4 UUIDs from secure randomness, the default key generator when identity columns do not fit.","body":{"slug":"gen-random-uuid","name":"GEN_RANDOM_UUID","h1":"SQL GEN_RANDOM_UUID function","category":"conversion","lede":"SELECT gen_random_uuid() returns a random version 4 uuid. It is built into PostgreSQL 13+ and is the usual DEFAULT for uuid primary keys.","syntax":"GEN_RANDOM_UUID()","return_type":"uuid","support":[{"engine_slug":"sql-server","status":"partial","note":"NEWID() is the v4 twin"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"UUID() is v1, not v4; no gen_random_uuid"},{"engine_slug":"sqlite","status":"no","note":"no built-in; randomblob(16) plus formatting"},{"engine_slug":"oracle","status":"partial","note":"UUID() from 23ai release update 23.9 returns a v4 RAW(16); SYS_GUID() before"}],"gotchas":["Before PostgreSQL 13 it lived in the pgcrypto extension; on 13+ it is core. CREATE EXTENSION pgcrypto is only needed on old clusters.","Random UUIDs scatter inserts across the B-tree. PostgreSQL 18 adds uuidv7(), which puts a millisecond timestamp first so new keys land at the end of the index; uuidv4() is an alias for gen_random_uuid().","The column type is uuid, not text: it stores 16 bytes, rejects malformed strings and compares natively. Casting text UUIDs on insert is the usual friction point."],"examples":[{"engine_slug":"postgresql","sql":"SELECT gen_random_uuid() AS id;"},{"engine_slug":"postgresql","sql":"CREATE TABLE events (\n  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n  label text\n);"},{"engine_slug":"sql-server","sql":"SELECT NEWID() AS id;"},{"engine_slug":"mysql","sql":"SELECT UUID() AS id;  -- v1, not v4"},{"engine_slug":"oracle","sql":"SELECT UUID() AS id FROM dual;  -- 23.9+"}],"faqs":[{"question":"Is it cryptographically random?","answer":"Yes, v4 UUIDs draw from a strong random source; only the version and variant bits are fixed. Fine for public identifiers as well as keys."},{"question":"Why does gen_random_uuid() not exist on my cluster?","answer":"PostgreSQL 12 or older needs the pgcrypto extension: CREATE EXTENSION pgcrypto. From 13 on it is built in."}],"related":["uuid-function","newid","sys-guid","randomblob"],"novel_uses":[{"body":"ORDER BY gen_random_uuid() LIMIT n is PostgreSQL's random-sample idiom: each row gets a random sort key, and the sort never leaves the statement. Fine for dashboards, not for a 100-million-row table.","sql":"SELECT id FROM users ORDER BY gen_random_uuid() LIMIT 10;"},{"body":"When the caller wants secret material rather than an identifier, pgcrypto's gen_random_bytes(n) returns a raw bytea of the exact size, 32 bytes for a key instead of a formatted uuid.","sql":"CREATE EXTENSION IF NOT EXISTS pgcrypto;\nSELECT gen_random_bytes(32) AS key_material;"}]},"source_url":"https://sqlly.app/sql-functions/gen-random-uuid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/generate-series","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GENERATE_SERIES function","description":"GENERATE_SERIES makes a sequence of rows on PostgreSQL (numbers and timestamps) and SQL Server 2022 (numbers only). MySQL and Oracle use recursive CTEs or CONNECT BY.","body":{"slug":"generate-series","name":"GENERATE_SERIES","h1":"SQL GENERATE_SERIES function","category":"conversion","lede":"FROM generate_series(1, 5) returns five rows from nothing. Calendars, gap-filling joins and test data all start from a generated sequence like this.","syntax":"GENERATE_SERIES(start, stop [, step])","return_type":"setof","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+ at compatibility level 160, numeric types only; the column is named value"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no equivalent; recursive CTEs"},{"engine_slug":"sqlite","status":"partial","note":"an extension built into the sqlite3 shell, not the core library"},{"engine_slug":"oracle","status":"no","note":"no equivalent; CONNECT BY LEVEL or a recursive CTE"}],"gotchas":["Counting down differs: PostgreSQL's generate_series(5, 1) returns zero rows unless you pass -1 as the step, while SQL Server's GENERATE_SERIES(5, 1) counts down by itself. A step of 0 is an error on both.","Dates are PostgreSQL-only: generate_series(DATE '2026-01-01', DATE '2026-01-07', INTERVAL '1 day') returns timestamps, so cast to date in the SELECT. SQL Server rejects date arguments; generate integers and add them with DATEADD.","MySQL and Oracle build sequences with recursive CTEs instead; the shape changes but the calendar-join technique is identical."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM generate_series(1, 5);"},{"engine_slug":"postgresql","sql":"SELECT d::date AS day\nFROM generate_series(DATE '2026-01-01', DATE '2026-01-07',\n                     INTERVAL '1 day') d;"},{"engine_slug":"mysql","sql":"WITH RECURSIVE seq(n) AS\n  (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 5)\nSELECT * FROM seq;"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(day, value, '2026-01-01') AS day\nFROM GENERATE_SERIES(0, 6);"},{"engine_slug":"sqlite","sql":"SELECT * FROM generate_series(1, 5);  -- sqlite3 shell"}],"faqs":[{"question":"How do I fill calendar gaps?","answer":"Generate the date range with generate_series and LEFT JOIN the facts onto it: FROM generate_series(...) d LEFT JOIN sales s ON s.day = d::date. Missing days appear with NULLs instead of vanishing."},{"question":"Does SQL Server have this?","answer":"Yes, from SQL Server 2022, for numbers only. Older versions use a numbers table or a recursive CTE, and the CTE needs OPTION (MAXRECURSION 0) past the default limit of 100 recursion levels (101 rows from a single anchor row)."}],"related":["unnest","date-trunc","string-split","row-number"],"novel_uses":[{"body":"generate_series over the key range with a step hands you batch bounds: each row is one WHERE id >= g AND id < g + 100000 slice. Smaller statements, shorter locks, resumable progress.","sql":"SELECT g, g + 99999 AS batch_end FROM generate_series(1, 5000000, 100000) g;"},{"body":"Cross joining the date series against rooms or slots materializes every combination once, which is the base table for availability checks and booking constraints.","sql":"SELECT d::date AS day, r.id AS room FROM generate_series(CURRENT_DATE, CURRENT_DATE + 13, INTERVAL '1 day') d CROSS JOIN rooms r;"}]},"source_url":"https://sqlly.app/sql-functions/generate-series","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/getdate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GETDATE function","description":"SQL Server's current-date-and-time functions: GETDATE, GETUTCDATE, SYSDATETIME and SYSDATETIMEOFFSET, and the precision each one returns.","body":{"slug":"getdate","name":"GETDATE / SYSDATETIME","h1":"SQL GETDATE function","category":"datetime","lede":"Returns the current SQL Server date and time. GETDATE() rounds to about 3 milliseconds; SYSDATETIME() carries full 100-nanosecond precision on datetime2.","syntax":"GETDATE()  |  SYSDATETIME()  |  GETUTCDATE() / SYSUTCDATETIME()  |  SYSDATETIMEOFFSET()","return_type":"datetime (GETDATE); SYSDATETIME() is datetime2(7); SYSDATETIMEOFFSET() is datetimeoffset(7)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"NOW()"},{"engine_slug":"mysql","status":"partial","note":"NOW()"},{"engine_slug":"sqlite","status":"partial","note":"datetime('now')"},{"engine_slug":"oracle","status":"partial","note":"SYSDATE"}],"gotchas":["GETDATE() returns datetime, which rounds to increments of .000, .003 and .007; rounding alone moves a value by up to about 1.7 ms, and a GETDATE() read can differ from a SYSDATETIME() read by more than 2 ms.","Each GETDATE() reference is evaluated once per query, not once per row, so an UPDATE of a million rows stamps them all with one value. SYSDATETIME() behaves the same.","For UTC, use GETUTCDATE() or SYSUTCDATETIME(). Subtracting a fixed offset from GETDATE() is wrong for half the year wherever daylight saving applies."],"examples":[{"engine_slug":"sql-server","sql":"SELECT GETDATE() AS loaded_at;"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIME() AS precise_ts;"},{"engine_slug":"sql-server","sql":"SELECT CAST(GETDATE() AS date) AS today;"},{"engine_slug":"postgresql","sql":"SELECT now() AS loaded_at;"},{"engine_slug":"mysql","sql":"SELECT NOW() AS loaded_at;"},{"engine_slug":"sqlite","sql":"SELECT datetime('now') AS loaded_at;"},{"engine_slug":"oracle","sql":"SELECT SYSDATE AS loaded_at FROM dual;"}],"faqs":[{"question":"Why does GETDATE() give .003 and .007 values?","answer":"datetime stores ticks of 1/300 second, so values round to .000, .003 and .007. SYSDATETIME() on datetime2 keeps real 100 ns precision."},{"question":"How do I get the UTC time on SQL Server?","answer":"GETUTCDATE() (datetime) or SYSUTCDATETIME() (datetime2). A hard-coded offset subtracted from GETDATE() breaks every time daylight saving starts or ends."}],"related":["now","sysdatetimeoffset","current-date"],"novel_uses":[{"body":"DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) rebuilds today at 00:00 as a datetime. That is the idiom for servers that predate the date type (SQL Server 2005 and earlier), where CAST(GETDATE() AS date) cannot compile.","sql":"SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) AS midnight;"},{"body":"A DEFAULT constraint accepts these clocks, so the column fills at insert time and the application never passes a timestamp. Point the default at SYSUTCDATETIME() when the stamp should stay UTC.","sql":"CREATE TABLE events (loaded_at datetime2 NOT NULL DEFAULT SYSDATETIME());"},{"body":"System-versioned temporal tables require period columns of type datetime2, and a DEFAULT of SYSUTCDATETIME() fills the start stamp with no application code involved.","sql":"ALTER TABLE dbo.orders ADD\n    ValidFrom datetime2 GENERATED ALWAYS AS ROW START NOT NULL DEFAULT SYSUTCDATETIME(),\n    ValidTo datetime2 GENERATED ALWAYS AS ROW END NOT NULL DEFAULT CONVERT(datetime2(7), '9999-12-31 23:59:59.9999999'),\n    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);\nALTER TABLE dbo.orders SET (SYSTEM_VERSIONING = ON);"}]},"source_url":"https://sqlly.app/sql-functions/getdate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/glob","corpus":"sql-functions","engine":null,"language":"en","title":"SQLite GLOB operator","description":"SQLite's GLOB matches Unix-style patterns with *, ? and [...] and is case-sensitive, unlike LIKE. What the other engines use for the same job.","body":{"slug":"glob","name":"GLOB","h1":"SQLite GLOB operator","category":"conditional","lede":"'file7.txt' GLOB 'file[0-9].txt' is 1. GLOB is SQLite's case-sensitive pattern match, with shell wildcards instead of % and _.","syntax":"expression GLOB pattern","return_type":"integer (1, 0 or NULL)","support":[{"engine_slug":"sql-server","status":"partial","note":"LIKE supports [0-9] classes; add a _CS_ collation for case"},{"engine_slug":"postgresql","status":"partial","note":"LIKE (case-sensitive) or ~ for character classes"},{"engine_slug":"mysql","status":"partial","note":"REGEXP, or LIKE under a _bin collation"},{"engine_slug":"sqlite","status":"yes","note":"GLOB"},{"engine_slug":"oracle","status":"partial","note":"LIKE (case-sensitive) or REGEXP_LIKE"}],"gotchas":["GLOB is case-sensitive: 'Apple' GLOB 'a*' is 0 while 'Apple' LIKE 'a%' is 1.","Negated classes use ^: '12a' GLOB '*[^0-9.]*' is 1, which makes GLOB a quick test for unexpected characters.","There is no ESCAPE clause. Match a literal * or ? with a one-character class: [*] or [?].","GLOB 'abc*' can use an index on a column with the default BINARY collation. LIKE 'abc%' needs a NOCASE column or case_sensitive_like for that."],"examples":[{"engine_slug":"sqlite","sql":"SELECT 'Apple' GLOB 'A*' AS a, 'Apple' GLOB 'a*' AS b, 'abc' GLOB '?b?' AS c;  -- 1, 0, 1"},{"engine_slug":"sqlite","sql":"SELECT name FROM (SELECT 'file7.txt' AS name UNION ALL SELECT 'fileX.txt')\nWHERE name GLOB 'file[0-9].txt';  -- file7.txt"},{"engine_slug":"sqlite","sql":"SELECT '12.5' GLOB '*[^0-9.]*' AS a, '12a' GLOB '*[^0-9.]*' AS b;  -- 0, 1"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN 'file7.txt' LIKE 'file[0-9].txt' THEN 1 ELSE 0 END AS cls,\n       CASE WHEN 'fileX.txt' LIKE 'file[0-9].txt' THEN 1 ELSE 0 END AS no_class;  -- 1, 0"},{"engine_slug":"postgresql","sql":"SELECT 'file7.txt' ~ '^file[0-9][.]txt$' AS m, 'Apple' ~ '^a' AS cs;  -- t, f"},{"engine_slug":"mysql","sql":"SELECT REGEXP_LIKE('file7.txt', '^file[0-9][.]txt$') AS m, REGEXP_LIKE('Apple', '^a', 'c') AS cs;  -- 1, 0"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN REGEXP_LIKE('file7.txt', '^file[0-9][.]txt$') THEN 'y' END AS m FROM dual;  -- y"}],"faqs":[{"question":"GLOB or LIKE?","answer":"LIKE for case-insensitive ASCII matching with % and _. GLOB for case-sensitive matching and character classes."},{"question":"Does SQLite support REGEXP?","answer":"The grammar has a REGEXP operator, but the core library ships no function behind it. The sqlite3 command-line shell loads one; applications must register their own or load an extension."}],"related":["like","similar-to","regexp-like"],"novel_uses":[{"body":"GLOB must match the entire string, the same rule as LIKE, which makes one pattern a complete column CHECK: a phone value that fails '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' is malformed, with no regex function needed, the one SQLite core does not ship.","sql":"CREATE TABLE contacts (\n  phone TEXT CHECK (phone GLOB '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')\n);\nINSERT INTO contacts VALUES ('555-1234');  -- ok\nINSERT INTO contacts VALUES ('5551234');  -- CHECK failed"},{"body":"A column declared COLLATE NOCASE makes LIKE fold case, but GLOB stays byte-exact no matter what the column declares. Mixed-case codes need upper(col) GLOB upper(pattern) to match the way readers expect.","sql":"SELECT 'ABC' LIKE 'a%' AS like_ci, 'ABC' GLOB 'a*' AS glob_cs;  -- 1, 0"}]},"source_url":"https://sqlly.app/sql-functions/glob","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/greatest","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GREATEST function","description":"GREATEST picks the largest argument: PostgreSQL and SQL Server 2022+ skip NULLs, MySQL and Oracle return NULL if any argument is NULL, and SQLite spells it max(a, b).","body":{"slug":"greatest","name":"GREATEST","h1":"SQL GREATEST function","category":"conditional","lede":"Returns the largest of two or more expressions.","syntax":"GREATEST(a, b, ...) | max(a, b, ...)","return_type":"highest-precedence argument type (Oracle: first argument's type; MySQL: a string if any argument is a string)","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+; skips NULLs"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"SQLite spells it max(a, b, ...) with two or more arguments"},{"engine_slug":"oracle","status":"yes","note":"result type comes from the first argument"}],"gotchas":["NULL semantics split the engines: PostgreSQL and SQL Server skip NULLs and return the largest non-NULL one, while MySQL, Oracle and SQLite's max() return NULL if any argument is NULL.","For uniform NULL-skipping, wrap each argument in COALESCE, but only when a NULL should really mean 'ignore me'.","Mixed strings and numbers split the engines: Oracle converts every argument to the first one's type and MySQL compares as strings once any argument is a string, so GREATEST('10', 9) returns '9' on both. PostgreSQL and SQL Server convert to the numeric type and return 10, while SQLite's max('10', 9) returns the text '10' because any text value sorts above any number.","SQLite has no GREATEST spelling: max(a, b) with several arguments is the scalar form, distinct from the aggregate max(col)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT GREATEST(updated_a, updated_b) FROM sync_state;"},{"engine_slug":"mysql","sql":"SELECT GREATEST(NULL, 3) AS n, GREATEST(COALESCE(NULL, 0), 3) AS safe;"},{"engine_slug":"sqlite","sql":"SELECT max(a, b) FROM t;"},{"engine_slug":"sql-server","sql":"SELECT GREATEST(updated_a, updated_b) FROM sync_state;"},{"engine_slug":"oracle","sql":"SELECT GREATEST(10, 3, 7) AS biggest FROM dual;"}],"faqs":[{"question":"What does GREATEST do with NULL?","answer":"Engine-dependent: PostgreSQL and SQL Server ignore it; MySQL, Oracle and SQLite's max() return NULL. COALESCE each argument for predictable behaviour."},{"question":"Does SQL Server have GREATEST?","answer":"Yes, since SQL Server 2022; older versions need a CASE or IIF chain."},{"question":"How does SQLite do it?","answer":"max(a, b) with two or more arguments is the scalar max; max(a) alone is the aggregate."}],"related":["least","max","coalesce","null","case"],"novel_uses":[{"body":"GREATEST(discount, 0) keeps a computed discount from going negative without a CASE; wrap a nullable input in COALESCE first so the clamp cannot wobble.","sql":"SELECT order_id, GREATEST(price - coupon, 0) AS charged FROM orders;"},{"body":"The greater of two tables' latest timestamps is the point both have reached, so an incremental load reads only rows newer than the watermark.","sql":"SELECT GREATEST((SELECT MAX(updated_at) FROM orders), (SELECT MAX(updated_at) FROM refunds)) AS resume_from;"}]},"source_url":"https://sqlly.app/sql-functions/greatest","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/group-concat","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUP_CONCAT function","description":"MySQL's GROUP_CONCAT joins grouped rows into one string: SEPARATOR, ORDER BY, the 1024-byte group_concat_max_len trap, and SQLite's twin.","body":{"slug":"group-concat","name":"GROUP_CONCAT","h1":"SQL GROUP_CONCAT function","category":"aggregate","lede":"Aggregates a column into one delimited string per group. MySQL's version is configurable but quietly truncates at 1024 bytes by default.","syntax":"GROUP_CONCAT([DISTINCT] column [ORDER BY ...] [SEPARATOR 'sep'])","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"STRING_AGG (2017+)"},{"engine_slug":"postgresql","status":"partial","note":"STRING_AGG"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"LISTAGG"}],"gotchas":["MySQL truncates the result at group_concat_max_len, default 1024 bytes. The only signal is warning 1260 (Row n was cut by GROUP_CONCAT()), which most clients never show. Raise it per session: SET SESSION group_concat_max_len = 1000000.","Default separator is ','; change it with SEPARATOR ' | '. ORDER BY inside the call orders the joined values.","SQLite accepts ORDER BY inside group_concat() from 3.44 (string_agg was added in the same release); older versions join in whatever order rows arrive. DISTINCT only works in the one-argument, comma-separated form.","A group whose values are all NULL aggregates to NULL, not an empty string."],"examples":[{"engine_slug":"mysql","sql":"SELECT department, GROUP_CONCAT(last_name ORDER BY last_name SEPARATOR ' | ') AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"sqlite","sql":"SELECT department, group_concat(last_name, ', ') AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"sql-server","sql":"SELECT department, STRING_AGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"postgresql","sql":"SELECT department, string_agg(last_name, ', ' ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"oracle","sql":"SELECT department, LISTAGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"}],"faqs":[{"question":"Why is my GROUP_CONCAT result cut off?","answer":"group_concat_max_len, which defaults to 1024 bytes, truncated it. Set it higher in the session; the effective maximum is also limited by max_allowed_packet (64 MB by default)."},{"question":"How do I get STRING_AGG behaviour in MySQL?","answer":"GROUP_CONCAT(column ORDER BY x SEPARATOR ', ') is the direct match for STRING_AGG(column, ', ' ORDER BY x)."},{"question":"Does SQLite have GROUP_CONCAT?","answer":"Yes: group_concat(X) or group_concat(X, separator), with ORDER BY inside the call from 3.44. DISTINCT cannot be combined with a custom separator."}],"related":["string-agg","listagg","concat"],"novel_uses":[{"body":"MD5(GROUP_CONCAT(email ORDER BY email)) gives a short value that is equal on both sides of a copy when the data matches, but it can also match different data: a value containing the separator hashes the same as two values, and NULLs are skipped. ORDER BY keeps the fingerprint stable between runs, and wide sets can still hit group_concat_max_len. Use a separator that cannot occur in the data, or hash each row first.","sql":"SELECT MD5(GROUP_CONCAT(email ORDER BY email)) AS fingerprint FROM users;"},{"body":"Grouping by a business key and collecting ids with GROUP_CONCAT turns HAVING COUNT(*) > 1 into a merge worksheet: the exact rows to fix, not just a count.","sql":"SELECT email, GROUP_CONCAT(id ORDER BY id) AS ids\nFROM users\nGROUP BY email\nHAVING COUNT(*) > 1;"}]},"source_url":"https://sqlly.app/sql-functions/group-concat","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/grouping","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUPING function","description":"GROUPING(col) returns 1 when a column was rolled up by ROLLUP, CUBE or GROUPING SETS: tell super-aggregate NULLs from real ones, per-engine support and usage.","body":{"slug":"grouping","name":"GROUPING","h1":"SQL GROUPING function","category":"aggregate","lede":"Returns 1 when the column is a rolled-up placeholder NULL, 0 when it is a real value.","syntax":"GROUPING(col) | GROUPING(col1, col2)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+, with ROLLUP only (no CUBE or GROUPING SETS)"},{"engine_slug":"sqlite","status":"no","note":"no ROLLUP, so nothing to flag"},{"engine_slug":"oracle","status":"yes","note":"one argument; GROUPING_ID for several"}],"gotchas":["Without ROLLUP, CUBE or GROUPING SETS in the query, GROUPING is always 0 on SQL Server and PostgreSQL; MySQL rejects it with error 1111 (Invalid use of group function).","PostgreSQL and MySQL accept several columns and return a bitmask (rightmost argument = lowest bit); SQL Server and Oracle take exactly one and offer GROUPING_ID for the bitmask.","It is the only reliable way to tell a real NULL value from the NULL that ROLLUP prints on subtotal rows."],"examples":[{"engine_slug":"postgresql","sql":"SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY ROLLUP(make);"},{"engine_slug":"sql-server","sql":"SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY make WITH ROLLUP;"},{"engine_slug":"mysql","sql":"SELECT make, GROUPING(make) AS is_total, SUM(sales) FROM items_sold GROUP BY make WITH ROLLUP;"},{"engine_slug":"oracle","sql":"SELECT make, GROUPING(make) AS is_total, SUM(sales) FROM items_sold GROUP BY ROLLUP(make);"}],"faqs":[{"question":"What do 0 and 1 mean?","answer":"0 = the column holds a real value; 1 = the row is a super-aggregate and the column shows a placeholder NULL."},{"question":"Can I filter subtotal rows?","answer":"Yes: HAVING GROUPING(make) = 1 keeps only the rolled-up rows; = 0 keeps only detail rows."},{"question":"Does it work without ROLLUP?","answer":"On SQL Server and PostgreSQL it runs, but every row returns 0. MySQL refuses it with error 1111 (Invalid use of group function)."}],"related":["grouping-id","grouping-sets","rollup","sum"],"novel_uses":[{"body":"ORDER BY GROUPING(make), make keeps detail rows alphabetical and pushes every subtotal after them, one sort instead of a UNION of two queries.","sql":"SELECT make, SUM(sales) FROM items_sold GROUP BY ROLLUP(make) ORDER BY GROUPING(make), make;"},{"body":"A CASE on GROUPING turns the placeholder NULL into the label readers expect while a real NULL make still shows as blank.","sql":"SELECT CASE WHEN GROUPING(make) = 1 THEN 'All makes' ELSE make END AS make_label, SUM(sales) FROM items_sold GROUP BY ROLLUP(make);"}]},"source_url":"https://sqlly.app/sql-functions/grouping","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/grouping-id","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUPING_ID function","description":"GROUPING_ID packs the GROUPING() flags of several columns into one integer: SQL Server and Oracle support, the multi-argument GROUPING() spelling in PostgreSQL and MySQL.","body":{"slug":"grouping-id","name":"GROUPING_ID","h1":"SQL GROUPING_ID function","category":"aggregate","lede":"Packs the per-column GROUPING flags of a rollup row into a single integer.","syntax":"GROUPING_ID(a, b) | GROUPING_ID(a, b, c)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"no GROUPING_ID; GROUPING(a, b) with several arguments returns the same bitmask"},{"engine_slug":"mysql","status":"partial","note":"no GROUPING_ID; GROUPING(a, b) with several arguments returns the same bitmask (8.0+)"},{"engine_slug":"sqlite","status":"no","note":"no ROLLUP or GROUPING SETS"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The last argument is the lowest bit: GROUPING_ID(a, b) = GROUPING(a) * 2 + GROUPING(b). On ROLLUP(a, b) that gives 0 for detail rows, 1 for per-a subtotals and 3 for the grand total.","PostgreSQL and MySQL have no GROUPING_ID, but their GROUPING(a, b) accepts several arguments and returns the same number, so a port is a rename.","Handy for a single CASE that labels each row as detail, subtotal or total, and for HAVING GROUPING_ID(a, b) = 0 to keep detail rows only."],"examples":[{"engine_slug":"sql-server","sql":"SELECT make, model, GROUPING_ID(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);"},{"engine_slug":"oracle","sql":"SELECT make, model, GROUPING_ID(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);"},{"engine_slug":"postgresql","sql":"SELECT make, model, GROUPING(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);"},{"engine_slug":"sqlite","sql":"SELECT make, 0 AS lvl, SUM(sales) FROM items_sold GROUP BY make UNION ALL SELECT NULL, 1, SUM(sales) FROM items_sold;"}],"faqs":[{"question":"How is GROUPING_ID different from GROUPING?","answer":"GROUPING handles one flag per call; GROUPING_ID packs several columns into one integer you can compare or label with."},{"question":"What is GROUPING_ID in PostgreSQL?","answer":"GROUPING(a, b) with several arguments. It uses the same bit order as SQL Server and Oracle, so the numbers match."},{"question":"Does MySQL have GROUPING_ID?","answer":"No, but MySQL 8.0's GROUPING(a, b) takes several columns and returns the same bitmask."}],"related":["grouping","grouping-sets","rollup","sum"],"novel_uses":[{"body":"0 for detail, 1 for make subtotals, 3 for the grand total, so ORDER BY GROUPING_ID(make, model) lays the report out top-down inside the query.","sql":"SELECT make, model, GROUPING_ID(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model) ORDER BY GROUPING_ID(make, model), make, model;"},{"body":"HAVING GROUPING_ID(make, model) IN (0, 3) keeps details and the grand total while discarding the per-make subtotals ROLLUP insists on computing.","sql":"SELECT make, model, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model) HAVING GROUPING_ID(make, model) IN (0, 3);"}]},"source_url":"https://sqlly.app/sql-functions/grouping-id","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/grouping-sets","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUPING SETS clause","description":"GROUPING SETS computes several grouping levels in one scan: PostgreSQL, SQL Server and Oracle support, MySQL's ROLLUP-only gap, and the SQLite UNION ALL emulation.","body":{"slug":"grouping-sets","name":"GROUPING SETS","h1":"SQL GROUPING SETS clause","category":"aggregate","lede":"Computes multiple grouping levels in a single pass instead of one query per level.","syntax":"GROUP BY GROUPING SETS ((a), (b), ()) | GROUP BY GROUPING SETS ((a, b), (a), ())","return_type":"one result set with rows for every grouping level","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"MySQL supports only ROLLUP (WITH ROLLUP, or ROLLUP(...) in 8.4); no GROUPING SETS, and CUBE is rejected without a HeatWave secondary engine"},{"engine_slug":"sqlite","status":"no","note":"emulate with UNION ALL of grouped queries"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The empty set () is the grand total row; omitted columns show placeholder NULLs, so pair the query with GROUPING or GROUPING_ID.","CUBE(a, b) is shorthand for all four sets of a and b; ROLLUP(a, b) is the prefix hierarchy.","MySQL has only ROLLUP (GROUP BY a, b WITH ROLLUP, or GROUP BY ROLLUP(a, b) in 8.4), which covers the prefix hierarchy and nothing else; SQLite has none of it. Both need UNION ALL of separate GROUP BY queries."],"examples":[{"engine_slug":"postgresql","sql":"SELECT make, model, SUM(sales) FROM items_sold GROUP BY GROUPING SETS ((make, model), (make), ());"},{"engine_slug":"sql-server","sql":"SELECT make, model, SUM(sales) FROM items_sold GROUP BY GROUPING SETS ((make, model), (make), ());"},{"engine_slug":"oracle","sql":"SELECT make, model, SUM(sales) FROM items_sold GROUP BY GROUPING SETS ((make, model), (make), ());"}],"faqs":[{"question":"GROUPING SETS vs multiple queries?","answer":"One scan of the source instead of one per level; the engine computes every level from that pass, though sets that are not a prefix chain, such as (a) and (b), can still need an extra sort or spool."},{"question":"What does GROUPING SETS ((a), ()) mean?","answer":"Detail rows by a plus one grand-total row with a NULL."},{"question":"Does MySQL support GROUPING SETS?","answer":"No, only ROLLUP: GROUP BY ... WITH ROLLUP, or GROUP BY ROLLUP(...) in 8.4. MySQL 8.4 still rejects GROUPING SETS, and CUBE without a HeatWave secondary engine; use UNION ALL of grouped queries for the rest."}],"related":["grouping","grouping-id","rollup","sum"],"novel_uses":[{"body":"GROUPING SETS ((region), (product)) totals each dimension on its own in a single pass over the fact table, replacing two full scans or a self-join.","sql":"SELECT region, product, SUM(amount) FROM sales GROUP BY GROUPING SETS ((region), (product));"},{"body":"Detail, subtotal and total levels in one ordered result set let a client render the whole hierarchy from a single query result.","sql":"SELECT region, city, SUM(amount) FROM sales GROUP BY GROUPING SETS ((region, city), (region), ()) ORDER BY GROUPING(region), GROUPING(city), region, city;"}]},"source_url":"https://sqlly.app/sql-functions/grouping-sets","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/groups-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUPS frame","description":"The GROUPS frame type: boundaries measured in peer groups rather than rows or values. PostgreSQL, SQLite and Oracle 21c+ run it; SQL Server and MySQL do not.","body":{"slug":"groups-frame","name":"GROUPS Frame","h1":"SQL GROUPS frame","category":"window","lede":"GROUPS counts groups of peers: 3 PRECEDING means the three preceding tie-groups, so tied rows always enter and leave frames together.","syntax":"SUM(x) OVER (ORDER BY d GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW)","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"no","note":"no GROUPS frame type, including SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 11+"},{"engine_slug":"mysql","status":"no","note":"rejected with ERROR 1235: This version of MySQL doesn't yet support 'GROUPS'"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.28+"},{"engine_slug":"oracle","status":"yes","note":"Oracle 21c+"}],"gotchas":["GROUPS differs from ROWS exactly on ties: with duplicate keys, ROWS can cut a tie group in half, GROUPS never does. With unique ORDER BY keys they are identical.","GROUPS differs from RANGE with numeric offsets by counting groups, not measuring value distance: RANGE 10 PRECEDING is a value band, GROUPS 10 PRECEDING is ten peer-groups back whatever their values.","SQL Server and MySQL reject GROUPS. When there are no ties GROUPS equals ROWS; with ties, aggregate to one row per ORDER BY value first, then use ROWS over those rows."],"examples":[{"engine_slug":"postgresql","sql":"-- average over the current peer group and the two before it\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3_groups\nFROM prices;"},{"engine_slug":"sqlite","sql":"-- 3.28+ for GROUPS: the two peer groups before, plus this one\nSELECT day, price,\n       AVG(price) OVER (ORDER BY price GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3_groups\nFROM prices;"},{"engine_slug":"oracle","sql":"-- 21c+ for GROUPS\nSELECT price, volume,\n       SUM(volume) OVER (ORDER BY price GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS band_volume\nFROM trades;"}],"faqs":[{"question":"When would I pick GROUPS over ROWS or RANGE?","answer":"When frames must align with distinct values: 'the last three distinct prices' regardless of how many rows each price has. ROWS cannot express it without splitting ties; RANGE cannot count groups."},{"question":"Which engines lack GROUPS?","answer":"SQL Server and MySQL 8. Oracle added it in 21c, so Oracle 19c lacks it too. The rewrite is to collapse each tie group to one row (GROUP BY the ORDER BY value), run a ROWS frame over that, and join back."}],"related":["rows-vs-range","groups-frame-support","range-frame"],"novel_uses":[{"body":"GROUPS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING sums every peer group before the current one, so the column is the total of all rows with a smaller key no matter how uneven the value steps are. RANGE with a numeric end offset measures value distance, so with uneven or fractional steps it drops groups (on the sample RANGE gives 1 at price 11 where the true total below it is 3); GROUPS is exact by construction. PostgreSQL 11+, SQLite 3.28+ and Oracle 21c+.","sql":"SELECT price, volume,\n       SUM(volume) OVER (ORDER BY price\n         GROUPS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS volume_below\nFROM trades;"},{"body":"GROUPS BETWEEN 1 PRECEDING AND 1 PRECEDING aggregates exactly the prior tie group: the average volume at the last different price, or the count at the previous distinct score. ROWS cannot express this without splitting the group, and RANGE measures value distance instead of counting groups.","sql":"SELECT price, volume,\n       AVG(volume) OVER (ORDER BY price\n         GROUPS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_level_avg\nFROM trades;"}]},"source_url":"https://sqlly.app/sql-functions/groups-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/groups-frame-support","corpus":"sql-functions","engine":null,"language":"en","title":"SQL GROUPS frame support by engine","description":"Which engines run GROUPS frames and since when: PostgreSQL 11+, SQLite 3.28+, Oracle 21c+, and the workaround for SQL Server and MySQL.","body":{"slug":"groups-frame-support","name":"GROUPS Frame Support","h1":"SQL GROUPS frame support by engine","category":"window","lede":"The support matrix for the GROUPS frame type, with the emulation path for the two engines that lack it.","syntax":"ORDER BY d GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW","return_type":"frame type","support":[{"engine_slug":"sql-server","status":"no","note":"not supported, including SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":"since PostgreSQL 11"},{"engine_slug":"mysql","status":"no","note":"not supported in MySQL 8.x (ROWS and RANGE only)"},{"engine_slug":"sqlite","status":"yes","note":"since SQLite 3.28.0 (2019-04-16), alongside EXCLUDE"},{"engine_slug":"oracle","status":"yes","note":"since Oracle 21c, alongside EXCLUDE and the WINDOW clause"}],"gotchas":["SQL Server and MySQL emulation: GROUP BY the ORDER BY value so each tie group becomes one row carrying SUM(x) and COUNT(x), run a ROWS frame over those rows, then join back to the detail rows.","A ROWS frame over DENSE_RANK() as the ORDER BY does not emulate GROUPS: ROWS still counts individual rows, so tied rows get different frames.","GROUPS and EXCLUDE arrived together everywhere: PostgreSQL 11, SQLite 3.28 and Oracle 21c added both, and SQL Server and MySQL have neither."],"examples":[{"engine_slug":"sql-server","sql":"-- GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW, emulated\nWITH per_day AS (\n  SELECT day, SUM(price) AS s, COUNT(price) AS n\n  FROM prices\n  GROUP BY day\n), framed AS (\n  SELECT day,\n         SUM(s) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS fs,\n         SUM(n) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS fn\n  FROM per_day\n)\nSELECT p.day, p.price, f.fs * 1.0 / NULLIF(f.fn, 0) AS ma3_groups\nFROM prices p\nJOIN framed f ON f.day = p.day;"},{"engine_slug":"postgresql","sql":"-- PostgreSQL 11+: GROUPS runs natively\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3_groups\nFROM prices;"},{"engine_slug":"sqlite","sql":"-- SQLite 3.28.0+: GROUPS runs natively\nSELECT price, volume,\n       COUNT(*) OVER (ORDER BY price GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS band_rows\nFROM trades;"},{"engine_slug":"oracle","sql":"-- Oracle 21c+: GROUPS runs natively\nSELECT price, volume,\n       SUM(volume) OVER (ORDER BY price\n         GROUPS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS volume_below\nFROM trades;"}],"faqs":[{"question":"Which engines support GROUPS frames today?","answer":"PostgreSQL (11+), SQLite (3.28+) and Oracle (21c+). SQL Server and MySQL do not; cross-engine code needs the aggregate-then-ROWS rewrite."},{"question":"Is GROUPS frame the same as GROUP BY?","answer":"No. GROUPS is a frame type describing which rows a window function sees, based on how many peer-groups away the boundary sits. GROUP BY collapses rows."}],"related":["groups-frame","window-exclude","sql-server-frame-support"],"novel_uses":[{"body":"Run the smallest GROUPS query you can against a one-row derived table and treat the error as the feature flag: the library then picks native GROUPS or the aggregate-then-ROWS rewrite per connection. Version strings lie more often than the parser does.","sql":"SELECT SUM(1) OVER (ORDER BY x\n  GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW)\nFROM (SELECT 1 AS x) probe;"},{"body":"The emulation aggregates per key and joins back, but NULL = NULL is false in a join, so an inner JOIN makes rows with a NULL key vanish silently. Join with IS NOT DISTINCT FROM on PostgreSQL, SQLite or SQL Server 2022, <=> on MySQL, or COALESCE both sides with a sentinel elsewhere; a LEFT JOIN keeps those rows but returns NULL for their value.","sql":"SELECT p.day, p.price, f.fs * 1.0 / NULLIF(f.fn, 0) AS ma3\nFROM prices p\nLEFT JOIN framed f ON f.day IS NOT DISTINCT FROM p.day;"}]},"source_url":"https://sqlly.app/sql-functions/groups-frame-support","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/hashbytes","corpus":"sql-functions","engine":null,"language":"en","title":"SQL HASHBYTES function","description":"How HASHBYTES computes MD5, SHA-1 and SHA-2 digests in SQL Server: algorithm names, NULL for unknown ones, varchar versus nvarchar input, and hex conversion.","body":{"slug":"hashbytes","name":"HASHBYTES","h1":"SQL HASHBYTES function","category":"string","lede":"Computes a hash of a value in SQL Server using an algorithm you name, returning binary bytes.","syntax":"HASHBYTES('algorithm', value)  |  algorithms: MD4, MD5, SHA, SHA1, SHA2_256, SHA2_512 (MD2 returns NULL on SQL Server 2022)","return_type":"varbinary","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"md5(), sha256() and friends, or pgcrypto's digest()."},{"engine_slug":"mysql","status":"partial","note":"MD5, SHA1 or SHA2."},{"engine_slug":"sqlite","status":"no","note":"No hash functions in the library; the sqlite3 shell adds sha1() and sha3()."},{"engine_slug":"oracle","status":"partial","note":"STANDARD_HASH(value, 'SHA256')."}],"gotchas":["An unsupported algorithm name such as 'SHA256' or 'SHA2_384' returns NULL, not an error, so a typo shows up as missing hashes rather than a failed query.","varchar and nvarchar hash differently: 'hello' is 5 bytes, N'hello' is 10 bytes of UTF-16. Match the type and encoding of whatever system you compare against.","The 8,000-byte input limit was removed in SQL Server 2016; older versions need chunking for larger values."],"examples":[{"engine_slug":"sql-server","sql":"SELECT HASHBYTES('SHA2_256', 'hello') AS digest;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(64), HASHBYTES('SHA2_256', email), 2) AS hex\nFROM users;"},{"engine_slug":"postgresql","sql":"SELECT encode(sha256('hello'), 'hex') AS digest;"},{"engine_slug":"mysql","sql":"SELECT SHA2('hello', 256) AS digest;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(STANDARD_HASH('hello', 'SHA256')) AS digest\nFROM dual;"}],"faqs":[{"question":"Why does HASHBYTES return weird characters?","answer":"It returns binary bytes, not text. Convert with style 2: CONVERT(varchar(64), digest, 2) gives a hex string without the 0x prefix."},{"question":"What are the supported algorithms?","answer":"MD4, MD5, SHA, SHA1, SHA2_256 and SHA2_512 return digests. MD2 is in the syntax block but returns NULL on SQL Server 2022 CU28, so do not rely on it. Since SQL Server 2016 everything except SHA2_256 and SHA2_512 is deprecated."},{"question":"What is the MySQL equivalent?","answer":"MD5(str), SHA1(str) and SHA2(str, n) return lowercase hex text directly."}],"related":["md5","sha2","hex","sha1"],"novel_uses":[{"body":"A persisted computed column hashes the concatenated business key, and a unique index over it blocks duplicate rows even when the columns are wide.","sql":"ALTER TABLE orders ADD sig AS\n  CAST(HASHBYTES('SHA2_256', CONCAT(customer_id, '|', order_date)) AS binary(32)) PERSISTED;\nCREATE UNIQUE INDEX ux_orders_sig ON orders (sig);"},{"body":"Comparing HASHBYTES('SHA2_256', body) to an expected binary digest screens out unchanged documents without shipping the text around; confirm with a full comparison before acting on a match. The digest below is SHA-256 of 'hello'. The body column must be varchar: on an nvarchar column the hash covers UTF-16 bytes and nothing matches.","sql":"SELECT id FROM documents\nWHERE HASHBYTES('SHA2_256', body) = 0x2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824;"}]},"source_url":"https://sqlly.app/sql-functions/hashbytes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/hex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL HEX function","description":"Hex-encode strings and numbers: HEX on MySQL and SQLite, to_hex and encode on PostgreSQL, RAWTOHEX on Oracle; encoding decides the bytes.","body":{"slug":"hex","name":"HEX","h1":"SQL HEX function","category":"string","lede":"Renders a value's bytes as hexadecimal text. The bytes come from the storage encoding, which is the entire gotcha.","syntax":"HEX(string)  |  hex(blob)  |  encode(data, 'hex')","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"no HEX; CONVERT(varchar(max), CAST(s AS varbinary(max)), 2) renders the bytes"},{"engine_slug":"postgresql","status":"partial","note":"to_hex() for integers; encode(convert_to(...), 'hex') for text"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"RAWTOHEX works on RAW-typed bytes"}],"gotchas":["The output encodes the stored bytes: HEX('é') is C3A9 under utf8mb4 and E9 under latin1. Two charsets, one string, two answers.","Case differs by engine: MySQL HEX, SQLite hex(), SQL Server's style-2 CONVERT and Oracle RAWTOHEX return uppercase, PostgreSQL's encode() and to_hex() lowercase. Normalize before comparing hex strings.","PostgreSQL splits the job: to_hex(n) formats integers, encode(bytea, 'hex') encodes bytes; convert_to turns text into bytea first.","SQL Server has no HEX function: CONVERT(VARBINARY, s) displays 0x-prefixed bytes, and CONVERT(VARCHAR, bin, 2) renders them as plain hex. Emoji need nvarchar input: a varchar string turns into ?? bytes (3F3F), while CAST(N'\uD83D\uDE00' AS varbinary(max)) gives 3DD800DE in UTF-16."],"examples":[{"engine_slug":"mysql","sql":"SELECT HEX('ab') AS h;  -- 6162"},{"engine_slug":"sqlite","sql":"SELECT hex('ab') AS h;  -- 6162"},{"engine_slug":"postgresql","sql":"SELECT encode(convert_to('ab', 'utf8'), 'hex') AS h;  -- 6162"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(max), CAST('ab' AS varbinary(max)), 2) AS h;  -- 6162"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX('ab') AS h FROM dual;  -- 6162, implicit cast to RAW"}],"faqs":[{"question":"Why is my hex string different on another server?","answer":"The stored bytes differ: a different charset or column type encodes the same text differently. HEX shows storage bytes, not abstract characters."},{"question":"How do I decode hex back to text?","answer":"UNHEX('6162') on MySQL, CAST(unhex('6162') AS TEXT) on SQLite 3.41+, convert_from(decode('6162', 'hex'), 'utf8') on PostgreSQL, HEXTORAW on Oracle."},{"question":"Does HEX work on numbers?","answer":"MySQL's HEX(255) is FF; it converts the number's value. SQLite's hex(255) is 323535, the bytes of the text '255'. Know which one your engine does."}],"related":["unhex","rawtohex","conv"],"novel_uses":[{"body":"HEX(a) = HEX(b) bypasses case- and accent-insensitive collations entirely, so it proves byte identity for audit keys that = would wave through.","sql":"SELECT * FROM payments WHERE HEX(ref) = HEX('aB3');  -- only byte-exact 'aB3' matches"},{"body":"HEX emits two characters per byte, so on a utf8mb4 column LENGTH(HEX(col)) above twice CHAR_LENGTH(col) marks rows carrying accents, CJK or emoji without any regex. Single-byte charsets like latin1 never trip it, because their accents are one byte each.","sql":"SELECT id FROM t WHERE LENGTH(HEX(col)) > 2 * CHAR_LENGTH(col);  -- multi-byte characters present"}]},"source_url":"https://sqlly.app/sql-functions/hex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/hour","corpus":"sql-functions","engine":null,"language":"en","title":"SQL HOUR function","description":"Get the hour 0-23 from a timestamp: HOUR() on MySQL, DATEPART(hour) on SQL Server, EXTRACT(hour FROM ts) on PostgreSQL and Oracle, strftime('%H') on SQLite.","body":{"slug":"hour","name":"HOUR","h1":"SQL HOUR function","category":"datetime","lede":"Returns the hour of day, the standard key for hourly traffic and shift-based grouping. MySQL and SQL Server return an integer, PostgreSQL returns numeric, and SQLite returns text.","syntax":"EXTRACT(hour FROM ts)  |  DATEPART(hour, ts)  -- SQL Server  |  HOUR(ts)  -- MySQL","return_type":"integer (MySQL, SQL Server); numeric (PostgreSQL); text (SQLite)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(hour, ts); no HOUR() shorthand"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(hour FROM ts)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%H', ts) returns text"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT(hour FROM ts) needs a TIMESTAMP, not a DATE"}],"gotchas":["Oracle's EXTRACT(hour) raises ORA-30076 on a plain DATE: CAST it to TIMESTAMP first, or use TO_CHAR(d, 'HH24').","SQLite's strftime('%H') returns zero-padded text; CAST to INTEGER before numeric comparisons.","PostgreSQL has no HOUR() shorthand: EXTRACT(hour FROM ts) or DATE_PART('hour', ts) are the spellings."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(hour FROM created_at) AS hr, COUNT(*)\nFROM orders GROUP BY 1 ORDER BY 1;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(hour, created_at) AS hr FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%H', created_at) AS INTEGER) AS hr FROM orders;"},{"engine_slug":"mysql","sql":"SELECT HOUR(created_at) AS hr FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(hour FROM CAST(created_at AS TIMESTAMP)) AS hr FROM orders;"}],"faqs":[{"question":"Why does EXTRACT(hour) fail on Oracle DATE columns?","answer":"EXTRACT reads datetime fields from TIMESTAMP values; a DATE needs TO_CHAR(d, 'HH24') or an explicit CAST to TIMESTAMP first."},{"question":"Is the hour 0-based?","answer":"Yes, 0 through 23 for any timestamp on every engine. MySQL's TIME type can hold durations, so HOUR('25:00:00') is 25 and HOUR('838:59:59') is 838. SQLite's %H is also zero-padded, which keeps text sorting correct."}],"related":["extract","minute","date-from-datetime"],"novel_uses":[{"body":"MySQL's HOUR() is duration-aware: HOUR('150:30:45') is 150, because the TIME type holds spans past 24 hours. Clock logic and duration logic share the function with different ranges.","sql":"SELECT HOUR('150:30:45') AS span_hours;"},{"body":"LEFT JOIN facts onto a 0 through 23 number list in SQL Server and GROUP BY the hour, so quiet hours appear as zeros instead of gaps in the report.","sql":"SELECT sv.number AS hr, COUNT(o.id) AS orders\nFROM master.dbo.spt_values sv\nLEFT JOIN orders o ON DATEPART(hour, o.created_at) = sv.number\nWHERE sv.type = 'P' AND sv.number BETWEEN 0 AND 23\nGROUP BY sv.number;"}]},"source_url":"https://sqlly.app/sql-functions/hour","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/hour-12-24","corpus":"sql-functions","engine":null,"language":"en","title":"SQL 12-hour vs 24-hour format","description":"Rendering 14:30 as '02:30 PM' or '14:30' per engine: HH12/HH24 masks, %h/%H codes, and the AM/PM tokens each engine spells differently.","body":{"slug":"hour-12-24","name":"12/24-hour","h1":"SQL 12-hour vs 24-hour format","category":"datetime","lede":"Every formatter has a 12-hour and a 24-hour code, and the letters differ by engine: HH24 vs HH12, %H vs %h, HH vs hh. Mixing them up shifts afternoon times by 12 hours.","syntax":"TO_CHAR(d, 'HH24:MI')  |  DATE_FORMAT(d, '%h:%i %p')","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"FORMAT(d, 'hh:mm tt'); no CONVERT style does 12-hour cleanly"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"%I and %p since 3.44; %H on any version"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Midnight and noon: 12-hour masks render midnight as 12, not 0; '%h:%i %p' at 00:30 gives 12:30 AM. Off-by-noon bugs come from mixing %h with %H.","AM/PM markers: SQL Server FORMAT 'tt' follows the culture argument, while MySQL's %p prints AM/PM under every lc_time_names setting, fr_FR included. PostgreSQL's AM/PM codes are not localized either.","PostgreSQL and Oracle: HH12 is the 12-hour clock and HH24 the 24-hour one. Plain HH is also 12-hour, so 'HH:MI' prints 14:30 as 02:30."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_char(TIMESTAMP '2026-08-01 14:30', 'HH24:MI');  -- 14:30"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT('2026-08-01 14:30:00', '%h:%i %p');  -- 02:30 PM"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(CAST('2026-08-01 14:30' AS datetime2), 'hh:mm tt', 'en-US');  -- 02:30 PM"},{"engine_slug":"sqlite","sql":"SELECT strftime('%I:%M %p', '2026-08-01 14:30:00');  -- 02:30 PM"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(TIMESTAMP '2026-08-01 14:30', 'HH12:MI AM') FROM dual;  -- 02:30 PM"}],"faqs":[{"question":"Why does my 'HH:MI' output show afternoon as 02?","answer":"Oracle and PostgreSQL's HH (and HH12) is the 12-hour clock. Use HH24, or add the AM/PM mask; HH alone hides whether 02 means morning."},{"question":"Which engines default to 24-hour?","answer":"The default text forms are 24-hour on PostgreSQL, MySQL, SQLite and Oracle, as are CONVERT styles 120 and 126. SQL Server's style 0 (what CAST(datetime AS varchar) gives you) is 12-hour: 'Aug  1 2026  2:30PM'."}],"related":["time-format","date-format-codes","lc-time-names","strftime"],"novel_uses":[{"body":"Oracle DATE hides its clock from EXTRACT until you cast to TIMESTAMP, then the hour arrives as a number for range checks and histograms.","sql":"SELECT EXTRACT(HOUR FROM CAST(SYSDATE AS TIMESTAMP)) FROM dual;"},{"body":"In MySQL, GROUP BY HOUR() collapses any timestamp column into a 24-row load profile, the fastest read on when traffic actually happens. PostgreSQL and SQL Server have no HOUR(), so use EXTRACT(HOUR FROM ts) or DATEPART(hour, ts) there; SQLite uses strftime('%H', ts).","sql":"SELECT HOUR(created_at) AS hr, COUNT(*) FROM events GROUP BY hr ORDER BY hr;"}]},"source_url":"https://sqlly.app/sql-functions/hour-12-24","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/hypothetical-set","corpus":"sql-functions","engine":null,"language":"en","title":"SQL hypothetical-set aggregates","description":"RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST gain a hypothetical form: RANK(value) WITHIN GROUP (ORDER BY col) scores a row that is not in the table, PG and Oracle only.","body":{"slug":"hypothetical-set","name":"RANK","h1":"SQL hypothetical-set aggregates","category":"aggregate","lede":"Ranks a hypothetical row as if it were inserted, without inserting it.","syntax":"RANK(v) WITHIN GROUP (ORDER BY col) | CUME_DIST(v) WITHIN GROUP (ORDER BY col)","return_type":"bigint for RANK and DENSE_RANK, double precision for PERCENT_RANK and CUME_DIST (NUMBER in Oracle)","support":[{"engine_slug":"sql-server","status":"no","note":"same UNION ALL emulation"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"emulate with UNION ALL of the hypothetical value plus a window function"},{"engine_slug":"sqlite","status":"no","note":"same UNION ALL emulation"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The hypothetical row's values are the function's arguments; the ORDER BY list must match in count and sortability.","RANK(v) is 1 plus the number of existing values that sort strictly before v; existing values equal to v tie with it rather than push it down.","The window versions of RANK and friends rank rows that exist; the WITHIN GROUP versions rank a value that does not.","Emulation recipe elsewhere: SELECT ... UNION ALL the value, then window-rank and filter out the injected row."],"examples":[{"engine_slug":"postgresql","sql":"SELECT rank(1500) WITHIN GROUP (ORDER BY salary) FROM employees;"},{"engine_slug":"oracle","sql":"SELECT RANK(1500) WITHIN GROUP (ORDER BY salary) FROM employees;"}],"faqs":[{"question":"What is a hypothetical-set aggregate for?","answer":"Placement questions: 'what rank would a salary of 1500 get?' without writing the row first."},{"question":"How is it different from window RANK?","answer":"Window RANK ranks existing rows after PARTITION BY; the hypothetical form ranks an argument value against the data."},{"question":"Which engines support it?","answer":"PostgreSQL and Oracle; MySQL, SQL Server and SQLite need the UNION ALL plus window-function emulation."}],"related":["rank","dense-rank","ordered-set-aggregates","percentile-disc"],"novel_uses":[{"body":"CUME_DIST(150000) WITHIN GROUP (ORDER BY salary) is the offer's percentile as if it were added to the table: salaries at or below it plus the offer itself, divided by the row count plus one, with no row inserted.","sql":"SELECT CUME_DIST(150000) WITHIN GROUP (ORDER BY salary) AS share_at_or_below FROM employees;"},{"body":"Test candidate cutoffs against the data with the hypothetical form before updating the row that stores the real boundary; one query per candidate, no writes.","sql":"SELECT CUME_DIST(60) WITHIN GROUP (ORDER BY score DESC) AS pass_share FROM exam_results;"}]},"source_url":"https://sqlly.app/sql-functions/hypothetical-set","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/identifier-quoting","corpus":"sql-functions","engine":null,"language":"en","title":"SQL identifier quoting","description":"Quote table and column names per engine: standard double quotes, MySQL backticks, SQL Server brackets, and the case-folding rules behind them.","body":{"slug":"identifier-quoting","name":"Quoting identifiers","h1":"SQL identifier quoting","category":"string","lede":"Identifiers need different delimiters than string literals, and each engine's case-folding rules turn quoting into a portability question of its own.","syntax":"\"name\"  |  `name`  |  [name]","return_type":"identifier","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The standard delimiter is double quotes; SQL Server accepts [brackets] (and quotes under QUOTED_IDENTIFIER); MySQL uses backticks, and double quotes name identifiers only with ANSI_QUOTES.","Case folding bites: PostgreSQL lowercases unquoted identifiers and preserves quoted ones, so users and \"Users\" are different tables. Oracle uppercases unquoted names.","MySQL's \"double quotes\" are string literals unless ANSI_QUOTES is set, the reverse of the standard, a classic cross-engine bug.","Reserved words and spaces always need quoting: order, group, select are legal column names everywhere once delimited."],"examples":[{"engine_slug":"postgresql","sql":"SELECT \"select\" FROM \"Users\";  -- quoted identifiers keep case"},{"engine_slug":"mysql","sql":"SELECT `order` FROM `order details`;  -- backticks for reserved words"},{"engine_slug":"sql-server","sql":"SELECT [order] FROM [Order Details];"},{"engine_slug":"sqlite","sql":"SELECT \"order\" FROM \"order details\";  -- double quotes; the name keeps its case but matches case-insensitively"},{"engine_slug":"oracle","sql":"SELECT \"select\" FROM \"Users\";  -- quoted keeps the exact case; unquoted names fold to upper"}],"faqs":[{"question":"Are double quotes a string or an identifier?","answer":"An identifier in the SQL standard, PostgreSQL, Oracle, SQL Server (QUOTED_IDENTIFIER ON, the driver default) and MySQL with ANSI_QUOTES. Default MySQL treats them as strings. SQLite treats them as identifiers but falls back to a string when no such column exists."},{"question":"Why does my quoted table name stop resolving?","answer":"Quoting preserves case: \"Users\" is not users on PostgreSQL. Drop the quotes to get case-folding, or match the exact stored case."},{"question":"How do I quote identifiers safely in dynamic SQL?","answer":"SQL Server's QUOTENAME doubles embedded closers; PostgreSQL's quote_ident() does the same job but quotes only names that need it, so quote_ident('users') returns users unquoted; MySQL's sys.quote_identifier() always wraps in backticks. Validating names against the catalog or an allowlist is still the safer first step."}],"related":["quotename","quote","backslash-escapes"],"novel_uses":[{"body":"Names that differ from their lowercase form are exactly the ones that break when quoting disappears, and information_schema lists them in one pass on PostgreSQL.","sql":"SELECT table_name FROM information_schema.tables\nWHERE table_schema = 'public' AND table_name <> LOWER(table_name);"},{"body":"all_tab_columns exposes the stored spelling, so comparing column_name against its uppercase form finds the quoted columns that SELECT name will never reach.","sql":"SELECT column_name FROM all_tab_columns\nWHERE table_name = 'CUSTOMERS' AND column_name <> UPPER(column_name);"}]},"source_url":"https://sqlly.app/sql-functions/identifier-quoting","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/if","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IF function","description":"IF(cond, then, else) in MySQL and SQLite 3.48+ picks one of two values: SQL Server spells it IIF, PostgreSQL and Oracle want CASE, and NULL goes to the else branch.","body":{"slug":"if","name":"IF","h1":"SQL IF function","category":"conditional","lede":"MySQL's inline conditional expression: two values, one condition.","syntax":"IF(cond, then_val, else_val) | IIF(cond, then_val, else_val)","return_type":"common type of then_val and else_val (a string if either branch is a string)","support":[{"engine_slug":"sql-server","status":"partial","note":"no IF(); IIF since SQL Server 2012"},{"engine_slug":"postgresql","status":"no","note":"no IF; use CASE WHEN"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"IIF since 3.32; IF() as an alias since 3.48"},{"engine_slug":"oracle","status":"no","note":"no IF; use CASE (or DECODE)"}],"gotchas":["A NULL condition behaves like false: the else branch runs, silently, so a missing flag looks the same as a negative one.","Only the chosen branch is evaluated, unlike Oracle's NVL.","SQL Server rewrites IIF(cond, a, b) into CASE WHEN cond THEN a ELSE b END, so the two behave identically, including the result type."],"examples":[{"engine_slug":"mysql","sql":"SELECT IF(paid = 1, 'paid', 'due') FROM invoices;"},{"engine_slug":"sql-server","sql":"SELECT IIF(paid = 1, 'paid', 'due') FROM invoices;"},{"engine_slug":"sqlite","sql":"SELECT IIF(total > 100, 'big', 'small') FROM orders;"}],"faqs":[{"question":"IF vs CASE WHEN?","answer":"Same semantics for the two-branch case; CASE is standard, nests readably and works on all five engines."},{"question":"What happens when the condition is NULL?","answer":"The else branch runs; NULL is not true, so the condition fails."},{"question":"Does PostgreSQL have IF()?","answer":"No, use CASE; IF is PL/pgSQL procedure syntax, not an expression."}],"related":["iif","case","nvl2","ifnull","decode"],"novel_uses":[{"body":"IF() in ORDER BY ranks high-priority rows first without a stored sort key and without a CASE ladder.","sql":"SELECT ticket_id FROM tickets ORDER BY IF(priority = 'high', 0, IF(priority = 'normal', 1, 2)), created_at;"},{"body":"SUM(IF(paid = 1, amount, 0)) is the MySQL spelling of the conditional-aggregation pivot, one aggregate per output column.","sql":"SELECT month, SUM(IF(paid = 1, amount, 0)) AS paid_amt, SUM(IF(paid = 0, amount, 0)) AS due_amt FROM invoices GROUP BY month;"},{"body":"IFNULL(col, d) is IF(col IS NULL, d, col) written once; same semantics, one level less nesting when the expression is long.","sql":"SELECT IFNULL(nickname, first_name) FROM users;"}]},"source_url":"https://sqlly.app/sql-functions/if","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ifnull","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IFNULL function","description":"The two-argument NULL fillers: IFNULL in MySQL and SQLite, ISNULL in SQL Server, NVL in Oracle, and why COALESCE is the portable spelling.","body":{"slug":"ifnull","name":"IFNULL / NVL / ISNULL","h1":"SQL IFNULL function","category":"conditional","lede":"Returns the second argument when the first is NULL. Each engine has its own name for it and slightly different type rules; COALESCE is the standard spelling that works everywhere.","syntax":"IFNULL(a, b)  -- MySQL, SQLite  |  ISNULL(a, b)  -- SQL Server  |  NVL(a, b)  -- Oracle","return_type":"type of the first argument","support":[{"engine_slug":"sql-server","status":"partial","note":"spelled ISNULL(a, b)"},{"engine_slug":"postgresql","status":"no","note":"no IFNULL or NVL; use COALESCE(a, b)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"spelled NVL(a, b)"}],"gotchas":["SQL Server's ISNULL casts the fallback to the first argument's type: ISNULL(col, 'too long for varchar(3)') silently truncates. COALESCE picks the higher-precedence type instead.","PostgreSQL has none of the three names: COALESCE(a, b) is the only option there, and the portable one everywhere else.","Oracle's NVL evaluates both arguments even when the first is not NULL; COALESCE stops at the first non-NULL one. That matters when the fallback is an expensive function call.","ISNULL on MySQL is a predicate: ISNULL(x) returns 1 or 0, not a fill value. Same spelling, different function from SQL Server's."],"examples":[{"engine_slug":"mysql","sql":"SELECT IFNULL(discount, 0) AS discount FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT ifnull(discount, 0) AS discount FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT ISNULL(discount, 0) AS discount FROM orders;"},{"engine_slug":"oracle","sql":"SELECT NVL(discount, 0) AS discount FROM orders;"}],"faqs":[{"question":"Is IFNULL available in every database?","answer":"No: MySQL and SQLite have IFNULL, SQL Server calls it ISNULL, Oracle calls it NVL, and PostgreSQL has none of them. COALESCE(a, b) works on all five."},{"question":"Why does ISNULL truncate my fallback value?","answer":"SQL Server's ISNULL adopts the first argument's type, so a fallback longer than the column's varchar width is cut. COALESCE returns the wider type and avoids the surprise."}],"related":["coalesce","nullif","concat"],"novel_uses":[{"body":"SET hits = IFNULL(hits, 0) + 1 works whether or not the row has been touched before, so the counter never needs a read-before-write and the race that comes with it. Each engine spells the filler its own way (ISNULL, NVL, COALESCE).","sql":"UPDATE pages SET hits = IFNULL(hits, 0) + 1\nWHERE path = '/pricing';"},{"body":"A plain GROUP BY leaves NULL rows as one unlabeled group that BI tools render as blanks or drop. Grouping on IFNULL(region, 'Unknown') keeps them visible under a name the reader can see. COALESCE is the same trick where IFNULL is missing (PostgreSQL).","sql":"SELECT IFNULL(region, 'Unknown') AS region, COUNT(*) AS customers\nFROM addresses\nGROUP BY 1;"}]},"source_url":"https://sqlly.app/sql-functions/ifnull","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ignore-nulls","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IGNORE NULLS in window functions","description":"IGNORE NULLS for FIRST_VALUE, LAST_VALUE, LAG and LEAD: full forward-fill support in Oracle and SQL Server 2022, and the portable emulation everywhere else.","body":{"slug":"ignore-nulls","name":"IGNORE NULLS","h1":"SQL IGNORE NULLS in window functions","category":"window","lede":"A modifier on offset functions that skips NULLs: LAST_VALUE(x) IGNORE NULLS OVER (...) returns the most recent non-NULL value instead of the literal last row's value.","syntax":"LAST_VALUE(x) IGNORE NULLS OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) | LAG(x) IGNORE NULLS OVER (ORDER BY id)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+ (and Azure SQL) for LAG, LEAD, FIRST_VALUE, LAST_VALUE"},{"engine_slug":"postgresql","status":"no","note":"not supported through PostgreSQL 18; emulate with the COUNT/MAX trick"},{"engine_slug":"mysql","status":"no","note":"parsed but refused ('doesn't yet support IGNORE NULLS'); emulate"},{"engine_slug":"sqlite","status":"no","note":"not supported; emulate with the COUNT/MAX trick"},{"engine_slug":"oracle","status":"yes","note":"FIRST_VALUE, LAST_VALUE, NTH_VALUE, LAG and LEAD"}],"gotchas":["Placement: SQL Server accepts IGNORE NULLS only after the closing parenthesis, LAST_VALUE(x) IGNORE NULLS OVER (...). Oracle accepts that form and also LAST_VALUE(x IGNORE NULLS). Write it after the parenthesis and the query runs on both.","The portable emulation is two windows: COUNT(x) OVER (ORDER BY id) only advances on non-NULL rows, so it gives each NULL run the same number as the value before it; MAX(x) OVER (PARTITION BY that number) then carries the value across the run.","LAG(x) IGNORE NULLS returns the previous non-NULL value, however far back. FIRST_VALUE and LAST_VALUE still obey the frame: for forward fill, end the frame at CURRENT ROW; ending it at UNBOUNDED FOLLOWING returns the partition's final non-NULL value on every row."],"examples":[{"engine_slug":"oracle","sql":"SELECT day, price,\n       LAST_VALUE(price IGNORE NULLS) OVER (\n         ORDER BY day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS last_known\nFROM prices;"},{"engine_slug":"all","sql":"-- portable forward fill: carry the last non-NULL price\nWITH marked AS (\n  SELECT p.*, COUNT(price) OVER (ORDER BY day) AS grp\n  FROM prices p\n)\nSELECT day,\n       MAX(price) OVER (PARTITION BY grp) AS price_ffill\nFROM marked;"}],"faqs":[{"question":"How do I forward-fill NULLs in PostgreSQL or MySQL?","answer":"COUNT(price) OVER (ORDER BY day) gives every NULL row the same number as the last non-NULL row before it; MAX(price) OVER (PARTITION BY that number) copies the value down. It runs on all five engines. NULLs before the first value stay NULL."},{"question":"Did SQL Server always support IGNORE NULLS?","answer":"No. SQL Server 2019 and earlier reject the keyword on all four functions; use the COUNT/MAX emulation there."}],"related":["first-value","last-value","nth-value"],"novel_uses":[{"body":"Run the frame forward instead of back: FIRST_VALUE(x) IGNORE NULLS over ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING fills each NULL with the next observation after it. SQL Server 2022 and Oracle accept the clause; forward fill repairs the past while backfill repairs the leading edge before the first reading.","sql":"SELECT day, price,\n       FIRST_VALUE(price) IGNORE NULLS OVER (\n         ORDER BY day\n         ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS next_known\nFROM prices;"},{"body":"LAG(x) IGNORE NULLS measures against the previous non-NULL value however far back it sits, so deltas describe real moves instead of zero moves across missing rows. Without it, each row after a gap reports a NULL change instead of the real move.","sql":"SELECT day, price,\n       price - LAG(price) IGNORE NULLS OVER (ORDER BY day) AS move_from_last_known\nFROM prices;"}]},"source_url":"https://sqlly.app/sql-functions/ignore-nulls","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/iif","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IIF function","description":"IIF and IF in SQL: available in SQL Server 2012+, SQLite 3.32+ and MySQL (as IF), missing in PostgreSQL and Oracle, with CASE as the portable form.","body":{"slug":"iif","name":"IIF / IF","h1":"SQL IIF function","category":"conditional","lede":"Returns one of two values depending on a condition: a CASE with exactly two branches. It is not standard SQL, so it exists on only some engines.","syntax":"IIF(condition, true_value, false_value)","return_type":"type of the chosen branch","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"no IIF; use CASE WHEN ... THEN ... ELSE ... END"},{"engine_slug":"mysql","status":"partial","note":"IF(condition, t, f) is the equivalent; there is no IIF"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"no IIF; CASE or DECODE"}],"gotchas":["SQL Server rewrites IIF into a CASE expression, so the same type rules apply: IIF(cond, 1, 'x') is an int expression and fails at run time on rows where 'x' is chosen.","SQLite added IIF in 3.32. From 3.48 it also accepts the name IF and a two-argument form, and from 3.49 any number of condition/value pairs with an optional default.","MySQL's IF() function is different from the IF statement in stored procedures; the function form works anywhere an expression does.","A NULL condition counts as false: IIF(NULL, 'yes', 'no') returns 'no'."],"examples":[{"engine_slug":"sql-server","sql":"SELECT IIF(amount > 1000, 'big', 'small') AS size FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT IIF(amount > 1000, 'big', 'small') AS size FROM orders;"},{"engine_slug":"mysql","sql":"SELECT IF(amount > 1000, 'big', 'small') AS size FROM orders;"}],"faqs":[{"question":"Does PostgreSQL have IIF?","answer":"No. Write CASE WHEN cond THEN a ELSE b END. For the common NULL case, COALESCE and NULLIF cover it in fewer characters."},{"question":"Is IIF the same as IF?","answer":"Same job, different names: SQL Server and SQLite say IIF, MySQL says IF. All three take (condition, true value, false value)."}],"related":["case","ifnull","coalesce"],"novel_uses":[{"body":"IIF in a computed column materializes a derived flag that indexes and statistics can use: ADD is_big AS IIF(amount > 1000, 1, 0) PERSISTED, then index it. SQL Server treats IIF as CASE internally, so the type rules apply.","sql":"ALTER TABLE orders ADD is_big AS IIF(amount > 1000, 1, 0) PERSISTED;\nCREATE INDEX orders_is_big ON orders (is_big);"},{"body":"SQL Server only gained LEAST and GREATEST in 2022. IIF(a < b, a, b) fills the gap and reads fine for two values; nested five deep it reads like a puzzle, and a CASE or a subquery wins there.","sql":"SELECT IIF(a < b, a, b) AS smaller FROM pairs;"}]},"source_url":"https://sqlly.app/sql-functions/iif","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ilike","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ILIKE operator","description":"PostgreSQL's ILIKE matches patterns ignoring case. How SQL Server, MySQL, SQLite and Oracle get case-insensitive LIKE through collations, ASCII folding and UPPER.","body":{"slug":"ilike","name":"ILIKE","h1":"SQL ILIKE operator","category":"conditional","lede":"name ILIKE 'smith%' matches Smith, SMITH and smith. Only PostgreSQL has the operator; the other engines decide case sensitivity through collation or need UPPER.","syntax":"expression ILIKE pattern [ESCAPE char]","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"LIKE follows the collation; default _CI_ collations already ignore case"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"LIKE under a _ci collation, the utf8mb4 default"},{"engine_slug":"sqlite","status":"partial","note":"LIKE ignores case for ASCII letters only"},{"engine_slug":"oracle","status":"partial","note":"UPPER(col) LIKE UPPER(pattern), or REGEXP_LIKE(col, pattern, 'i')"}],"gotchas":["A plain B-tree index does not help ILIKE. Use a trigram index (pg_trgm with gin_trgm_ops), or rewrite the query as lower(col) LIKE 'abc%' over an expression index on (lower(col) text_pattern_ops); under a non-C collation a plain lower(col) index does not serve LIKE.","SQLite's LIKE folds ASCII only: 'Ä' LIKE 'ä' is 0.","ILIKE is the ~~* operator, and NOT ILIKE is !~~*. EXPLAIN output shows these forms.","On MySQL, a _bin or _cs collation (COLLATE utf8mb4_bin) or CAST(pattern AS BINARY) makes LIKE case-sensitive again. The older LIKE BINARY form still works but warns that BINARY expr is deprecated."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'Apple' ILIKE 'apple' AS is_ilike, 'Apple' LIKE 'apple' AS is_like;  -- t, f"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN 'Apple' LIKE 'apple' THEN 1 ELSE 0 END AS default_ci,\n       CASE WHEN 'Apple' LIKE 'apple' COLLATE Latin1_General_CS_AS THEN 1 ELSE 0 END AS cs;  -- 1, 0 under a CI default"},{"engine_slug":"sqlite","sql":"SELECT 'Apple' LIKE 'apple' AS ascii, 'Ä' LIKE 'ä' AS non_ascii;  -- 1, 0"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN REGEXP_LIKE('Apple', '^app', 'i') THEN 'match' END AS m FROM dual;  -- match"},{"engine_slug":"mysql","sql":"SELECT 'Apple' LIKE 'apple' AS default_ci, 'Apple' LIKE 'apple' COLLATE utf8mb4_bin AS bin_cs;  -- 1, 0"}],"faqs":[{"question":"Is ILIKE slower than LIKE?","answer":"Yes. Without an index both do a full scan, but ILIKE folds case on every row and runs several times slower (about 5x over 200,000 rows on PostgreSQL 18). With an index the gap grows: a prefix LIKE can use a text_pattern_ops B-tree index, while ILIKE needs a pg_trgm index or a rewrite to lower(col) LIKE against a lower(col) text_pattern_ops index."},{"question":"Does MySQL have ILIKE?","answer":"No. MySQL's default collations are case-insensitive, so LIKE already matches regardless of case."}],"related":["like","case-insensitive-collation","lower","regexp-like"],"novel_uses":[{"body":"The citext extension makes one column's equality and unique indexes case-insensitive, so an email column folds case in joins and constraints while query text stays plain. citext also overloads LIKE and the regex operators, so email LIKE 'SMITH%' matches as well; casting to text (email::text LIKE ...) brings case sensitivity back.","sql":"CREATE EXTENSION IF NOT EXISTS citext;\nCREATE TABLE users (email citext UNIQUE);\nSELECT count(*) FROM users WHERE email = 'SMITH@x.io';  -- folds case"},{"body":"A pg_trgm GIN index serves ILIKE at any wildcard position, so WHERE email ILIKE '%@example.com' finds a domain's users without a full scan. A B-tree index cannot help a leading wildcard at all, which is what makes the trigram index the fix here.","sql":"CREATE EXTENSION IF NOT EXISTS pg_trgm;\nCREATE INDEX idx_users_email_trgm ON users USING gin (email gin_trgm_ops);\nSELECT id FROM users WHERE email ILIKE '%@example.com';"}]},"source_url":"https://sqlly.app/sql-functions/ilike","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/implicit-conversion","corpus":"sql-functions","engine":null,"language":"en","title":"SQL implicit conversion","description":"What '123' + 1 and text_column + 1 return on each engine, how MySQL and SQLite read 'abc' as 0, and how a conversion on the column side loses the index seek.","body":{"slug":"implicit-conversion","name":"Implicit conversion","h1":"SQL implicit conversion","category":"conversion","lede":"When types collide, the engine converts one side without telling you. '123' + 1 is 124 on all five engines, but a text column plus 1 is an error on PostgreSQL, and 'abc' + 1 is 1 on MySQL and SQLite.","syntax":"mixing types in expressions, comparisons and joins","return_type":"depends on the winning type","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"strictest: text + integer is an error; cast explicitly"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL treats a quoted literal as type unknown and resolves it from context, so '123' + 1 is 124. A value that is already text is different: '123'::text + 1, or a text column plus 1, fails with 'operator does not exist: text + integer'.","SQLite and MySQL read the leading digits: '123abc' + 1 is 124 and 'abc' + 1 is 1. MySQL records a warning; SQLite says nothing. SQL Server and Oracle raise a conversion error for 'abc' + 1.","An implicit conversion on the column side, as in WHERE varchar_col = 10248, converts every row's value and loses the index seek on SQL Server and MySQL. Quote the literal so it matches the column type.","On SQL Server, + between two strings is concatenation: '1' + '1' is '11'. With one number involved, data type precedence converts the string to int, so '123' + 1 and 1 + '123' are both 124."],"examples":[{"engine_slug":"all","sql":"SELECT '123' + 1 AS n;"},{"engine_slug":"sql-server","sql":"-- customer_code is varchar: the literal matches, so the index seek stays\nSELECT * FROM orders\nWHERE customer_code = '10248';"}],"faqs":[{"question":"Why is my index suddenly unused?","answer":"A type mismatch between column and literal forces a per-row conversion of the column. Match the literal's type to the column (quotes around the value for varchar columns) and the seek returns."},{"question":"Which engine is strictest about types?","answer":"PostgreSQL: once a value has a type, mixing it with an incompatible type is an error rather than a conversion. SQL Server and Oracle convert but error on unparseable text; MySQL and SQLite convert anything, falling back to 0."}],"related":["cast","pg-cast-operator","cast-truncation","decimal-cast"],"novel_uses":[{"body":"datetime plus an integer adds that many days, so GETDATE() + 1 is tomorrow in legacy T-SQL. Read it as implicit conversion at work: the int converts to datetime (1 becomes 1900-01-02, one day past the zero date) and the two add. It works only on datetime and smalldatetime; a date or datetime2 column fails with 'Operand type clash', so use DATEADD there.","sql":"SELECT ship_date + 1 AS due FROM shipments;"},{"body":"On MySQL a string compared with a number reads as its leading number, or 0 when it has none, so WHERE raw_value = 0 surfaces the rows whose numeric prefix is zero or missing. It is a one-line dirty-data probe before any real cast. SQLite compares a TEXT column with 0 as text and matches only '0', so write raw_value + 0 = 0 there to force the numeric read.","sql":"SELECT raw_value FROM staging.imports WHERE raw_value = 0;"},{"body":"Comparing a text column with a number converts every row, and Oracle does not guarantee predicate order, so a single unconvertible value can fail the whole query even when another WHERE term should have excluded it. Find the offender with a pattern test instead of rearranging predicates.","sql":"SELECT id FROM invoices WHERE NOT REGEXP_LIKE(amount_text, '^[0-9]+(\\.[0-9]+)?$');"}]},"source_url":"https://sqlly.app/sql-functions/implicit-conversion","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/in","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IN operator","description":"IN tests membership in a list or subquery: expansion to OR, NULL members that never match, NOT IN's silent-empty trap and engine limits on very long lists.","body":{"slug":"in","name":"IN","h1":"SQL IN operator","category":"conditional","lede":"True when the value matches any member of the list or subquery.","syntax":"x IN (1, 2, 3) | x IN (SELECT ...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["x IN ('a', NULL) matches 'a' rows only; the NULL member makes the remaining comparisons UNKNOWN, never true.","NOT IN with a single NULL in the subquery returns zero rows: the most famous NULL trap in SQL.","For subqueries, IN is a semi-join; correlated cases often read and plan better as EXISTS.","Long IN lists hit engine limits: 1000 expressions in Oracle, and 2100 parameters per call in SQL Server (literal values are not capped there, a 5000-value list still runs)."],"examples":[{"engine_slug":"all","sql":"SELECT id, status FROM orders WHERE status IN ('new', 'paid');"},{"engine_slug":"postgresql","sql":"SELECT * FROM orders WHERE customer_id IN (SELECT id FROM vip_customers);"}],"faqs":[{"question":"Why does IN ignore NULL members?","answer":"x IN (a, NULL) is x = a OR x = NULL; if the first is false the second is UNKNOWN, and WHERE keeps only TRUE."},{"question":"IN vs EXISTS for subqueries?","answer":"For uncorrelated subqueries the planner usually makes them identical; for correlated checks, EXISTS states the intent and short-circuits."},{"question":"How big can an IN list be?","answer":"Oracle caps at 1000 expressions (ORA-01795); SQL Server at 2100 parameters; prefer a temp table or = ANY(array) at that size."}],"related":["not-in","in-clause-limit","any","exists","three-valued-logic"],"novel_uses":[{"body":"Composite keys filter without OR chains; PostgreSQL, MySQL, Oracle and SQLite (3.15+) take it directly, SQL Server joins a VALUES list instead.","sql":"SELECT * FROM sales WHERE (yr, mon) IN ((2026, 10), (2026, 11));"},{"body":"IN inside a CASE gives flagged rows the first sort slot with no stored priority column to maintain.","sql":"SELECT ticket_id FROM tickets ORDER BY CASE WHEN status IN ('new', 'escalated') THEN 0 ELSE 1 END, created_at;"}]},"source_url":"https://sqlly.app/sql-functions/in","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/in-clause-limit","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IN list limits","description":"Long IN lists hit engine ceilings: Oracle's ORA-01795 at 1000 expressions, SQL Server's 2100 parameters, SQLite's bound-variable cap, and the temp-table fixes.","body":{"slug":"in-clause-limit","name":"IN","h1":"SQL IN list limits","category":"conditional","lede":"The per-engine ceilings on IN lists and the standard ways around them.","syntax":"x IN (SELECT id FROM temp_keys) | x = ANY (ARRAY[...])","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"2100 parameter limit per request"},{"engine_slug":"postgresql","status":"yes","note":"no cap on literal lists; bound parameters stop at 65535 per statement, and giant lists plan and cache badly"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"SQLITE_MAX_VARIABLE_NUMBER: default 999 before 3.32, then 32766"},{"engine_slug":"oracle","status":"partial","note":"ORA-01795: maximum 1000 expressions in a list"}],"gotchas":["Oracle counts expressions: 1000 literals max. Because the list is usually generated, ORA-01795 tends to surface only when production data first pushes it past 1000.","SQL Server's 2100 limit counts every parameterized value in the request, so other parameters eat into it.","SQLite's cap is on bound variables; it jumped from 999 to a 32766 default in 3.32.","The durable fix is a temp table plus IN (subquery) or a join; on PostgreSQL, x = ANY($1::bigint[]) squeezes the list into one parameter."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE id = ANY($1::bigint[]);"},{"engine_slug":"sql-server","sql":"CREATE TABLE #keys (id INT PRIMARY KEY); INSERT INTO #keys VALUES (1), (2); SELECT * FROM orders o JOIN #keys k ON o.id = k.id;"},{"engine_slug":"mysql","sql":"SELECT o.* FROM orders o JOIN (SELECT 1 AS id UNION ALL SELECT 2 UNION ALL SELECT 3) k ON o.id = k.id;"},{"engine_slug":"sqlite","sql":"WITH k(id) AS (VALUES (1), (2), (3)) SELECT o.* FROM orders o JOIN k ON o.id = k.id;"},{"engine_slug":"oracle","sql":"SELECT * FROM orders WHERE id IN (SELECT id FROM stage_keys);"}],"faqs":[{"question":"Why does Oracle fail with ORA-01795?","answer":"More than 1000 expressions in one IN list; split the list or load the keys into a table."},{"question":"What is the SQLite limit on IN?","answer":"Bound variables: 999 before 3.32, 32766 by default after, overridable at compile time."},{"question":"Best fix for huge ID lists?","answer":"A temp table with a primary key and a join: the planner gets statistics instead of a wall of literals (on PostgreSQL, ANALYZE it first, since autovacuum never analyzes temp tables)."}],"related":["in","not-in","any","null-safe-join"],"novel_uses":[{"body":"A constant first column turns the list into tuples, which ORA-01795's 1000-expression cap does not count; the same ids go through in one statement.","sql":"SELECT * FROM orders WHERE (1, customer_id) IN ((1, 101), (1, 102), (1, 103));"},{"body":"SQLite builds older than 3.32 default to 999 bound variables, which forces a split: batch the keys into 900-sized IN lists joined by OR, same result, no temp table.","sql":"SELECT * FROM t WHERE id IN (1, 2) OR id IN (3, 4) OR id IN (5, 6);"},{"body":"MySQL sets no expression count: a literal list is capped only by max_allowed_packet on the SQL text (64 MB by default since 8.0), while a prepared statement stops at 65535 placeholders (error 1390).","sql":"SHOW VARIABLES LIKE 'max_allowed_packet';"}]},"source_url":"https://sqlly.app/sql-functions/in-clause-limit","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/infinity","corpus":"sql-functions","engine":null,"language":"en","title":"SQL infinity","description":"Infinity is 'Infinity' on PostgreSQL, BINARY_DOUBLE_INFINITY on Oracle and an overflow result on SQLite. SQL Server and MySQL raise an error instead.","body":{"slug":"infinity","name":"Infinity","h1":"SQL infinity","category":"math","lede":"Covers how infinite values arise and are tested: literals, arithmetic overflow to inf, and Oracle's IS INFINITE predicate.","syntax":"'Infinity'::float8  -- PostgreSQL  |  IS INFINITE  -- Oracle  |  9e999  -- SQLite inf","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No infinite float values: overflow raises an arithmetic overflow error instead"},{"engine_slug":"postgresql","status":"yes","note":"'Infinity' and '-Infinity' literals for float; '1e308'::float8 * 10 raises 'value out of range: overflow', so inf arrives via literals, casts or functions like cot(0)"},{"engine_slug":"mysql","status":"no","note":"No infinity: 1e308 * 10 raises 'DOUBLE value is out of range'"},{"engine_slug":"sqlite","status":"partial","note":"9e999 evaluates to Inf and stores fine; inf - inf gives NULL (NaN becomes NULL)"},{"engine_slug":"oracle","status":"yes","note":"BINARY_DOUBLE_INFINITY literal and IS INFINITE / IS NOT INFINITE predicates"}],"gotchas":["PostgreSQL distinguishes overflow from literal infinity: 'Infinity'::float8 is fine, but '1e308'::float8 * 10 errors. A bare 1e308 * 10 is numeric there and simply returns a 310-digit number (a 1 followed by 309 zeros). Only SQLite and Oracle BINARY_DOUBLE (1e308d * 10) turn float overflow into Inf.","Infinity compares greater than every finite number, and inf - inf is NaN (which SQLite then stores as NULL).","Oracle's IS INFINITE is the only real predicate of the five. On PostgreSQL test x IN ('Infinity', '-Infinity'); on SQLite compare ABS(x) > 1.7976931348623157e308."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'Infinity'::float8 > 1e308 AS always_true;  -- true"},{"engine_slug":"oracle","sql":"SELECT * FROM t WHERE x IS INFINITE;"},{"engine_slug":"sqlite","sql":"SELECT 9e999 AS inf, 1e308 * 10 AS also_inf;  -- Inf, Inf"}],"faqs":[{"question":"Does 1e308 * 10 return Infinity in SQL?","answer":"Only on SQLite and Oracle BINARY_DOUBLE. MySQL and SQL Server raise an overflow error. PostgreSQL treats the literal as numeric and returns an exact 1 followed by 309 zeros; as float8 it raises an overflow error. Oracle NUMBER overflows (ORA-01426), while BINARY_DOUBLE gives Inf."},{"question":"How do I test for infinity in SQL?","answer":"Oracle: x IS INFINITE. PostgreSQL: x IN ('Infinity'::float8, '-Infinity'::float8). SQLite: ABS(x) > 1.7976931348623157e308, since it has no predicate. SQL Server and MySQL never store infinity, so there is nothing to test."},{"question":"What is Infinity minus Infinity?","answer":"NaN, under IEEE rules, and on SQLite that NaN immediately becomes NULL, so inf - inf returns NULL there."}],"related":["nan-infinity","nan-check","integer-overflow","double-precision"],"novel_uses":[{"body":"A bounds table with 'Infinity'::float8 as the upper edge makes every comparison plain SQL: value <= upper just works, with no IS NULL branches. The sentinel sorts last, so range scans stay correct.","sql":"SELECT * FROM bands WHERE value <= upper;  -- upper holds 'Infinity'::float8 for the open-ended band"},{"body":"Defaulting score to '-Infinity'::float8 makes ORDER BY score DESC place never-scored rows last, with no UNION of missing rows. On PostgreSQL the literal sorts below every real score.","sql":"SELECT id FROM items ORDER BY COALESCE(score, '-Infinity'::float8) DESC;"}]},"source_url":"https://sqlly.app/sql-functions/infinity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/initcap","corpus":"sql-functions","engine":null,"language":"en","title":"SQL INITCAP function","description":"INITCAP title-cases every word (uppercasing the first letter and lowercasing the rest) in PostgreSQL and Oracle, with caveats for names and apostrophes.","body":{"slug":"initcap","name":"INITCAP","h1":"SQL INITCAP function","category":"string","lede":"Capitalises the first letter of every word and lowercases the rest. Fine for O'Brien and Jean-Luc, wrong for McDonald, iPhone and it's.","syntax":"INITCAP(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Every non-alphanumeric character starts a new word. That gets O'Brien and Jean-Luc right, but INITCAP('it''s') is 'It'S'.","The rest of each word is lowercased, so INITCAP('iPhone') is 'Iphone'. Digits count as word characters, so INITCAP('3rd street') is '3rd Street'.","SQL Server and MySQL have no INITCAP. Whole-string capitalisation is UPPER(LEFT(s,1)) + LOWER(SUBSTRING(s,2,...)) in SQL Server; in MySQL, + is arithmetic and returns 0, so use CONCAT(UPPER(LEFT(s,1)), LOWER(SUBSTRING(s,2))). Word-by-word needs a UDF or the app layer.","Casing follows the locale: Oracle's NLS_INITCAP and PostgreSQL's collation decide how dotted and accented letters convert."],"examples":[{"engine_slug":"postgresql","sql":"SELECT INITCAP('the quiet lake') AS t;  -- The Quiet Lake"},{"engine_slug":"postgresql","sql":"SELECT INITCAP('jean-luc o''brien') AS t;  -- Jean-Luc O'Brien"},{"engine_slug":"oracle","sql":"SELECT INITCAP('mcdonald holdings') AS t FROM dual;  -- Mcdonald Holdings"}],"faqs":[{"question":"Is INITCAP available in SQL Server or MySQL?","answer":"No. PostgreSQL and Oracle have it; everywhere else you hand-roll it: UPPER + LOWER + SUBSTRING for the whole string, a function for word-by-word."},{"question":"Why does INITCAP mangle names like McDonald?","answer":"It lowercases everything after the first letter of each word, so McDonald becomes Mcdonald. Apostrophes and hyphens start new words, which suits O'Brien but turns it's into It'S."},{"question":"Should I store INITCAP output?","answer":"Rarely. Casing is presentation. Store a canonical form and INITCAP (or better, app-side formatting) at display time."}],"related":["upper","lower","title-case","nls-initcap"],"novel_uses":[{"body":"INITCAP('JOHN SMITH') gives 'John Smith', which makes it the one-call fix for columns typed in capitals decades ago.","sql":"SELECT INITCAP(name) AS display FROM legacy;  -- 'JOHN SMITH' becomes 'John Smith'"},{"body":"Run INITCAP first, then patch the known misses with word-boundary regex: this keeps McDonald out of the Mcdonald pile without hand-editing rows.","sql":"SELECT REGEXP_REPLACE(INITCAP(name), '\\mMcdonald\\M', 'McDonald') AS fixed FROM brands;"}]},"source_url":"https://sqlly.app/sql-functions/initcap","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/insert-string","corpus":"sql-functions","engine":null,"language":"en","title":"SQL INSERT (string) function","description":"How MySQL's INSERT(str, pos, len, newstr) deletes len characters and inserts new text: out-of-range positions, NULL results and the STUFF and OVERLAY equivalents.","body":{"slug":"insert-string","name":"INSERT","h1":"SQL INSERT (string) function","category":"string","lede":"MySQL string splicing: removes len characters at a 1-based position and inserts a replacement string there.","syntax":"INSERT(str, pos, len, new_str)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"Use STUFF(str, start, len, new)."},{"engine_slug":"postgresql","status":"partial","note":"Use OVERLAY(str PLACING new FROM start FOR len)."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No INSERT function; splice with SUBSTR and ||."},{"engine_slug":"oracle","status":"no","note":"No INSERT function; splice with SUBSTR and ||."}],"gotchas":["The name collides with the INSERT statement; MySQL tells them apart by position, so INSERT(...) inside an expression is always the string function.","A pos outside the string (0, negative, or past the end) returns the original string unchanged, so INSERT cannot append.","A len of 0 is a pure insert; a len longer than the rest of the string replaces everything from pos to the end: INSERT('abc', 2, 99, 'X') is 'aX'. Any NULL argument returns NULL."],"examples":[{"engine_slug":"mysql","sql":"SELECT INSERT('abcdef', 2, 3, 'XY') AS result;  -- aXYef"},{"engine_slug":"mysql","sql":"SELECT INSERT(card, 8, 4, '****') AS masked\nFROM payments;"},{"engine_slug":"sql-server","sql":"SELECT STUFF('abcdef', 2, 3, 'XY') AS result;  -- aXYef"},{"engine_slug":"postgresql","sql":"SELECT OVERLAY('abcdef' PLACING 'XY' FROM 2 FOR 3) AS result;  -- aXYef"}],"faqs":[{"question":"Is INSERT(str, pos, len, new) related to INSERT INTO?","answer":"No. The function edits a string value; the statement adds rows."},{"question":"What is the SQL Server equivalent?","answer":"STUFF(str, pos, len, new), with the same pure insert at len 0. Out-of-range positions differ: STUFF returns NULL, INSERT returns the input."},{"question":"What happens when pos is larger than the string?","answer":"MySQL returns the original string unchanged instead of appending. Use CONCAT to add text at the end."}],"related":["stuff","overlay","replace","substr"],"novel_uses":[{"body":"REPLACE hits every occurrence and MySQL has no replace-first function, but INSERT(s, LOCATE('old', s), CHAR_LENGTH('old'), 'new') changes exactly one. When the token is absent LOCATE returns 0, an out-of-range position, so the string passes through unchanged.","sql":"UPDATE notes\nSET body = INSERT(body, LOCATE('colour', body), 6, 'color');"},{"body":"A len longer than the rest of the string is clamped, so INSERT(s, pos, CHAR_LENGTH(s), repl) replaces the suffix from pos onward without RIGHT or LEN arithmetic.","sql":"SELECT INSERT(status_line, LOCATE('draft', status_line),\n       CHAR_LENGTH(status_line), 'published') AS promoted\nFROM articles;"},{"body":"INSERT returns the original string unchanged when pos falls outside it, but a splice that writes the character already there also returns the original, so the comparison cannot tell the two apart. Compare the position with CHAR_LENGTH(s) instead.","sql":"SELECT IF(20 <= CHAR_LENGTH(code), 'in range', 'out of range') AS pos_check\nFROM items;"}]},"source_url":"https://sqlly.app/sql-functions/insert-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/instr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL INSTR function","description":"Find where a substring starts: CHARINDEX in SQL Server, POSITION and STRPOS in PostgreSQL, INSTR in MySQL, SQLite and Oracle (all 1-based, 0 when absent).","body":{"slug":"instr","name":"INSTR / CHARINDEX / POSITION","h1":"SQL INSTR function","category":"string","lede":"Returns the position of the first occurrence of a substring, or 0 when it is not there. The argument order is the portability trap: SQL Server puts the needle first, most others put the haystack first.","syntax":"CHARINDEX(needle, haystack)  |  POSITION(needle IN haystack)  |  INSTR(haystack, needle)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"CHARINDEX(needle, haystack [, start])"},{"engine_slug":"postgresql","status":"partial","note":"POSITION(needle IN haystack) or STRPOS(haystack, needle)"},{"engine_slug":"mysql","status":"yes","note":"INSTR(haystack, needle), plus LOCATE(needle, haystack [, start]) and POSITION"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Positions are 1-based and 0 means not found on all five engines.","SQL Server's CHARINDEX and MySQL's LOCATE take the needle first; INSTR on MySQL, SQLite and Oracle takes the haystack first. Swapping them returns a wrong number, not an error.","Oracle's INSTR has optional occurrence and start-position arguments: INSTR(s, 'a', -1) searches backwards."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('@', email) AS at_sign\nFROM users;"},{"engine_slug":"mysql","sql":"SELECT INSTR(email, '@') AS at_sign FROM users;"},{"engine_slug":"postgresql","sql":"SELECT POSITION('@' IN email) AS at_sign FROM users;"},{"engine_slug":"sqlite","sql":"SELECT instr(email, '@') AS at_sign FROM users;"},{"engine_slug":"oracle","sql":"SELECT INSTR('a@b.com', '@', -1) AS last_at FROM dual;  -- 2"}],"faqs":[{"question":"What does INSTR return when the substring is not found?","answer":"0 on every major engine. Combined with 1-based positions, that makes INSTR(s, x) > 0 the portable contains test."},{"question":"Why do CHARINDEX and INSTR have different argument orders?","answer":"They come from different vendors' traditions: SQL Server's CHARINDEX is (needle, haystack), while INSTR on MySQL, SQLite and Oracle is (haystack, needle). Nothing errors when you swap them; you just get a wrong number."}],"related":["substring","left","regexp-replace"],"novel_uses":[{"body":"LEFT(name, POSITION(' ' IN name) - 1) takes the first word, but a single-word name makes POSITION return 0 and the offset -1: MySQL renders that as an empty string and PostgreSQL as everything except the last letter. Guard with CASE so both fall through to the whole name.","sql":"SELECT CASE WHEN POSITION(' ' IN name) > 0\n            THEN SUBSTRING(name FOR POSITION(' ' IN name) - 1)\n            ELSE name END AS first_word\nFROM people;"},{"body":"Sorting by the match position puts titles containing the term near the front above titles that only mention it deep in the string. Two calls to INSTR, no full-text machinery, good enough for small result sets.","sql":"SELECT id, title\nFROM articles\nWHERE INSTR(title, 'sql') > 0\nORDER BY INSTR(title, 'sql'), title;"}]},"source_url":"https://sqlly.app/sql-functions/instr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/integer-division","corpus":"sql-functions","engine":null,"language":"en","title":"SQL integer division","description":"int / int truncates on SQL Server, PostgreSQL and SQLite, so 1 / 2 is 0. MySQL and Oracle return 0.5; MySQL's DIV and PostgreSQL's div() truncate on purpose.","body":{"slug":"integer-division","name":"DIV","h1":"SQL integer division","category":"math","lede":"Divides two integers and drops the fraction toward zero: 7 / 2 is 3 and -7 / 2 is -3 on SQL Server, PostgreSQL and SQLite. MySQL needs DIV and Oracle needs TRUNC.","syntax":"7 / 2  |  7 DIV 2  -- MySQL  |  div(7, 2)  -- PostgreSQL  |  TRUNC(7 / 2)  -- Oracle","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"/ on integers truncates toward zero"},{"engine_slug":"postgresql","status":"yes","note":"int / int truncates; div(numeric, numeric) is the explicit integer-division function"},{"engine_slug":"mysql","status":"yes","note":"DIV is a keyword: 7 DIV 2 is 3; the plain / always returns a decimal on MySQL"},{"engine_slug":"sqlite","status":"yes","note":"int / int truncates toward zero"},{"engine_slug":"oracle","status":"partial","note":"/ never truncates: 7 / 2 is 3.5. Use TRUNC(7 / 2) for integer division"}],"gotchas":["The fix for 1/2 = 0 on SQL Server, PostgreSQL and SQLite is decimal promotion: 1.0 / 2, CAST(x AS REAL), or multiply by 1.0 before dividing. CAST(x AS DECIMAL) works on SQL Server and PostgreSQL but stays an integer on SQLite.","Truncation is toward zero: -7 / 2 is -3, which differs from FLOOR(-3.5) = -4. Do not swap FLOOR for integer division on negatives.","MySQL and Oracle never truncate on /: 7 / 2 is 3.5000 on MySQL and 3.5 on Oracle. Code ported from SQL Server that relies on truncation silently changes results there; use DIV (MySQL) or TRUNC (Oracle).","Division by zero stays an error or NULL per engine; integer division does not change that."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 7 / 2 AS int_div, -7 / 2 AS toward_zero;  -- 3, -3"},{"engine_slug":"oracle","sql":"SELECT 7 / 2 AS plain, TRUNC(7 / 2) AS int_div FROM dual;  -- 3.5, 3"},{"engine_slug":"mysql","sql":"SELECT 7 DIV 2 AS three, 7 / 2 AS decimal_result;  -- 3, 3.5000"},{"engine_slug":"postgresql","sql":"SELECT total_rows / page_size AS full_pages, div(total_rows, page_size) AS same\nFROM jobs;"},{"engine_slug":"sqlite","sql":"SELECT 7 / 2 AS int_div, -7 / 2 AS toward_zero;  -- 3, -3"}],"faqs":[{"question":"Why is 1/2 equal to 0 in my query?","answer":"Integer division: on SQL Server, PostgreSQL and SQLite, two integer operands give an integer result with the fraction dropped. Write 1.0 / 2 or CAST one operand to REAL to get 0.5; CAST to DECIMAL also works on SQL Server and PostgreSQL but stays an integer on SQLite. MySQL and Oracle already return 0.5."},{"question":"Does -7 / 2 round or truncate?","answer":"It truncates toward zero: -3 on SQL Server, PostgreSQL and SQLite, and with MySQL's -7 DIV 2. That is not the same as FLOOR(-3.5), which is -4, a common off-by-one on negatives."},{"question":"What is MySQL's DIV operator?","answer":"The explicit integer-division keyword: 7 DIV 2 is 3. It exists because MySQL's plain / always returns a decimal and never truncates."}],"related":["arithmetic-operators","modulo-operator","cast-to-int","floor"],"novel_uses":[{"body":"lo + (hi - lo) / 2 computes a binary-search midpoint without the overflow (lo + hi) / 2 risks near the top of the range. It matters in SQL where the operands are BIGINT ids. On MySQL write (hi - lo) DIV 2 so the midpoint stays an integer.","sql":"SELECT lo + (hi - lo) / 2 AS mid FROM ranges;"},{"body":"(row_number - 1) / 1000 groups rows into consecutive 1000-row batches for chunked migrations. Window functions cannot sit in GROUP BY, so group inside a subquery. On SQL Server, PostgreSQL and SQLite the plain slash does it; MySQL needs DIV and Oracle needs TRUNC.","sql":"SELECT batch, COUNT(*) FROM (SELECT (ROW_NUMBER() OVER (ORDER BY id) - 1) / 1000 AS batch FROM t) x GROUP BY batch;"}]},"source_url":"https://sqlly.app/sql-functions/integer-division","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/integer-overflow","corpus":"sql-functions","engine":null,"language":"en","title":"SQL integer overflow","description":"2147483647 + 1 errors on SQL Server and PostgreSQL but is fine on MySQL, which computes in 64 bits. SQLite turns BIGINT overflow into a float.","body":{"slug":"integer-overflow","name":"INT overflow","h1":"SQL integer overflow","category":"math","lede":"What happens when integer arithmetic exceeds the type's range, per engine: an error, a silent switch to float, or (for Oracle NUMBER) nothing until 1e126.","syntax":"2147483647 + 1  |  CAST(x AS BIGINT) + 1","return_type":"integer / float / error","support":[{"engine_slug":"sql-server","status":"yes","note":"Arithmetic overflow error: the statement fails; CAST to BIGINT first"},{"engine_slug":"postgresql","status":"yes","note":"ERROR: integer out of range; bigint overflows raise 'bigint out of range'"},{"engine_slug":"mysql","status":"partial","note":"Integer expressions are evaluated as 64-bit BIGINT, so 2147483647 + 1 is fine; past BIGINT it raises 'BIGINT value is out of range'. Clamping happens only when storing into a narrower column in non-strict mode"},{"engine_slug":"sqlite","status":"partial","note":"Silently promotes to REAL: 9223372036854775807 + 1 becomes 9.22337203685478e+18, losing precision"},{"engine_slug":"oracle","status":"no","note":"NUMBER holds 38 digits and overflows only near 1e126 (ORA-01426); PLS_INTEGER in PL/SQL does overflow at 2^31"}],"gotchas":["SQLite's promotion is the sneakiest: the result looks like a number but is a float, so equality with the true value fails and digits past 15 are gone.","The fix is to widen before operating: CAST(a AS BIGINT) * b on SQL Server and PostgreSQL. The operand types decide overflow, not the column the result is stored in. SQL Server's SUM(int_col) returns INT and overflows the same way; use SUM(CAST(x AS BIGINT)).","ABS of the smallest bigint overflows even on widened types: there is no positive counterpart two's complement can represent."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(2147483647 AS BIGINT) + 1 AS safe;  -- 2147483648"},{"engine_slug":"sqlite","sql":"SELECT 9223372036854775807 + 1 AS promoted;  -- 9.22337203685478e+18 (REAL)"},{"engine_slug":"mysql","sql":"SELECT 2147483647 + 1 AS fine, 9223372036854775807 + 1 AS boom;  -- ERROR: BIGINT value is out of range"},{"engine_slug":"postgresql","sql":"SELECT 2147483647 + 1 AS boom;  -- ERROR: integer out of range"}],"faqs":[{"question":"Why does my sum overflow when the column is bigint?","answer":"Usually the column is bigint but the expression feeding it is not. SQL Server's SUM over an INT column returns INT and fails past 2147483647; PostgreSQL's SUM(int) returns bigint and MySQL's returns DECIMAL, so they do not. CAST operands to BIGINT before the arithmetic, not after."},{"question":"Does SQLite overflow integers?","answer":"Plain arithmetic never errors: past the 64-bit range the result becomes a float, silently losing precision past about 15 digits. The aggregate SUM() and abs() do fail with 'integer overflow'; TOTAL() returns the float instead."},{"question":"How do I avoid integer overflow in SQL?","answer":"Widen before computing: CAST to BIGINT or NUMERIC on the operands. SQL Server and PostgreSQL error at the INT boundary, MySQL at the BIGINT boundary, and SQLite silently switches to float past BIGINT. An early cast to NUMERIC/DECIMAL avoids the overflow on SQL Server, PostgreSQL and MySQL; SQLite has no exact decimal type, so past BIGINT the cast still yields a float."}],"related":["arithmetic-operators","decimal-overflow","cast","negation"],"novel_uses":[{"body":"COUNT(*) on SQL Server returns INT and errors past 2147483647 rows. COUNT_BIG returns BIGINT and is the same scan, so big-table scripts should use it by default.","sql":"SELECT COUNT_BIG(*) FROM events;"},{"body":"Integer chains force a choice: a / b * c avoids overflow but truncates at the division, while a * c / b keeps precision and risks it. Try both on sample data to see which risk is real at your magnitudes. MySQL's / returns an exact decimal, so the division truncates only on SQL Server, PostgreSQL and SQLite.","sql":"SELECT 9 / 2 * 3 AS truncates, 9 * 3 / 2 AS precise, 2147483647 * 2 AS overflows;  -- SQL Server and PostgreSQL: the last term errors. MySQL and SQLite: 4294967294, no error"}]},"source_url":"https://sqlly.app/sql-functions/integer-overflow","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/interval-arithmetic","corpus":"sql-functions","engine":null,"language":"en","title":"SQL interval arithmetic","description":"Intervals are numbers you can add, subtract, scale and negate in PostgreSQL and Oracle: month/day/second fields, the overflow rule, and per-engine limits.","body":{"slug":"interval-arithmetic","name":"Interval arithmetic","h1":"SQL interval arithmetic","category":"datetime","lede":"Durations support real math: interval + interval, interval * n, date - interval, as long as you respect the month/day/second field split.","syntax":"d - INTERVAL '1 day'  |  iv1 + iv2  |  iv * 2.5","return_type":"interval / timestamp","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD per part; no interval values to do math on"},{"engine_slug":"postgresql","status":"yes","note":"full arithmetic on intervals"},{"engine_slug":"mysql","status":"partial","note":"per-call INTERVAL terms, no interval values"},{"engine_slug":"sqlite","status":"partial","note":"modifier chains only"},{"engine_slug":"oracle","status":"yes","note":"intervals add and scale; DATE math is days"}],"gotchas":["PostgreSQL stores months, days and seconds separately: INTERVAL '1 month' + INTERVAL '30 days' keeps both parts, and EXTRACT(EPOCH) then assumes 30 days per month; do epoch math only when that assumption is fine.","Multiplication and division push fractions down but never carry up: INTERVAL '3 days' / 2 is 1 day 12:00:00 and INTERVAL '1 month' / 2 is 15 days, yet INTERVAL '20 hours' * 2 stays 40:00:00. justify_interval() does the carrying.","Oracle DATE arithmetic works in days (d - 7), and DATE + INTERVAL works too: DATE '2026-08-01' + INTERVAL '1 02:30:00' DAY TO SECOND is 2026-08-02 02:30. Adding a month interval to a 31st errors (ORA-01839) instead of clamping."],"examples":[{"engine_slug":"postgresql","sql":"SELECT now() - INTERVAL '90 minutes';"},{"engine_slug":"postgresql","sql":"SELECT INTERVAL '45 minutes' * 2;  -- 01:30:00"},{"engine_slug":"oracle","sql":"SELECT TIMESTAMP '2026-08-01 00:00:00' - INTERVAL '2' DAY FROM dual;  -- 2026-07-30 00:00:00"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MINUTE, -90, '2026-08-01 12:00');  -- 2026-08-01 10:30:00"},{"engine_slug":"mysql","sql":"SELECT '2026-08-01 12:00:00' - INTERVAL 90 MINUTE;  -- 2026-08-01 10:30:00"},{"engine_slug":"sqlite","sql":"SELECT datetime('2026-08-01 12:00:00', '-90 minutes');  -- 2026-08-01 10:30:00"}],"faqs":[{"question":"Why is my interval average showing days and hours mixed oddly?","answer":"Averaging keeps each field separate and may leave out-of-range values; wrap with justify_interval(avg(iv)) or justify_hours to carry into sensible fields."},{"question":"Can I multiply intervals in SQL Server?","answer":"No interval values exist; multiply the unit count first: DATEADD(MINUTE, 45 * 2, d)."}],"related":["interval-literal","justify-interval","timestamp-difference","make-interval"],"novel_uses":[{"body":"Multiplying an integer by a one-unit interval builds evenly spaced series, the core of calendar spines generated from generate_series.","sql":"SELECT now()::date + n * INTERVAL '1 day' FROM generate_series(0, 6) AS n;"},{"body":"Store the direction as an integer and scale the interval by it, so one expression walks both ways and reversals need no second query.","sql":"SELECT started_at + direction * span FROM legs;  -- direction -1 walks backward"},{"body":"Interval comparison carries across fields: ninety minutes equals one hour thirty minutes, so tests can assert on spelling-independent spans. Months compare as 30 days, so INTERVAL '1 month' = INTERVAL '30 days' is also true.","sql":"SELECT INTERVAL '90 minutes' = INTERVAL '1 hour 30 minutes';  -- t"}]},"source_url":"https://sqlly.app/sql-functions/interval-arithmetic","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/interval-keyword","corpus":"sql-functions","engine":null,"language":"en","title":"SQL INTERVAL keyword in MySQL","description":"MySQL's INTERVAL keyword: INTERVAL 7 DAY, INTERVAL '1-6' YEAR_MONTH and the compound units, distinct from the SQL-standard INTERVAL literal.","body":{"slug":"interval-keyword","name":"INTERVAL n unit","h1":"SQL INTERVAL keyword in MySQL","category":"datetime","lede":"MySQL spells durations as INTERVAL n unit (a keyword, count and unit name), usable in DATE_ADD, DATE_SUB and direct date arithmetic.","syntax":"d + INTERVAL 7 DAY  |  DATE_ADD(d, INTERVAL '1-6' YEAR_MONTH)","return_type":"date or datetime (INTERVAL is an operand, never a standalone value)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(unit, n, d); unit as bare keyword too"},{"engine_slug":"postgresql","status":"partial","note":"INTERVAL '7 days' literal instead"},{"engine_slug":"mysql","status":"yes","note":"this form, the portable-in-MySQL spelling"},{"engine_slug":"sqlite","status":"partial","note":"modifiers: date(d, '+7 days')"},{"engine_slug":"oracle","status":"partial","note":"INTERVAL '7' DAY literals or NUMTODSINTERVAL"}],"gotchas":["The unit list runs MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR plus compound pairs like DAY_HOUR, HOUR_MINUTE and YEAR_MONTH, whose values are quoted strings with any punctuation between the parts: INTERVAL '2:30' HOUR_MINUTE.","Direct arithmetic accepts it: SELECT '2026-08-01' + INTERVAL 7 DAY; no DATE_ADD call needed, and it beats string-plus-number coercion which does numeric addition.","WEEK is exactly 7 days here; MONTH clamps to month ends (Jan 31 + 1 MONTH gives Feb 28), the same month rule as DATE_ADD, because it is DATE_ADD."],"examples":[{"engine_slug":"mysql","sql":"SELECT '2026-08-01' + INTERVAL 7 DAY;  -- 2026-08-08"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-08-01', INTERVAL '1-6' YEAR_MONTH);  -- 2028-02-01"},{"engine_slug":"mysql","sql":"SELECT created_at + INTERVAL 90 MINUTE FROM jobs;"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(day, 7, '2026-08-01');  -- 2026-08-08"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-08-01' + INTERVAL '7 days';  -- 2026-08-08 00:00:00"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-01', '+7 days');  -- 2026-08-08"},{"engine_slug":"oracle","sql":"SELECT DATE '2026-08-01' + INTERVAL '7' DAY FROM dual;  -- 2026-08-08"}],"faqs":[{"question":"Why does MySQL use INTERVAL 7 DAY instead of a literal?","answer":"MySQL reuses one keyword grammar for arithmetic units; the SQL-standard INTERVAL '7 days' literal form is not accepted there, the reverse of PostgreSQL."},{"question":"What units exist?","answer":"MICROSECOND through YEAR, plus compound YEAR_MONTH, DAY_HOUR, DAY_MINUTE, DAY_SECOND, HOUR_MINUTE, HOUR_SECOND, MINUTE_SECOND and the *_MICROSECOND variants, each taking a quoted multi-part value."}],"related":["interval-literal","adddate","date-sub","interval-arithmetic"],"novel_uses":[{"body":"MySQL 8.0.13 expression defaults accept interval arithmetic, so expires_at can set itself at insert without a trigger.","sql":"CREATE TABLE tokens (issued_at DATETIME, expires_at DATETIME DEFAULT (NOW() + INTERVAL 1 DAY));"},{"body":"The keyword accepts negative counts, so d + INTERVAL -7 DAY subtracts and one arithmetic path covers rolling windows forward and back.","sql":"SELECT '2026-08-08' + INTERVAL -7 DAY;  -- 2026-08-01"}]},"source_url":"https://sqlly.app/sql-functions/interval-keyword","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/interval-literal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL INTERVAL literal","description":"Standard INTERVAL '1 day' literals on PostgreSQL and Oracle, MySQL's INTERVAL 1 DAY spelling: how each engine writes a span of time in plain SQL.","body":{"slug":"interval-literal","name":"INTERVAL literal","h1":"SQL INTERVAL literal","category":"datetime","lede":"Returns an interval value written inline in SQL on PostgreSQL and Oracle, which quote a text literal. MySQL has no standalone interval value: INTERVAL 1 DAY works only as an operand of + or DATE_ADD, and it puts the unit keyword outside the quotes.","syntax":"INTERVAL '1 day'  -- PostgreSQL  |  INTERVAL '1' DAY  -- Oracle  |  INTERVAL 1 DAY  -- MySQL","return_type":"interval","support":[{"engine_slug":"sql-server","status":"no","note":"no interval type; DATEADD(month, 1, d) applies spans"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"INTERVAL 1 DAY or INTERVAL '1' DAY; the whole '1 DAY' string is a syntax error"},{"engine_slug":"sqlite","status":"no","note":"no interval type; modifiers like '+1 day'"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL splits it: INTERVAL 1 DAY or INTERVAL '1' DAY; the quoted PostgreSQL form INTERVAL '1 DAY' is a syntax error there.","Oracle needs the unit separated: INTERVAL '1' DAY (PostgreSQL accepts that form too), and composite literals spell the range: INTERVAL '1 2:30:00' DAY TO SECOND.","Oracle keeps year-to-month and day-to-second intervals as separate types, so one literal cannot hold both. PostgreSQL can: INTERVAL '1 month 1 day' is valid there."],"examples":[{"engine_slug":"postgresql","sql":"SELECT now() + INTERVAL '1 day 2 hours' AS deadline;"},{"engine_slug":"mysql","sql":"SELECT created_at + INTERVAL 30 DAY AS deadline FROM orders;"},{"engine_slug":"oracle","sql":"SELECT d + INTERVAL '2' HOUR AS later FROM events;"}],"faqs":[{"question":"Why does INTERVAL '1 DAY' fail on MySQL?","answer":"MySQL separates the amount from the unit: INTERVAL 1 DAY or INTERVAL '1' DAY. The whole-string PostgreSQL form does not parse there."},{"question":"Can I mix months and days in one interval?","answer":"On PostgreSQL, yes: INTERVAL '1 month 1 day'. On Oracle they are separate types, so add INTERVAL '1' MONTH and INTERVAL '1' DAY in two steps. MySQL's INTERVAL takes one unit (or a compound like DAY_HOUR) per INTERVAL operand; chain operands to mix them: + INTERVAL 1 MONTH + INTERVAL 1 DAY."}],"related":["make-interval","dateadd","to-dsinterval"],"novel_uses":[{"body":"One expression can carry two units: INTERVAL '1 2' DAY_HOUR adds a day and two hours, one of the paired forms from DAY_HOUR down to SECOND_MICROSECOND.","sql":"SELECT d + INTERVAL '1 2' DAY_HOUR AS later FROM events;"},{"body":"Long day totals stop reading like durations. justify_interval folds each block of 30 days into a month and each 24 hours into a day, so '45 days' becomes '1 mon 15 days'.","sql":"SELECT justify_interval(interval '45 days') AS tidy;"}]},"source_url":"https://sqlly.app/sql-functions/interval-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/inverse-trig-domain","corpus":"sql-functions","engine":null,"language":"en","title":"SQL inverse trig domain errors","description":"ASIN(2) and ACOS(2) have no real answer: MySQL and SQLite return NULL, while PostgreSQL, Oracle and SQL Server raise an error. Clamp inputs first.","body":{"slug":"inverse-trig-domain","name":"trig domain","h1":"SQL inverse trig domain errors","category":"math","lede":"Each engine's reaction to inverse-trig input outside [-1, 1], the ACOSH and ATANH domains, and the LEAST/GREATEST clamp (MAX/MIN on SQLite) that prevents it.","syntax":"ASIN(2)  |  ASIN(LEAST(1, GREATEST(-1, x)))","return_type":"float / NULL / error","support":[{"engine_slug":"sql-server","status":"yes","note":"Msg 3623: An invalid floating point operation occurred; the statement fails"},{"engine_slug":"postgresql","status":"yes","note":"ERROR: input is out of range; the statement fails"},{"engine_slug":"mysql","status":"yes","note":"Returns NULL; no warning is raised"},{"engine_slug":"sqlite","status":"yes","note":"NULL; out-of-domain input is a soft failure"},{"engine_slug":"oracle","status":"yes","note":"ORA-01428: argument is out of range"}],"gotchas":["Float error pushes borderline inputs out of domain: a computed cosine of 1.0000000000000002 fails in ACOS on PostgreSQL even though the math says 1.0.","The clamp is two functions: ASIN(LEAST(1, GREATEST(-1, x))) on SQL Server 2022+, PostgreSQL, MySQL and Oracle; SQLite has no LEAST/GREATEST, so write ASIN(MAX(-1, MIN(1, x))).","ACOSH has a [1, infinity) domain: ACOSH(0.5) errors on PostgreSQL and is NULL on SQLite. ATANH(1) is not an error on either; both return Infinity."],"examples":[{"engine_slug":"mysql","sql":"SELECT ASIN(2) AS out_of_domain;  -- NULL"},{"engine_slug":"postgresql","sql":"SELECT ASIN(2) AS boom;  -- ERROR: input is out of range"},{"engine_slug":"postgresql","sql":"SELECT ASIN(LEAST(1, GREATEST(-1, 2))) AS clamped;  -- 1.5707963267948966"},{"engine_slug":"sqlite","sql":"SELECT asin(max(-1, min(1, 2))) AS clamped;  -- 1.5707963267949"},{"engine_slug":"sql-server","sql":"SELECT ASIN(2) AS boom;  -- Msg 3623, an invalid floating point operation occurred"},{"engine_slug":"oracle","sql":"SELECT ASIN(2) AS boom FROM dual;  -- ORA-01428: argument is out of range"}],"faqs":[{"question":"Why does ASIN(2) error on PostgreSQL but return NULL on MySQL?","answer":"The engines chose differently: PostgreSQL treats out-of-domain math as a hard error, MySQL as a soft NULL. SQLite also returns NULL; Oracle and SQL Server error like PostgreSQL."},{"question":"How do I stop ACOS from failing on float noise?","answer":"Clamp the input into [-1, 1]: ACOS(LEAST(1, GREATEST(-1, x))), or ACOS(MAX(-1, MIN(1, x))) on SQLite. Computed cosine sums land just outside the domain often enough that this guard is standard practice."},{"question":"What is the domain of ATANH?","answer":"Strictly between -1 and 1; the endpoints correspond to infinity. At exactly 1 or -1, PostgreSQL and SQLite return Infinity or -Infinity rather than failing. Beyond them, PostgreSQL errors and SQLite returns NULL."}],"related":["asin","acos","acosh","atanh","nan-check"],"novel_uses":[{"body":"A clamp around ATAN(y / x) usually means the formula wanted ATAN2(y, x), which accepts every input pair and keeps the quadrant. Reaching for LEAST and GREATEST is often a sign the domain was avoidable.","sql":"SELECT DEGREES(ATAN2(dy, dx)) AS angle FROM vectors;  -- SQL Server: DEGREES(ATN2(dy, dx))"},{"body":"WHERE ABS(opposite) > ABS(hypotenuse) lists the rows whose ratio would blow up every downstream ASIN. Geometric feeds produce these on bad frames, and the filter names them before the report fails.","sql":"SELECT * FROM fits WHERE ABS(opposite) > ABS(hypotenuse);"}]},"source_url":"https://sqlly.app/sql-functions/inverse-trig-domain","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/is-null","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IS NULL predicate","description":"IS NULL and IS NOT NULL are the two-valued predicates that actually detect NULL: why x = NULL never works, tuple forms, and index use for sparse columns.","body":{"slug":"is-null","name":"IS NULL","h1":"SQL IS NULL predicate","category":"conditional","lede":"Tests for NULL directly, returning TRUE or FALSE and never UNKNOWN.","syntax":"x IS NULL | x IS NOT NULL | (a, b) IS NULL","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["x = NULL is UNKNOWN even when x is NULL; only IS NULL reports it.","For a single value, IS NULL is exactly NOT (x IS NOT NULL), and both are TRUE-or-FALSE, so they compose with NOT cleanly.","Row forms break that symmetry in PostgreSQL: (a, b) IS NULL is TRUE only when every field is NULL, and (a, b) IS NOT NULL is TRUE only when every field is non-NULL, so (1, NULL) fails both.","WHERE col IS NULL can use a plain B-tree index in PostgreSQL, SQL Server, MySQL and SQLite. Oracle B-tree indexes skip rows whose key columns are all NULL, so a single-column index cannot answer IS NULL; index (col, 0) instead."],"examples":[{"engine_slug":"all","sql":"SELECT * FROM users WHERE deleted_at IS NULL;"},{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE (a, b) IS NULL;"}],"faqs":[{"question":"Why does x = NULL fail?","answer":"Any comparison with NULL yields UNKNOWN, and WHERE keeps only TRUE; IS NULL is the predicate built for it."},{"question":"How is IS NULL different from ISNULL()?","answer":"IS NULL tests; ISNULL (SQL Server), IFNULL and NVL substitute a value for NULL. MySQL's ISNULL(x) is the exception: it tests, returning 1 or 0."},{"question":"What does (a, b) IS NULL check?","answer":"In PostgreSQL, that all fields are NULL. (a, b) IS NOT NULL checks that all fields are non-NULL, so the two are not complements: a half-NULL row fails both."}],"related":["null","distinct-from","nullif","coalesce","three-valued-logic"],"novel_uses":[{"body":"(email IS NOT NULL) puts a has-value boolean in the SELECT or a view in PostgreSQL, MySQL and SQLite, no stored column for the client to trust; SQL Server has no boolean select-list values, so spell it CASE WHEN email IS NOT NULL THEN 1 ELSE 0 END there.","sql":"SELECT id, (email IS NOT NULL) AS has_email FROM users;"},{"body":"Only PostgreSQL accepts the (a, b) IS NULL row form; MySQL, SQL Server and SQLite reject it, so spelling both columns keeps the same all-NULL check running on all five engines.","sql":"SELECT * FROM t WHERE a IS NULL AND b IS NULL;"}]},"source_url":"https://sqlly.app/sql-functions/is-null","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/is-true","corpus":"sql-functions","engine":null,"language":"en","title":"SQL IS TRUE predicate","description":"IS TRUE, IS FALSE and IS UNKNOWN handle NULL explicitly: PostgreSQL and MySQL have all three, SQLite lacks IS UNKNOWN; SQL Server and Oracle alternatives.","body":{"slug":"is-true","name":"IS TRUE","h1":"SQL IS TRUE predicate","category":"conditional","lede":"Tests a boolean expression explicitly, with a separate outcome for NULL.","syntax":"x IS TRUE | x IS NOT TRUE | x IS FALSE | x IS UNKNOWN","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"use col = 1"},{"engine_slug":"postgresql","status":"yes","note":"IS TRUE / IS NOT TRUE / IS FALSE / IS UNKNOWN"},{"engine_slug":"mysql","status":"yes","note":"IS TRUE / IS FALSE / IS UNKNOWN over 0/1 values; any nonzero number counts as true"},{"engine_slug":"sqlite","status":"yes","note":"IS TRUE / IS FALSE since 3.23; any nonzero number counts as true; no IS UNKNOWN, use IS NULL"},{"engine_slug":"oracle","status":"partial","note":"23ai+ IS TRUE / IS FALSE on BOOLEAN; older releases use col = 1"}],"gotchas":["IS TRUE is never UNKNOWN: it returns TRUE or FALSE, so x IS NOT TRUE catches both false and NULL, while NOT (x = TRUE) is still UNKNOWN for NULL and drops the row.","x IS NOT TRUE and x IS FALSE differ exactly on NULL rows; pick deliberately which one drops them.","MySQL and SQLite test truthiness, not equality to 1: 2 IS TRUE returns 1 even though 2 = TRUE is false.","On SQL Server and pre-23ai Oracle there is no predicate: write col = 1 for IS TRUE and (col <> 1 OR col IS NULL) for IS NOT TRUE."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE flag IS NOT TRUE;"},{"engine_slug":"mysql","sql":"SELECT * FROM t WHERE flag IS TRUE;"},{"engine_slug":"sqlite","sql":"SELECT * FROM t WHERE flag IS TRUE;"},{"engine_slug":"oracle","sql":"SELECT * FROM subscriptions WHERE verified IS NOT TRUE;"}],"faqs":[{"question":"IS NOT TRUE vs IS FALSE?","answer":"IS NOT TRUE matches FALSE and NULL; IS FALSE matches only FALSE. The difference is exactly the NULL rows."},{"question":"What do I use in SQL Server?","answer":"col = 1 for IS TRUE and (col <> 1 OR col IS NULL) for IS NOT TRUE, spelled out by hand."},{"question":"Does IS TRUE ever return UNKNOWN?","answer":"No, it is two-valued by definition; that is its whole purpose."}],"related":["boolean","three-valued-logic","is-null","xor"],"novel_uses":[{"body":"IS UNKNOWN matches exactly the NULL rows that both flag = 0 and flag = 1 miss, the audit query for MySQL 0/1 columns; PostgreSQL accepts it only on a boolean column, and SQLite has no IS UNKNOWN, so write verified IS NULL there.","sql":"SELECT * FROM accounts WHERE verified IS UNKNOWN;"},{"body":"TRUE, FALSE and NULL each get a label in one CASE, so a report never prints the third state as if it were off.","sql":"SELECT id, CASE WHEN flag IS TRUE THEN 'on' WHEN flag IS FALSE THEN 'off' ELSE 'unset' END FROM t;"}]},"source_url":"https://sqlly.app/sql-functions/is-true","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/isdate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ISDATE function","description":"SQL Server's ISDATE depends on DATEFORMAT and rejects datetime2 precision. Equivalents with pg_input_is_valid, STR_TO_DATE, date() and VALIDATE_CONVERSION.","body":{"slug":"isdate","name":"ISDATE","h1":"SQL ISDATE function","category":"conversion","lede":"ISDATE(s) returns 1 when s converts to datetime. The answer depends on session settings, which makes it a poor validator for imported data.","syntax":"ISDATE(expression)","return_type":"int (1 or 0)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"pg_input_is_valid(s, 'date') from 16"},{"engine_slug":"mysql","status":"partial","note":"STR_TO_DATE(s, format) IS NOT NULL"},{"engine_slug":"sqlite","status":"partial","note":"date(s) = s; date() alone moves 2026-02-30 to March"},{"engine_slug":"oracle","status":"partial","note":"VALIDATE_CONVERSION(s AS DATE, 'YYYY-MM-DD') from 12.2"}],"gotchas":["ISDATE reads the string with the session's DATEFORMAT and language: '13/01/2026' is 1 under SET DATEFORMAT dmy and 0 under mdy.","ISDATE tests against datetime, so more than three fractional digits fail: ISDATE('2026-01-01 10:00:00.1234567') is 0 although datetime2 accepts the value. TRY_CAST(s AS datetime2) IS NOT NULL avoids that.","ISDATE('2026') is 1: a four-digit year on its own is a valid datetime string.","SQLite's date() normalizes an out-of-range day instead of rejecting it: date('2026-02-30') returns 2026-03-02. Compare the result with the input to catch impossible dates."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ISDATE('2026-02-30') AS feb30, ISDATE('2026-02-28') AS feb28, ISDATE('2026') AS year_only;  -- 0, 1, 1"},{"engine_slug":"postgresql","sql":"SELECT pg_input_is_valid('2026-02-30', 'date') AS feb30, pg_input_is_valid('2026-02-28', 'date') AS feb28;  -- f, t"},{"engine_slug":"sqlite","sql":"SELECT date('2026-02-30') AS normalized, date('2026-02-30') = '2026-02-30' AS is_valid;  -- 2026-03-02, 0"},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('2026-02-30', '%Y-%m-%d') AS feb30, STR_TO_DATE('2026-02-28', '%Y-%m-%d') AS feb28;  -- NULL, 2026-02-28"},{"engine_slug":"oracle","sql":"SELECT VALIDATE_CONVERSION('2026-02-30' AS DATE, 'YYYY-MM-DD') AS feb30,\n       VALIDATE_CONVERSION('2026-02-28' AS DATE, 'YYYY-MM-DD') AS feb28 FROM dual;  -- 0, 1"}],"faqs":[{"question":"ISDATE or TRY_CAST?","answer":"TRY_CAST, or TRY_CONVERT with an explicit style. ISDATE only knows datetime and depends on session settings; TRY_CONVERT(date, s, 23) reads numeric dates as year-month-day whatever DATEFORMAT says, but it still accepts unambiguous forms such as 'Feb 28 2026' and '20260228', so add s LIKE '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' when only yyyy-mm-dd is allowed."},{"question":"How do I find the bad date strings in a column?","answer":"SELECT raw FROM staging WHERE raw IS NOT NULL AND TRY_CONVERT(date, raw, 23) IS NULL on SQL Server; on PostgreSQL 16+ use NOT pg_input_is_valid(raw, 'date')."}],"related":["isnumeric","try-cast","to-date","str-to-date"],"novel_uses":[{"body":"MySQL's ALLOW_INVALID_DATES sql_mode accepts any day from 1 to 31, so the same STR_TO_DATE check that rejects 2026-02-30 in a normal session passes it when that mode is on. A validator built on STR_TO_DATE must pin the sql_mode, not assume it.","sql":"SELECT STR_TO_DATE('2026-02-30', '%Y-%m-%d') AS normal;  -- NULL\nSET sql_mode = 'ALLOW_INVALID_DATES';\nSELECT STR_TO_DATE('2026-02-30', '%Y-%m-%d') AS loose;  -- 2026-02-30"},{"body":"Oracle's CAST(s AS DATE DEFAULT NULL ON CONVERSION ERROR), from 12.2, returns the date or NULL in one expression and reads the same session NLS settings as VALIDATE_CONVERSION. One pass instead of validate-then-cast, and the bad values fall out as NULL for a NOT NULL insert to catch.","sql":"SELECT CAST('2026-02-30' AS DATE DEFAULT NULL ON CONVERSION ERROR) AS feb30,\n       CAST('2026-02-28' AS DATE DEFAULT NULL ON CONVERSION ERROR) AS feb28\nFROM dual;  -- NULL, 2026-02-28"}]},"source_url":"https://sqlly.app/sql-functions/isdate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/isnull","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ISNULL function","description":"ISNULL(expr, replacement) on SQL Server: two arguments only, result typed by the first argument, the one-argument MySQL ISNULL(expr) predicate, COALESCE differences.","body":{"slug":"isnull","name":"ISNULL","h1":"SQL ISNULL function","category":"conditional","lede":"SQL Server's two-argument NULL substitution, typed by its first argument.","syntax":"ISNULL(col, 0) | ISNULL(name, 'unknown')","return_type":"same as first argument","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"no ISNULL function; x ISNULL is a nonstandard postfix spelling of x IS NULL"},{"engine_slug":"mysql","status":"no","note":"MySQL's ISNULL(expr) takes one argument and returns 1 or 0"},{"engine_slug":"sqlite","status":"no","note":"no ISNULL function; x ISNULL is a postfix spelling of x IS NULL"},{"engine_slug":"oracle","status":"no","note":"use NVL"}],"gotchas":["The result type is the first argument's type: ISNULL(smallint_col, 50000) raises error 220 (arithmetic overflow for smallint) where COALESCE(smallint_col, 50000) widens to int. With strings it truncates instead: ISNULL(CAST(NULL AS varchar(3)), 'unknown') returns 'unk'.","It takes exactly two arguments; COALESCE chains any number and is the standard.","In MySQL the same name is a one-argument predicate returning 1 or 0: same word, different language."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ISNULL(discount, 0) FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT ISNULL(CAST(NULL AS SMALLINT), 32767) AS fits, ISNULL(CAST(NULL AS SMALLINT), 50000) AS overflows;\n-- the second column raises error 220, so the statement fails"}],"faqs":[{"question":"ISNULL vs COALESCE on SQL Server?","answer":"ISNULL is typed by the first argument and takes two; COALESCE is standard, multi-argument and picks the highest-precedence type. Prefer COALESCE for new code."},{"question":"What is ISNULL in MySQL?","answer":"A predicate: ISNULL(expr) returns 1 when expr is NULL, else 0."},{"question":"Does Oracle have ISNULL?","answer":"No, it is NVL."}],"related":["coalesce","nvl","ifnull","nullif","case"],"novel_uses":[{"body":"T-SQL has no NULLS FIRST or LAST, so ORDER BY ISNULL(end_date, '9999-12-31') pins open-ended contracts to the bottom of an ascending list.","sql":"SELECT contract_id FROM contracts ORDER BY ISNULL(end_date, '9999-12-31');"},{"body":"SUM(ISNULL(flag, 0)) reads a group of all-NULL flags as 0 where a bare SUM would return NULL and leak into client code.","sql":"SELECT dept, SUM(ISNULL(bonus_flag, 0)) FROM employees GROUP BY dept;"},{"body":"Wrapping each optional part keeps a missing middle initial from erasing the whole concatenated name.","sql":"SELECT first_name + ' ' + ISNULL(middle_initial, '') + ' ' + last_name FROM employees;"}]},"source_url":"https://sqlly.app/sql-functions/isnull","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/isnumeric","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ISNUMERIC function","description":"SQL Server's ISNUMERIC says yes to '$', '12,3' and a tab character. Safer checks with TRY_CAST, pg_input_is_valid, REGEXP and VALIDATE_CONVERSION.","body":{"slug":"isnumeric","name":"ISNUMERIC","h1":"SQL ISNUMERIC function","category":"conversion","lede":"ISNUMERIC(s) returns 1 when s converts to any numeric type, money and float included. That is rarely the question you meant to ask.","syntax":"ISNUMERIC(expression)","return_type":"int (1 or 0)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"pg_input_is_valid(s, 'numeric') from 16; a regex before that"},{"engine_slug":"mysql","status":"partial","note":"no function; s REGEXP '^-?[0-9]+([.][0-9]+)?$'"},{"engine_slug":"sqlite","status":"partial","note":"no function; GLOB, or typeof() after storing into a NUMERIC column"},{"engine_slug":"oracle","status":"partial","note":"VALIDATE_CONVERSION(s AS NUMBER) from 12.2"}],"gotchas":["ISNUMERIC returns 1 for strings that do not convert to int or decimal: '$', '.', '-', '12,3' and CHAR(9) all give 1, because money or float accepts them. TRY_CAST(s AS DECIMAL(18, 4)) IS NOT NULL is the check most code needs.","ISNUMERIC('') is 0, but TRY_CAST('' AS INT) is 0, not NULL: an empty string converts to integer zero on SQL Server. Cast to DECIMAL to get NULL.","PostgreSQL's pg_input_is_valid ignores surrounding blanks: ' 7 ' is a valid integer.","Oracle's VALIDATE_CONVERSION reads the decimal separator from NLS_NUMERIC_CHARACTERS, so '12.5' can fail in a session set to a comma decimal."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ISNUMERIC('$') AS dollar, ISNUMERIC('12,3') AS comma, TRY_CAST('12,3' AS DECIMAL(10, 2)) AS as_decimal;  -- 1, 1, NULL"},{"engine_slug":"postgresql","sql":"SELECT pg_input_is_valid('12.5', 'numeric') AS a, pg_input_is_valid('12,3', 'numeric') AS b;  -- t, f"},{"engine_slug":"mysql","sql":"SELECT '12.5' REGEXP '^-?[0-9]+([.][0-9]+)?$' AS a, '12.5e3' REGEXP '^-?[0-9]+([.][0-9]+)?$' AS b;  -- 1, 0"},{"engine_slug":"oracle","sql":"SELECT VALIDATE_CONVERSION('12.5' AS NUMBER) AS a, VALIDATE_CONVERSION('12,5x' AS NUMBER) AS b FROM dual;  -- 1, 0"},{"engine_slug":"sqlite","sql":"SELECT CAST('12.5' AS REAL) = '12.5' AS a, CAST('abc' AS REAL) = 'abc' AS b;  -- 1, 0, a CAST that cannot fail"}],"faqs":[{"question":"Why does ISNUMERIC return 1 but CAST fails?","answer":"ISNUMERIC accepts anything some numeric type accepts. '$' is a valid money value and '1d2' a valid float, yet CAST('$' AS INT) fails. Test with TRY_CAST to the type you are converting to."},{"question":"Is there TRY_CAST in PostgreSQL?","answer":"No. From PostgreSQL 16 use CASE WHEN pg_input_is_valid(s, 'numeric') THEN s::numeric END; on older versions match a regex first."}],"related":["try-cast","isdate","cast-to-int","regexp-like"],"novel_uses":[{"body":"MySQL's CAST(' 12 ' AS SIGNED) trims surrounding spaces and succeeds, while the anchored REGEXP from this page rejects ' 12 '. Decide which behavior the loader wants: padded input that the cast accepts is exactly what a strict regex check exists to catch.","sql":"SELECT CAST(' 12 ' AS SIGNED) AS cast_ok,\n       ' 12 ' REGEXP '^-?[0-9]+([.][0-9]+)?$' AS regex_strict;  -- 12, 0"},{"body":"SQLite's CAST never raises: CAST('abc' AS INTEGER) is 0 and CAST('12abc' AS INTEGER) is 12, so a loader that leans on CAST for validation accepts everything. typeof() after storage, or the GLOB check, is what actually rejects bad rows.","sql":"SELECT CAST('abc' AS INTEGER) AS a, CAST('12abc' AS INTEGER) AS b;  -- 0, 12"}]},"source_url":"https://sqlly.app/sql-functions/isnumeric","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/iso-8601-format","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ISO 8601 date format","description":"Producing ISO 8601 ('2026-08-01T14:30:00') from every engine: CONVERT 126, to_char with the literal T, %Y-%m-%dT%H:%M:%S and Oracle's quote tricks.","body":{"slug":"iso-8601-format","name":"ISO 8601 output","h1":"SQL ISO 8601 date format","category":"datetime","lede":"ISO 8601 output is the interchange-safe shape for timestamps: unambiguous, sortable, and one quoted mask character away on PostgreSQL and Oracle; MySQL and SQLite take the bare T.","syntax":"TO_CHAR(d, 'YYYY-MM-DD\"T\"HH24:MI:SS')","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":"CONVERT(varchar, d, 126): ISO 8601 natively"},{"engine_slug":"postgresql","status":"yes","note":"to_char(d, 'YYYY-MM-DD\"T\"HH24:MI:SS')"},{"engine_slug":"mysql","status":"yes","note":"DATE_FORMAT(d, '%Y-%m-%dT%H:%i:%s')"},{"engine_slug":"sqlite","status":"yes","note":"strftime('%Y-%m-%dT%H:%M:%S', d)"},{"engine_slug":"oracle","status":"yes","note":"TO_CHAR(d, 'YYYY-MM-DD\"T\"HH24:MI:SS')"}],"gotchas":["Literal characters inside format masks need quoting: the T in PostgreSQL and Oracle is \"T\" (double quotes), MySQL and SQLite splice it straight in.","Offsets are engine-specific: SQL Server style 126 on a datetimeoffset keeps its offset (+02:00) and style 127 converts to UTC with a trailing Z; PostgreSQL's to_char has OF (+02) and TZH:TZM; MySQL has no offset code, so append it yourself.","MySQL's STR_TO_DATE parses the shape back with '%Y-%m-%dT%H:%i:%s', and SQL Server's style 126 parses it in CONVERT; keep output and parse styles symmetric."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(30), CAST('2026-08-01 14:30:00 +02:00' AS datetimeoffset), 127);  -- 2026-08-01T12:30:00Z"},{"engine_slug":"postgresql","sql":"SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"');"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%dT%H:%M:%SZ', 'now');"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT('2026-08-01 14:30:00', '%Y-%m-%dT%H:%i:%s');  -- 2026-08-01T14:30:00"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(CAST('2026-08-01 14:30:00' AS TIMESTAMP), 'YYYY-MM-DD\"T\"HH24:MI:SS') FROM dual;  -- 2026-08-01T14:30:00"}],"faqs":[{"question":"Should I store ISO strings instead of timestamps?","answer":"No. Store a real timestamp type and format on the way out. ISO text storage loses type-enforced range checks and needs a cast before date arithmetic."},{"question":"Why does my 'T' come out wrong?","answer":"In PostgreSQL masks, T followed by H is read as the TH ordinal-suffix code, so 'YYYY-MM-DDTHH24:MI:SS' prints a literal HH24 (2026-08-15THH24:37:12). Quote the T: 'YYYY-MM-DD\"T\"HH24:MI:SS'."}],"related":["convert-style","date-format-codes","to-char","date-to-text"],"novel_uses":[{"body":"PostgreSQL's MS template adds milliseconds between the seconds and the Z suffix, for log shapes that JavaScript's Date constructor parses directly.","sql":"SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"');"},{"body":"Fixed-width ISO strings sort chronologically as text, so SQLite tables need no date type for ORDER BY or index-ordered time scans.","sql":"SELECT * FROM events ORDER BY created_at;  -- ISO text sorts by time"}]},"source_url":"https://sqlly.app/sql-functions/iso-8601-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-agg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_AGG function","description":"PostgreSQL's json_agg and jsonb_agg collect a group's rows into a JSON array; JSON_ARRAYAGG (also PostgreSQL 16+) and json_group_array do it on the other engines.","body":{"slug":"json-agg","name":"JSON_AGG","h1":"SQL JSON_AGG function","category":"string","lede":"jsonb_agg(name) turns a column's values into one JSON array per group, and jsonb_agg(jsonb_build_object(...)) turns rows into an array of objects.","syntax":"JSON_AGG(expression)  |  jsonb_agg(expression [ORDER BY ...])","return_type":"JSON array or jsonb","support":[{"engine_slug":"sql-server","status":"partial","note":"JSON_ARRAYAGG on SQL Server 2025; FOR JSON subqueries before"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"JSON_ARRAYAGG (5.7.22+)"},{"engine_slug":"sqlite","status":"partial","note":"json_group_array"},{"engine_slug":"oracle","status":"partial","note":"JSON_ARRAYAGG (12.2+)"}],"gotchas":["jsonb_agg neither sorts nor removes duplicates. Element order is whatever order rows arrive in, unless you write ORDER BY inside the call: jsonb_agg(name ORDER BY name).","An empty input set gives SQL NULL, not '[]': COALESCE(jsonb_agg(x), '[]'::jsonb) when the empty case must be an array.","SQL Server gained JSON_ARRAYAGG in SQL Server 2025. Earlier versions build per-group arrays with a correlated subquery and FOR JSON PATH."],"examples":[{"engine_slug":"postgresql","sql":"SELECT region, jsonb_agg(name ORDER BY name) AS names\nFROM users GROUP BY region;"},{"engine_slug":"sqlite","sql":"SELECT region, json_group_array(name) AS names\nFROM users GROUP BY region;"},{"engine_slug":"mysql","sql":"SELECT region, JSON_ARRAYAGG(name) AS names\nFROM users GROUP BY region;"},{"engine_slug":"sql-server","sql":"SELECT region, JSON_ARRAYAGG(name) AS names\nFROM users GROUP BY region;  -- 2025"},{"engine_slug":"oracle","sql":"SELECT region, JSON_ARRAYAGG(name) AS names\nFROM users GROUP BY region;"}],"faqs":[{"question":"Array of scalars or of objects?","answer":"Both: jsonb_agg(name) for scalars, jsonb_agg(jsonb_build_object('name', name, 'id', id)) for objects. The build-function-inside-aggregate pattern covers most document needs."},{"question":"Why is my array unordered?","answer":"Without ORDER BY inside the call, element order is input order, which no plan guarantees. An ORDER BY on the outer query sorts groups, not the elements inside each array."}],"related":["json-objectagg","json-array","json-group-array","array-agg"],"novel_uses":[{"body":"jsonb_agg(DISTINCT name ORDER BY name) collapses repeated values and orders the array in one pass, with no outer SELECT DISTINCT and no application sort.","sql":"SELECT region, jsonb_agg(DISTINCT name ORDER BY name) AS names FROM users GROUP BY region;"},{"body":"jsonb_agg(to_jsonb(u) ORDER BY u.id) turns each row into an object with every column, so adding a column to the table extends the payload with no query change.","sql":"SELECT jsonb_agg(to_jsonb(u) ORDER BY u.id) AS team FROM users u WHERE u.region = 'eu';"}]},"source_url":"https://sqlly.app/sql-functions/json-agg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-array","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_ARRAY function","description":"JSON_ARRAY builds a JSON array from its arguments on SQL Server 2022+, PostgreSQL 16+, MySQL, SQLite and Oracle, and the engines disagree on keeping NULLs.","body":{"slug":"json-array","name":"JSON_ARRAY","h1":"SQL JSON_ARRAY function","category":"string","lede":"JSON_ARRAY(1, 'abc', NULL) is [1, \"abc\", null] on MySQL and SQLite but [1, \"abc\"] on SQL Server, Oracle and PostgreSQL, which drop NULLs unless told otherwise.","syntax":"JSON_ARRAY(value [, value ...] [NULL ON NULL | ABSENT ON NULL])","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+"},{"engine_slug":"postgresql","status":"yes","note":"JSON_ARRAY constructor on 16+; jsonb_build_array earlier"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":"12.2+"}],"gotchas":["NULL handling follows the standard on SQL Server, Oracle and PostgreSQL: ABSENT ON NULL is the default, so NULLs vanish. Add NULL ON NULL to keep them. MySQL and SQLite always keep them as null.","Arguments come from one row. Nest constructors freely, JSON_ARRAY(1, JSON_OBJECT(...)), but collecting values across rows takes an aggregate: JSON_ARRAYAGG, json_agg or json_group_array.","The result type differs: JSON on MySQL, json on PostgreSQL (jsonb with RETURNING jsonb), nvarchar on SQL Server, text on SQLite, VARCHAR2 on Oracle."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_ARRAY(1, 'abc', NULL) AS arr;"},{"engine_slug":"sqlite","sql":"SELECT json_array(1, 2, 3) AS arr;"},{"engine_slug":"sql-server","sql":"SELECT JSON_ARRAY(city, country) AS dest\nFROM trips;"},{"engine_slug":"postgresql","sql":"SELECT JSON_ARRAY(1, 'abc', NULL) AS arr;"},{"engine_slug":"oracle","sql":"SELECT JSON_ARRAY(1, 'abc', NULL) AS arr FROM dual;"}],"faqs":[{"question":"How do I build an array from multiple rows?","answer":"Aggregate instead of construct: JSON_ARRAYAGG (MySQL, Oracle, PostgreSQL 16+, SQL Server 2025), json_agg/jsonb_agg (PostgreSQL), json_group_array (SQLite), FOR JSON on older SQL Server. JSON_ARRAY only wraps the values you hand it."},{"question":"Why did my NULLs disappear?","answer":"SQL Server, Oracle and PostgreSQL default to ABSENT ON NULL. Write JSON_ARRAY(a, b NULL ON NULL) to keep them. On MySQL and SQLite NULLs are always kept and there is no ABSENT ON NULL, so substitute a default with COALESCE or leave the argument out of the call when it is NULL."}],"related":["json-object","json-agg","json-objectagg","to-json"],"novel_uses":[{"body":"When the client reads point[0] as latitude and point[1] as longitude, the default ABSENT ON NULL drops a NULL latitude and shifts the longitude into slot 0, so [-77.04] silently reads as a latitude. NULL ON NULL keeps a null placeholder in the slot: [null, -77.04].","sql":"SELECT JSON_ARRAY(lat, lon NULL ON NULL) AS point FROM stops;"},{"body":"A string argument is stored as a string: JSON_ARRAY('{\"x\":1}') nests escaped text. Cast the argument to JSON first and the value lands as a real nested object.","sql":"SELECT JSON_ARRAY(CAST('{\"x\": 1}' AS JSON), 2) AS doc;"}]},"source_url":"https://sqlly.app/sql-functions/json-array","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-array-elements","corpus":"sql-functions","engine":null,"language":"en","title":"SQL json_array_elements function","description":"PostgreSQL's json(b)_array_elements turns a JSON array into one row per element, usually joined laterally to the table that holds the array.","body":{"slug":"json-array-elements","name":"json_array_elements","h1":"SQL json_array_elements function","category":"string","lede":"FROM jsonb_array_elements(items) gives one row per array element. It is UNNEST for JSON arrays, and jsonb_array_elements_text returns the elements as text.","syntax":"json_array_elements(json)  |  jsonb_array_elements(jsonb)","return_type":"setof json or jsonb","support":[{"engine_slug":"sql-server","status":"no","note":"OPENJSON covers it"},{"engine_slug":"postgresql","status":"yes","note":"both json and jsonb variants"},{"engine_slug":"mysql","status":"no","note":"JSON_TABLE covers it"},{"engine_slug":"sqlite","status":"partial","note":"json_each covers it"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Elements come back as JSON, so strings keep their quotes: '[\"a\"]' yields \"a\". Use jsonb_array_elements_text when you want plain text values.","Calling jsonb_array_elements on something that is not an array raises 'cannot extract elements from an object' (or from a scalar); json_array_elements raises 'cannot call json_array_elements on a non-array' (or on a scalar). Guard with jsonb_typeof(x) = 'array' (json_typeof for json) when documents vary.","Correlated per-row arrays are the common shape: FROM orders o, jsonb_array_elements(o.items) je; each order's items join back to the order."],"examples":[{"engine_slug":"postgresql","sql":"SELECT je.value\nFROM orders o, jsonb_array_elements(o.items) je;"},{"engine_slug":"postgresql","sql":"SELECT je.value->>'sku' AS sku,\n       (je.value->>'qty')::int AS qty\nFROM orders o, jsonb_array_elements(o.items) je;"},{"engine_slug":"sqlite","sql":"SELECT je.value\nFROM orders o, json_each(o.items) je;"}],"faqs":[{"question":"How do I join parent rows to array elements?","answer":"Comma or LATERAL join from the parent table: FROM orders o, jsonb_array_elements(o.items) je. Every parent row multiplies by its array length, including zero, which drops empty arrays from the result."},{"question":"Where is the element index?","answer":"There is none on this function: use jsonb_array_elements WITH ORDINALITY AS je(value, pos) to add positions, the same pattern as unnest."}],"related":["json-each","unnest","json-table","openjson"],"novel_uses":[{"body":"jsonb_array_elements_text feeds a join: each array element looks up its row in a real table, turning a denormalized tag list into proper foreign keys in one query.","sql":"SELECT a.id, g.id AS tag_id FROM articles a, jsonb_array_elements_text(a.tag_names) t JOIN tags g ON g.name = t;"},{"body":"A LIMIT inside a LATERAL over the elements caps each parent's contribution, so one query returns the top two items of every order instead of every item everywhere.","sql":"SELECT o.id, je.value->>'sku' AS sku FROM orders o, LATERAL (SELECT * FROM jsonb_array_elements(o.items) LIMIT 2) je;"}]},"source_url":"https://sqlly.app/sql-functions/json-array-elements","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-arrayagg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_ARRAYAGG function","description":"JSON_ARRAYAGG builds a JSON array per group: MySQL, Oracle, PostgreSQL 16+ and SQL Server 2025 support, SQLite's json_group_array, and the split NULL defaults.","body":{"slug":"json-arrayagg","name":"JSON_ARRAYAGG","h1":"SQL JSON_ARRAYAGG function","category":"aggregate","lede":"Aggregates the rows of a group into one JSON array value.","syntax":"JSON_ARRAYAGG(col) | JSON_ARRAYAGG(col ORDER BY col)","return_type":"json","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 / Azure SQL; earlier versions build arrays with FOR JSON PATH"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 16+; json_agg and jsonb_agg work on every version"},{"engine_slug":"mysql","status":"yes","note":"no ORDER BY inside the aggregate"},{"engine_slug":"sqlite","status":"no","note":"use json_group_array"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without ORDER BY the array order is undefined. SQL Server 2025, PostgreSQL and Oracle accept JSON_ARRAYAGG(x ORDER BY x); MySQL rejects it with a syntax error, so the order is not guaranteed, and ordering a derived table first did not reliably order the result in our MySQL 8.4 run.","NULL defaults split: the standard form drops NULLs (ABSENT ON NULL) in Oracle, SQL Server and PostgreSQL's JSON_ARRAYAGG, while MySQL's JSON_ARRAYAGG and PostgreSQL's json_agg keep them as JSON null. Write NULL ON NULL or ABSENT ON NULL where the engine accepts it.","To collect key/value rows into an object instead, you want JSON_OBJECTAGG."],"examples":[{"engine_slug":"mysql","sql":"SELECT dept_id, JSON_ARRAYAGG(name) FROM employees GROUP BY dept_id;"},{"engine_slug":"oracle","sql":"SELECT JSON_ARRAYAGG(name ORDER BY name NULL ON NULL) FROM employees;"},{"engine_slug":"postgresql","sql":"SELECT dept_id, jsonb_agg(name ORDER BY name) FROM employees GROUP BY dept_id;"},{"engine_slug":"sql-server","sql":"SELECT JSON_ARRAYAGG(name ORDER BY name) FROM employees;  -- SQL Server 2025 / Azure SQL"}],"faqs":[{"question":"What is JSON_ARRAYAGG in PostgreSQL?","answer":"PostgreSQL 16 added JSON_ARRAYAGG itself. On any version, json_agg and jsonb_agg do the same job; they keep NULLs as JSON null, while JSON_ARRAYAGG drops them by default."},{"question":"Does JSON_ARRAYAGG include NULL values?","answer":"Engine-dependent: MySQL includes them as JSON null; Oracle, SQL Server and PostgreSQL's JSON_ARRAYAGG omit them unless you write NULL ON NULL."},{"question":"How do I order the array elements?","answer":"Put ORDER BY inside the aggregate on SQL Server 2025, PostgreSQL, Oracle and SQLite 3.44+ (json_group_array). MySQL has no supported way to order JSON_ARRAYAGG."}],"related":["json-objectagg","json-group-array","array-agg","group-concat"],"novel_uses":[{"body":"jsonb_agg over a LEFT JOIN with no children returns [null], not NULL, because the outer row still feeds one NULL into the aggregate. FILTER drops those rows, and COALESCE turns the empty case into an empty array.","sql":"SELECT c.id, COALESCE(jsonb_agg(o.total) FILTER (WHERE o.id IS NOT NULL), '[]'::jsonb) AS totals FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.id;"},{"body":"DISTINCT works inside the aggregate: json_agg(DISTINCT tag ORDER BY tag) collapses repeats on the way in.","sql":"SELECT post_id, json_agg(DISTINCT tag ORDER BY tag) FROM post_tags GROUP BY post_id;"},{"body":"A correlated FOR JSON PATH subquery builds the per-parent array on any SQL Server release with FOR JSON. Each element is an object named after the column, such as [{\"total\":5.00}], and the order holds only with ORDER BY inside the subquery; a parent with no rows gets NULL.","sql":"SELECT c.id, COALESCE((SELECT o.total FROM orders o WHERE o.customer_id = c.id ORDER BY o.id FOR JSON PATH), '[]') AS totals FROM customers c;"}]},"source_url":"https://sqlly.app/sql-functions/json-arrayagg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-contains","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_CONTAINS function","description":"MySQL's JSON_CONTAINS tests whether one JSON value sits inside another, with JSON_CONTAINS_PATH for key existence and json_each-based checks on SQLite.","body":{"slug":"json-contains","name":"JSON_CONTAINS","h1":"SQL JSON_CONTAINS function","category":"string","lede":"JSON_CONTAINS(config->'$.tags', '\"pro\"') asks whether the value pro is among the tags. The candidate must itself be JSON, quoting included.","syntax":"JSON_CONTAINS(target, candidate [, path])","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"the @> containment operator on jsonb"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no JSON_CONTAINS; EXISTS over json_each"},{"engine_slug":"oracle","status":"partial","note":"JSON_EXISTS condition covers the key case"}],"gotchas":["The candidate is JSON, not a literal: to find the string pro you search for '\"pro\"'; the double quotes are part of the value being matched.","Key existence is a different function: JSON_CONTAINS_PATH(doc, 'one' | 'all', '$.region'), the counterpart of PostgreSQL's ?, ?| and ?& operators ('one' over several paths is ?|, 'all' is ?&).","Large documents scan linearly without help: a MySQL multi-valued index over the array or a PostgreSQL GIN index on the jsonb column is what makes this fast at scale."],"examples":[{"engine_slug":"mysql","sql":"SELECT * FROM settings\nWHERE JSON_CONTAINS(config->'$.tags', '\"pro\"');"},{"engine_slug":"mysql","sql":"SELECT * FROM settings\nWHERE JSON_CONTAINS_PATH(config, 'one', '$.region');"},{"engine_slug":"sqlite","sql":"SELECT * FROM settings WHERE EXISTS\n  (SELECT 1 FROM json_each(config, '$.tags')\n   WHERE value = 'pro');"},{"engine_slug":"postgresql","sql":"SELECT * FROM settings\nWHERE config->'tags' @> '[\"pro\"]';"},{"engine_slug":"oracle","sql":"SELECT * FROM settings\nWHERE JSON_EXISTS(config, '$.tags[*]?(@ == \"pro\")');"}],"faqs":[{"question":"How do I check whether a key exists?","answer":"JSON_CONTAINS_PATH(config, 'one', '$.region') on MySQL, config ? 'region' on PostgreSQL jsonb, JSON_EXISTS on Oracle. JSON_CONTAINS is for values, not keys."},{"question":"Why does my search for pro raise Invalid JSON text?","answer":"You passed the SQL text pro, not the JSON string '\"pro\"', and MySQL rejects it with error 3141 (Invalid JSON text in argument 2). JSON_CONTAINS compares JSON to JSON; quote string candidates."}],"related":["jsonb-contains","jsonb-exists","json-type","json-extract"],"novel_uses":[{"body":"A multi-valued index over the cast array (MySQL 8.0.17+) turns JSON_CONTAINS into a range scan instead of a parse per row. MEMBER OF probes use the same index.","sql":"CREATE INDEX ix_tags ON settings ((CAST(config->'$.tags' AS CHAR(32) ARRAY)));"},{"body":"'pro' MEMBER OF (config->'$.tags') asks the same question with the scalar on the left, no quoting gymnastics, and it is index-eligible through a multi-valued index. It reads like a set test because it is one.","sql":"SELECT id FROM settings WHERE 'pro' MEMBER OF (config->'$.tags');"}]},"source_url":"https://sqlly.app/sql-functions/json-contains","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-depth","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_DEPTH function","description":"MySQL's JSON_DEPTH returns how many levels a document nests: 1 for scalars and empty containers, plus 1 for each level of non-empty nesting. No other engine has it.","body":{"slug":"json-depth","name":"JSON_DEPTH","h1":"SQL JSON_DEPTH function","category":"string","lede":"JSON_DEPTH('[[1]]') is 3. It is a quick way to flag documents that nest deeper than your queries or indexes expect.","syntax":"JSON_DEPTH(json_doc)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"no equivalent"},{"engine_slug":"postgresql","status":"no","note":"no equivalent; a recursive CTE over jsonb_each and jsonb_array_elements can compute it"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no json_depth; json_tree's fullkey paths show the nesting"},{"engine_slug":"oracle","status":"no","note":"no equivalent"}],"gotchas":["A scalar, an empty array and an empty object all have depth 1. A non-empty array or object adds 1 to the deepest thing it contains: '[1]' is 2, '[[1]]' is 3.","There is no path argument: depth is for the whole value. Pass JSON_EXTRACT(doc, '$.items') to measure a subtree.","MySQL rejects JSON nested more than 100 arrays or objects deep (error 3157, \"exceeds the maximum depth\"), so a stored or parsed document tops out at JSON_DEPTH 101: 100 containers plus a scalar leaf."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_DEPTH(config) AS levels FROM settings;"},{"engine_slug":"mysql","sql":"SELECT JSON_DEPTH('{}') AS empty_obj, JSON_DEPTH('[[1]]') AS nested;  -- 1, 3"}],"faqs":[{"question":"Why is {} depth 1 but {\"a\": 1} depth 2?","answer":"Empty containers count as one level, like scalars. A container only adds a level when it holds something, so {\"a\": 1} is 2 and {\"a\": {\"b\": 1}} is 3."},{"question":"How do I measure depth on SQLite?","answer":"Walk the tree: json_tree returns one row per node with its fullkey path, such as $.a.b[0]. Counting the path separators in the longest fullkey and adding 1 gives JSON_DEPTH's number, as long as no key contains a dot or bracket (those keys are quoted, as in $.\"a.b\", and inflate the count)."}],"related":["json-length","json-type","json-each","json-valid"],"novel_uses":[{"body":"Documents deeper than your queries expect break shredding and inflate storage: WHERE JSON_DEPTH(config) > 5 lists the outliers so they can be flattened before something downstream chokes.","sql":"SELECT id, JSON_DEPTH(config) AS levels FROM settings WHERE JSON_DEPTH(config) > 5;"},{"body":"GROUP BY JSON_DEPTH(config) shows the whole table's nesting profile in one query. A producer change that starts wrapping payloads shows up immediately as a new deeper bucket.","sql":"SELECT JSON_DEPTH(config) AS levels, COUNT(*) AS docs FROM settings GROUP BY levels ORDER BY levels;"}]},"source_url":"https://sqlly.app/sql-functions/json-depth","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-each","corpus":"sql-functions","engine":null,"language":"en","title":"SQL json_each function","description":"SQLite's json_each is a table-valued walk over any JSON value: one row per element or member, with json_tree for the whole depth-first subtree.","body":{"slug":"json-each","name":"json_each","h1":"SQL json_each function","category":"string","lede":"FROM json_each(config) gives one row per member or element, with key, value, type and path columns. Joined to a table, it is how SQLite unnests JSON arrays and objects.","syntax":"json_each(json [, path])  |  json_tree(json [, path])","return_type":"rowset","support":[{"engine_slug":"sql-server","status":"no","note":"OPENJSON covers it"},{"engine_slug":"postgresql","status":"partial","note":"json_each / jsonb_each for objects, jsonb_array_elements for arrays"},{"engine_slug":"mysql","status":"no","note":"JSON_TABLE covers it"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"JSON_TABLE covers it"}],"gotchas":["json_each walks one level: members of an object or elements of an array. Nested structure arrives as whole JSON values; json_tree recurses the whole subtree with fullkey paths.","The columns are key, value, type, atom, id, parent, fullkey and path; join it against the source table with a comma (cross join) or an explicit JOIN for correlation.","PostgreSQL's jsonb_each works on objects only and errors on an array; arrays need jsonb_array_elements. SQLite's json_each takes either."],"examples":[{"engine_slug":"sqlite","sql":"SELECT key, value FROM json_each('{\"a\": 1, \"b\": 2}');"},{"engine_slug":"sqlite","sql":"SELECT je.key, je.value\nFROM settings s, json_each(s.config) je;"},{"engine_slug":"sqlite","sql":"SELECT jt.fullkey, jt.value\nFROM events e, json_tree(e.payload) jt;"},{"engine_slug":"postgresql","sql":"SELECT key, value FROM json_each_text('{\"a\": 1, \"b\": 2}');"}],"faqs":[{"question":"How do I count JSON array items per row?","answer":"Join and group: SELECT o.id, count(je.key) FROM orders o LEFT JOIN json_each(o.items) je GROUP BY o.id. One row per element makes counting a plain aggregate; the LEFT JOIN keeps rows whose array is empty as 0, which a comma join drops. json_array_length(o.items) gives the same number without the join."},{"question":"json_each or json_tree?","answer":"json_each for the top level of an array or object; json_tree when you need every nested value with its path. Tree output includes each container too, not just leaves."}],"related":["json-group-array","json-table","json-array-elements","json-length"],"novel_uses":[{"body":"json_each unnests the array, so max(value), sum(value) and avg(value) work straight over a JSON array with the ordinary aggregates. Add type IN ('integer', 'real') to skip text and nested elements; text sorts above every number, so one stray string would win max().","sql":"SELECT max(je.value) AS top_score FROM profiles p, json_each(p.stats, '$.scores') je WHERE je.type IN ('integer', 'real');"},{"body":"Pair json_each with json_group_array and the SELECT list becomes a per-element expression: one statement doubles every score or renames fields, no procedural code.","sql":"SELECT json_group_array(value * 2) FROM json_each('{\"scores\": [1, 2, 3]}', '$.scores');"},{"body":"SELECT DISTINCT fullkey, type across json_tree of many documents is the de facto schema census: it lists every path any document ever used, plus the type each path carries.","sql":"SELECT DISTINCT jt.fullkey, jt.type FROM events e, json_tree(e.payload) jt ORDER BY jt.fullkey;"}]},"source_url":"https://sqlly.app/sql-functions/json-each","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-exists","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_EXISTS","description":"Check whether a path exists in JSON: JSON_EXISTS in PostgreSQL 17+ and Oracle, JSON_PATH_EXISTS in SQL Server, JSON_CONTAINS_PATH in MySQL, json_type in SQLite.","body":{"slug":"json-exists","name":"JSON_EXISTS","h1":"SQL JSON_EXISTS","category":"string","lede":"JSON_EXISTS(doc, '$.a') is true when the path is present, even when its value is JSON null. That is the difference from testing JSON_VALUE for NULL.","syntax":"JSON_EXISTS(doc, path)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"JSON_PATH_EXISTS(doc, path), 2022+; JSON_EXISTS is not recognized"},{"engine_slug":"postgresql","status":"yes","note":"JSON_EXISTS from 17; jsonb_path_exists and the ? operator before"},{"engine_slug":"mysql","status":"partial","note":"JSON_CONTAINS_PATH(doc, 'one', path)"},{"engine_slug":"sqlite","status":"partial","note":"json_type(doc, path) IS NOT NULL"},{"engine_slug":"oracle","status":"yes","note":"JSON_EXISTS"}],"gotchas":["A key whose value is JSON null exists: JSON_EXISTS on '{\"a\":null}' and '$.a' is true. JSON_VALUE(doc, '$.a') IS NOT NULL treats the same key as missing.","Before 23ai, Oracle's JSON_EXISTS is a condition for WHERE and CASE WHEN. 23ai's BOOLEAN type also lets you select it.","PostgreSQL and Oracle accept filter expressions in the path: '$.items[*] ? (@.qty > 5)' is true when any item has qty over 5."],"examples":[{"engine_slug":"postgresql","sql":"SELECT JSON_EXISTS('{\"a\":null}'::jsonb, '$.a') AS null_key, JSON_EXISTS('{\"a\":1}'::jsonb, '$.b') AS missing;  -- t, f"},{"engine_slug":"sql-server","sql":"SELECT JSON_PATH_EXISTS('{\"a\":null}', '$.a') AS null_key, JSON_PATH_EXISTS('{\"a\":1}', '$.b') AS missing;  -- 1, 0"},{"engine_slug":"mysql","sql":"SELECT JSON_CONTAINS_PATH('{\"a\":null}', 'one', '$.a') AS null_key, JSON_CONTAINS_PATH('{\"a\":1}', 'one', '$.b') AS missing;  -- 1, 0"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN JSON_EXISTS('{\"a\":1}', '$.b') THEN 'y' ELSE 'n' END AS has_b FROM dual;  -- n"},{"engine_slug":"sqlite","sql":"SELECT json_type('{\"a\":null}', '$.a') IS NOT NULL AS null_key, json_type('{\"a\":1}', '$.b') IS NOT NULL AS missing;  -- 1, 0"}],"faqs":[{"question":"How do I filter rows that contain a key?","answer":"WHERE JSON_EXISTS(doc, '$.region') on PostgreSQL 17+ and Oracle, WHERE JSON_PATH_EXISTS(doc, '$.region') = 1 on SQL Server, WHERE JSON_CONTAINS_PATH(doc, 'one', '$.region') on MySQL, WHERE doc ? 'region' on PostgreSQL jsonb."},{"question":"Can JSON_EXISTS test a value, not just a path?","answer":"With a filter, yes: JSON_EXISTS(doc, '$.items[*] ? (@.qty > 5)') on PostgreSQL and Oracle. MySQL's JSON_CONTAINS tests for a value instead."}],"related":["json-value","jsonb-exists","json-contains","json-extract"],"novel_uses":[{"body":"SQLite's json_type(doc, '$.a') returns the JSON type at the path or NULL when absent, so one call answers both 'does it exist' and 'is it a number'. Pages that must reject \"5\" stored as text get the check for free.","sql":"SELECT json_type('{\"a\":5}', '$.a') AS a, json_type('{\"a\":\"5\"}', '$.a') AS b;  -- integer, text"},{"body":"JSON_VALUE returns NULL, or errors in strict mode, when the key holds an object or array, so a null result can mean missing or complex. JSON_PATH_EXISTS does not care what the value is, which is why the existence test belongs to it on SQL Server.","sql":"SELECT JSON_VALUE('{\"a\":{\"b\":1}}', '$.a') AS value_of_object,\n       JSON_PATH_EXISTS('{\"a\":{\"b\":1}}', '$.a') AS exists_check;  -- NULL, 1"}]},"source_url":"https://sqlly.app/sql-functions/json-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-extract","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_EXTRACT function","description":"JSON_EXTRACT on MySQL and SQLite, and PostgreSQL's arrow operators: what comes back (JSON or text), path syntax, and reading the last array element.","body":{"slug":"json-extract","name":"JSON_EXTRACT","h1":"SQL JSON_EXTRACT function","category":"string","lede":"JSON_EXTRACT(config, '$.region') walks a path into a JSON document. The returned value is still JSON, which is the source of half the confusion.","syntax":"JSON_EXTRACT(json_doc, path [, path ...])","return_type":"JSON value","support":[{"engine_slug":"sql-server","status":"partial","note":"no JSON_EXTRACT; JSON_VALUE for scalars, JSON_QUERY for fragments"},{"engine_slug":"postgresql","status":"partial","note":"the -> operator is the same job"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"JSON_VALUE or simple dot-notation paths"}],"gotchas":["The result is a JSON value, not text: MySQL returns an extracted string still double-quoted ('\"eu\"') until you unwrap it with ->> or JSON_UNQUOTE. SQLite's json_extract returns strings unquoted, which is the usual porting surprise.","Both engines require a path that starts with $; SQLite rejects json_extract(doc, 'a.b') as a bad path. Only SQLite's -> and ->> operators accept a bare key like 'a'.","There are no negative indexes: '$[-1]' is an error on both. The last element is '$[last]' on MySQL and '$[#-1]' on SQLite.","Several paths return an array of the results: JSON_EXTRACT(doc, '$.a', '$.b') gives [va, vb] on MySQL and SQLite."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_EXTRACT(config, '$.region') AS region\nFROM settings;"},{"engine_slug":"sqlite","sql":"SELECT json_extract(payload, '$.items[0].sku') AS sku\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT JSON_EXTRACT(config, '$.tags[1]') AS second_tag\nFROM settings;"},{"engine_slug":"sql-server","sql":"SELECT JSON_VALUE(config, '$.region') AS region\nFROM settings;"},{"engine_slug":"postgresql","sql":"SELECT config->'region' AS region\nFROM settings;"},{"engine_slug":"oracle","sql":"SELECT JSON_VALUE(config, '$.region') AS region\nFROM settings;"}],"faqs":[{"question":"Why is my result wrapped in quotes?","answer":"Because it is a JSON string, not SQL text. Use ->> (MySQL, PostgreSQL) or JSON_UNQUOTE (MySQL) to strip the JSON quoting; SQLite's json_extract already returns unwrapped text."},{"question":"How do I extract from an array?","answer":"Zero-based indexes in the path: '$.tags[0]', or with member access '$.items[2].sku'. For the last element, write '$.tags[last]' on MySQL and '$.tags[#-1]' on SQLite."}],"related":["json-path-operator","json-unquote","json-valid","json-value"],"novel_uses":[{"body":"The $**.name path matches that key at every level, so one call finds totals or ids no matter how the documents nest. Several matches come back as an array.","sql":"SELECT JSON_EXTRACT(doc, '$**.total') AS totals FROM invoices;"},{"body":"SQLite indexes expressions, so CREATE INDEX on json_extract(payload, '$.type') turns the path into a btree lookup. Filters that repeat the identical expression use it directly.","sql":"CREATE INDEX idx_events_type ON events(json_extract(payload, '$.type'));"},{"body":"A JSON column itself cannot be indexed, but a generated column that unwraps the field can: writes pay once, and filters on that column or on the identical JSON_UNQUOTE(JSON_EXTRACT(...)) expression use the index. On 8.0.13+ a functional index on CAST(config->>'$.region' AS CHAR(8)) does the same without a named column.","sql":"ALTER TABLE settings ADD COLUMN region VARCHAR(8) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(config, '$.region'))) STORED, ADD INDEX (region);"}]},"source_url":"https://sqlly.app/sql-functions/json-extract","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-group-array","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_GROUP_ARRAY function","description":"SQLite's json_group_array and json_group_object: collect group rows into JSON, order elements with ORDER BY inside the aggregate, and the equivalents elsewhere.","body":{"slug":"json-group-array","name":"JSON_GROUP_ARRAY","h1":"SQL JSON_GROUP_ARRAY function","category":"aggregate","lede":"SQLite's pair of JSON aggregates that collect group values into arrays and objects.","syntax":"json_group_array(x) | json_group_array(x ORDER BY x) | json_group_object(k, v)","return_type":"json","support":[{"engine_slug":"sql-server","status":"partial","note":"FOR JSON PATH per row; JSON_ARRAYAGG only on SQL Server 2025 / Azure SQL"},{"engine_slug":"postgresql","status":"partial","note":"json_agg or jsonb_agg"},{"engine_slug":"mysql","status":"partial","note":"JSON_ARRAYAGG; rejects ORDER BY inside the aggregate"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Without ORDER BY the element order is arbitrary; SQLite 3.44+ accepts ORDER BY inside the aggregate, as in json_group_array(x ORDER BY x).","NULL values become JSON null elements, they do not disappear.","json_group_object keeps duplicate keys as separate pairs and silently drops pairs whose key is NULL.","Elsewhere: PostgreSQL json_agg, MySQL and Oracle JSON_ARRAYAGG (MySQL rejects ORDER BY inside it), SQL Server 2025 JSON_ARRAYAGG or FOR JSON PATH (one array of objects per row, with NULL keys left out)."],"examples":[{"engine_slug":"sqlite","sql":"SELECT post_id, json_group_array(tag ORDER BY tag) FROM post_tags GROUP BY post_id;"},{"engine_slug":"sqlite","sql":"SELECT json_group_object(code, label) FROM status_codes;"}],"faqs":[{"question":"How do I keep the array sorted?","answer":"Use ORDER BY inside the aggregate (SQLite 3.44+). An ordered subquery usually comes out in that order too, but SQLite does not promise it."},{"question":"What is the MySQL equivalent?","answer":"JSON_ARRAYAGG(x): same idea, standard name."}],"related":["json-arrayagg","json-objectagg","group-concat"],"novel_uses":[{"body":"group_concat breaks when a value contains the separator; json_group_array stores each element whole and json_array_length counts them.","sql":"SELECT post_id, json_group_array(tag) AS tags, json_array_length(json_group_array(tag)) AS tag_count FROM post_tags GROUP BY post_id;"},{"body":"Wrap json_object in the aggregate to build one document per parent straight out of SQLite.","sql":"SELECT post_id, json_group_array(json_object('tag', tag, 'added', added_on)) FROM post_tags GROUP BY post_id;"}]},"source_url":"https://sqlly.app/sql-functions/json-group-array","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-insert","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_INSERT function","description":"JSON_INSERT adds a value only when the path does not already exist on MySQL and SQLite: a no-op on existing paths, unlike JSON_SET's unconditional overwrite.","body":{"slug":"json-insert","name":"JSON_INSERT","h1":"SQL JSON_INSERT function","category":"string","lede":"JSON_INSERT(config, '$.created', NOW()) adds the key only if it is missing, so re-running the statement never overwrites the first value.","syntax":"JSON_INSERT(json_doc, path, value [, path, value ...])","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"no","note":"no JSON_INSERT; JSON_MODIFY overwrites"},{"engine_slug":"postgresql","status":"no","note":"jsonb_insert errors on an existing key; 'new'::jsonb || doc keeps existing keys"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"JSON1 functions"},{"engine_slug":"oracle","status":"no","note":"JSON_TRANSFORM on 21c+ has add semantics"}],"gotchas":["Existing paths are left untouched: run it twice and the second run changes nothing. If overwrite is wanted, that is JSON_SET.","An array index past the end appends: JSON_INSERT('{\"tags\":[\"a\"]}', '$.tags[5]', 'x') gives [\"a\", \"x\"] on MySQL. SQLite's spelling for append is '$.tags[#]'.","PostgreSQL's jsonb_insert raises 'cannot replace existing key' instead of skipping. For insert-if-missing on objects, put the defaults on the left: '{\"created\": \"2026-01-01\"}'::jsonb || config, since the right side wins."],"examples":[{"engine_slug":"mysql","sql":"UPDATE settings\nSET config = JSON_INSERT(config, '$.created', NOW());"},{"engine_slug":"sqlite","sql":"UPDATE settings\nSET config = json_insert(config, '$.note', 'first');"}],"faqs":[{"question":"Insert, set or replace?","answer":"INSERT creates only; REPLACE overwrites only; SET does both. Using JSON_SET where insert-only semantics matter silently overwrites data the caller did not mean to touch."},{"question":"How do I append to a JSON array?","answer":"MySQL: JSON_ARRAY_APPEND(doc, '$.tags', 'new'). SQLite: json_insert(doc, '$.tags[#]', 'new'). PostgreSQL: tags = tags || '\"new\"'::jsonb."}],"related":["json-set","json-replace","json-remove","json-mergepatch"],"novel_uses":[{"body":"JSON_INSERT guards the timestamp that must never move, JSON_SET refreshes the one that should: JSON_SET(JSON_INSERT(config, '$.created', NOW()), '$.updated', NOW()) does both in a single pass.","sql":"UPDATE settings SET config = JSON_SET(JSON_INSERT(config, '$.created', NOW()), '$.updated', NOW());"},{"body":"A SELECT-then-UPDATE check leaves a window where two sessions both decide the key is missing. JSON_INSERT is atomic per row, so the first writer seeds and the second is a no-op.","sql":"UPDATE prefs SET cfg = JSON_INSERT(cfg, '$.theme', 'light');"}]},"source_url":"https://sqlly.app/sql-functions/json-insert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-keys","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_KEYS function","description":"MySQL's JSON_KEYS returns an object's member names as a JSON array. PostgreSQL's jsonb_object_keys returns them as rows, and SQLite reads them from json_each.","body":{"slug":"json-keys","name":"JSON_KEYS","h1":"SQL JSON_KEYS function","category":"string","lede":"JSON_KEYS(config) lists the object's top-level keys as a JSON array, such as [\"a\", \"b\", \"ccc\"]. Pass a path to list the keys of a nested object.","syntax":"JSON_KEYS(json_doc [, path])","return_type":"JSON array or setof text","support":[{"engine_slug":"sql-server","status":"no","note":"no JSON_KEYS; OPENJSON's key column over the object"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_object_keys / json_object_keys return a rowset"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no json_keys; SELECT key FROM json_each(doc)"},{"engine_slug":"oracle","status":"no","note":"no direct twin; shred with JSON_TABLE"}],"gotchas":["Do not rely on order: MySQL stores object keys sorted (shorter keys first, then by byte value) and drops duplicates, so JSON_KEYS('{\"b\":1,\"a\":2,\"ccc\":3}') is [\"a\", \"b\", \"ccc\"].","Top-level only without the path argument: JSON_KEYS(config, '$.user') digs one level down.","PostgreSQL's jsonb_object_keys returns a set of rows, one per key. It runs in the SELECT list too, but in FROM with a lateral join you can filter and aggregate the keys."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_KEYS(config) AS keys_arr FROM settings;"},{"engine_slug":"mysql","sql":"SELECT JSON_KEYS(config, '$.user') AS user_keys FROM settings;"},{"engine_slug":"postgresql","sql":"SELECT k FROM settings s,\njsonb_object_keys(s.config) k;"},{"engine_slug":"sqlite","sql":"SELECT je.key\nFROM settings s, json_each(s.config) je;"}],"faqs":[{"question":"How do I iterate all keys and values?","answer":"PostgreSQL: jsonb_each. MySQL: JSON_KEYS plus a join over JSON_EXTRACT, or JSON_TABLE. SQLite: json_each does both in one pass, the most convenient of the set."},{"question":"Why are my keys reordered?","answer":"MySQL's JSON type and PostgreSQL's jsonb both store keys sorted (shorter first, then by byte value, so uppercase before lowercase). PostgreSQL's json and SQLite's text JSON keep them as written. JSON objects are unordered by definition, so do not depend on it."}],"related":["json-each","json-length","json-extract","json-type"],"novel_uses":[{"body":"A DISTINCT over jsonb_object_keys across all rows lists the union of member names, which is the quickest schema inventory a schemaless column can give you.","sql":"SELECT DISTINCT k FROM payloads p, jsonb_object_keys(p.doc) k ORDER BY k;"},{"body":"GROUP BY JSON_KEYS(config) collects documents that share a shape, so the odd variant with an extra or missing member surfaces as its own small group instead of hiding in the average.","sql":"SELECT JSON_KEYS(config) AS shape, COUNT(*) AS docs FROM settings GROUP BY shape ORDER BY docs DESC;"}]},"source_url":"https://sqlly.app/sql-functions/json-keys","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_LENGTH function","description":"MySQL's JSON_LENGTH counts an object's members or an array's elements; SQLite and PostgreSQL only count arrays, with json_array_length and jsonb_array_length.","body":{"slug":"json-length","name":"JSON_LENGTH","h1":"SQL JSON_LENGTH function","category":"string","lede":"JSON_LENGTH(config, '$.tags') returns how many elements the tags array holds, which is the usual test for empty arrays and the basis for per-row item counts.","syntax":"JSON_LENGTH(json_doc [, path])  -- MySQL  |  json_array_length(json [, path])  -- SQLite  |  jsonb_array_length(jsonb)  -- PostgreSQL","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"no JSON_LENGTH; (SELECT count(*) FROM OPENJSON(...))"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_array_length for arrays; count jsonb_object_keys for objects"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"json_array_length, arrays only"},{"engine_slug":"oracle","status":"partial","note":"the size() item method: JSON_VALUE(doc, '$.tags.size()')"}],"gotchas":["Only MySQL's JSON_LENGTH counts object members. SQLite's json_array_length returns 0 for an object, and PostgreSQL's jsonb_array_length raises 'cannot get array length of a non-array'.","On MySQL a scalar and JSON null both have length 1, an empty array or object 0, and a missing path returns SQL NULL, not 0.","PostgreSQL takes no path argument: navigate first, jsonb_array_length(config->'tags'). MySQL and SQLite accept the path inline."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_LENGTH(config, '$.tags') AS tag_count\nFROM settings;"},{"engine_slug":"sqlite","sql":"SELECT json_array_length(payload, '$.items') AS item_count\nFROM events;"},{"engine_slug":"postgresql","sql":"SELECT jsonb_array_length(data->'tags') AS tag_count\nFROM payloads;"},{"engine_slug":"oracle","sql":"SELECT JSON_VALUE(config, '$.tags.size()') AS tag_count\nFROM settings;"}],"faqs":[{"question":"How do I find rows with empty JSON arrays?","answer":"WHERE JSON_LENGTH(config, '$.tags') = 0 (MySQL), json_array_length(config, '$.tags') = 0 (SQLite) or jsonb_array_length(data->'tags') = 0 (PostgreSQL). A missing path gives NULL, so add OR ... IS NULL if absence counts as empty."},{"question":"How do I count an object's keys on PostgreSQL?","answer":"There is no jsonb_object_length. Use (SELECT count(*) FROM jsonb_object_keys(doc)) as a scalar subquery."}],"related":["json-depth","json-keys","json-each","json-type"],"novel_uses":[{"body":"Indexing past the end returns NULL, which is indistinguishable from a stored null. Checking json_array_length first separates 'element 2 does not exist' from 'element 2 is null'.","sql":"SELECT id FROM carts WHERE json_array_length(payload, '$.items') > 2 AND json_extract(payload, '$.items[2].sku') IS NULL;"},{"body":"ORDER BY JSON_LENGTH(config) DESC on MySQL surfaces the rows with the most top-level members, a quick pass to find documents drifting into denormalized junk before they bloat every read.","sql":"SELECT id, JSON_LENGTH(config) AS members FROM settings ORDER BY members DESC LIMIT 5;"}]},"source_url":"https://sqlly.app/sql-functions/json-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-mergepatch","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_MERGEPATCH function","description":"RFC 7396 merge patch, where null deletes a member: JSON_MERGEPATCH on Oracle, JSON_MERGE_PATCH on MySQL, json_patch on SQLite. PostgreSQL's jsonb || is shallower.","body":{"slug":"json-mergepatch","name":"JSON_MERGEPATCH","h1":"SQL JSON_MERGEPATCH function","category":"string","lede":"JSON_MERGEPATCH(doc, '{\"region\": \"us\", \"old\": null}') sets region and deletes old in one call. Nested objects in the patch merge recursively.","syntax":"JSON_MERGEPATCH(target, patch)  -- Oracle  |  JSON_MERGE_PATCH(target, patch)  -- MySQL  |  json_patch(target, patch)  -- SQLite","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"no","note":"no merge patch; JSON_MODIFY per path"},{"engine_slug":"postgresql","status":"partial","note":"jsonb || is a shallow merge, not RFC 7396"},{"engine_slug":"mysql","status":"yes","note":"spelled JSON_MERGE_PATCH (8.0.3+)"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":"JSON_MERGEPATCH, 19c+"}],"gotchas":["A null value in the patch deletes the target member under RFC 7396: {\"a\": null} removes a; it does not store JSON null. The single most surprising rule of the format.","PostgreSQL's || is a shallow merge, not merge-patch: nested objects are replaced whole instead of deep-merged, and nulls do not delete anything.","MySQL spells it with an extra underscore, JSON_MERGE_PATCH; JSON_MERGEPATCH is Oracle's name. MySQL's deprecated JSON_MERGE is JSON_MERGE_PRESERVE, which combines duplicate keys into arrays instead of replacing them.","Arrays are replaced, not merged: patching {\"tags\": [\"a\"]} with {\"tags\": [\"b\"]} gives [\"b\"]."],"examples":[{"engine_slug":"mysql","sql":"UPDATE settings\nSET config = JSON_MERGE_PATCH(config,\n  '{\"region\": \"us\", \"legacy\": null}');"},{"engine_slug":"sqlite","sql":"SELECT json_patch(config, '{\"tier\": \"pro\"}')\nFROM settings;"},{"engine_slug":"postgresql","sql":"UPDATE settings\nSET config = config || '{\"tier\": \"pro\"}'::jsonb;"},{"engine_slug":"oracle","sql":"UPDATE settings\nSET config = JSON_MERGEPATCH(config,\n  '{\"region\": \"us\", \"legacy\": null}');"}],"faqs":[{"question":"How do I deep-merge in PostgreSQL?","answer":"Not with ||, which replaces nested objects whole. Use jsonb_set for each nested path you change, write a recursive SQL function over jsonb_each, or merge in the application."},{"question":"Why did my member disappear instead of becoming null?","answer":"RFC 7396 defines null in a patch as delete. To store an actual JSON null, use a path function instead: JSON_SET(doc, '$.a', CAST('null' AS JSON)) on MySQL, json_set(doc, '$.a', json('null')) on SQLite."}],"related":["json-set","json-remove","jsonb-contains","json-object"],"novel_uses":[{"body":"RFC 7396 is exactly the JSON body of an HTTP PATCH request, and null means unset. Applying the client's body with JSON_MERGE_PATCH (MySQL) or JSON_MERGEPATCH (Oracle) implements the standard with no field-by-field code.","sql":"UPDATE docs SET body = JSON_MERGE_PATCH(body, ?) WHERE id = ?;"},{"body":"Replacing the whole column erases every concurrent write to other members since you read it. Merge patch touches only the members the patch names, so the rest of the document survives untouched.","sql":"UPDATE prefs SET cfg = JSON_MERGE_PATCH(cfg, '{\"theme\": \"dark\"}') WHERE user_id = 12;"}]},"source_url":"https://sqlly.app/sql-functions/json-mergepatch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-object","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_OBJECT function","description":"JSON_OBJECT builds a JSON object from key-value pairs on SQL Server 2022+, MySQL, SQLite, Oracle and PostgreSQL 16+, with a different pair separator per dialect.","body":{"slug":"json-object","name":"JSON_OBJECT","h1":"SQL JSON_OBJECT function","category":"string","lede":"JSON_OBJECT('id': 7, 'total': 42.5) builds {\"id\":7,\"total\":42.5}. The standard writes pairs with : or VALUE; MySQL and SQLite separate keys and values with commas.","syntax":"JSON_OBJECT(key : value, ...)  -- SQL Server, Oracle, PostgreSQL  |  JSON_OBJECT(key, value, ...)  -- MySQL, SQLite","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+"},{"engine_slug":"postgresql","status":"yes","note":"JSON_OBJECT on 16+; jsonb_build_object always available"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":"12.2+"}],"gotchas":["The pair separator differs: SQL Server, Oracle and PostgreSQL 16+ take 'key' : value (Oracle and PostgreSQL also 'key' VALUE value); MySQL and SQLite take 'key', value. Oracle rejects the comma form with ORA-02000, and PostgreSQL with a function-not-found error.","NULL values are kept as null by default (NULL ON NULL); ABSENT ON NULL drops the member on SQL Server, Oracle and PostgreSQL. Note the opposite default from JSON_ARRAY.","Before PostgreSQL 16, use json_build_object(key, value, ...) or jsonb_build_object, which take MySQL's comma-separated shape."],"examples":[{"engine_slug":"sql-server","sql":"SELECT JSON_OBJECT('id': id, 'total': total) AS doc\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT JSON_OBJECT('region', region, 'tier', tier) AS doc\nFROM settings;"},{"engine_slug":"sqlite","sql":"SELECT json_object('a', 1, 'b', 2) AS doc;"},{"engine_slug":"postgresql","sql":"SELECT JSON_OBJECT('id': id, 'total': total) AS doc\nFROM orders;"},{"engine_slug":"oracle","sql":"SELECT JSON_OBJECT('id' VALUE id, 'total' VALUE total) AS doc\nFROM orders;"}],"faqs":[{"question":"How do I turn a whole row into JSON?","answer":"PostgreSQL: to_jsonb(t). SQL Server: SELECT ... FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Oracle: JSON_OBJECT(*). MySQL and SQLite: list the columns as key-value pairs."},{"question":"Must keys be string literals?","answer":"No. A key is any string expression, so JSON_OBJECT(col_name : col_value) builds keys from data. A NULL key is an error rather than a skipped member."}],"related":["json-array","json-objectagg","to-json","json-set"],"novel_uses":[{"body":"ABSENT ON NULL drops any member whose value is NULL, so JSON_OBJECT('note': NULLIF(note, '') ABSENT ON NULL) ships only filled fields. Clients stop receiving \"note\": null for every empty string.","sql":"SELECT JSON_OBJECT('id': id, 'note': NULLIF(note, '') ABSENT ON NULL) AS doc FROM orders;"},{"body":"JSON_OBJECT escapes a string argument, so passing a JSON column nests it as escaped text. Wrap the value in JSON_QUERY and it lands as a real nested object.","sql":"SELECT JSON_OBJECT('id': id, 'meta': JSON_QUERY(meta_json)) AS doc FROM jobs;"}]},"source_url":"https://sqlly.app/sql-functions/json-object","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-objectagg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_OBJECTAGG function","description":"JSON_OBJECTAGG turns key/value rows into one JSON object per group: per-engine syntax (comma, KEY VALUE, colon), PostgreSQL's jsonb_object_agg, duplicate and NULL keys.","body":{"slug":"json-objectagg","name":"JSON_OBJECTAGG","h1":"SQL JSON_OBJECTAGG function","category":"aggregate","lede":"Aggregates two columns of a group into one JSON object keyed by the first.","syntax":"JSON_OBJECTAGG(key, value) | JSON_OBJECTAGG(KEY key VALUE value) | JSON_OBJECTAGG(key : value)","return_type":"json","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 / Azure SQL, colon syntax: JSON_OBJECTAGG(k : v)"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 16+ as JSON_OBJECTAGG(k VALUE v); json_object_agg and jsonb_object_agg on every version"},{"engine_slug":"mysql","status":"yes","note":"comma syntax: JSON_OBJECTAGG(k, v)"},{"engine_slug":"sqlite","status":"no","note":"use json_group_object"},{"engine_slug":"oracle","status":"yes","note":"JSON_OBJECTAGG(KEY k VALUE v); the comma form also parses"}],"gotchas":["The argument syntax differs per engine: MySQL takes a comma, PostgreSQL 16+ takes k VALUE v (the colon form also parses there; the comma does not), SQL Server 2025 uses k : v, and Oracle accepts KEY k VALUE v or the comma.","Duplicate keys: MySQL and jsonb_object_agg keep the last value; PostgreSQL's json_object_agg, SQL Server, Oracle and SQLite emit both pairs, producing an object most JSON parsers will read as last-wins.","NULL keys: PostgreSQL, MySQL, SQL Server and Oracle raise an error; SQLite silently drops the pair. NULL values are fine and become JSON null.","JSON keys are always strings, so numeric keys come out quoted."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_OBJECTAGG(id, name) FROM employees;"},{"engine_slug":"postgresql","sql":"SELECT jsonb_object_agg(code, label) FROM status_codes;"},{"engine_slug":"sql-server","sql":"SELECT JSON_OBJECTAGG(code : label) FROM status_codes;"},{"engine_slug":"sqlite","sql":"SELECT json_group_object(code, label) FROM status_codes;"},{"engine_slug":"oracle","sql":"SELECT JSON_OBJECTAGG(KEY code VALUE label) FROM status_codes;"}],"faqs":[{"question":"What happens with duplicate keys?","answer":"MySQL and jsonb_object_agg keep the last value per key. PostgreSQL's json_object_agg, SQL Server, Oracle and SQLite write every pair, which leaves a duplicate-key object that parsers resolve inconsistently."},{"question":"What is JSON_OBJECTAGG in PostgreSQL?","answer":"PostgreSQL 16+ has JSON_OBJECTAGG(k VALUE v). On older versions use json_object_agg(k, v) or jsonb_object_agg(k, v)."},{"question":"How do I build an array of objects per group?","answer":"Combine them: JSON_ARRAYAGG over JSON_OBJECT is one way, or PostgreSQL's jsonb_agg(to_jsonb(row))."}],"related":["json-arrayagg","json-group-array","array-agg"],"novel_uses":[{"body":"Aggregate a key column and a value column into one JSON value and the app reads each tenant's whole configuration as one row.","sql":"SELECT tenant_id, JSON_OBJECTAGG(setting_key, setting_value) AS config FROM settings GROUP BY tenant_id;"},{"body":"PostgreSQL jsonb_object_agg keeps the last value per key, so an aggregate ordered by priority merges base defaults and user overrides into one map.","sql":"SELECT jsonb_object_agg(k, v ORDER BY prio) AS merged FROM (SELECT 'theme' AS k, 'light' AS v, 1 AS prio UNION ALL SELECT 'theme', 'dark', 2) d;"},{"body":"SQLite json_group_object keeps integer and real columns as JSON numbers instead of quoted strings, so the client reads the number 3 and not the string '3'.","sql":"SELECT json_group_object(code, weight) FROM status_codes;"}]},"source_url":"https://sqlly.app/sql-functions/json-objectagg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-path-operator","corpus":"sql-functions","engine":null,"language":"en","title":"SQL -> JSON operator","description":"The -> and ->> JSON operators on PostgreSQL, MySQL and SQLite: -> returns JSON, ->> returns text, and each engine reads the right-hand side differently.","body":{"slug":"json-path-operator","name":"-> and ->>","h1":"SQL -> JSON operator","category":"string","lede":"payload->'user' navigates; payload->>'user' navigates and unwraps to text. On PostgreSQL, MySQL and SQLite (3.38+) the arrows are the everyday way to read JSON.","syntax":"json -> 'key'  |  json ->> 'key'  -- PostgreSQL, SQLite  |  col -> '$.key'  -- MySQL, SQLite","return_type":"JSON or text","support":[{"engine_slug":"sql-server","status":"no","note":"no arrow operators; JSON_VALUE and JSON_QUERY"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"column -> path only; the left side must be a column"},{"engine_slug":"sqlite","status":"yes","note":"3.38+; accepts a $ path, a key or an array index; ->> returns the SQL value, so numbers stay numeric"},{"engine_slug":"oracle","status":"no","note":"dot-notation or JSON_VALUE"}],"gotchas":["->> is not 'dig deeper': it unwraps the JSON quoting into text. Navigate with -> and unwrap only at the leaf you want as text: payload->'user'->>'name', not ->> in the middle.","PostgreSQL GIN indexes and containment (@>) work on jsonb, not json: store columns as jsonb and cast literals with ::jsonb for the operator path.","The right-hand side differs: MySQL takes a $ path ('$.a.b'), PostgreSQL takes one key or an integer index per arrow (->'a'->'b', ->0), SQLite takes either. PostgreSQL's ->-1 counts from the end.","MySQL's arrows are shorthand for JSON_EXTRACT and JSON_UNQUOTE on a column; config->'$.a' works but a literal or expression on the left is a syntax error."],"examples":[{"engine_slug":"postgresql","sql":"SELECT payload->'user'->>'name' AS name\nFROM events;"},{"engine_slug":"mysql","sql":"SELECT config->>'$.region' AS region\nFROM settings;"},{"engine_slug":"postgresql","sql":"SELECT payload->'tags' AS tags_json\nFROM events;"},{"engine_slug":"sqlite","sql":"SELECT payload->'user'->>'name' AS name\nFROM events;"}],"faqs":[{"question":"When do I use -> versus ->>?","answer":"-> when the result feeds more JSON work (further arrows, @>); ->> when it feeds SQL comparisons, ORDER BY or display. So the last arrow in a chain is usually ->>."},{"question":"Do the arrows work on arrays?","answer":"Yes. MySQL: config->>'$.tags[0]'. PostgreSQL: config->'tags'->>0. SQLite: config->>'$.tags[0]'. All zero-based."}],"related":["json-extract","jsonb-contains","jsonb-exists","json-unquote"],"novel_uses":[{"body":"The JSON-returning arrow makes missing and JSON null distinguishable: an absent key gives SQL NULL, while a present null gives the jsonb value 'null'. Existence filters therefore use ->, not ->>.","sql":"SELECT id FROM events WHERE payload->'retry_of' IS NOT NULL AND payload->'retry_of' <> 'null'::jsonb;"},{"body":"-> keeps the result as jsonb, so an extracted tags array can feed @> directly. A GIN index on the column does not serve this expression: index the expression itself, CREATE INDEX ... USING gin ((payload->'tags')), or write payload @> '{\"tags\":[\"vip\"]}' to use the column index. This tests membership without shredding rows.","sql":"SELECT id FROM events WHERE payload->'tags' @> '[\"vip\"]'::jsonb;"}]},"source_url":"https://sqlly.app/sql-functions/json-path-operator","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-pretty","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_PRETTY","description":"Format JSON with line breaks and indentation: JSON_PRETTY in MySQL, jsonb_pretty in PostgreSQL, json_pretty in SQLite 3.46+, JSON_SERIALIZE ... PRETTY in Oracle.","body":{"slug":"json-pretty","name":"JSON_PRETTY","h1":"SQL JSON_PRETTY","category":"string","lede":"Compact JSON is hard to read in a result grid. Four of the five engines can indent it for you.","syntax":"JSON_PRETTY(doc)  |  jsonb_pretty(doc)  |  json_pretty(doc [, indent])  |  JSON_SERIALIZE(doc PRETTY)","return_type":"text","support":[{"engine_slug":"sql-server","status":"no","note":"no pretty-printer; FOR JSON returns compact text and JSON_QUERY returns the fragment with its original whitespace"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_pretty(jsonb)"},{"engine_slug":"mysql","status":"yes","note":"JSON_PRETTY(doc)"},{"engine_slug":"sqlite","status":"yes","note":"json_pretty(doc [, indent]) from 3.46"},{"engine_slug":"oracle","status":"partial","note":"JSON_SERIALIZE(doc PRETTY)"}],"gotchas":["Indentation differs: MySQL and Oracle indent by two spaces, PostgreSQL and SQLite by four. Oracle also puts an array's opening bracket on its own line.","jsonb_pretty takes jsonb, so the output follows jsonb rules: keys are reordered and only the last of duplicate keys survives.","SQLite's json_pretty takes an optional indent string: json_pretty(doc, '  ') indents by two spaces."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_PRETTY('{\"a\":1,\"b\":[1,2]}') AS pretty;  -- two-space indent"},{"engine_slug":"postgresql","sql":"SELECT jsonb_pretty('{\"a\":1,\"b\":[1,2]}');  -- four-space indent"},{"engine_slug":"sqlite","sql":"SELECT json_pretty('{\"a\":1,\"b\":[1,2]}', '  ') AS pretty;"},{"engine_slug":"oracle","sql":"SELECT JSON_SERIALIZE('{\"a\":1,\"b\":[1,2]}' PRETTY) AS pretty FROM dual;"}],"faqs":[{"question":"How do I compact JSON instead?","answer":"SQLite: json(doc) strips the whitespace. Oracle: JSON_SERIALIZE(doc) without PRETTY. PostgreSQL's jsonb and MySQL's JSON type store a normalized form and print it on one line."},{"question":"Does pretty-printing change the stored value?","answer":"No. These functions return new text; the column keeps whatever was stored."}],"related":["to-json","json-object","json-valid"],"novel_uses":[{"body":"jsonb_pretty prints keys in jsonb's fixed order (shorter keys first, then byte order) with one value per line and four-space indents, so two snapshots of a document diff line by line and a changed value shows up as one changed line. Compact JSON puts the whole document on one line, so any change marks the entire document as different.","sql":"SELECT jsonb_pretty('{\"b\":2,\"a\":1}');  -- a prints before b"},{"body":"JSON_SERIALIZE defaults to a VARCHAR2(4000) result on Oracle, so pretty-printing a real document fails on length. Add RETURNING CLOB, the one change between a working export and an error.","sql":"SELECT JSON_SERIALIZE('{\"a\":1}' PRETTY RETURNING CLOB) FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/json-pretty","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-query","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_QUERY function","description":"JSON_QUERY on SQL Server, Oracle and PostgreSQL 17 returns an object or array as JSON text, the counterpart to JSON_VALUE, which only returns scalars.","body":{"slug":"json-query","name":"JSON_QUERY","h1":"SQL JSON_QUERY function","category":"string","lede":"JSON_QUERY(doc, '$.tags') returns the whole tags array as JSON text, where JSON_VALUE on the same path returns NULL.","syntax":"JSON_QUERY(expression, path)","return_type":"JSON text (jsonb on PostgreSQL)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"PostgreSQL 17+; -> and ->> before that"},{"engine_slug":"mysql","status":"no","note":"no JSON_QUERY; JSON_EXTRACT plays this role"},{"engine_slug":"sqlite","status":"no","note":"json_extract returns fragments too"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Scalars differ by engine: SQL Server's JSON_QUERY returns NULL for a scalar path in lax mode, while PostgreSQL and Oracle 23ai return it as JSON text ('\"x\"', quotes included). WITH WRAPPER turns it into a one-element array.","Output is JSON text in the engine's own formatting, so whitespace and key order can differ between engines. Compare results as parsed JSON, not as strings.","A wildcard path matching several values needs a wrapper: JSON_QUERY(doc, '$.items[*].sku' WITH ARRAY WRAPPER) collects them into one array on Oracle, PostgreSQL and SQL Server 2025."],"examples":[{"engine_slug":"sql-server","sql":"SELECT JSON_QUERY(config, '$.tags') AS tags\nFROM settings;"},{"engine_slug":"postgresql","sql":"SELECT JSON_QUERY(config, '$.items[*].sku' WITH WRAPPER) AS skus\nFROM settings;"},{"engine_slug":"oracle","sql":"SELECT JSON_QUERY(config, '$.tags') AS tags\nFROM settings;"}],"faqs":[{"question":"How do I get an array as rows?","answer":"Shred it: OPENJSON on SQL Server, JSON_TABLE on Oracle and MySQL, json_array_elements on PostgreSQL, json_each on SQLite. JSON_QUERY extracts; the rowset functions flatten."},{"question":"Why does JSON_QUERY return NULL for a simple string?","answer":"On SQL Server it only returns objects and arrays, so a scalar path gives NULL in lax mode and an error in strict mode. Use JSON_VALUE for scalars."}],"related":["json-value","openjson","json-table","json-extract"],"novel_uses":[{"body":"JSON_QUERY(doc, '$' PRETTY) re-renders the whole document with indentation and line breaks, which makes stored JSON readable in logs and comparable in diffs. Plain extraction keeps the compact stored form.","sql":"SELECT JSON_QUERY(doc, '$' PRETTY) AS readable FROM payloads WHERE id = 42;"},{"body":"JSON_QUERY keeps the object shape that JSON_VALUE would NULL out, so a frequently read sub-object can be copied into its own jsonb column once and then served by GIN or btree indexes.","sql":"UPDATE payloads SET user_b = JSON_QUERY(doc, '$.user')::jsonb WHERE user_b IS NULL;"}]},"source_url":"https://sqlly.app/sql-functions/json-query","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-quote","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_QUOTE and STRING_ESCAPE","description":"Turn text into a valid JSON string literal, escapes included: JSON_QUOTE in MySQL, json_quote in SQLite, to_json in PostgreSQL, STRING_ESCAPE in SQL Server.","body":{"slug":"json-quote","name":"JSON_QUOTE","h1":"SQL JSON_QUOTE and STRING_ESCAPE","category":"string","lede":"JSON_QUOTE('a\"b') returns \"a\\\"b\": the text wrapped in double quotes with the inner quote escaped, ready to splice into a JSON document.","syntax":"JSON_QUOTE(s)  |  json_quote(s)  |  to_json(s::text)::text  |  STRING_ESCAPE(s, 'json')","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"STRING_ESCAPE(s, 'json') escapes but adds no surrounding quotes"},{"engine_slug":"postgresql","status":"partial","note":"to_json(s::text)::text"},{"engine_slug":"mysql","status":"yes","note":"JSON_QUOTE(s)"},{"engine_slug":"sqlite","status":"yes","note":"json_quote(s)"},{"engine_slug":"oracle","status":"partial","note":"JSON_SCALAR(s)"}],"gotchas":["STRING_ESCAPE escapes quotes, backslashes and control characters but does not add the surrounding double quotes. JSON_QUOTE and json_quote do.","Building JSON by concatenating strings breaks on the first quote or newline in the data. JSON_OBJECT, json_build_object and FOR JSON do the escaping for you.","NULL handling differs: SQLite's json_quote(NULL) returns the JSON text null, while MySQL's JSON_QUOTE(NULL) returns SQL NULL."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_QUOTE('a\"b') AS q;  -- \"a\\\"b\""},{"engine_slug":"sqlite","sql":"SELECT json_quote('a\"b') AS q, json_quote(NULL) AS null_input;  -- \"a\\\"b\", null"},{"engine_slug":"postgresql","sql":"SELECT to_json('a\"b'::text)::text AS q;  -- \"a\\\"b\""},{"engine_slug":"sql-server","sql":"SELECT '\"' + STRING_ESCAPE('a\"b', 'json') + '\"' AS q;  -- \"a\\\"b\""},{"engine_slug":"oracle","sql":"SELECT JSON_SCALAR('a\"b') AS q FROM dual;  -- \"a\\\"b\""}],"faqs":[{"question":"When do I need to quote a string by hand?","answer":"Rarely. Prefer the JSON constructors (JSON_OBJECT, json_build_object, FOR JSON PATH), which quote values themselves. Manual quoting fits when you assemble a document from pieces."},{"question":"Does STRING_ESCAPE support other formats?","answer":"Only 'json' as of SQL Server 2025."}],"related":["json-object","to-json","quote-literal","backslash-escapes"],"novel_uses":[{"body":"Quoting text that is already JSON stores the fragment as a string: JSON_QUOTE of '{\"a\":1}' produces a JSON string, not an object, the usual bug after a pipeline quotes twice. MySQL's JSON_VALID on the stored text catches it, because raw scalars are invalid JSON and quoted ones are valid.","sql":"SELECT JSON_VALID('abc') AS raw, JSON_VALID(JSON_QUOTE('abc')) AS quoted;  -- 0, 1"},{"body":"SQLite's json_quote accepts numbers and NULL too: json_quote(123) is the text 123 and json_quote(NULL) is the text null, so it converts any single scalar to its JSON form without building an object first.","sql":"SELECT json_quote(123) AS n, json_quote('a') AS s, json_quote(NULL) AS z;  -- 123, \"a\", null"}]},"source_url":"https://sqlly.app/sql-functions/json-quote","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-remove","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_REMOVE function","description":"JSON_REMOVE deletes paths from a JSON document on MySQL and SQLite, with PostgreSQL's jsonb '#-' operator playing the same role.","body":{"slug":"json-remove","name":"JSON_REMOVE","h1":"SQL JSON_REMOVE function","category":"string","lede":"JSON_REMOVE(config, '$.legacy') drops a member or array element. Missing paths are not errors; the document comes back unchanged.","syntax":"JSON_REMOVE(json_doc, path [, path ...])","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"no","note":"JSON_MODIFY(doc, '$.key', NULL) deletes object keys in lax mode; array elements become null"},{"engine_slug":"postgresql","status":"partial","note":"jsonb - 'key' for top-level keys, #- '{a,b}' for paths"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"JSON_TRANSFORM on 21c+ has remove"}],"gotchas":["Removing an array element shifts the indexes: delete '$.items[0]' and the old items[1] becomes items[0]. Remove from the end when deleting several, or collect the survivors instead.","A missing path returns the document unchanged: no error, no warning, so typos vanish silently.","SQL Server deletes by setting NULL: JSON_MODIFY(doc, '$.legacy', NULL) removes the key in lax mode. Storing an actual JSON null needs 'strict $.legacy'."],"examples":[{"engine_slug":"mysql","sql":"UPDATE settings\nSET config = JSON_REMOVE(config, '$.legacy');"},{"engine_slug":"sqlite","sql":"SELECT json_remove(payload, '$.items[0]') AS trimmed\nFROM events;"},{"engine_slug":"postgresql","sql":"UPDATE settings\nSET config = config - 'legacy';"}],"faqs":[{"question":"How do I delete from an array by value?","answer":"PostgreSQL: tags - 'old' removes matching string elements from a jsonb array. MySQL: JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))) removes the first match, but when nothing matches JSON_SEARCH returns NULL and so does JSON_REMOVE, so guard an UPDATE with WHERE JSON_SEARCH(doc, 'one', 'old') IS NOT NULL. Otherwise rebuild the array with json_each or JSON_TABLE."},{"question":"Does removing the last element empty the array?","answer":"Yes, and removing all elements of a container leaves the empty container, not SQL NULL. JSON_REMOVE only ever edits the document it is given."}],"related":["json-set","json-insert","json-replace","json-length"],"novel_uses":[{"body":"One UPDATE with several paths strips email, ip and phone from every document, and reruns are free because missing paths are no-ops. That property makes redaction jobs idempotent.","sql":"UPDATE events SET payload = JSON_REMOVE(payload, '$.email', '$.ip', '$.phone');"},{"body":"The last keyword in a path removes the final array element without knowing its index: JSON_REMOVE(doc, '$.items[last]') is a stack pop. Plain numeric paths shift after every delete; last never does.","sql":"SELECT JSON_REMOVE(doc, '$.items[last]') AS shorter FROM carts WHERE id = 3;"}]},"source_url":"https://sqlly.app/sql-functions/json-remove","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-replace","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_REPLACE function","description":"JSON_REPLACE overwrites a path only when it already exists on MySQL and SQLite; missing paths are silently ignored, the mirror image of JSON_INSERT.","body":{"slug":"json-replace","name":"JSON_REPLACE","h1":"SQL JSON_REPLACE function","category":"string","lede":"JSON_REPLACE(config, '$.region', 'us') updates keys that exist and ignores the rest. The safe half of JSON_SET for updates.","syntax":"JSON_REPLACE(json_doc, path, value [, path, value ...])","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"no","note":"JSON_MODIFY with a 'strict $...' path errors instead of creating"},{"engine_slug":"postgresql","status":"no","note":"jsonb_set(doc, path, val, false) never creates a missing key"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"JSON1 functions"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["A path that does not exist is skipped without warning: a typo in '$.regon' changes nothing at all. Verify with JSON_CONTAINS_PATH or a SELECT before the UPDATE.","JSON_SET = insert + replace combined; JSON_REPLACE matters only when new keys must not appear (schema-preserved documents).","PostgreSQL's jsonb_set creates missing keys by default; pass false as the fourth argument (create_if_missing) to get replace-only behaviour."],"examples":[{"engine_slug":"mysql","sql":"UPDATE settings\nSET config = JSON_REPLACE(config, '$.region', 'us');"},{"engine_slug":"sqlite","sql":"UPDATE settings\nSET config = json_replace(config, '$.tier', 'pro');"}],"faqs":[{"question":"Why did my JSON_REPLACE change nothing?","answer":"The path did not exist, and JSON_REPLACE never creates one. Run SELECT JSON_EXTRACT(config, '$.region') first to check the spelling."},{"question":"Which function guarantees no new keys?","answer":"JSON_REPLACE. JSON_SET would create the key if missing, which is exactly the difference to test for in schema-sensitive documents."}],"related":["json-set","json-insert","json-remove","json-mergepatch"],"novel_uses":[{"body":"Lowercase a stored status across documents: JSON_REPLACE(config, '$.status', LOWER(JSON_UNQUOTE(JSON_EXTRACT(config, '$.status')))) with a WHERE that the stored value is a string. Documents without the field are skipped twice over, by the predicate and by the no-create rule, and a JSON null status is not rewritten to the string \"null\".","sql":"UPDATE settings SET config = JSON_REPLACE(config, '$.status', LOWER(JSON_UNQUOTE(JSON_EXTRACT(config, '$.status')))) WHERE JSON_TYPE(JSON_EXTRACT(config, '$.status')) = 'STRING';"},{"body":"A typo under JSON_SET quietly adds a stray key while the real key keeps its old value, and strict clients choke on the extra member; under JSON_REPLACE the same typo changes nothing. In schema-sensitive stores, replace-only semantics are the safer default.","sql":"UPDATE configs SET doc = JSON_REPLACE(doc, '$.timeout', 30);"}]},"source_url":"https://sqlly.app/sql-functions/json-replace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-search","corpus":"sql-functions","engine":null,"language":"en","title":"MySQL JSON_SEARCH","description":"MySQL's JSON_SEARCH returns the path where a string value sits in a JSON document, with LIKE wildcards. How to run the same search on the other engines.","body":{"slug":"json-search","name":"JSON_SEARCH","h1":"MySQL JSON_SEARCH","category":"string","lede":"JSON_SEARCH(doc, 'one', 'x') answers 'where in this document is the string x?' with a path such as \"$.a\".","syntax":"JSON_SEARCH(doc, 'one' | 'all', search_str [, escape_char [, path ...]])","return_type":"JSON (a path string or an array of paths), or NULL","support":[{"engine_slug":"sql-server","status":"no","note":"no direct function; recursive OPENJSON can rebuild paths"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_path_exists with a filter tests for a value but returns no path"},{"engine_slug":"mysql","status":"yes","note":"JSON_SEARCH"},{"engine_slug":"sqlite","status":"partial","note":"json_tree(doc) with WHERE atom = 'x' returns fullkey paths"},{"engine_slug":"oracle","status":"partial","note":"JSON_EXISTS with a filter tests for a value but returns no path"}],"gotchas":["It finds string values only: JSON_SEARCH('[1,2]', 'one', '1') is NULL.","The search string is a LIKE pattern, so % and _ are wildcards: 'ab%' matches both \"abc\" and \"abd\". Pass an escape character as the fourth argument to search for them literally.","'one' returns a single path as a JSON string. 'all' returns an array of paths, but a single match comes back as a plain string, not a one-element array. Wrap a 'one' result in JSON_UNQUOTE before passing it to JSON_EXTRACT or JSON_REMOVE."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_SEARCH('{\"a\":\"x\",\"b\":[\"y\",\"x\"]}', 'one', 'x') AS first_path,\n       JSON_SEARCH('{\"a\":\"x\",\"b\":[\"y\",\"x\"]}', 'all', 'x') AS all_paths;  -- \"$.a\", [\"$.a\", \"$.b[1]\"]"},{"engine_slug":"mysql","sql":"SELECT JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))) AS cleaned\nFROM (SELECT '[\"new\", \"old\"]' AS doc) AS t;  -- [\"new\"]"},{"engine_slug":"sqlite","sql":"SELECT fullkey FROM json_tree('{\"a\":\"x\",\"b\":[\"y\",\"x\"]}') WHERE atom = 'x';  -- $.a, $.b[1]"},{"engine_slug":"postgresql","sql":"SELECT jsonb_path_exists('{\"a\":\"x\",\"b\":[\"y\",\"x\"]}', '$.** ? (@ == \"x\")') AS found;  -- t, but no path comes back"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN JSON_EXISTS('{\"a\":\"x\",\"b\":[\"y\",\"x\"]}', '$.b[*]?(@ == \"x\")') THEN 'y' END AS found FROM dual;  -- y, but no path comes back"}],"faqs":[{"question":"How do I remove an array element by value in MySQL?","answer":"Find its path and remove it: JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))). Guard against a NULL path when the value is absent, because JSON_REMOVE with a NULL path returns NULL."},{"question":"Can JSON_SEARCH find numbers?","answer":"No. For numbers use JSON_CONTAINS(doc, '1') to test, or JSON_TABLE to unnest and filter."}],"related":["json-extract","json-remove","json-contains","json-each"],"novel_uses":[{"body":"The fifth argument limits where JSON_SEARCH looks: JSON_SEARCH(doc, 'one', 'x', NULL, '$.tags[*]') searches the tags array only, so the same string in a description field cannot win. 'one' plus a scope is the deterministic lookup the bare call is not.","sql":"SELECT JSON_SEARCH('{\"tags\":[\"x\"],\"note\":\"x\"}', 'one', 'x', NULL, '$.tags[*]') AS scoped;  -- \"$.tags[0]\""},{"body":"When the callers need indexes, JSON_TABLE with FOR ORDINALITY numbers the matches in one pass: the ord column is the 1-based array position (the path index plus one) that JSON_SEARCH only exposes inside a path string which then needs parsing. MySQL 8.0 added JSON_TABLE; on 5.7 the path parsing is the way.","sql":"SELECT jt.ord, jt.val\nFROM t, JSON_TABLE(t.doc, '$.tags[*]'\n  COLUMNS (ord FOR ORDINALITY, val VARCHAR(100) PATH '$')) jt\nWHERE jt.val = 'x';"}]},"source_url":"https://sqlly.app/sql-functions/json-search","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-set","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_SET function","description":"JSON_SET updates existing paths and adds missing ones in one call on MySQL and SQLite, with jsonb_set as PostgreSQL's jsonb-flavoured twin.","body":{"slug":"json-set","name":"JSON_SET","h1":"SQL JSON_SET function","category":"string","lede":"JSON_SET(config, '$.region', 'eu') returns the document with that path set: replaced if present, added if absent. It is the usual way to change one field.","syntax":"JSON_SET(json_doc, path, value [, path, value ...])","return_type":"JSON text","support":[{"engine_slug":"sql-server","status":"no","note":"JSON_MODIFY is the equivalent"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_set for jsonb; no json variant"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"JSON_TRANSFORM on 21c+"}],"gotchas":["jsonb_set wants a text[] path and JSON-typed values: jsonb_set(config, '{region}', '\"eu\"'); the quoted '\"eu\"' is a JSON string, while bare eu is a JSON syntax error.","jsonb_set only creates the last path step: jsonb_set('{}', '{a,b}', '1') returns {} unchanged because a does not exist. MySQL's JSON_SET likewise skips a path whose parent is missing.","MySQL 8.0 can update a JSON column in place when an UPDATE uses JSON_SET, JSON_REPLACE or JSON_REMOVE on the same column and the new value is no larger. PostgreSQL always writes a new copy of the jsonb value.","One call can touch many paths: JSON_SET(doc, '$.a', 1, '$.b', 2). SQL Server's JSON_MODIFY takes one path per call."],"examples":[{"engine_slug":"mysql","sql":"UPDATE settings\nSET config = JSON_SET(config, '$.region', 'eu');"},{"engine_slug":"sqlite","sql":"UPDATE settings\nSET config = json_set(config, '$.tier', 'pro');"},{"engine_slug":"postgresql","sql":"UPDATE settings\nSET config = jsonb_set(config, '{region}', '\"eu\"');"}],"faqs":[{"question":"JSON_SET, JSON_INSERT or JSON_REPLACE?","answer":"JSON_SET does both; JSON_INSERT only creates missing paths; JSON_REPLACE only overwrites existing ones. Pick the narrow one when overwrite-or-create would be a bug."},{"question":"Why does jsonb_set fail on my value?","answer":"The new value must be valid JSON in jsonb: strings need embedded quotes ('\"eu\"'), numbers do not. Wrap with to_jsonb(value) when the type is unclear."}],"related":["json-insert","json-replace","json-remove","json-mergepatch"],"novel_uses":[{"body":"JSON_SET(doc, '$.hits', CAST(JSON_EXTRACT(doc, '$.hits') AS SIGNED) + 1) reads and writes in the same UPDATE, so no app round trip or SELECT-then-write race. Keep the CAST on MySQL: plain JSON_EXTRACT(...) + 1 does double arithmetic and stores 6.0 instead of 6.","sql":"UPDATE pages SET config = JSON_SET(config, '$.hits', CAST(JSON_EXTRACT(config, '$.hits') AS SIGNED) + 1) WHERE id = 7;"},{"body":"SQLite paths are just strings, so json_set('{}', '$.' || :name, :value) writes a field whose name arrives at runtime. Chained calls build arbitrary user-defined records.","sql":"UPDATE docs SET payload = json_set(payload, '$.' || key_name, key_value) WHERE id = 1;"},{"body":"Guard with a WHERE on the same path: UPDATE ... SET config = JSON_SET(config, '$.schema', 2) WHERE JSON_EXTRACT(config, '$.schema') IS NULL. Reruns touch only the stragglers, so a big migration resumes safely.","sql":"UPDATE settings SET config = JSON_SET(config, '$.schema', 2) WHERE JSON_EXTRACT(config, '$.schema') IS NULL;"}]},"source_url":"https://sqlly.app/sql-functions/json-set","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-table","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_TABLE function","description":"The SQL-standard JSON_TABLE maps a JSON document to rows and columns through a COLUMNS clause, on Oracle, MySQL 8.0 and PostgreSQL 17. SQL Server uses OPENJSON.","body":{"slug":"json-table","name":"JSON_TABLE","h1":"SQL JSON_TABLE function","category":"string","lede":"JSON_TABLE(doc, '$[*]' COLUMNS (...)) turns a JSON array into rows you can join, filter and group. The COLUMNS clause declares a type and path for each output column.","syntax":"JSON_TABLE(expr, path COLUMNS (col type PATH '$.x', ...))","return_type":"rowset","support":[{"engine_slug":"sql-server","status":"no","note":"no JSON_TABLE; OPENJSON WITH is the dialect's answer"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 17+"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"json_each for one level of shredding"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["COLUMNS entries take PATH for location, EXISTS PATH for a 0/1 presence flag, FOR ORDINALITY for a row number, and NESTED PATH to unroll a child array into extra rows.","Missing and unconvertible values become NULL by default: a qty of \"abc\" in an INT column returns NULL on MySQL, PostgreSQL and Oracle without an error. Add ERROR ON ERROR (and ERROR ON EMPTY) to a column when bad data should stop the query.","SQL Server never received JSON_TABLE: OPENJSON WITH covers flat arrays; nested arrays take CROSS APPLY chains."],"examples":[{"engine_slug":"oracle","sql":"SELECT jt.sku, jt.qty\nFROM orders o,\nJSON_TABLE(o.items, '$[*]'\n  COLUMNS (sku VARCHAR2(40) PATH '$.sku',\n           qty NUMBER PATH '$.qty')) jt;"},{"engine_slug":"mysql","sql":"SELECT jt.sku, jt.qty\nFROM imports i,\nJSON_TABLE(i.items, '$[*]'\n  COLUMNS (sku CHAR(40) PATH '$.sku',\n           qty INT PATH '$.qty')) jt;"},{"engine_slug":"postgresql","sql":"SELECT jt.sku, jt.qty\nFROM imports i,\nJSON_TABLE(i.items, '$[*]'\n  COLUMNS (sku text PATH '$.sku',\n           qty int PATH '$.qty')) jt;"}],"faqs":[{"question":"How do I flatten an array of objects?","answer":"That is JSON_TABLE's core case: '$[*]' as the row pattern, one COLUMNS entry per object key. Nested arrays inside each element take a NESTED PATH clause."},{"question":"JSON_TABLE or OPENJSON?","answer":"Whichever your engine has: JSON_TABLE on Oracle, MySQL and PostgreSQL 17, OPENJSON on SQL Server. JSON_TABLE handles nested arrays inside one call with NESTED PATH; OPENJSON chains CROSS APPLY per level."}],"related":["openjson","json-each","json-array-elements","json-query"],"novel_uses":[{"body":"A COLUMNS entry can end in DEFAULT '0' ON ERROR, so one bad value yields 0 instead of a NULL. Put DEFAULT '0' ON EMPTY before it when a missing key should fall back too; ERROR ON EMPTY would stop the query instead. MySQL only accepts a quoted string as the DEFAULT value.","sql":"SELECT jt.sku, jt.qty FROM imports i, JSON_TABLE(i.items, '$[*]' COLUMNS (sku CHAR(40) PATH '$.sku', qty INT PATH '$.qty' DEFAULT '0' ON EMPTY DEFAULT '0' ON ERROR)) jt;"},{"body":"Declare the same path twice: note VARCHAR(200) PATH '$.note' for the value and has_note INT EXISTS PATH '$.note' for presence. A present-but-null note then reads as has_note 1 with a NULL note, not as a missing row.","sql":"SELECT jt.has_note, jt.note FROM docs d, JSON_TABLE(d.payload, '$' COLUMNS (note VARCHAR(200) PATH '$.note', has_note INT EXISTS PATH '$.note')) jt;"}]},"source_url":"https://sqlly.app/sql-functions/json-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-type","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_TYPE function","description":"JSON_TYPE (MySQL), json_type (SQLite) and jsonb_typeof (PostgreSQL) name the kind of a JSON value, each with its own vocabulary and letter case.","body":{"slug":"json-type","name":"JSON_TYPE","h1":"SQL JSON_TYPE function","category":"string","lede":"JSON_TYPE(JSON_EXTRACT(doc, '$.tags')) tells you whether a value is an array, object, string or number, which predicts whether JSON_VALUE or JSON_QUERY will return it.","syntax":"JSON_TYPE(json_val)  -- MySQL  |  json_type(json [, path])  -- SQLite  |  jsonb_typeof(jsonb)  -- PostgreSQL","return_type":"text","support":[{"engine_slug":"sql-server","status":"no","note":"no JSON_TYPE; OPENJSON's type column (0-5), or ISJSON(x, ARRAY) on 2022+"},{"engine_slug":"postgresql","status":"partial","note":"jsonb_typeof; also json_typeof for the json type"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"the type() item method: JSON_VALUE(doc, '$.tags.type()')"}],"gotchas":["The vocabularies differ. MySQL returns upper case: OBJECT, ARRAY, STRING, INTEGER, UNSIGNED INTEGER, DOUBLE, DECIMAL, BOOLEAN, NULL, plus names such as DATETIME for SQL values cast to JSON. Positive integers from 4294967296 up report UNSIGNED INTEGER, so a test for 'INTEGER' misses large IDs. SQLite returns object, array, text, integer, real, true, false, null. PostgreSQL returns object, array, string, number, boolean, null.","MySQL's result has a binary collation, so JSON_TYPE(x) = 'array' is false for an array; compare with 'ARRAY'.","MySQL's JSON_TYPE takes one argument: JSON_TYPE(doc, '$.tags') is a parameter-count error, so extract first. SQLite accepts a path; PostgreSQL navigates with -> and then calls jsonb_typeof."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_TYPE(config) AS doc_type,\n       JSON_TYPE(config->'$.tags') AS tags_type\nFROM settings;"},{"engine_slug":"sqlite","sql":"SELECT json_type(payload, '$.count') FROM events;"},{"engine_slug":"postgresql","sql":"SELECT jsonb_typeof(data->'count') FROM payloads;"}],"faqs":[{"question":"How do I check if a path holds an array?","answer":"MySQL: JSON_TYPE(doc->'$.tags') = 'ARRAY'. SQLite: json_type(doc, '$.tags') = 'array'. PostgreSQL: jsonb_typeof(data->'tags') = 'array'. Oracle: JSON_VALUE(doc, '$.tags.type()') = 'array'."},{"question":"Does JSON_TYPE return NULL for JSON null?","answer":"No. A JSON null reports as 'null' (MySQL: 'NULL'). SQL NULL comes back when the input is SQL NULL or, on SQLite, when the path does not exist."}],"related":["json-valid","json-length","json-value","json-extract"],"novel_uses":[{"body":"Cast (doc->>'amount')::numeric only when jsonb_typeof says 'number'; string-typed amounts would abort the query. The type check becomes a cheap WHERE guard on mixed-quality documents.","sql":"SELECT id, (doc->>'amount')::numeric AS amount FROM charges WHERE jsonb_typeof(doc->'amount') = 'number';"},{"body":"Schemaless 'value' fields change type per row. A CASE on the type function picks the right coercion per row instead of one cast that some rows survive and others crash.","sql":"SELECT CASE jsonb_typeof(doc->'value') WHEN 'number' THEN (doc->>'value')::numeric::text ELSE doc->>'value' END AS value_text FROM readings;"}]},"source_url":"https://sqlly.app/sql-functions/json-type","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-unquote","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_UNQUOTE function","description":"MySQL's JSON_UNQUOTE removes the JSON quoting and escapes from an extracted string value: the explicit, longer spelling of the ->> operator.","body":{"slug":"json-unquote","name":"JSON_UNQUOTE","h1":"SQL JSON_UNQUOTE function","category":"string","lede":"JSON_UNQUOTE(JSON_EXTRACT(doc, '$.region')) turns '\"eu\"' into eu. What ->> does in one character, spelled out as a function.","syntax":"JSON_UNQUOTE(json_value)","return_type":"text","support":[{"engine_slug":"sql-server","status":"no","note":"JSON_VALUE already returns unquoted text"},{"engine_slug":"postgresql","status":"no","note":"->> unwraps; no function needed"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"json_extract already unwraps"},{"engine_slug":"oracle","status":"no","note":"JSON_VALUE already returns unquoted text"}],"gotchas":["Prefer ->>: it is exactly JSON_UNQUOTE(JSON_EXTRACT(...)) in one token and reads better in WHERE clauses.","Only a complete JSON string gets unquoted. JSON_UNQUOTE('eu') and JSON_UNQUOTE('\"eu') both come back unchanged, so a malformed value slips through looking like data.","The other engines unquote by construction (->> on PostgreSQL, JSON_VALUE on SQL Server and Oracle, unwrapping json_extract on SQLite), so this function rarely survives a port."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_UNQUOTE(JSON_EXTRACT(config, '$.region')) AS region\nFROM settings;"},{"engine_slug":"mysql","sql":"SELECT config->>'$.region' AS region\nFROM settings;"}],"faqs":[{"question":"Why is my JSON value double-quoted?","answer":"JSON_EXTRACT returns JSON, and JSON strings are quoted. Unwrap with JSON_UNQUOTE or the ->> operator when the SQL side wants plain text."},{"question":"Does JSON_UNQUOTE also unescape?","answer":"Yes, it strips quoting and the JSON escapes inside the string, yielding the original text value, not just the outer quotes."}],"related":["json-extract","json-path-operator","json-value","json-valid"],"novel_uses":[{"body":"A cell holding the literal \"line1\\nline2\" (backslash included) becomes a real newline through CAST(cell AS JSON) plus JSON_UNQUOTE. The same pass decodes \\\" and \\u00e9 escapes, all in SQL.","sql":"SELECT JSON_UNQUOTE(CAST(cell AS JSON)) AS decoded FROM imports WHERE cell LIKE '\"%';"},{"body":"A direct = between JSON_EXTRACT and a text column does match, because MySQL compares the text as a JSON string. Once the extraction passes through a string context (LIKE, CONCAT, a user variable, or a staged VARCHAR column) its quotes come back and the join silently returns zero rows. Unquoting the extraction side keeps the join matching in every case.","sql":"SELECT b.* FROM order_headers o JOIN orders b ON b.id = o.id AND JSON_UNQUOTE(JSON_EXTRACT(o.meta, '$.channel')) = b.channel;"}]},"source_url":"https://sqlly.app/sql-functions/json-unquote","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-valid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_VALID function","description":"Checking text before treating it as JSON: JSON_VALID on MySQL and SQLite, ISJSON on SQL Server, and the IS JSON predicate on Oracle and PostgreSQL 16+.","body":{"slug":"json-valid","name":"JSON_VALID / ISJSON","h1":"SQL JSON_VALID function","category":"string","lede":"JSON_VALID(raw) = 1 says the text parses as JSON. Checking at load time turns a query-time error into a rejected row.","syntax":"JSON_VALID(str)  -- MySQL, SQLite  |  ISJSON(str)  -- SQL Server  |  str IS JSON  -- Oracle, PostgreSQL 16+","return_type":"integer or boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"the IS JSON predicate, PostgreSQL 16+"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":"the IS JSON condition, 12c+"}],"gotchas":["MySQL, SQLite and SQL Server's ISJSON return 1 or 0, and NULL for NULL input; Oracle's and PostgreSQL's IS JSON is a predicate used directly in WHERE and CHECK. SQL Server's ISJSON returns 0 for a bare scalar such as '1' or '\"x\"', which the others accept, unless you write ISJSON(x, VALUE) on SQL Server 2022+.","Oracle's IS JSON is lax by default and accepts {a: 1} with an unquoted key; write IS JSON STRICT for RFC 8259. SQLite's json_valid(x) is strict, while json_valid(x, 6) accepts JSON5.","PostgreSQL's json and jsonb types reject invalid input on insert, so IS JSON is for text columns. It also tests shape: raw IS JSON OBJECT, IS JSON ARRAY, IS JSON SCALAR."],"examples":[{"engine_slug":"mysql","sql":"SELECT JSON_VALID('{\"a\": 1}') AS ok,\n       JSON_VALID('{a: 1}') AS not_ok;"},{"engine_slug":"sql-server","sql":"SELECT * FROM staging\nWHERE ISJSON(raw) = 1;"},{"engine_slug":"sqlite","sql":"SELECT * FROM imports WHERE json_valid(raw);"},{"engine_slug":"postgresql","sql":"SELECT * FROM staging WHERE raw IS JSON;"},{"engine_slug":"oracle","sql":"SELECT * FROM payloads WHERE doc IS JSON;"}],"faqs":[{"question":"Can a CHECK constraint enforce JSON?","answer":"Yes: CHECK (raw IS JSON) on Oracle and PostgreSQL 16+, CHECK (ISJSON(raw) = 1) on SQL Server, CHECK (json_valid(raw)) on SQLite. On MySQL, a native JSON column validates by itself; for text columns, CHECK (JSON_VALID(raw)) works from 8.0.16."},{"question":"Does JSON_VALID accept JSON5 or trailing commas?","answer":"MySQL's JSON_VALID and SQL Server's ISJSON do not. SQLite's json_valid accepts JSON5 only when you pass flags (json_valid(x, 6)). Oracle's default lax IS JSON accepts unquoted keys and single quotes; add STRICT to reject them."}],"related":["json-extract","json-type","to-json","cast"],"novel_uses":[{"body":"JSON_VALID alone cannot tell an object from an array; pair it with JSON_TYPE on MySQL to route mixed documents, or use PostgreSQL's shape tests (raw IS JSON ARRAY) directly in the filter.","sql":"SELECT * FROM staging.imports WHERE JSON_VALID(raw) = 1 AND JSON_TYPE(raw) = 'ARRAY';"},{"body":"RFC 8259 allows repeated keys, and naive parsers keep only the last one. IS JSON WITH UNIQUE KEYS fails any document that ships one, catching the problem at load instead of at read.","sql":"SELECT * FROM staging.docs WHERE raw IS NOT JSON WITH UNIQUE KEYS;"}]},"source_url":"https://sqlly.app/sql-functions/json-valid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/json-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JSON_VALUE function","description":"JSON_VALUE on SQL Server, MySQL 8.0.21+, Oracle and PostgreSQL 17: extract one scalar as SQL text, with lax or strict paths deciding between NULL and an error.","body":{"slug":"json-value","name":"JSON_VALUE","h1":"SQL JSON_VALUE function","category":"string","lede":"JSON_VALUE(doc, '$.user.name') reads one scalar from a JSON document as SQL text. It is the usual way to index, filter or cast a single JSON field.","syntax":"JSON_VALUE(expression, path)","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"PostgreSQL 17+; the ->> operator before that"},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0.21+, with an optional RETURNING type"},{"engine_slug":"sqlite","status":"no","note":"no JSON_VALUE; json_extract already returns unquoted SQL values"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["JSON_VALUE is scalar-only on SQL Server, Oracle and PostgreSQL: pointed at an object or array it returns NULL by default. SQL Server raises an error instead with a 'strict $...' path, Oracle and PostgreSQL with ERROR ON ERROR. A silent NULL usually means you asked for structure; use JSON_QUERY. MySQL is the exception: it returns the object or array as JSON text, even with ERROR ON ERROR.","The result is text (nvarchar(4000) on SQL Server). Cast it for arithmetic, TRY_CAST(JSON_VALUE(...) AS int), or declare the type with RETURNING on MySQL, Oracle and PostgreSQL.","Malformed JSON behaves differently: PostgreSQL raises an error even with NULL ON ERROR, because the text fails its cast to jsonb before the path runs. SQL Server raises one in lax mode too, but it parses lazily, so a document broken only after the requested value can still return that value. MySQL returns NULL with a warning, and Oracle returns NULL by default. Validate on load with ISJSON, IS JSON or a CHECK constraint."],"examples":[{"engine_slug":"sql-server","sql":"SELECT JSON_VALUE(config, '$.region') AS region\nFROM settings;"},{"engine_slug":"oracle","sql":"SELECT JSON_VALUE(doc, '$.user.name') AS name\nFROM payloads;"},{"engine_slug":"sql-server","sql":"SELECT JSON_VALUE(config, 'strict $.owner.email') AS email\nFROM settings;"},{"engine_slug":"mysql","sql":"SELECT JSON_VALUE(config, '$.region') AS region\nFROM settings;"},{"engine_slug":"postgresql","sql":"SELECT config->>'region' AS region\nFROM settings;"}],"faqs":[{"question":"JSON_VALUE or JSON_QUERY?","answer":"JSON_VALUE for scalars (strings, numbers, booleans); JSON_QUERY for objects and arrays. JSON_VALUE returns NULL for an object or array by default (MySQL, which has no JSON_QUERY, returns the fragment as JSON text instead); JSON_QUERY on a scalar returns NULL on SQL Server and the quoted JSON scalar on PostgreSQL and Oracle 23ai."},{"question":"Why does JSON_VALUE return NULL on my array?","answer":"Lax mode hides the type error: a path into an object or array yields NULL. Switch to JSON_QUERY for the fragment, or make the mistake loud with a 'strict $...' path on SQL Server or ERROR ON ERROR on PostgreSQL and Oracle; a strict path alone still returns NULL on PostgreSQL, and MySQL returns the fragment as JSON text."}],"related":["json-query","json-extract","openjson","json-valid"],"novel_uses":[{"body":"JSON_VALUE is deterministic, so SQL Server lets it back a persisted computed column, and the index on that column does the seeking. This is the standard pattern for fast JSON filters there.","sql":"ALTER TABLE settings ADD region AS JSON_VALUE(config, '$.region') PERSISTED; CREATE INDEX ix_settings_region ON settings (region);"},{"body":"MySQL, Oracle and PostgreSQL accept RETURNING with DEFAULT ... ON EMPTY and DEFAULT ... ON ERROR, so one call extracts, types and falls back: missing or unusable values become 0 instead of NULL or a raised error. Both clauses matter: ON ERROR alone leaves a missing key NULL, and without RETURNING a non-numeric string passes through as text. Reads then need no COALESCE ladder.","sql":"SELECT JSON_VALUE(doc, '$.retries' RETURNING DECIMAL DEFAULT 0 ON EMPTY DEFAULT 0 ON ERROR) AS retries FROM tasks;"}]},"source_url":"https://sqlly.app/sql-functions/json-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/jsonb-contains","corpus":"sql-functions","engine":null,"language":"en","title":"SQL @> JSON containment operator","description":"PostgreSQL's @> containment operator asks whether one jsonb document contains another, the indexable replacement for membership checks and partial matches.","body":{"slug":"jsonb-contains","name":"@> (jsonb)","h1":"SQL @> JSON containment operator","category":"string","lede":"payload @> '{\"tags\": [\"pro\"]}' is true when the right-hand document fits inside the left one. Containment, not equality, and GIN-indexable.","syntax":"jsonb @> jsonb  |  jsonb <@ jsonb","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"no equivalent short of OPENJSON shredding"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"JSON_CONTAINS(target, candidate); nested arrays match more loosely"},{"engine_slug":"sqlite","status":"no","note":"no operator; emulate with json_each"},{"engine_slug":"oracle","status":"no","note":"no operator; JSON_EXISTS for paths"}],"gotchas":["@> is containment, not equality: '{\"a\":1,\"b\":2}' @> '{\"a\":1}' is true. The reversed order asks the opposite question; <@ is contained-in.","The operator exists for jsonb only: a json column or a text literal needs the ::jsonb cast, and the error names the types, not the fix.","Paired with a GIN index (jsonb_ops or jsonb_path_ops) it answers from the index; without one, every row is parsed and compared.","Array containment means all elements: tags @> '[\"a\",\"b\"]' requires both. For any-of matching on string elements, use ?|: tags ?| array['a', 'b']."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM events\nWHERE payload @> '{\"tags\": [\"pro\"]}';"},{"engine_slug":"postgresql","sql":"SELECT * FROM events\nWHERE payload->'user' @> '\"matt\"';"},{"engine_slug":"postgresql","sql":"CREATE INDEX ON events USING gin (payload);"},{"engine_slug":"mysql","sql":"SELECT * FROM events\nWHERE JSON_CONTAINS(payload, '{\"tags\": [\"pro\"]}');"}],"faqs":[{"question":"@> or ->> comparisons?","answer":"@> for 'has this member/element' queries, indexable with GIN. ->> for comparing extracted text. Mixing them works but the index only helps @>."},{"question":"Why does @> fail on my json column?","answer":"The containment operator is defined for jsonb. Cast both sides (::jsonb) or, better, migrate the column to jsonb; json cannot use GIN indexes either."}],"related":["jsonb-exists","json-contains","json-path-operator","to-json"],"novel_uses":[{"body":"roles <@ '[\"admin\",\"editor\",\"viewer\"]'::jsonb passes only rows whose roles all sit inside the allowed set, the authorization question written as one indexable operator. @> asks the mirror question.","sql":"SELECT id FROM accounts WHERE roles <@ '[\"admin\",\"editor\",\"viewer\"]'::jsonb;"},{"body":"Containment works at any depth, so payload @> '{\"status\": \"active\", \"address\": {\"city\": \"Berlin\"}}' tests two nested facts without path chains. A GIN index on the column serves it.","sql":"SELECT id FROM events WHERE payload @> '{\"status\": \"active\", \"address\": {\"city\": \"Berlin\"}}';"}]},"source_url":"https://sqlly.app/sql-functions/jsonb-contains","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/jsonb-exists","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ? jsonb key-exists operator","description":"PostgreSQL's jsonb ? operator checks key or array-element existence in one shot, with ?| and ?& for any-or-all lists, indexable where ->> IS NOT NULL is not.","body":{"slug":"jsonb-exists","name":"? (jsonb)","h1":"SQL ? jsonb key-exists operator","category":"string","lede":"config ? 'region' is true when the object has that key, or when the array contains that element. The existence test that GIN indexes actually serve.","syntax":"jsonb ? text  |  jsonb ?| text[]  |  jsonb ?& text[]","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"no operator; JSON_PATH_EXISTS on 2022+"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"JSON_CONTAINS_PATH is the twin"},{"engine_slug":"sqlite","status":"partial","note":"json_type(doc, '$.key') IS NOT NULL"},{"engine_slug":"oracle","status":"partial","note":"JSON_EXISTS condition"}],"gotchas":["? on an object checks top-level keys and on an array checks string elements. A scalar string counts as itself: '\"foo\"'::jsonb ? 'foo' is true. Nested keys need -> first.","JDBC and some drivers treat ? as a parameter placeholder: double it as ??. The underlying function jsonb_exists(config, 'region') also sidesteps the parser, but the planner cannot use a GIN index for it, so it scans the table.","->> IS NOT NULL looks equivalent but cannot use the GIN index, and differs on JSON null: a member set to null passes ? and fails IS NOT NULL. Only the default jsonb_ops GIN serves ?, ?| and ?&; a jsonb_path_ops GIN index does not."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM settings WHERE config ? 'region';"},{"engine_slug":"postgresql","sql":"SELECT * FROM settings\nWHERE config ?| array['region', 'zone'];"},{"engine_slug":"postgresql","sql":"SELECT * FROM settings WHERE config->'tags' ? 'pro';"},{"engine_slug":"mysql","sql":"SELECT * FROM settings\nWHERE JSON_CONTAINS_PATH(config, 'one', '$.region');"},{"engine_slug":"sqlite","sql":"SELECT * FROM settings\nWHERE json_type(config, '$.region') IS NOT NULL;"},{"engine_slug":"oracle","sql":"SELECT * FROM settings WHERE JSON_EXISTS(config, '$.region');"}],"faqs":[{"question":"? or ->> IS NOT NULL?","answer":"? for existence: it uses a default (jsonb_ops) GIN index and counts JSON null as present. ->> IS NOT NULL for 'has a non-null value'. Different questions with different plans."},{"question":"Why is my ? parameter a bind placeholder?","answer":"Driver parsing: JDBC eats ? as a parameter. Write ?? (the driver escape) to keep the operator and its GIN index. The function form jsonb_exists(col, 'key') sidesteps the parser too, but the planner cannot use a GIN index for it."}],"related":["jsonb-contains","json-contains","json-path-operator","json-length"],"novel_uses":[{"body":"payload->'tags' ?| array['beta', 'alpha'] passes when the extracted array holds either element. It is the any-of membership test for array-valued fields, distinct from top-level key checks.","sql":"SELECT id FROM events WHERE payload->'tags' ?| array['beta', 'alpha'];"},{"body":"A partial btree index on NOT config ? 'region' tracks exactly the documents still missing the field, so a backfill job scans only them, and the index shrinks to nothing once they are gone.","sql":"CREATE INDEX ix_missing_region ON settings (id) WHERE NOT config ? 'region';"}]},"source_url":"https://sqlly.app/sql-functions/jsonb-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/julianday","corpus":"sql-functions","engine":null,"language":"en","title":"SQL JULIANDAY function","description":"SQLite's julianday() converts a date to a Julian day number (days since 4714 BC with the fraction carrying the time), ideal for day arithmetic.","body":{"slug":"julianday","name":"JULIANDAY","h1":"SQL JULIANDAY function","category":"datetime","lede":"Returns the date as a REAL count of days since November 24, 4714 BC; subtract two Julian days and you get the days between them.","syntax":"JULIANDAY('2024-01-15')  |  JULIANDAY('now')  |  julianday(d2) - julianday(d1)","return_type":"REAL (days)","support":[{"engine_slug":"sql-server","status":"no","note":"DATEDIFF(day, d1, d2) for day counts"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'J') gives the integer Julian day as text"},{"engine_slug":"mysql","status":"no","note":"DATEDIFF(d2, d1) for day counts; TO_DAYS for a day number"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'J') gives the integer Julian day"}],"gotchas":["The number includes the time as a fraction: julianday('2024-01-15 12:00') is .5 past the midnight value; CAST(julianday(d) + 0.5 AS INTEGER) gives the calendar day number, matching PostgreSQL's to_char(d, 'J'). A bare CAST to INTEGER is wrong before noon: 2024-01-15 00:00 gives 2460324 while 12:00 gives 2460325.","It is not an epoch: Julian days count from 4714 BC, not 1970. strftime('%s') is the seconds-since-1970 form.","Unparseable input returns NULL silently, so a malformed date string looks like a missing value rather than an error."],"examples":[{"engine_slug":"sqlite","sql":"SELECT julianday('2024-02-01') - julianday('2024-01-15') AS days_between;"},{"engine_slug":"sqlite","sql":"SELECT CAST(julianday('now') + 0.5 AS INTEGER) AS julian_day;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(SYSDATE, 'J') AS julian_day FROM dual;"},{"engine_slug":"postgresql","sql":"SELECT to_char(created_at, 'J') AS julian_day FROM orders;"}],"faqs":[{"question":"What is a Julian day number?","answer":"A continuous count of days since 4714 BC used by astronomers: no months, no zones, just days, which is why date subtraction is trivial."},{"question":"How is it different from Unix time?","answer":"Julian days count days (with fractional time) from 4714 BC; Unix time counts seconds from 1970. julianday('1970-01-01') is 2440587.5."}],"related":["sqlite-datetime","strftime","to-days"],"novel_uses":[{"body":"A REAL column holding julianday() output is compact, sorts as a number, and date arithmetic is plain subtraction; render it through datetime(at) only at the edge.","sql":"CREATE TABLE events (at REAL);\nINSERT INTO events VALUES (julianday('now'));\nSELECT datetime(at) AS readable FROM events;"},{"body":"Julian day integers are noon and midnight is .5, so julianday(v) - julianday(date(v)) isolates the clock: 0.75 means 18:00, with no strftime call in sight.","sql":"SELECT julianday('2024-01-15 18:00') - julianday(date('2024-01-15 18:00')) AS day_fraction;"}]},"source_url":"https://sqlly.app/sql-functions/julianday","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/justify-interval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL justify_interval function","description":"justify_interval, justify_hours and justify_days in PostgreSQL: carry 27 hours into 1 day 03:00 and 45 days into 1 mon 15 days for readable output.","body":{"slug":"justify-interval","name":"justify_interval","h1":"SQL justify_interval function","category":"datetime","lede":"Normalizes an interval by carrying 24-hour blocks into days and 30-day blocks into months.","syntax":"justify_interval(iv)  |  justify_hours(iv)  |  justify_days(iv)","return_type":"interval","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"DAY TO SECOND intervals auto-normalize on output"}],"gotchas":["justify_hours carries 24-hour blocks into days: INTERVAL '27 hours' becomes 1 day 03:00:00. justify_days carries 30-day blocks into months. justify_interval does both and also fixes mixed signs.","The 30-day month is an assumption, not a calendar rule: justify_days(INTERVAL '45 days') gives 1 mon 15 days. Useful for display, wrong for billing periods.","AVG on intervals is where these shine: raw averages leave giant hours fields; justify_interval(avg(duration)) reads like a human wrote it."],"examples":[{"engine_slug":"postgresql","sql":"SELECT justify_hours(INTERVAL '27 hours');  -- 1 day 03:00:00"},{"engine_slug":"postgresql","sql":"SELECT justify_interval(INTERVAL '45 days');  -- 1 mon 15 days"},{"engine_slug":"postgresql","sql":"SELECT justify_interval(avg(ended - started)) FROM jobs;"},{"engine_slug":"oracle","sql":"SELECT INTERVAL '27' HOUR FROM dual;  -- +01 03:00:00, normalized on output"}],"faqs":[{"question":"Why does my interval show 9000 hours?","answer":"SUM, AVG and multiplication keep hours in the time field: summing 400 shifts of 22:30:00 gives 9000:00:00. justify_interval carries that into days, months and years for display (9000 hours becomes 1 year 15 days)."},{"question":"Does Oracle need this?","answer":"No. INTERVAL DAY TO SECOND values normalize on creation and display; there is no raw uncarried state to fix."}],"related":["interval-arithmetic","timestamp-difference","extract-epoch","interval-literal"],"novel_uses":[{"body":"to_char prints only the fields the format names, so HH24:MI:SS drops the day count: justify first for clock-shaped labels instead of a four-digit hour counter (27 hours gives 03:00:00; 9000 hours gives 00:00:00 once justified), or add DD to keep the days (27 hours gives 01 03:00:00).","sql":"SELECT to_char(justify_interval(avg(ended - started)), 'HH24:MI:SS') FROM jobs;"},{"body":"Adding and subtracting several spans can leave a result like one day minus thirty hours; justify_interval folds it into a single signed value.","sql":"SELECT justify_interval(INTERVAL '1 day -30 hours');  -- -06:00:00"}]},"source_url":"https://sqlly.app/sql-functions/justify-interval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lag","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LAG function","description":"LAG in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: read the previous row without a self-join, for deltas, streaks and session gaps.","body":{"slug":"lag","name":"LAG","h1":"SQL LAG function","category":"window","lede":"Reads a value from an earlier row in the same partition, without a self-join. It is the usual tool for period-over-period deltas and for gaps between events.","syntax":"LAG(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The first row has no previous one: LAG returns NULL unless you pass a default (LAG(x, 1, 0)).","LAG needs an ORDER BY in the OVER clause; without it the previous row is undefined.","Filtering on a LAG result needs a CTE: window functions evaluate after WHERE.","IGNORE NULLS (take the previous non-NULL value) works on Oracle and SQL Server 2022+, not on PostgreSQL, MySQL or SQLite."],"examples":[{"engine_slug":"all","sql":"-- CHANGE is a reserved word in MySQL, so the alias is delta\nSELECT day, revenue,\n       revenue - LAG(revenue) OVER (ORDER BY day) AS delta\nFROM daily_sales;"},{"engine_slug":"postgresql","sql":"-- timestamp - timestamp is an interval here; date arithmetic differs per engine\nSELECT user_id, at,\n       at - LAG(at) OVER (PARTITION BY user_id ORDER BY at) AS gap\nFROM events;"}],"faqs":[{"question":"What does LAG return for the first row?","answer":"NULL, or the default you pass as the third argument: LAG(revenue, 1, 0) returns 0 instead."},{"question":"Do I still need a self-join for period-over-period?","answer":"Not when the comparison is the previous row: revenue - LAG(revenue) OVER (ORDER BY month) reads the table once. A self-join is still needed when the match is by value rather than position, such as the same month last year when some months are missing."}],"related":["lead","row-number","first-value"],"novel_uses":[{"body":"Flag rows whose gap from the previous event exceeds the session timeout, then running-sum the flags: every row in the same session shares a session number, computed in two window passes with no procedural loop.","sql":"WITH g AS (\n  SELECT user_id, at,\n         CASE WHEN at - LAG(at) OVER (PARTITION BY user_id ORDER BY at)\n                   > INTERVAL '30 minutes' THEN 1 ELSE 0 END AS new_session\n  FROM events\n)\nSELECT user_id, at,\n       SUM(new_session) OVER (PARTITION BY user_id ORDER BY at) AS session_no\nFROM g;"},{"body":"Comparing each row's plan with LAG(plan) finds exactly the rows where the attribute changed, which are the validity starts of a slowly changing dimension. IS DISTINCT FROM handles the NULL transitions PostgreSQL-style; MySQL's <=> and SQLite's IS NOT do the same job.","sql":"SELECT user_id, plan, at AS valid_from\nFROM (\n  SELECT user_id, plan, at,\n         LAG(plan) OVER (PARTITION BY user_id ORDER BY at) AS prev_plan\n  FROM subscriptions\n) s\nWHERE plan IS DISTINCT FROM prev_plan;"}]},"source_url":"https://sqlly.app/sql-functions/lag","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/last-day","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LAST_DAY function","description":"Get the last day of a month: LAST_DAY in MySQL and Oracle, EOMONTH in SQL Server, date_trunc arithmetic in PostgreSQL, strftime on SQLite.","body":{"slug":"last-day","name":"LAST_DAY / EOMONTH","h1":"SQL LAST_DAY function","category":"datetime","lede":"Returns the last day of the month containing the input: billing periods, month-end cutoffs, expiry dates. Leap years are handled for you.","syntax":"LAST_DAY(d)  -- MySQL, Oracle  |  EOMONTH(d [, months])  -- SQL Server","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"EOMONTH(d) since 2012, with an optional month offset"},{"engine_slug":"postgresql","status":"no","note":"no LAST_DAY; (date_trunc('month', d) + interval '1 month - 1 day')::date"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"date(d, 'start of month', '+1 month', '-1 day')"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["EOMONTH takes a month offset: EOMONTH(d, -1) is the end of the previous month.","The PostgreSQL idiom needs the cast: (date_trunc('month', d) + interval '1 month - 1 day')::date, or the result is a timestamp.","Oracle's LAST_DAY keeps the time of day: LAST_DAY of 2026-02-10 13:00 is 2026-02-28 13:00. TRUNC it before comparing.","WHERE ts <= LAST_DAY(d) misses everything after midnight on the last day when ts is a timestamp. Use ts < the first day of the next month instead.","In SQLite, the modifier order matters: 'start of month' must come before '+1 month'. Written the other way, January 31 plus a month overflows to March 3 and the result is February 28."],"examples":[{"engine_slug":"mysql","sql":"SELECT LAST_DAY(order_date) AS cutoff FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT EOMONTH(order_date) AS cutoff FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT (date_trunc('month', order_date) + interval '1 month - 1 day')::date AS cutoff\nFROM orders;"},{"engine_slug":"oracle","sql":"SELECT LAST_DAY(order_date) AS cutoff FROM orders;"}],"faqs":[{"question":"What is the PostgreSQL equivalent of LAST_DAY?","answer":"There is none; the idiom is (date_trunc('month', d) + interval '1 month - 1 day')::date. Wrap it in an IMMUTABLE SQL function if you use it everywhere."},{"question":"Does EOMONTH handle leap years?","answer":"Yes. EOMONTH('2028-02-10') is 2028-02-29, and the other engines' versions get leap years right too."}],"related":["dateadd","date-trunc","months-between"],"novel_uses":[{"body":"DAY(LAST_DAY(d)) gives the month's length, so days_in_month - DAY(d) + 1 over days_in_month is the fraction of the month still to bill. No calendar table, and leap years come out right because LAST_DAY handles them.","sql":"SELECT DAY(d) AS day_no,\n       DAY(LAST_DAY(d)) AS days_in_month,\n       (DAY(LAST_DAY(d)) - DAY(d) + 1) / DAY(LAST_DAY(d)) AS prorate\nFROM billing_periods;"},{"body":"CHECK (renews_on = LAST_DAY(renews_on)) rejects any policy date that is not a month end, moving the invariant from application code into the schema. MySQL has enforced CHECK since 8.0.16; PostgreSQL has no LAST_DAY, so express the same test with the date_trunc idiom.","sql":"ALTER TABLE policies\nADD CONSTRAINT chk_month_end\nCHECK (renews_on = LAST_DAY(renews_on));"}]},"source_url":"https://sqlly.app/sql-functions/last-day","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/last-insert-id","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LAST_INSERT_ID and SCOPE_IDENTITY","description":"Read the id of the row you just inserted on SQL Server, PostgreSQL, MySQL, SQLite and Oracle, and why @@IDENTITY and MAX(id) can return the wrong row.","body":{"slug":"last-insert-id","name":"LAST_INSERT_ID / SCOPE_IDENTITY","h1":"SQL LAST_INSERT_ID and SCOPE_IDENTITY","category":"system","lede":"After an INSERT into an auto-numbered table you usually need the new key. Each engine keeps it per connection, and RETURNING or OUTPUT hands it back from the INSERT itself.","syntax":"SCOPE_IDENTITY()  |  LAST_INSERT_ID()  |  last_insert_rowid()  |  INSERT ... RETURNING id","return_type":"the generated key (numeric)","support":[{"engine_slug":"sql-server","status":"yes","note":"SCOPE_IDENTITY(); OUTPUT inserted.id returns every new key"},{"engine_slug":"postgresql","status":"partial","note":"INSERT ... RETURNING id; lastval() or currval('seq') afterwards"},{"engine_slug":"mysql","status":"yes","note":"LAST_INSERT_ID()"},{"engine_slug":"sqlite","status":"partial","note":"last_insert_rowid(); RETURNING from 3.35"},{"engine_slug":"oracle","status":"partial","note":"INSERT ... RETURNING id INTO a PL/SQL variable or bind"}],"gotchas":["SQL Server's @@IDENTITY returns the last identity value the session generated in any scope, including a trigger that wrote to an audit table. SCOPE_IDENTITY() stays in the current scope, and IDENT_CURRENT('table') ignores the session altogether.","After a multi-row INSERT, MySQL's LAST_INSERT_ID() is the id of the first row in that statement. SQL Server's SCOPE_IDENTITY() is the last one.","SELECT MAX(id) races with other sessions and can return someone else's row. The functions here are per connection, so they are safe only when the INSERT and the read run on the same connection.","When one INSERT adds several rows, return the keys from the statement: OUTPUT inserted.id on SQL Server, RETURNING id on PostgreSQL and SQLite."],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE notes (id INT IDENTITY PRIMARY KEY, body VARCHAR(50));\nINSERT INTO notes (body) VALUES ('a'), ('b'), ('c');\nSELECT SCOPE_IDENTITY() AS new_id;  -- 3"},{"engine_slug":"mysql","sql":"CREATE TABLE notes (id INT AUTO_INCREMENT PRIMARY KEY, body VARCHAR(50));\nINSERT INTO notes (body) VALUES ('a'), ('b'), ('c');\nSELECT LAST_INSERT_ID() AS new_id;  -- 1, the first row of the statement"},{"engine_slug":"postgresql","sql":"CREATE TABLE notes (id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body TEXT);\nINSERT INTO notes (body) VALUES ('a'), ('b') RETURNING id;  -- 1, 2"},{"engine_slug":"sqlite","sql":"CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT);\nINSERT INTO notes (body) VALUES ('a'), ('b');\nSELECT last_insert_rowid() AS new_id;  -- 2"},{"engine_slug":"oracle","sql":"CREATE TABLE notes (id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body VARCHAR2(50));\nDECLARE\n  v_id notes.id%TYPE;\nBEGIN\n  INSERT INTO notes (body) VALUES ('a') RETURNING id INTO v_id;\n  DBMS_OUTPUT.PUT_LINE(v_id);  -- 1\nEND;\n/"}],"faqs":[{"question":"Is SCOPE_IDENTITY safe with concurrent inserts?","answer":"Yes. It reads the value your own session generated in the current scope, so another connection inserting at the same moment does not change it. A later insert into another identity table in the same scope does."},{"question":"How do I get every id from a multi-row insert?","answer":"Return them from the INSERT: OUTPUT inserted.id on SQL Server, RETURNING id on PostgreSQL and SQLite, RETURNING ... BULK COLLECT INTO in Oracle PL/SQL. MySQL has no RETURNING, so insert one row at a time or look the rows up again by a natural key."}],"related":["nextval","row-count","uuid-function","newid"],"novel_uses":[{"body":"A trigger that inserts into an audit table with its own serial or identity key updates lastval() too, so reading lastval() after the INSERT can return the audit table's id. Call currval('orders_id_seq') with the named sequence, or take the key from RETURNING id.","sql":"INSERT INTO orders (note) VALUES ('a');\nSELECT currval('orders_id_seq') AS my_id;  -- not lastval(), which may hold the trigger's sequence"},{"body":"An OUTPUT clause without INTO fails with error 334 when the target table has an enabled trigger, a common setup on audited tables. Route the keys through a table variable with OUTPUT ... INTO, or read SCOPE_IDENTITY() for a single row.","sql":"DECLARE @ids TABLE (id INT);\nINSERT INTO notes (body)\nOUTPUT inserted.id INTO @ids (id)\nVALUES ('a'), ('b');\nSELECT id FROM @ids;"}]},"source_url":"https://sqlly.app/sql-functions/last-insert-id","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/last-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LAST_VALUE function","description":"LAST_VALUE in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle, and the default frame that makes it return the current row instead of the last.","body":{"slug":"last-value","name":"LAST_VALUE","h1":"SQL LAST_VALUE function","category":"window","lede":"Returns an expression from the last row of the window frame. The famous trap: the default frame ends at the current row, so naive LAST_VALUE returns the row you are on.","syntax":"LAST_VALUE(expression) OVER (ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so LAST_VALUE(price) OVER (ORDER BY day) returns the current row's price. The fix is an explicit frame: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.","FIRST_VALUE does not hit this, because the default frame always starts at the partition's first row. It only reaches the partition's last row on that last row.","With RANGE (the default) and ties in the ORDER BY, LAST_VALUE returns the last of the current row's peers, not the current row, which makes the wrong result harder to spot."],"examples":[{"engine_slug":"all","sql":"-- returns the day's own price without the frame fix!\nSELECT day, price,\n       LAST_VALUE(price) OVER (ORDER BY day) AS wrong\nFROM prices;"},{"engine_slug":"all","sql":"-- the correct form\nSELECT day, price,\n       LAST_VALUE(price) OVER (\n         ORDER BY day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS close_price\nFROM prices;"}],"faqs":[{"question":"Why does LAST_VALUE return the current row?","answer":"The default window frame stops at the current row, so the last row of the frame is the row you are on. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to stretch the frame over the whole partition."},{"question":"Is there an easier way to get the last row's value?","answer":"Yes: FIRST_VALUE with the order reversed. FIRST_VALUE(price) OVER (ORDER BY day DESC) returns the last day's price with the default frame, no frame clause needed."}],"related":["first-value","lead","row-number"],"novel_uses":[{"body":"The mirror of forward-fill: a frame from the current row to the partition's end plus IGNORE NULLS takes the next real reading instead of the last one, which is what closing prices and final statuses need when the feed has holes. IGNORE NULLS exists on Oracle and SQL Server 2022+.","sql":"SELECT at,\n       LAST_VALUE(price IGNORE NULLS) OVER (\n         ORDER BY at\n         ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS next_known\nFROM prices;"},{"body":"A frame bounded by an interval rather than a row count sees all events within the next hour, which is what burst detection wants. PostgreSQL (11+) and Oracle accept interval bounds on RANGE; the other engines fall back to a self join.","sql":"SELECT at,\n       LAST_VALUE(at) OVER (\n         ORDER BY at\n         RANGE BETWEEN CURRENT ROW AND INTERVAL '1 hour' FOLLOWING) AS burst_end\nFROM clicks;"}]},"source_url":"https://sqlly.app/sql-functions/last-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lc-time-names","corpus":"sql-functions","engine":null,"language":"en","title":"SQL lc_time_names variable","description":"MySQL's lc_time_names and its equivalents elsewhere: how the session locale changes month and weekday names in DATE_FORMAT, DAYNAME and MONTHNAME.","body":{"slug":"lc-time-names","name":"lc_time_names","h1":"SQL lc_time_names variable","category":"datetime","lede":"A session variable selecting the language MySQL uses for month and day names in formatted output: 'de_DE', 'ja_JP', 'fr_FR' and so on.","syntax":"SET lc_time_names = 'de_DE'","return_type":"session variable","support":[{"engine_slug":"sql-server","status":"partial","note":"SET LANGUAGE: changes DATENAME output and date parsing order"},{"engine_slug":"postgresql","status":"partial","note":"lc_time setting plus the TM prefix in to_char"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"names are not produced at all"},{"engine_slug":"oracle","status":"partial","note":"NLS_DATE_LANGUAGE per session or per TO_CHAR call"}],"gotchas":["lc_time_names changes %W, %a, %M and %b in DATE_FORMAT, plus DAYNAME and MONTHNAME. It does not touch STR_TO_DATE, which parses English names only: STR_TO_DATE('1 Juli 2026', '%d %M %Y') is NULL even on a de_DE session.","Locale names use an underscore: 'de_DE', not 'de-DE'. An unknown name fails with error 1649 (Unknown locale) instead of falling back to English.","Per-call overrides beat session changes for mixed-locale reports: Oracle TO_CHAR(d, 'DD Month', 'NLS_DATE_LANGUAGE=FRENCH'). PostgreSQL's to_char(d, 'DD TMMonth') follows the lc_time setting, which SET can change per session, but only for locales the server OS has installed: on the stock postgres:18 image SET lc_time = 'fr_FR' fails with an invalid value error and only C and en_US.utf8 work.","%p is not localized: DATE_FORMAT(d, '%p') prints AM or PM under fr_FR too."],"examples":[{"engine_slug":"mysql","sql":"SET lc_time_names = 'fr_FR';  SELECT DATE_FORMAT('2026-08-01', '%W %d %M');  -- samedi 01 août"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(DATE '2026-08-01', 'DD Month', 'NLS_DATE_LANGUAGE=FRENCH') FROM dual;  -- 01 Août"},{"engine_slug":"sql-server","sql":"SET LANGUAGE FRENCH;  SELECT DATENAME(MONTH, '2026-08-01');  -- août"},{"engine_slug":"postgresql","sql":"SET lc_time = 'fr_FR';  SELECT to_char(DATE '2026-08-01', 'TMDay, TMMonth');  -- samedi, août"}],"faqs":[{"question":"Does lc_time_names change how dates are stored?","answer":"No. Stored values never localize. It changes formatted output only; STR_TO_DATE keeps parsing English names."},{"question":"How do I localize dates in SQL Server?","answer":"SET LANGUAGE (affects DATENAME) or FORMAT(d, 'MMMM', 'de-DE') with an explicit culture; FORMAT is the per-call option that does not leak session-wide."}],"related":["date-format","dayname","format-date","nls-date-format"],"novel_uses":[{"body":"Connection pools recycle sessions with their state, so a SET lc_time_names leaks into the next borrower's output. Reset it after use or format per call.","sql":"SET lc_time_names = 'fr_FR';  SELECT DAYNAME('2026-08-01');  SET lc_time_names = 'en_US';"},{"body":"%p prints AM or PM under every locale, so build the localized marker with CASE on HOUR for reports that should read matin and apres-midi.","sql":"SELECT CONCAT(TIME_FORMAT('14:30:00', '%h:%i'), ' ', CASE WHEN HOUR('14:30:00') < 12 THEN 'matin' ELSE 'apres-midi' END);"}]},"source_url":"https://sqlly.app/sql-functions/lc-time-names","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lcase","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LCASE function","description":"LCASE lowercases a string in MySQL, a synonym of LOWER with identical collation behaviour, and absent from every other major engine.","body":{"slug":"lcase","name":"LCASE","h1":"SQL LCASE function","category":"string","lede":"Returns the string with every character lowercased. The MySQL-only alias: same engine, same rules, different spelling.","syntax":"LCASE(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["LCASE is an exact synonym of LOWER in MySQL; there is no reason to prefer either except consistency with your codebase.","Every other major engine spells it LOWER only, so LCASE in a shared migration or ORM query will not port.","Casing does not follow the collation: under utf8mb4_tr_0900_ai_ci, LCASE('I') still returns 'i'. For matching, a *_ci collation already ignores case without the function.","The index rule applies as with LOWER: LCASE(column) = constant cannot use a plain index on the column."],"examples":[{"engine_slug":"mysql","sql":"SELECT LCASE('ShIP') AS quiet;  -- ship"},{"engine_slug":"mysql","sql":"UPDATE users SET email = LCASE(email) WHERE id = 3;"}],"faqs":[{"question":"Should I use LCASE or LOWER?","answer":"They are the same in MySQL. LOWER is the portable spelling every engine accepts, so new code defaults to it."},{"question":"Does LCASE change how comparisons work?","answer":"The rule does not change: comparisons still follow the column's collation. The value does change, though. On a binary column, LCASE(email) = 'ada@example.com' matches 'Ada@Example.com' while email = 'ada@example.com' does not."},{"question":"Why does LCASE('É') stay accented?","answer":"LCASE maps É to é, not to e. Accent-insensitive matching needs a collation such as utf8mb4_0900_ai_ci, not a casing function."}],"related":["lower","ucase","upper"],"novel_uses":[{"body":"A functional index on LOWER(email) enforces case-insensitive uniqueness in MySQL 8.0.13+ without changing the column's collation.","sql":"ALTER TABLE users ADD UNIQUE INDEX idx_email_lower ((LOWER(email)));"},{"body":"Grouping by LOWER(tag) and keeping MIN(tag) as the display form lists every case-only duplicate family in one query.","sql":"SELECT MIN(tag) AS keep_tag, LOWER(tag) AS folded, COUNT(*)\nFROM labels\nGROUP BY LOWER(tag)\nHAVING COUNT(*) > 1;"}]},"source_url":"https://sqlly.app/sql-functions/lcase","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lcm","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LCM function","description":"lcm(a, b) is the smallest number both divide into, a PostgreSQL 13+ builtin via gcd, and definable anywhere as abs(a / gcd(a, b)) * b once you have a GCD.","body":{"slug":"lcm","name":"LCM","h1":"SQL LCM function","category":"math","lede":"Returns the least common multiple of two integers: lcm(4, 6) is 12, related to gcd by the identity lcm(a, b) * gcd(a, b) = a * b for positive integers.","syntax":"LCM(a, b)","return_type":"integer / bigint / numeric","support":[{"engine_slug":"sql-server","status":"no","note":"No built-in; compute via a GCD helper and abs(a / gcd(a, b)) * b"},{"engine_slug":"postgresql","status":"yes","note":"Built in since PostgreSQL 13; computed as abs(a / gcd(a, b)) * b, dividing before multiplying, and lcm(0, x) is 0"},{"engine_slug":"mysql","status":"no","note":"No built-in; recursive CTE for GCD, then the identity"},{"engine_slug":"sqlite","status":"no","note":"No built-in; same approach"},{"engine_slug":"oracle","status":"no","note":"No built-in; same approach"}],"gotchas":["lcm(0, x) is 0 on PostgreSQL: zero is the only multiple zero shares with anything.","The product a * b can overflow bigint before the division: PostgreSQL's builtin guards internally, but a hand-rolled a * b / gcd(a, b) can overflow; divide first where possible.","Everything about availability mirrors GCD: one builtin (PostgreSQL 13+), Euclidean fallback elsewhere."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LCM(4, 6) AS twelve;  -- 12"},{"engine_slug":"postgresql","sql":"SELECT LCM(cadence_a, cadence_b) AS sync_days\nFROM schedules;"}],"faqs":[{"question":"What is the relation between LCM and GCD?","answer":"lcm(a, b) * gcd(a, b) = a * b (for positive integers). So once a GCD exists (PostgreSQL's gcd() or your own Euclidean CTE), LCM is a*b/gcd."},{"question":"Which engines have LCM?","answer":"PostgreSQL 13+. Elsewhere compute abs(a / gcd(a, b)) * b with a hand-rolled GCD, dividing first so the intermediate product cannot overflow."},{"question":"Why is lcm(0, 5) equal to 0?","answer":"PostgreSQL defines it that way: zero has no positive multiples other than zero itself, so zero is the least common multiple it shares with 5."}],"related":["gcd","modulo-operator","factorial"],"novel_uses":[{"body":"Common denominator first: lcm(d1, d2), then scale each numerator by its share. Adding rational columns this way avoids the rounding a float conversion costs.","sql":"SELECT 1 * (lcm(4, 6) / 4) + 1 * (lcm(4, 6) / 6) AS sum_num, lcm(4, 6) AS sum_den;  -- 5, 12 on PostgreSQL 13+"},{"body":"For positive integers, lcm(a, b) = b exactly when a divides b. A negative b never matches, because lcm is never negative. On PostgreSQL 13+ this is a one-call config check, handy where % on a zero would error.","sql":"SELECT * FROM cadences WHERE lcm(source_period, target_period) = target_period;"}]},"source_url":"https://sqlly.app/sql-functions/lcm","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lead","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LEAD function","description":"LEAD in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: peek at the next row for durations until the next event, next-step funnels and end markers.","body":{"slug":"lead","name":"LEAD","h1":"SQL LEAD function","category":"window","lede":"The mirror of LAG: reads a value from a later row in the partition. Time until the next event, the next step in a funnel and is-last flags all come from it.","syntax":"LEAD(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The last row has no next one: LEAD returns NULL by default, or your chosen default value.","LEAD(at, 1, at) makes the last event's time-until-next zero instead of NULL.","Offsets must be non-negative on SQL Server, Oracle and MySQL; PostgreSQL and SQLite accept LEAD(x, -1) and treat it as LAG(x). Write LAG when you mean the previous row.","LEAD(x) IS NULL marks the last row of each partition only when x itself is never NULL. Test LEAD(id) or ROW_NUMBER instead."],"examples":[{"engine_slug":"postgresql","sql":"SELECT user_id, at,\n       LEAD(at) OVER (PARTITION BY user_id ORDER BY at) - at AS until_next\nFROM events;"},{"engine_slug":"all","sql":"SELECT step, LEAD(step) OVER (ORDER BY position) AS next_step\nFROM funnel_steps;"}],"faqs":[{"question":"What is the difference between LEAD and LAG?","answer":"Direction: LAG looks at earlier rows, LEAD at later ones, both according to the OVER clause's ORDER BY."},{"question":"How do I compute time until the next event?","answer":"LEAD(at) OVER (PARTITION BY user ORDER BY at) - at. Pass a default (LEAD(at, 1, at)) if the last event's open-ended duration should be zero rather than NULL."}],"related":["lag","row-number","last-value"],"novel_uses":[{"body":"The next version's start is this version's end. LEAD with a far-future default keeps the current version open instead of ending at NULL, so the validity interval is complete on every row.","sql":"SELECT user_id, plan, at AS valid_from,\n       LEAD(at, 1, TIMESTAMPTZ '9999-12-31') OVER (PARTITION BY user_id ORDER BY at) AS valid_to\nFROM subscriptions;"},{"body":"Pair every step with LEAD(step) and count the pairs: that table is the funnel's transition matrix, and the collapse from one step to the next is precisely where users drop out. One scan of the event log, no self join.","sql":"WITH s AS (\n  SELECT user_id, step,\n         LEAD(step) OVER (PARTITION BY user_id ORDER BY at) AS next_step\n  FROM funnel_events\n)\nSELECT step, next_step, COUNT(*) AS users\nFROM s\nGROUP BY 1, 2\nORDER BY 1, 2;"}]},"source_url":"https://sqlly.app/sql-functions/lead","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/least","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LEAST function","description":"LEAST picks the smallest argument: PostgreSQL and SQL Server 2022+ skip NULLs while MySQL, Oracle and SQLite's min(a, b) return NULL, plus NULL-safe recipes.","body":{"slug":"least","name":"LEAST","h1":"SQL LEAST function","category":"conditional","lede":"Returns the smallest of two or more expressions.","syntax":"LEAST(a, b, ...) | min(a, b, ...)","return_type":"highest-precedence argument type (Oracle: first argument's type)","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+; skips NULLs"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"SQLite spells it min(a, b, ...) with two or more arguments"},{"engine_slug":"oracle","status":"yes","note":"result type comes from the first argument"}],"gotchas":["Same NULL split as GREATEST: PostgreSQL and SQL Server return the smallest non-NULL argument; MySQL, Oracle and SQLite's min() return NULL if any argument is NULL.","Wrap arguments in COALESCE when a NULL should be skipped rather than poison the result.","SQLite's spelling is min(a, b) with two or more arguments; min(col) with one is the aggregate."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LEAST(started_at, finished_at) FROM runs;"},{"engine_slug":"mysql","sql":"SELECT LEAST(NULL, 3) AS n, LEAST(COALESCE(NULL, 9999), 3) AS safe;"},{"engine_slug":"sqlite","sql":"SELECT min(a, b) FROM t;"},{"engine_slug":"sql-server","sql":"SELECT LEAST(started_at, finished_at) FROM runs;"},{"engine_slug":"oracle","sql":"SELECT LEAST(10, 3, 7) AS smallest FROM dual;"}],"faqs":[{"question":"Does LEAST ignore NULLs?","answer":"In PostgreSQL and SQL Server yes; in MySQL, Oracle and SQLite's min(a, b) a single NULL makes the result NULL."},{"question":"SQL Server equivalent?","answer":"LEAST since SQL Server 2022; before that, CASE or IIF chains."},{"question":"LEAST vs aggregate MIN?","answer":"LEAST compares expressions within one row; MIN scans a column across rows."}],"related":["greatest","min","coalesce","null","case"],"novel_uses":[{"body":"LEAST(requested, stock) never promises more units than exist, the one-line guard behind reserve-now-notify-later flows.","sql":"SELECT sku, LEAST(requested_qty, stock_qty) AS shippable FROM reservations;"},{"body":"The lesser of two tables' high-water marks is the newest timestamp both can serve, so a replay starts where the data is consistent.","sql":"SELECT LEAST((SELECT MAX(processed_at) FROM charges), (SELECT MAX(processed_at) FROM payouts)) AS replay_from;"}]},"source_url":"https://sqlly.app/sql-functions/least","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/left","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LEFT function","description":"Take the first n characters with SQL LEFT in SQL Server, PostgreSQL and MySQL, and the SUBSTRING equivalents you need on SQLite and Oracle.","body":{"slug":"left","name":"LEFT","h1":"SQL LEFT function","category":"string","lede":"Returns the leftmost n characters of a string. SQL Server, PostgreSQL and MySQL have it; SQLite and Oracle use SUBSTR instead.","syntax":"LEFT(string, n)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no LEFT(); use SUBSTR(string, 1, n)"},{"engine_slug":"oracle","status":"partial","note":"no LEFT(); use SUBSTR(string, 1, n)"}],"gotchas":["If n is longer than the string, LEFT returns the whole string, with no padding and no error.","Negative n differs: SQL Server raises 'Invalid length parameter', MySQL returns '', and PostgreSQL returns all but the last |n| characters, so LEFT('abc', -1) is 'ab'.","The SQLite and Oracle stand-in is SUBSTR(string, 1, n), which behaves the same for positive n."],"examples":[{"engine_slug":"sql-server","sql":"-- same on PostgreSQL and MySQL\nSELECT LEFT('2026-08-01', 4) AS year;  -- 2026"},{"engine_slug":"postgresql","sql":"SELECT LEFT('2026-08-01', 4) AS year;  -- 2026"},{"engine_slug":"mysql","sql":"SELECT LEFT('2026-08-01', 4) AS year;  -- 2026"},{"engine_slug":"sqlite","sql":"SELECT SUBSTR('2026-08-01', 1, 4) AS year;  -- 2026"},{"engine_slug":"oracle","sql":"SELECT SUBSTR('2026-08-01', 1, 4) AS year FROM dual;  -- 2026"}],"faqs":[{"question":"Does Oracle have a LEFT function?","answer":"No. Use SUBSTR(string, 1, n), which returns the same first n characters."},{"question":"What happens if n is bigger than the string?","answer":"LEFT returns the entire string. It never pads, so LEFT(code, 3) on a two-character code gives two characters back."}],"related":["right","substring","lpad"],"novel_uses":[{"body":"Grouping by LEFT(postcode, 2) or the first three SKU characters turns a high-cardinality code into a small prefix dimension for reports. SQLite and Oracle have no LEFT; SUBSTR(code, 1, 2) is identical for positive lengths.","sql":"SELECT LEFT(postcode, 2) AS area, COUNT(*) AS customers\nFROM addresses\nGROUP BY 1;"},{"body":"WHERE LEFT(sku, 3) = 'ABC' and WHERE sku LIKE 'ABC%' select the same rows, but the LIKE form can use an index as a range scan while the function call always scans the table. PostgreSQL wants the C collation or a text_pattern_ops index for the LIKE form; SQL Server does it with a plain one.","sql":"SELECT * FROM products\nWHERE sku LIKE 'ABC%';"}]},"source_url":"https://sqlly.app/sql-functions/left","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LENGTH function","description":"String length in SQL Server (LEN), PostgreSQL, MySQL, SQLite and Oracle: characters versus bytes, trailing spaces, and UTF-8 multi-byte surprises.","body":{"slug":"length","name":"LENGTH / LEN","h1":"SQL LENGTH function","category":"string","lede":"Returns how long a string is. The catch is the unit: LEN and LENGTH usually count characters, but MySQL's LENGTH counts bytes, which differs as soon as accents or emoji appear.","syntax":"LEN(string)  -- SQL Server  |  LENGTH(string)  |  CHAR_LENGTH(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"spelled LEN; ignores trailing spaces; DATALENGTH counts bytes"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"LENGTH counts bytes, CHAR_LENGTH counts characters"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL: LENGTH('é') is 2 (UTF-8 bytes), CHAR_LENGTH('é') is 1. Use CHAR_LENGTH for user-visible text.","SQL Server's LEN ignores trailing spaces: LEN('ab ') is 2. DATALENGTH keeps them but counts bytes, so DATALENGTH(N'ab ') is 6.","PostgreSQL has LENGTH and CHAR_LENGTH (characters) and OCTET_LENGTH (bytes). Oracle's LENGTH counts characters and LENGTHB counts bytes. SQLite's LENGTH counts characters for text and bytes for blobs."],"examples":[{"engine_slug":"postgresql","sql":"-- LENGTH counts characters on PostgreSQL, SQLite and Oracle\nSELECT LENGTH('héllo') AS chars;  -- 5"},{"engine_slug":"sql-server","sql":"-- LEN ignores trailing spaces; DATALENGTH counts bytes\nSELECT LEN('héllo') AS chars;  -- 5"},{"engine_slug":"mysql","sql":"SELECT LENGTH('héllo') AS bytes, CHAR_LENGTH('héllo') AS chars;\n-- 6, 5"},{"engine_slug":"sqlite","sql":"SELECT length('héllo') AS chars;  -- 5"},{"engine_slug":"oracle","sql":"SELECT LENGTH('héllo') AS chars FROM dual;  -- 5"}],"faqs":[{"question":"Does LENGTH count characters or bytes?","answer":"On MySQL, bytes, so 'é' counts as 2 and an emoji as 4. CHAR_LENGTH counts characters. PostgreSQL's LENGTH counts characters and OCTET_LENGTH counts bytes."},{"question":"Why does LEN ignore my trailing spaces?","answer":"SQL Server's LEN excludes trailing spaces by design. DATALENGTH does not, but counts bytes, not characters."}],"related":["trim","substring","concat"],"novel_uses":[{"body":"MIN, MAX and AVG of LENGTH over a batch expose the real width to allocate and the dirty rows: a max far above the typical length usually means pasted garbage or padding. On SQL Server, remember LEN ignores trailing spaces, so measure right-padding with DATALENGTH.","sql":"SELECT MIN(LENGTH(email)) AS shortest,\n       MAX(LENGTH(email)) AS longest,\n       AVG(LENGTH(email)) AS typical\nFROM users;"},{"body":"On Oracle '' is NULL, so WHERE s = '' matches nothing, and s <> '' silently excludes rows on every engine when s is NULL. LENGTH(TRIM(s)) > 0 says a value has real content everywhere (LEN on SQL Server); the inverse catches NULL, empty and whitespace-only values in one condition.","sql":"SELECT * FROM users\nWHERE email IS NULL OR LENGTH(TRIM(email)) = 0;"}]},"source_url":"https://sqlly.app/sql-functions/length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lengthb","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LENGTHB function","description":"Oracle's LENGTHB returns a string's length in bytes, the encoding-aware twin of LENGTH, with LENGTHC, LENGTH2 and LENGTH4 completing the family.","body":{"slug":"lengthb","name":"LENGTHB","h1":"SQL LENGTHB function","category":"string","lede":"Byte count under the database charset: the number storage limits actually enforce when VARCHAR2 semantics are bytes.","syntax":"LENGTHB(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The family: LENGTH (characters in the input's character set), LENGTHB (bytes), LENGTHC (complete Unicode characters), LENGTH2 (UTF-16 code units), LENGTH4 (code points).","Under AL32UTF8, LENGTHB('é') is 2 and LENGTH('é') is 1. An emoji in a VARCHAR2 is LENGTH 1, LENGTH2 2, LENGTH4 1 and LENGTHB 4; in an NVARCHAR2 (AL16UTF16) plain LENGTH counts it as 2.","It reflects the database character set, not the client's: the same data has different LENGTHB values in different databases.","VARCHAR2(n) without CHAR or NLS_LENGTH_SEMANTICS=CHAR limits bytes; LENGTHB is the check that mirrors what INSERT enforces."],"examples":[{"engine_slug":"oracle","sql":"SELECT LENGTHB('é') AS bytes, LENGTH('é') AS chars FROM dual;\n-- 2, 1"},{"engine_slug":"oracle","sql":"SELECT LENGTH4('\uD83D\uDE00') AS codepoints, LENGTH2('\uD83D\uDE00') AS utf16_units, LENGTHB('\uD83D\uDE00') AS bytes FROM dual;\n-- 1, 2, 4"}],"faqs":[{"question":"How is LENGTHB different from LENGTH in Oracle?","answer":"LENGTH counts characters; LENGTHB counts encoded bytes under the database charset. Accents and emoji are where they diverge."},{"question":"Why does LENGTH count an emoji as 2?","answer":"The value is NVARCHAR2, stored as AL16UTF16, where an emoji is a surrogate pair. On VARCHAR2 in an AL32UTF8 database LENGTH gives 1. LENGTH4 gives 1 for both."},{"question":"What should I check before a VARCHAR2 insert?","answer":"LENGTHB under byte semantics: it is the measure that matches what the column will enforce on insert."}],"related":["length","octet-length","varchar-char-semantics","emoji-length"],"novel_uses":[{"body":"A concatenation whose result passes the 4000-byte SQL limit raises ORA-01489, so a WHERE on LENGTHB finds the values that would overflow before the report query does.","sql":"SELECT id FROM t WHERE LENGTHB(col) > 3900;"},{"body":"After a database moves to AL32UTF8, accented text costs more bytes per character; LENGTHB reports the bytes of the current database charset, so run this check on a copy already in AL32UTF8; the rows it lists are the ones that will not fit VARCHAR2(n BYTE) after conversion.","sql":"SELECT id FROM customers WHERE LENGTHB(name) > 30;  -- will not fit VARCHAR2(30 BYTE) as AL32UTF8"}]},"source_url":"https://sqlly.app/sql-functions/lengthb","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/levenshtein","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LEVENSHTEIN function","description":"How Levenshtein edit distance works in PostgreSQL's fuzzystrmatch and in Oracle, SQL Server 2025 and SQLite: edit costs, case, and the 255-character limit.","body":{"slug":"levenshtein","name":"LEVENSHTEIN","h1":"SQL LEVENSHTEIN function","category":"string","lede":"Returns the minimum number of single-character edits needed to turn one string into another.","syntax":"levenshtein(str1, str2)  |  levenshtein(str1, str2, ins_cost, del_cost, sub_cost)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"EDIT_DISTANCE in SQL Server 2025, a preview feature (PREVIEW_FEATURES = ON)."},{"engine_slug":"postgresql","status":"partial","note":"Requires the fuzzystrmatch extension."},{"engine_slug":"mysql","status":"no","note":"No built-in; stored functions or application code."},{"engine_slug":"sqlite","status":"partial","note":"editdist3 in the spellfix1 extension, with different default costs."},{"engine_slug":"oracle","status":"partial","note":"UTL_MATCH.EDIT_DISTANCE(s1, s2)."}],"gotchas":["The distance is case-sensitive: levenshtein('abc', 'ABC') is 3. Lower both sides first when casing should not count.","The optional cost arguments weight insertions, deletions and substitutions separately. They do not add transpositions, so swapping two letters ('teh' to 'the') still costs 2.","fuzzystrmatch rejects inputs longer than 255 characters. For threshold filters, levenshtein_less_equal(a, b, max) stops once the distance passes max and runs much faster on unrelated strings. It returns max + 1 once the distance is over max, not the exact distance."],"examples":[{"engine_slug":"postgresql","sql":"SELECT levenshtein('kitten', 'sitting') AS distance;  -- 3"},{"engine_slug":"postgresql","sql":"SELECT name, levenshtein(lower(name), 'smith') AS d\nFROM people\nORDER BY d, name LIMIT 5;"},{"engine_slug":"sql-server","sql":"SELECT EDIT_DISTANCE('kitten', 'sitting') AS distance;  -- 3"},{"engine_slug":"sqlite","sql":"SELECT editdist3('kitten', 'sitting') AS distance;  -- 400"},{"engine_slug":"oracle","sql":"SELECT UTL_MATCH.EDIT_DISTANCE('kitten', 'sitting') AS distance\nFROM dual;  -- 3"}],"faqs":[{"question":"What counts as one edit?","answer":"Inserting, deleting or substituting one character. 'kitten' to 'sitting' is distance 3: k to s, e to i, then insert g."},{"question":"How do I make Levenshtein ignore case?","answer":"Lower both inputs: levenshtein(lower(a), lower(b)). The function itself does not fold case."},{"question":"Which engines have Levenshtein without an extension?","answer":"Oracle via UTL_MATCH.EDIT_DISTANCE and SQL Server 2025 via EDIT_DISTANCE once preview features are enabled. PostgreSQL needs CREATE EXTENSION fuzzystrmatch, SQLite needs the spellfix1 extension for editdist3 (a different function name), and MySQL has nothing."}],"related":["editdist3","similarity","soundex","difference"],"novel_uses":[{"body":"The cost arguments reprice edits: levenshtein(a, b, 2, 2, 1) makes an insertion or deletion cost 2 while a substitution costs 1, so 'cat' to 'cot' (1) ranks closer than 'cat' to 'cats' (2). With default costs both are 1.","sql":"SELECT levenshtein('cat', 'cot', 2, 2, 1) AS sub_cost, levenshtein('cat', 'cats', 2, 2, 1) AS ins_cost;"},{"body":"Dividing the distance by the longer string's length gives a ratio from 0 to 1 (NULL for two empty strings, where NULLIF avoids a division-by-zero error), so one threshold works for short codes and long titles alike.","sql":"SELECT levenshtein(a, b)::float / NULLIF(GREATEST(length(a), length(b)), 0) AS ratio;"},{"body":"A self join with a small distance cap finds suspected duplicates inside one table. The comparison is quadratic, so pre-filter by first letter or length bucket when the table is large.","sql":"SELECT a.id, b.id\nFROM docs a JOIN docs b ON a.id < b.id\nWHERE levenshtein(lower(a.title), lower(b.title)) < 3;"}]},"source_url":"https://sqlly.app/sql-functions/levenshtein","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/like","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LIKE operator","description":"LIKE pattern matching with % and _: case sensitivity per engine (ILIKE, collations, SQLite's ASCII-only folding), NULL operands yielding UNKNOWN and NOT LIKE traps.","body":{"slug":"like","name":"LIKE","h1":"SQL LIKE operator","category":"conditional","lede":"Pattern matching where percent matches any run of characters and underscore matches exactly one.","syntax":"col LIKE 'a%' | col NOT LIKE 'a%' | col LIKE 'a!%' ESCAPE '!'","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"case-sensitive; ILIKE for the insensitive form"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"LIKE folds ASCII case only; PRAGMA case_sensitive_like changes it"},{"engine_slug":"oracle","status":"yes","note":"case-sensitive unless NLS_COMP=LINGUISTIC with a case-insensitive NLS_SORT"}],"gotchas":["NULL on either side yields UNKNOWN, so NOT LIKE drops NULL rows too, just like an = comparison would.","Case sensitivity differs: PostgreSQL and Oracle LIKE are case-sensitive (PostgreSQL has ILIKE), SQLite folds ASCII only ('A' LIKE 'a' is true, 'Ä' LIKE 'ä' is false), MySQL and SQL Server follow the column collation.","T-SQL adds bracket classes: LIKE '[0-9]%' matches a leading digit, and LIKE '[%]' matches a literal percent. The other four engines treat brackets as ordinary characters.","A leading % defeats B-tree index use; full-text or trigram indexes cover those cases."],"examples":[{"engine_slug":"all","sql":"SELECT name FROM products WHERE name LIKE 'tee-%';"},{"engine_slug":"postgresql","sql":"SELECT name FROM products WHERE name ILIKE 'tee-%';"}],"faqs":[{"question":"How do I make LIKE case-insensitive?","answer":"ILIKE in PostgreSQL; SQLite's LIKE already folds ASCII case; MySQL and SQL Server depend on the column collation."},{"question":"Does LIKE match NULL?","answer":"No: NULL LIKE anything is UNKNOWN, and the row is filtered out even with NOT LIKE."},{"question":"How do I match a literal percent sign?","answer":"Use the ESCAPE clause: col LIKE '100!%' ESCAPE '!'."}],"related":["like-escape","three-valued-logic","lower","regexp-replace","replace"],"novel_uses":[{"body":"Each underscore counts exactly one character, so a pattern of underscores and dashes validates fixed-format codes with no regex engine.","sql":"SELECT * FROM refs WHERE code LIKE '___-____';"},{"body":"SQLite stores dates as ISO text, so a LIKE prefix picks a whole month out of a text column.","sql":"SELECT * FROM events WHERE day LIKE '2026-11%';"}]},"source_url":"https://sqlly.app/sql-functions/like","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/like-escape","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LIKE ESCAPE clause","description":"The ESCAPE clause makes LIKE match literal percent and underscore characters: choosing the escape character, per-engine defaults and user-input sanitizing recipes.","body":{"slug":"like-escape","name":"ESCAPE","h1":"SQL LIKE ESCAPE clause","category":"conditional","lede":"Declares the one-character escape that turns LIKE wildcards into literals.","syntax":"col LIKE '100!%' ESCAPE '!' | col LIKE 'a!_b' ESCAPE '!'","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["You choose the escape character after ESCAPE; pick something the user will never type, like !, and escape only % and _ in their input.","The escape must be a single character; multi-character escapes are rejected everywhere, and PostgreSQL and MySQL also accept ESCAPE '' to switch escaping off, which SQL Server and SQLite reject. A pattern ending in a lone escape character is an error in PostgreSQL, matches nothing in SQL Server and SQLite, and is read as a literal in MySQL.","Bracket character classes [0-9], [^a-z] are a T-SQL extension; PostgreSQL, MySQL, Oracle and SQLite treat brackets literally in LIKE."],"examples":[{"engine_slug":"all","sql":"SELECT * FROM t WHERE note LIKE '100!%' ESCAPE '!';"},{"engine_slug":"all","sql":"SELECT * FROM t WHERE code LIKE 'a!_b' ESCAPE '!';"}],"faqs":[{"question":"Is backslash the default escape?","answer":"In PostgreSQL and MySQL, yes: 'a_b' LIKE 'a\\_b' is true there. SQL Server, Oracle and SQLite have no default escape character, so the same pattern looks for a literal backslash. Declare ESCAPE explicitly for portable code, and in MySQL double the backslash inside the literal (ESCAPE '\\\\'), or the statement is a syntax error."},{"question":"How do I sanitize user input for LIKE?","answer":"Escape the wildcards in their input: REPLACE(input, '!', '!!') then REPLACE(..., '%', '!%') and same for _, then append ESCAPE '!'."},{"question":"Do [0-9] classes work in LIKE?","answer":"Only in SQL Server (T-SQL); the other engines match the brackets literally."}],"related":["like","instr","replace","substring"],"novel_uses":[{"body":"A literal substring search has no wildcards to escape: INSTR on MySQL, SQLite and Oracle, strpos on PostgreSQL, CHARINDEX on SQL Server.","sql":"SELECT * FROM notes WHERE INSTR(note, '100%') > 0;"},{"body":"LEFT (SQL Server, PostgreSQL, MySQL) or SUBSTR(code, 1, 4) (SQLite) compares the first characters literally, dodging both wildcard parsing and the escape character debate.","sql":"SELECT * FROM codes WHERE LEFT(code, 4) = 'AB-1';"}]},"source_url":"https://sqlly.app/sql-functions/like-escape","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/listagg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LISTAGG function","description":"Oracle's LISTAGG folds many rows into one delimited string: WITHIN GROUP ordering, the 4000-byte ORA-01489 limit, ON OVERFLOW and DISTINCT.","body":{"slug":"listagg","name":"LISTAGG","h1":"SQL LISTAGG function","category":"aggregate","lede":"Aggregates column values into one delimited string per group, ordered how you choose. Oracle's answer to STRING_AGG and GROUP_CONCAT.","syntax":"LISTAGG(column, separator) WITHIN GROUP (ORDER BY ...)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"STRING_AGG (2017+)"},{"engine_slug":"postgresql","status":"partial","note":"STRING_AGG"},{"engine_slug":"mysql","status":"partial","note":"GROUP_CONCAT"},{"engine_slug":"sqlite","status":"partial","note":"group_concat()"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ORA-01489: the result cannot exceed 4000 bytes (32767 with MAX_STRING_SIZE=EXTENDED). Since 12.2, LISTAGG(col, ', ' ON OVERFLOW TRUNCATE '...' WITH COUNT) cuts the list off instead of failing.","Order is unspecified without WITHIN GROUP (ORDER BY ...). Always spell it out for stable output.","NULL values are skipped, and a group with only NULLs aggregates to NULL.","WMSYS.WM_CONCAT is the old undocumented workaround, unsupported and gone in modern releases; use LISTAGG."],"examples":[{"engine_slug":"oracle","sql":"SELECT department, LISTAGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"oracle","sql":"SELECT LISTAGG(tag, ', ' ON OVERFLOW TRUNCATE '...' WITH COUNT)\n       WITHIN GROUP (ORDER BY tag) AS tags\nFROM bookmarks;"},{"engine_slug":"sql-server","sql":"SELECT department, STRING_AGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"postgresql","sql":"SELECT department, string_agg(last_name, ', ' ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"mysql","sql":"SELECT department, GROUP_CONCAT(last_name ORDER BY last_name SEPARATOR ', ') AS team\nFROM employees\nGROUP BY department;"},{"engine_slug":"sqlite","sql":"SELECT department, group_concat(last_name, ', ' ORDER BY last_name) AS team\nFROM employees\nGROUP BY department;"}],"faqs":[{"question":"Why do I get ORA-01489 with LISTAGG?","answer":"The concatenated result passed 4000 bytes. Switch to MAX_STRING_SIZE=EXTENDED, aggregate fewer or shorter values, or add ON OVERFLOW TRUNCATE inside the LISTAGG parentheses (12.2+)."},{"question":"How do I remove duplicates in LISTAGG?","answer":"LISTAGG(DISTINCT column, sep) works from Oracle 19c. Before that, deduplicate in a subquery first."},{"question":"What is the PostgreSQL equivalent?","answer":"STRING_AGG(column, separator ORDER BY ...). MySQL's GROUP_CONCAT and SQLite's group_concat cover the same ground with different clauses."}],"related":["string-agg","group-concat","concat"],"novel_uses":[{"body":"Wrapping each id in quotes with LISTAGG('''' || id || '''', ', ') prints a ready IN (...) fragment for ad-hoc debugging when you cannot bind a collection.","sql":"SELECT LISTAGG('''' || id || '''', ', ') WITHIN GROUP (ORDER BY id) AS in_list\nFROM picked;"},{"body":"A CASE inside LISTAGG splits one pass into several string columns: NULL CASE results are skipped by LISTAGG, so the filter comes for free.","sql":"SELECT department,\n       LISTAGG(CASE WHEN kind = 'email' THEN value END, ', ')\n         WITHIN GROUP (ORDER BY value) AS emails,\n       LISTAGG(CASE WHEN kind = 'phone' THEN value END, ', ')\n         WITHIN GROUP (ORDER BY value) AS phones\nFROM contacts\nGROUP BY department;"}]},"source_url":"https://sqlly.app/sql-functions/listagg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/listagg-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL string aggregation as a window function","description":"LISTAGG, string_agg and group_concat as window functions: the partition's values as one string on every row, and why SQL Server and MySQL refuse.","body":{"slug":"listagg-window","name":"String Aggregates with OVER","h1":"SQL string aggregation as a window function","category":"window","lede":"String aggregation gains a window context like any aggregate: partition-wide concatenations or frame-local lists beside the detail rows.","syntax":"LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) OVER (PARTITION BY g) | string_agg(name, ', ') OVER (PARTITION BY g ORDER BY name)","return_type":"text","support":[{"engine_slug":"sql-server","status":"no","note":"STRING_AGG 'is not a valid windowing function'; aggregate in a CTE and join back"},{"engine_slug":"postgresql","status":"yes","note":"string_agg OVER works; order via the window's ORDER BY, not inside the call"},{"engine_slug":"mysql","status":"no","note":"GROUP_CONCAT is not permitted as a window function; GROUP BY + join, or JSON_ARRAYAGG OVER (8.0.14+)"},{"engine_slug":"sqlite","status":"yes","note":"group_concat OVER works (3.25+); no ORDER BY inside the call in window form"},{"engine_slug":"oracle","status":"yes","note":"LISTAGG ... WITHIN GROUP (...) OVER (PARTITION BY ...); no ORDER BY or frame in the OVER"}],"gotchas":["List order is set differently per engine: Oracle by WITHIN GROUP (ORDER BY ...), with OVER limited to PARTITION BY. PostgreSQL ('aggregate ORDER BY is not implemented for window functions') and SQLite ('ORDER BY may not be used with non-aggregate group_concat()') reject ORDER BY inside the call in window form, so put ORDER BY in the OVER clause and use a full frame.","SQL Server and MySQL reject string aggregates with OVER outright. GROUP BY the partition key in a CTE to build the list, then join it back to the detail rows.","Length limits bite in window form too: LISTAGG returns VARCHAR2, so 4000 bytes by default or 32767 with MAX_STRING_SIZE = EXTENDED, and since 12.2 ON OVERFLOW TRUNCATE avoids the ORA-01489 error."],"examples":[{"engine_slug":"oracle","sql":"SELECT department, employee_name,\n       LISTAGG(employee_name, ', ') WITHIN GROUP (ORDER BY employee_name)\n         OVER (PARTITION BY department) AS dept_roster\nFROM employees;"},{"engine_slug":"postgresql","sql":"-- ORDER BY goes in the window; the full frame gives every row the whole list\nSELECT department, employee_name,\n       string_agg(employee_name, ', ') OVER (\n         PARTITION BY department ORDER BY employee_name\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS dept_roster\nFROM employees;"},{"engine_slug":"sqlite","sql":"-- group_concat takes OVER; no ORDER BY inside the call in window form\nSELECT department, employee_name,\n       group_concat(employee_name, ', ') OVER (\n         PARTITION BY department ORDER BY employee_name\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS dept_roster\nFROM employees;"}],"faqs":[{"question":"Why does GROUP_CONCAT() OVER fail on MySQL?","answer":"MySQL does not permit GROUP_CONCAT as a window function. Aggregate in a CTE and join back, or use JSON_ARRAYAGG(x) OVER (...) if a JSON array will do."},{"question":"How do I keep the list ordered in a window?","answer":"Oracle: LISTAGG(x, sep) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g). PostgreSQL and SQLite: string_agg / group_concat(x, sep) OVER (PARTITION BY g ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING). SQL Server: STRING_AGG(x, sep) WITHIN GROUP (ORDER BY x) in a GROUP BY CTE, joined back."}],"related":["aggregate-over","string-agg","over-clause"],"novel_uses":[{"body":"String aggregation over an ordered frame without UNBOUNDED gives a cumulative list: every row shows who had joined up to that day. PostgreSQL and SQLite (3.44+ for the STRING_AGG name; group_concat before that) run this; Oracle's window LISTAGG takes no ORDER BY in the OVER, so the growing form is not available there.","sql":"SELECT joined_day, member_name,\n       STRING_AGG(member_name, ', ') OVER (ORDER BY joined_day) AS members_so_far\nFROM club_joins;"},{"body":"Deduplicate the pair in a CTE first, then aggregate over the partition: the list holds each name once even though the base table repeats it. DISTINCT inside the windowed call is rejected everywhere but Oracle.","sql":"WITH pairs AS (\n  SELECT DISTINCT department, employee_name FROM employees\n)\nSELECT department, employee_name,\n       STRING_AGG(employee_name, ', ') OVER (PARTITION BY department) AS roster\nFROM pairs;"}]},"source_url":"https://sqlly.app/sql-functions/listagg-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ln","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LN function","description":"LN(x) is the log base e, the inverse of EXP. Which engines spell it LN, why SQL Server says LOG, and the errors when x is zero or negative.","body":{"slug":"ln","name":"LN","h1":"SQL LN function","category":"math","lede":"Returns the natural logarithm (base e) of a positive number: LN(1) is 0 and LN(EXP(5)) is about 5.","syntax":"LN(number)","return_type":"float / double (numeric in, numeric out on PostgreSQL)","support":[{"engine_slug":"sql-server","status":"partial","note":"No LN; LOG(x) is the natural log on SQL Server"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Needs 3.35+ with SQLITE_ENABLE_MATH_FUNCTIONS; PRAGMA compile_options lists it as ENABLE_MATH_FUNCTIONS (no SQLITE_ prefix), so you can confirm before relying on it"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["LN(0) and LN(negative) have no answer: MySQL and SQLite return NULL, PostgreSQL raises 'cannot take logarithm of zero' (or 'cannot take logarithm of a negative number' for negatives), Oracle raises ORA-01428, SQL Server's LOG(0) raises 'An invalid floating point operation occurred'.","SQL Server spells it LOG. LOG(x, 2) there is the base-2 log of x, not the natural log, and LN raises 'not a recognized built-in function name'.","Filter the domain first: WHERE x > 0, or CASE WHEN x > 0 THEN LN(x) END for the rest."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LN(1) AS zero, LN(EXP(5)) AS five;  -- 0, 5"},{"engine_slug":"sql-server","sql":"SELECT LOG(10) AS natural_log;  -- 2.302..."},{"engine_slug":"postgresql","sql":"SELECT LN(growth_factor) AS log_growth\nFROM populations WHERE growth_factor > 0;"},{"engine_slug":"mysql","sql":"SELECT LN(1) AS zero, LN(EXP(5)) AS five;  -- 0, 5"},{"engine_slug":"sqlite","sql":"SELECT ln(1) AS zero, ln(exp(5)) AS five;  -- 0.0, 5.0"},{"engine_slug":"oracle","sql":"SELECT LN(1) AS zero, LN(EXP(5)) AS five FROM dual;  -- 0, 5"}],"faqs":[{"question":"What is the difference between LN and LOG?","answer":"LN is always base e. LOG means base e on SQL Server, base 10 with one argument on PostgreSQL and SQLite, and takes the base first as LOG(base, n) on MySQL and Oracle. Check the engine before you swap them."},{"question":"What does LN(0) return?","answer":"Nothing valid: MySQL gives NULL with warning 3020 and SQLite gives NULL, while PostgreSQL, Oracle and SQL Server (LOG(0)) raise an error. Guard with WHERE x > 0."},{"question":"Why is EXP(LN(10)) not exactly 10?","answer":"Both are floating point operations, so the round trip can drift in the last digit: SQL Server returns 10.000000000000002 for EXP(LOG(10)). Round the result if exact display matters."}],"related":["exp","log","log-domain"],"novel_uses":[{"body":"LN(2) / LN(1 + rate) gives the exact periods to double at a compound rate, replacing the rule of 72 with arithmetic the query repeats per row. SQL Server spells LN as LOG.","sql":"SELECT LN(2) / LN(1 + 0.07) AS years_to_double;"},{"body":"Averaging percentages lies when returns compound. EXP(AVG(LN(1 + r))) - 1 is the constant per-period rate that reproduces the actual end value, the number the business usually wants. SQL Server has no LN, so use EXP(AVG(LOG(1 + monthly_return))) - 1 there.","sql":"SELECT EXP(AVG(LN(1 + monthly_return))) - 1 AS geo_mean_monthly FROM fund_returns;"}]},"source_url":"https://sqlly.app/sql-functions/ln","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/localtimestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOCALTIMESTAMP function","description":"LOCALTIMESTAMP returns the current timestamp stripped of its time zone: standard on PostgreSQL, MySQL and Oracle, absent on SQL Server and SQLite.","body":{"slug":"localtimestamp","name":"LOCALTIMESTAMP","h1":"SQL LOCALTIMESTAMP function","category":"datetime","lede":"Returns the current date and time as a plain timestamp, without any time-zone information, unlike CURRENT_TIMESTAMP on zone-aware engines.","syntax":"LOCALTIMESTAMP  |  LOCALTIMESTAMP(p)  |  NOW()  -- MySQL synonym","return_type":"timestamp","support":[{"engine_slug":"sql-server","status":"no","note":"GETDATE(); no LOCALTIMESTAMP keyword"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no keyword; datetime('now', 'localtime')"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["On PostgreSQL the difference is real: CURRENT_TIMESTAMP is timestamptz, LOCALTIMESTAMP is timestamp; storing the wrong one bakes the session zone into the data.","MySQL treats CURRENT_TIMESTAMP, NOW() and LOCALTIMESTAMP as exact synonyms; all three return the session time_zone's wall clock.","LOCALTIMESTAMP is the transaction start time on PostgreSQL; clock_timestamp() is the moving wall clock."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LOCALTIMESTAMP(3) AS loaded_at;"},{"engine_slug":"mysql","sql":"SELECT LOCALTIMESTAMP AS loaded_at;"},{"engine_slug":"oracle","sql":"SELECT LOCALTIMESTAMP FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT GETDATE() AS local_now;"},{"engine_slug":"sqlite","sql":"SELECT datetime('now', 'localtime') AS local_now;"}],"faqs":[{"question":"When should I use LOCALTIMESTAMP instead of CURRENT_TIMESTAMP?","answer":"Only when you genuinely want zone-less wall time. For event timestamps on PostgreSQL, CURRENT_TIMESTAMP (timestamptz) survives time-zone changes better. On MySQL, CURRENT_TIMESTAMP is the same zone-less wall clock, so store it in a TIMESTAMP column (kept as UTC internally) or SET time_zone = '+00:00' before writing."},{"question":"Is LOCALTIMESTAMP available on SQL Server?","answer":"No keyword. GETDATE() or SYSDATETIME() return the server's local wall time as a zone-less value, which is the same idea (SQL Server has no per-session zone)."}],"related":["now","current-time","session-timezone"],"novel_uses":[{"body":"MySQL columns can restamp themselves: ON UPDATE CURRENT_TIMESTAMP fills the column with the session clock every time the row changes, no trigger and no application code.","sql":"ALTER TABLE orders ADD modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;"},{"body":"On MySQL, SET time_zone before the batch and NOW() and LOCALTIMESTAMP follow it, so a backfill can stamp one zone without touching the server configuration.","sql":"SET time_zone = '+00:00';\nSELECT LOCALTIMESTAMP AS utc_wall;"}]},"source_url":"https://sqlly.app/sql-functions/localtimestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/locate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOCATE function","description":"How LOCATE(substr, str, pos) searches in MySQL and MariaDB: 1-based results, the start-offset argument, case-insensitivity by collation, and the INSTR alternative.","body":{"slug":"locate","name":"LOCATE","h1":"SQL LOCATE function","category":"string","lede":"MySQL's substring search: returns the first position of a substring, optionally searching from a given position.","syntax":"LOCATE(substr, str)  |  LOCATE(substr, str, start_position)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"CHARINDEX(substr, str, start) has the same argument order."},{"engine_slug":"postgresql","status":"partial","note":"Use POSITION or STRPOS; no start argument."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"Use INSTR(str, substr)."},{"engine_slug":"oracle","status":"partial","note":"Use INSTR(str, substr, start)."}],"gotchas":["LOCATE puts the substring first; INSTR(str, substr) puts it second. Mixing the orders silently searches for the wrong needle.","The third argument is the position to start searching at, and the answer is still counted from the start of the string: LOCATE('bar', 'foobarbar', 5) is 7.","Returns 0 when not found and NULL when any argument is NULL. Case is folded by the collation, so the default _ci collations match regardless of case; accents still must match exactly, so LOCATE('cafe', 'café') returns 0 even under utf8mb4_0900_ai_ci."],"examples":[{"engine_slug":"mysql","sql":"SELECT LOCATE('@', email) AS at_pos FROM users;"},{"engine_slug":"mysql","sql":"SELECT LOCATE('-', sku, LOCATE('-', sku) + 1) AS second_dash\nFROM products;"},{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('bar', 'foobarbar', 5) AS pos;  -- 7"},{"engine_slug":"postgresql","sql":"SELECT strpos('foobarbar', 'bar') AS pos;  -- 4"},{"engine_slug":"sqlite","sql":"SELECT INSTR('foobarbar', 'bar') AS pos;  -- 4"},{"engine_slug":"oracle","sql":"SELECT INSTR('foobarbar', 'bar', 5) AS pos\nFROM dual;  -- 7"}],"faqs":[{"question":"What is the difference between LOCATE and INSTR in MySQL?","answer":"Argument order and the start offset. LOCATE(substr, str [, pos]) takes the substring first and accepts a start position; INSTR(str, substr) takes the string first and has no start argument. POSITION(substr IN str) is a synonym for two-argument LOCATE."},{"question":"Is LOCATE case-sensitive?","answer":"It depends on the collation of the string being searched, the second argument. The common *_ci collations make it case-insensitive; a _bin collation, or BINARY on the string, makes it exact. A _bin collation or BINARY on the substring alone does not: LOCATE(BINARY 'B', 'abc') returns 2."}],"related":["instr","charindex","position","substring-index"],"novel_uses":[{"body":"Wrapping both sides with commas, LOCATE(CONCAT(',', tag, ','), CONCAT(',', list, ',')), matches whole elements in MySQL, so 'red' no longer matches 'bordered'. Elements must still be written exactly, without the stray spaces FIND_IN_SET also rejects.","sql":"SELECT * FROM roles\nWHERE LOCATE(CONCAT(',', 'admin', ','), CONCAT(',', permissions, ',')) > 0;"},{"body":"MySQL's LEAST returns NULL when any argument is NULL, so turn a 0 into a sentinel of length + 1 first. The result is the earliest real delimiter position, or a value past the end when none occur.","sql":"SELECT LEAST(COALESCE(NULLIF(LOCATE('-', code), 0), CHAR_LENGTH(code) + 1),\n             COALESCE(NULLIF(LOCATE('_', code), 0), CHAR_LENGTH(code) + 1)) AS split_at\nFROM skus;"},{"body":"Starting the search at 9 steps over the eight characters of 'https://', so the result describes the path rather than the protocol. The same idea skips any fixed prefix you do not want to match.","sql":"SELECT LOCATE('/', url, 9) AS path_slash\nFROM links;"}]},"source_url":"https://sqlly.app/sql-functions/locate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/log","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOG function","description":"LOG's base argument flips order between engines: LOG(base, n) on MySQL and Oracle, LOG(n, base) on SQL Server, LOG(x) alone is base 10 on PG and SQLite.","body":{"slug":"log","name":"LOG","h1":"SQL LOG function","category":"math","lede":"Returns a logarithm, but the argument order and the one-argument default base differ per engine: the single most error-prone swap in SQL math.","syntax":"LOG(base, number)  -- MySQL, Oracle, SQLite  |  LOG(number, base)  -- SQL Server  |  LOG(number)  -- base 10 on PostgreSQL, SQLite","return_type":"float / double (PostgreSQL two-argument LOG returns numeric)","support":[{"engine_slug":"sql-server","status":"partial","note":"LOG(number [, base]): value first, base second, the reverse of MySQL and Oracle"},{"engine_slug":"postgresql","status":"yes","note":"log(x) with one argument is base 10; log(base, x) with two takes the base first"},{"engine_slug":"mysql","status":"yes","note":"LOG(x) with one argument is the natural log, LOG(base, x) takes the base first (the opposite default from PostgreSQL)"},{"engine_slug":"sqlite","status":"partial","note":"Requires 3.35+; log(x) is base 10, log(base, x) takes the base first, ln(x) is natural"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL LOG(10, 100) is 2 (base 10); SQL Server LOG(10, 100) is the log of 10 in base 100. Swapping the order silently returns a wrong number instead of an error.","PostgreSQL log(100) with one argument is base 10, but MySQL LOG(100) is the natural log: the same call means different things.","Oracle's LOG needs two arguments and a positive base other than 1: LOG(0.5, 4) is -2, LOG(1, 4) raises ORA-01428. Use LN for base e."],"examples":[{"engine_slug":"mysql","sql":"SELECT LOG(2, 8) AS three;  -- 3"},{"engine_slug":"sql-server","sql":"SELECT LOG(8, 2) AS three;  -- 3: value first, base second"},{"engine_slug":"postgresql","sql":"SELECT LOG(100) AS base_ten, LOG(2, 8) AS base_two;  -- 2, 3"},{"engine_slug":"sqlite","sql":"SELECT log(100) AS base_ten, log(2, 8) AS base_two;  -- 2.0, 3.0"},{"engine_slug":"oracle","sql":"SELECT LOG(10, 1000) AS three FROM dual;  -- 3: base first, two arguments required"}],"faqs":[{"question":"Why does my LOG return the wrong number?","answer":"Almost always the base is in the wrong position. MySQL, Oracle and SQLite take LOG(base, number); SQL Server takes LOG(number, base). A one-argument LOG is base e on MySQL but base 10 on PostgreSQL and SQLite."},{"question":"How do I write a log in an arbitrary base?","answer":"Use the change-of-base formula: LN(x) / LN(b) on PostgreSQL, MySQL, SQLite and Oracle, and LOG(x) / LOG(b) on SQL Server, which has no LN. Either form avoids the argument-order trap entirely."},{"question":"What is the base of a one-argument LOG?","answer":"Depends on the engine: natural (e) on SQL Server and MySQL, base 10 on PostgreSQL and SQLite. Prefer LOG10 for base 10 and LN for the natural log when you mean something specific; SQL Server has no LN, so use LOG(x) there."}],"related":["ln","log10","log2","log-domain"],"novel_uses":[{"body":"FLOOR(LOG(10, x)) + 1 counts decimal digits on MySQL, SQLite and PostgreSQL, which take the base first. SQL Server reverses it to LOG(x, 10), so the same count swaps arguments per engine.","sql":"SELECT FLOOR(LOG(10, 4523)) + 1 AS digits;  -- 4 on MySQL, SQLite, PostgreSQL; on SQL Server write FLOOR(LOG(4523, 10)) + 1"},{"body":"LOG(p) - LOG(1 - p) computes the logit of a probability with no division by p * (1 - p), the standard transform before combining probabilities additively. One-argument LOG is the natural log on SQL Server and MySQL; PostgreSQL and SQLite need LN.","sql":"SELECT LOG(0.7) - LOG(1 - 0.7) AS log_odds;  -- natural on SQL Server and MySQL"}]},"source_url":"https://sqlly.app/sql-functions/log","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/log-domain","corpus":"sql-functions","engine":null,"language":"en","title":"SQL log of zero and negatives","description":"LN(0) and LOG of a negative are undefined: MySQL and SQLite return NULL while PostgreSQL, SQL Server and Oracle raise an error. Guard the domain first.","body":{"slug":"log-domain","name":"LOG(0)","h1":"SQL log of zero and negatives","category":"math","lede":"Covers non-positive input to LN and LOG: which engines soften it to NULL, which fail the statement, and the CASE/NULLIF patterns that keep queries alive.","syntax":"LN(0)  |  LN(-1)  |  CASE WHEN x > 0 THEN LN(x) END","return_type":"float / NULL / error","support":[{"engine_slug":"sql-server","status":"partial","note":"LOG(0) raises 'An invalid floating point operation occurred'; LOG of a negative also fails"},{"engine_slug":"postgresql","status":"yes","note":"ERROR: cannot take logarithm of zero; negatives raise ERROR: cannot take logarithm of a negative number"},{"engine_slug":"mysql","status":"partial","note":"Returns NULL with a warning for zero and negative input"},{"engine_slug":"sqlite","status":"partial","note":"NULL, and the statement keeps running"},{"engine_slug":"oracle","status":"yes","note":"ORA-01428: Argument 0 is out of range (likewise for negatives)"}],"gotchas":["The domain of every real logarithm is (0, infinity). The same rows that return NULL on MySQL abort the whole statement on PostgreSQL, so a query can pass tests on one engine and fail in production on another.","Guard with CASE WHEN x > 0 THEN LN(x) END (LOG(x) on SQL Server) for a NULL result on every engine, or filter WHERE x > 0 to drop the rows.","For the same soft-NULL treatment with a fallback, wrap: COALESCE(CASE WHEN x > 0 THEN LN(x) END, 0)."],"examples":[{"engine_slug":"mysql","sql":"SELECT LN(0) AS ln_zero;  -- NULL"},{"engine_slug":"postgresql","sql":"SELECT LN(0) AS boom;  -- ERROR: cannot take logarithm of zero"},{"engine_slug":"postgresql","sql":"SELECT CASE WHEN x > 0 THEN LN(x) END AS safe_log FROM t;"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN x > 0 THEN LOG(x) END AS safe_log FROM t;  -- SQL Server spells LN as LOG"},{"engine_slug":"sqlite","sql":"SELECT ln(0) AS ln_zero, ln(-1) AS ln_negative;  -- NULL, NULL"},{"engine_slug":"oracle","sql":"SELECT LN(0) AS boom FROM dual;  -- ORA-01428: argument 0 is out of range"}],"faqs":[{"question":"What does LN(0) return?","answer":"NULL on MySQL and SQLite; an error on PostgreSQL, Oracle and SQL Server. There is no real logarithm of zero, so the engines either fail the statement or soften it to NULL."},{"question":"How do I log-guard a column with zeros?","answer":"CASE WHEN x > 0 THEN LN(x) END (LOG(x) on SQL Server) yields NULL for non-positive values on every engine; a WHERE x > 0 filter drops the rows instead. Pick based on whether NULLs or missing rows fit the report."},{"question":"Why does the same query work on MySQL but fail on PostgreSQL?","answer":"MySQL's NULL-on-domain-error philosophy versus PostgreSQL's error philosophy: the same split shows up in ASIN, ACOS and division by zero. Portable SQL guards the domain explicitly."}],"related":["ln","log","inverse-trig-domain","division-by-zero"],"novel_uses":[{"body":"In doubles, 1 + 1e-16 collapses to 1, so LN(1 + r) returns 0 for microscopic rates. Branch tiny r to r itself, the first-order approximation, and the growth math stops flattening to zero. The cutoff sits near the square root of machine epsilon: at 1e-12 the LN branch is about 9e-5 off, while 1e-8 keeps both branches within about 1e-8. SQL Server spells the call LOG(1 + r).","sql":"SELECT CASE WHEN r > 1e-8 THEN LN(1 + r) ELSE r END AS safe_log_growth FROM rates;"},{"body":"SIGN(x) and LN(ABS(x)) split a signed, zero-heavy column into a sign flag and a magnitude log that both survive zero and negatives. Store the pair at write time and recombine at read time. SQL Server spells LN as LOG.","sql":"SELECT SIGN(pnl) AS sgn, LN(ABS(NULLIF(pnl, 0))) AS log_mag FROM positions;"}]},"source_url":"https://sqlly.app/sql-functions/log-domain","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/log10","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOG10 function","description":"LOG10(x) is the base-10 logarithm, how many powers of ten fit in x. Built in on four engines; Oracle has no LOG10 and needs LOG(10, x).","body":{"slug":"log10","name":"LOG10","h1":"SQL LOG10 function","category":"math","lede":"Returns the base-10 logarithm: LOG10(100) is 2 and LOG10(0.001) is -3.","syntax":"LOG10(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"log10(x) since PostgreSQL 12; one-argument log(x) is also base 10"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"log10(X) and log(X) are both base 10 on 3.35+"},{"engine_slug":"oracle","status":"partial","note":"No LOG10; write LOG(10, x)"}],"gotchas":["LOG10(1000) is 3 but LOG10(999) is 2.9995...; floats, so round when checking digit counts.","Domain is positive only: LOG10(0) and LOG10(-1) return NULL on MySQL and SQLite and raise an error on SQL Server and PostgreSQL, as Oracle's LOG(10, 0) does.","PostgreSQL accepts both log10(x) and log(x) for base 10. Its two-argument log(base, x) takes the base first, the reverse of SQL Server's LOG(x, base)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT LOG10(1000) AS three;  -- 3"},{"engine_slug":"postgresql","sql":"SELECT LOG10(1000) AS a, LOG(1000) AS b;  -- 3, 3: one-argument log is base 10"},{"engine_slug":"mysql","sql":"SELECT ORDER_SIZE, LOG10(ORDER_SIZE) AS digits\nFROM shipments;"},{"engine_slug":"sqlite","sql":"SELECT log10(1000) AS three, log(1000) AS same;  -- 3.0, 3.0"},{"engine_slug":"oracle","sql":"SELECT LOG(10, 1000) AS three FROM dual;  -- 3: LOG(10, x) is Oracle's LOG10"}],"faqs":[{"question":"Does PostgreSQL have LOG10?","answer":"Yes, since PostgreSQL 12, and one-argument log(x) is base 10 as well. For two-argument logs, PostgreSQL takes the base first: log(10, 1000) is 3."},{"question":"What is the Oracle equivalent of LOG10?","answer":"LOG(10, x): Oracle's LOG takes the base as the first argument, and there is no one-argument form."},{"question":"Why is LOG10(0) an error or NULL?","answer":"The base-10 log of zero is undefined. MySQL and SQLite return NULL; SQL Server, PostgreSQL and Oracle (LOG(10, 0)) raise an error. Filter x > 0 first."}],"related":["log","ln","log2"],"novel_uses":[{"body":"FLOOR(LOG10(ABS(x))) gives the exponent and x / POWER(10, that) the mantissa, which lands in [1, 10) for positive x; for negative x divide ABS(x) instead, and filter x <> 0 first, for scientific-style display and magnitude comparisons. Oracle writes LOG(10, x) instead of LOG10.","sql":"SELECT FLOOR(LOG10(4523.0)) AS exp10, 4523.0 / POWER(10, FLOOR(LOG10(4523.0))) AS mantissa;"},{"body":"ABS(LOG10(cur) - LOG10(prev)) measures change in decades: 3 means a thousandfold jump. Decades add across steps where ratios multiply, so a tenfold rise followed by a hundredfold rise reads as 3 decades in total.","sql":"SELECT id FROM counters WHERE CASE WHEN cur_value > 0 AND prev_value > 0 THEN ABS(LOG10(cur_value) - LOG10(prev_value)) ELSE 0 END > 3;"}]},"source_url":"https://sqlly.app/sql-functions/log10","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/log2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOG2 function","description":"LOG2(x) is the base-2 logarithm, the power you raise 2 to, common for tree depths and bit counts. Only MySQL and SQLite have it by name.","body":{"slug":"log2","name":"LOG2","h1":"SQL LOG2 function","category":"math","lede":"Returns the base-2 logarithm: LOG2(8) is 3 and LOG2(1024) is 10.","syntax":"LOG2(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"partial","note":"No LOG2; LOG(x, 2) with the base as second argument"},{"engine_slug":"postgresql","status":"partial","note":"No LOG2; log(2, x) with the base as first argument, or ln(x)/ln(2)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"log2(X) on 3.35+ with math functions"},{"engine_slug":"oracle","status":"partial","note":"No LOG2; LOG(2, x)"}],"gotchas":["Same function, three spellings: LOG2(x) on MySQL and SQLite, LOG(x, 2) on SQL Server, LOG(2, x) on PostgreSQL and Oracle; note SQL Server reverses the arguments.","Domain is positive: LOG2(0) is NULL (MySQL, SQLite) or an error elsewhere.","For bit-length work, FLOOR(LOG2(n)) + 1 is the number of binary digits for 1 <= n <= 2^48. Above that, LOG2 is a double and rounds values just under a power of two up to it: LOG2(2^49 - 1) is 49 on MySQL and SQLite, one bit too many. For exact bit counts on large integers, compare against powers of two in integer arithmetic instead."],"examples":[{"engine_slug":"mysql","sql":"SELECT LOG2(1024) AS ten;  -- 10"},{"engine_slug":"postgresql","sql":"SELECT LOG(2, 1024) AS ten;  -- 10"},{"engine_slug":"sql-server","sql":"SELECT LOG(1024, 2) AS ten;  -- 10"},{"engine_slug":"sqlite","sql":"SELECT log2(1024) AS ten;  -- 10.0"},{"engine_slug":"oracle","sql":"SELECT LOG(2, 1024) AS ten FROM dual;  -- 10: LOG(2, x) is Oracle's LOG2"}],"faqs":[{"question":"What is the PostgreSQL equivalent of LOG2?","answer":"log(2, x): PostgreSQL's two-argument log takes the base first. There is no log2 keyword; ln(x) / ln(2) also works."},{"question":"How do I compute LOG2 on SQL Server?","answer":"LOG(x, 2). SQL Server's LOG puts the value first and the base second, the reverse of MySQL, Oracle and SQLite two-argument logs."},{"question":"What is LOG2 used for?","answer":"Tree depth and bit-count math: LOG2(1024) is 10 because 2 to the 10th is 1024, and FLOOR(LOG2(n)) + 1 counts an integer's binary digits up to 2^48."}],"related":["log","log10","ln"],"novel_uses":[{"body":"POWER(2, CEILING(LOG2(n))) gives the next power of two, the size a buffer, shard or batch actually gets allocated. PostgreSQL and Oracle substitute the change of base LOG(n) / LOG(2).","sql":"SELECT POWER(2, CEILING(LOG2(1000))) AS next_pow2;  -- 1024 on MySQL"},{"body":"-SUM(p * LOG2(p)) over value counts measures spread in bits: 0 for one repeated value, up to LOG2(distinct). It is a quick index-worthiness check on MySQL or SQLite.","sql":"SELECT -SUM(cnt * 1.0 / total * LOG2(cnt * 1.0 / total)) AS entropy_bits FROM (SELECT status AS v, COUNT(*) AS cnt, SUM(COUNT(*)) OVER () AS total FROM orders GROUP BY status) c;"}]},"source_url":"https://sqlly.app/sql-functions/log2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lower","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LOWER function","description":"Lowercase text with LOWER in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: locale effects, citext and expression indexes for case-insensitive lookups.","body":{"slug":"lower","name":"LOWER","h1":"SQL LOWER function","category":"string","lede":"Returns the string with every character lowercased. Its main job is normalizing emails, codes and identifiers before comparing or storing them.","syntax":"LOWER(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Normalization usually happens once, on write: UPDATE users SET email = LOWER(email) beats LOWER() on every read afterwards.","PostgreSQL's citext extension gives a case-insensitive text type, so plain = comparisons ignore case without LOWER() calls or expression indexes.","Like UPPER, LOWER(column) = constant in a WHERE clause disables a plain index; index the expression instead."],"examples":[{"engine_slug":"all","sql":"SELECT LOWER('MiXeD') AS quiet;  -- mixed"},{"engine_slug":"postgresql","sql":"CREATE INDEX users_email_lower_idx ON users (LOWER(email));"}],"faqs":[{"question":"Is LOWER the same in every database?","answer":"For ASCII, yes. Beyond that it depends on the collation: SQLite's built-in LOWER only handles ASCII, and special cases like the Turkish dotted İ come out differently between engines and between collations on one engine."},{"question":"Should I LOWER data on the way in or the way out?","answer":"On the way in, if the lowercase form is the data (emails, codes). Lowering on every read costs CPU and index usage forever."}],"related":["upper","trim","replace"],"novel_uses":[{"body":"A unique index on LOWER(email) rejects A@x.com when a@x.com already exists, which a plain unique index on email does not. PostgreSQL takes expression indexes directly; on SQL Server, add a computed column and index that.","sql":"CREATE UNIQUE INDEX users_email_ci_unique\nON users (LOWER(email));"},{"body":"Free-text status columns collect New, new and NEW with stray spaces. Grouping on LOWER(TRIM(status)) shows the true distribution and its worst offenders before you write the cleanup.","sql":"SELECT LOWER(TRIM(status)) AS status_norm, COUNT(*) AS n\nFROM imports\nGROUP BY 1\nORDER BY 2 DESC;"}]},"source_url":"https://sqlly.app/sql-functions/lower","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/lpad","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LPAD function","description":"Pad strings to a fixed width with LPAD and RPAD in PostgreSQL, MySQL and Oracle, and the printf or RIGHT(REPLICATE()) forms for SQL Server and SQLite.","body":{"slug":"lpad","name":"LPAD / RPAD","h1":"SQL LPAD function","category":"string","lede":"Pads a string to a target width with a fill string: zero-padded invoice numbers, aligned codes, fixed-width exports. PostgreSQL, MySQL and Oracle have it built in; SQL Server and SQLite build it from other functions.","syntax":"LPAD(string, width [, fill])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"no LPAD; use RIGHT(REPLICATE('0', n) + s, n) or FORMAT"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no LPAD; use printf('%05d', x) for numbers"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["If the string is longer than the width, it is cut to width: LPAD('123456', 4, '0') is '1234'. LPAD never returns more than width characters.","Zero-padding numbers is the common use. PostgreSQL needs text: LPAD(CAST(n AS text), 5, '0'), because there is no LPAD(integer, ...). MySQL and Oracle convert the number for you: LPAD(42, 5, '0') is '00042'.","SQLite's printf (also spelled format from 3.38) handles numeric padding: printf('%05d', 42) is 00042."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LPAD(CAST(invoice_no AS text), 6, '0') AS invoice\nFROM invoices;"},{"engine_slug":"mysql","sql":"SELECT LPAD(invoice_no, 6, '0') AS invoice FROM invoices;"},{"engine_slug":"sql-server","sql":"SELECT RIGHT(REPLICATE('0', 6) + CAST(invoice_no AS varchar(10)), 6) AS invoice\nFROM invoices;"},{"engine_slug":"sqlite","sql":"SELECT printf('%06d', invoice_no) AS invoice FROM invoices;"},{"engine_slug":"oracle","sql":"SELECT LPAD('42', 6, '0') AS invoice FROM dual;  -- 000042"}],"faqs":[{"question":"Why does LPAD truncate my value?","answer":"LPAD pads up to the target width and truncates anything longer. It is a to-width function, not a minimum-width function."},{"question":"How do I zero-pad a number in SQL Server?","answer":"There is no LPAD. RIGHT(REPLICATE('0', 6) + CAST(x AS varchar), 6) is the classic; FORMAT(x, '000000') works but is slow for large sets."}],"related":["left","cast","numeric-trunc"],"novel_uses":[{"body":"RPAD(name, 20) and LPAD(total, 12) line up a monospace report or a legacy fixed-width feed entirely in the query, with no formatting pass in the app. LPAD truncates values already wider than the target, so pick widths above your data's maximum.","sql":"SELECT RPAD(name, 20) || LPAD(CAST(total AS text), 12) AS line\nFROM orders;"},{"body":"Hex output is as wide as the number needs, so 255 renders as ff but 65280 as ff00. Padding to a fixed width keeps fixed-position parsers and comparisons working: PostgreSQL's TO_HEX here, MySQL's HEX() in the same slot.","sql":"SELECT LPAD(TO_HEX(flags), 8, '0') AS flags_hex\nFROM devices;"}]},"source_url":"https://sqlly.app/sql-functions/lpad","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ltrim","corpus":"sql-functions","engine":null,"language":"en","title":"SQL LTRIM function","description":"How LTRIM strips characters from the start of a string in every major engine: the default space set, which engines take a character-set argument, and collation effects.","body":{"slug":"ltrim","name":"LTRIM","h1":"SQL LTRIM function","category":"string","lede":"Removes the longest run of the given characters (spaces by default) from the start of a string.","syntax":"LTRIM(string [, characters])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"The characters argument needs SQL Server 2022; before that, spaces only."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"One argument only; trims spaces. TRIM(LEADING x FROM s) strips a repeated string."},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Every engine has LTRIM(string). The character-set argument exists in PostgreSQL, Oracle, SQLite and SQL Server 2022+; MySQL's LTRIM takes one argument and removes spaces only.","The argument is a set of characters, not a prefix: LTRIM('ababc', 'ab') is 'c' because every leading a or b is peeled away.","Trimming stops at the first character outside the set; the interior of the string is never touched."],"examples":[{"engine_slug":"all","sql":"SELECT LTRIM('   padded') AS trimmed;  -- padded"},{"engine_slug":"postgresql","sql":"SELECT LTRIM('00123', '0') AS trimmed;  -- 123"},{"engine_slug":"mysql","sql":"SELECT TRIM(LEADING '0' FROM '00123') AS trimmed;  -- 123"}],"faqs":[{"question":"Does LTRIM remove a prefix string?","answer":"No, it removes any leading characters from the set. To strip an exact prefix, test it with LIKE 'prefix%' and take SUBSTR from the prefix length + 1. MySQL's TRIM(LEADING 'prefix' FROM s) also works but removes repeated copies."},{"question":"Why are tabs still present after LTRIM in SQL Server?","answer":"Before SQL Server 2022, LTRIM trims spaces only. From 2022 pass the set: LTRIM(s, ' ' + CHAR(9) + CHAR(10) + CHAR(13)). Elsewhere pass the set as the second argument."},{"question":"Is LTRIM case-sensitive?","answer":"PostgreSQL, Oracle and SQLite match characters exactly. SQL Server 2022 compares with the collation, so under a case-insensitive collation LTRIM('aab', 'A') returns 'b'."}],"related":["rtrim","btrim","translate","replace"],"novel_uses":[{"body":"LTRIM(phone, '+') strips the leading + so stored numbers compare as plain digits. MySQL's LTRIM takes one argument, so there it is TRIM(LEADING '+' FROM phone).","sql":"SELECT LTRIM(phone, '+') AS e164\nFROM contacts;"},{"body":"LTRIM(code, '0') turns '000' into '', not '0'. COALESCE with NULLIF restores the single zero, the standard guard for zero-stripped codes. MySQL's LTRIM takes one argument, so there use COALESCE(NULLIF(TRIM(LEADING '0' FROM code), ''), '0') instead.","sql":"SELECT COALESCE(NULLIF(LTRIM(code, '0'), ''), '0') AS digits\nFROM parts;"}]},"source_url":"https://sqlly.app/sql-functions/ltrim","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/make-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MAKE_DATE function","description":"PostgreSQL's make_date, make_time, make_timestamp and make_timestamptz build values from integers, the family DATEFROMPARTS covers on SQL Server.","body":{"slug":"make-date","name":"MAKE_DATE","h1":"SQL MAKE_DATE function","category":"datetime","lede":"Returns a date from year, month and day integers. The make_ family is PostgreSQL's constructor set; make_timestamptz also takes a zone.","syntax":"MAKE_DATE(year, month, day)  |  MAKE_TIMESTAMP(y, m, d, hh, mi, ss)  |  MAKE_TIMESTAMPTZ(y, m, d, hh, mi, ss, zone)","return_type":"date / timestamp","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEFROMPARTS / DATETIMEFROMPARTS"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"MAKEDATE is day-of-year only; no full constructor"},{"engine_slug":"sqlite","status":"partial","note":"compose a string for date() or datetime()"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE of a composed string"}],"gotchas":["Omit the zone on make_timestamptz and PostgreSQL applies the session time zone; the same integers give different instants in different sessions.","The whole family validates: month 13 or February 30 raises an error rather than rolling over.","SQL Server's DATEFROMPARTS is the name equivalent; MySQL has no full-date constructor: its MAKEDATE counts day-of-year."],"examples":[{"engine_slug":"postgresql","sql":"SELECT make_date(2024, 2, 29) AS leap_day;"},{"engine_slug":"postgresql","sql":"SELECT make_timestamptz(2024, 1, 15, 9, 30, 0, 'UTC') AS utc_meeting;"},{"engine_slug":"sql-server","sql":"SELECT DATEFROMPARTS(2024, 2, 29) AS leap_day;"},{"engine_slug":"mysql","sql":"SELECT MAKEDATE(2024, 41) AS day_41;  -- 2024-02-10, day-of-year only"},{"engine_slug":"sqlite","sql":"SELECT date(2024 || '-02-29') AS leap_day;"},{"engine_slug":"oracle","sql":"SELECT TO_DATE(2024 || '-02-29', 'YYYY-MM-DD') AS leap_day FROM dual;"}],"faqs":[{"question":"Is make_date the same as DATEFROMPARTS?","answer":"Functionally yes for positive years: year, month, day in, date out. Negative years differ: make_date(-44, 3, 15) is 0044-03-15 BC, while DATEFROMPARTS(-44, 3, 15) raises error 289. PostgreSQL names it make_date; SQL Server names it DATEFROMPARTS."},{"question":"When do I need make_timestamptz?","answer":"When the constructed instant must be zone-aware. Passing the zone explicitly beats relying on the session zone, which can differ per connection."}],"related":["datefromparts","datetimefromparts","date-literal"],"novel_uses":[{"body":"generate_series over month numbers feeds make_date directly, so a reporting query can produce all twelve month starts and LEFT JOIN the facts against the gaps.","sql":"SELECT m, make_date(2024, m, 1) AS month_start\nFROM generate_series(1, 12) AS months(m);"},{"body":"PostgreSQL 18 has no one-argument make_timestamptz. The epoch route is to_timestamp(), which takes Unix seconds and returns timestamp with time zone.","sql":"SELECT to_timestamp(1700000000) AS from_epoch;"}]},"source_url":"https://sqlly.app/sql-functions/make-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/make-interval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MAKE_INTERVAL function","description":"PostgreSQL's make_interval builds an interval from integer years, months, weeks, days, hours and mins plus fractional secs, handy when the parts arrive as columns.","body":{"slug":"make-interval","name":"MAKE_INTERVAL","h1":"SQL MAKE_INTERVAL function","category":"datetime","lede":"Returns an interval assembled from up to seven optional integer or double arguments, instead of writing INTERVAL '1 day' text literals.","syntax":"MAKE_INTERVAL(years => 1, months => 2)  |  MAKE_INTERVAL(days => 3, hours => 4)  |  MAKE_INTERVAL(1, 2, 0, 3, 4, 5, 0)","return_type":"interval","support":[{"engine_slug":"sql-server","status":"no","note":"no interval type; DATEADD applies parts directly"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"INTERVAL expr unit builds spans from expressions"},{"engine_slug":"sqlite","status":"no","note":"no interval type; date modifiers"},{"engine_slug":"oracle","status":"partial","note":"NUMTODSINTERVAL and NUMTOYMINTERVAL from numbers"}],"gotchas":["All arguments are optional and positional order is years, months, weeks, days, hours, mins, secs; named arguments avoid the classic skipped-field bug.","Months and days do not convert: make_interval(months => 1, days => 30) stays mixed, and adding it to a date applies the months first, then the days.","Oracle's NUMTODSINTERVAL is the closest shape: it also builds from numbers, but only days-to-seconds or years-to-months spans."],"examples":[{"engine_slug":"postgresql","sql":"SELECT now() + make_interval(days => 3, hours => 4) AS deadline;"},{"engine_slug":"postgresql","sql":"SELECT make_interval(years => 1, months => 2) AS tenure;"},{"engine_slug":"oracle","sql":"SELECT d + NUMTODSINTERVAL(4, 'hour') FROM events;"},{"engine_slug":"mysql","sql":"SELECT NOW() + INTERVAL 3 DAY + INTERVAL 4 HOUR AS deadline;"}],"faqs":[{"question":"Why use make_interval over INTERVAL '1 day'?","answer":"When the amounts come from columns or parameters, composing a text literal needs format gymnastics; make_interval takes integers directly."},{"question":"Does make_interval normalize units?","answer":"No. 1 month plus 30 days stays as written; the calendar rules decide the result only when it is added to a date or compared, because comparison counts a month as 30 days."}],"related":["interval-literal","dateadd","to-dsinterval"],"novel_uses":[{"body":"The secs field is a double, so make_interval(secs => 1.5) is one and a half seconds, no rounding to a coarser unit involved.","sql":"SELECT make_interval(secs => 1.5) AS span;"},{"body":"make_interval(weeks => 2) stores plain days (fourteen of them), so a weeks column in your data converts without any multiplication in the query.","sql":"SELECT make_interval(weeks => 2) AS span;"}]},"source_url":"https://sqlly.app/sql-functions/make-interval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/makedate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MAKEDATE function","description":"MySQL's MAKEDATE builds a date from a year and day-of-year: MAKEDATE(2024, 60) is February 29, not a month/day constructor like DATEFROMPARTS.","body":{"slug":"makedate","name":"MAKEDATE","h1":"SQL MAKEDATE function","category":"datetime","lede":"Returns a date given a year and a day number from 1 to 366. Larger day numbers spill into the following year.","syntax":"MAKEDATE(year, dayofyear)","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(day, n-1, DATEFROMPARTS(year, 1, 1))"},{"engine_slug":"postgresql","status":"partial","note":"make_date(year, 1, 1) + (n - 1)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"date(year || '-01-01', '+' || (n - 1) || ' days')"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE(year || LPAD(n, 3, '0'), 'YYYYDDD')"}],"gotchas":["Day 0 returns NULL and days past the year's end spill into the next year: MAKEDATE(2024, 367) is 2025-01-01.","It is not a month-and-day constructor: MAKEDATE(2024, 3) is January 3, not March. That mix-up is the classic bug.","Non-leap years have no day 366: MAKEDATE(2023, 366) becomes 2024-01-01, silently shifting the year."],"examples":[{"engine_slug":"mysql","sql":"SELECT MAKEDATE(2024, 60) AS leap_day;  -- 2024-02-29"},{"engine_slug":"mysql","sql":"SELECT MAKEDATE(2024, 0) AS nothing;  -- NULL"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(day, 60 - 1, DATEFROMPARTS(2024, 1, 1)) AS leap_day;"},{"engine_slug":"postgresql","sql":"SELECT make_date(2024, 1, 1) + 59 AS leap_day;  -- 2024-02-29"},{"engine_slug":"sqlite","sql":"SELECT date(2024 || '-01-01', '+59 days') AS leap_day;  -- 2024-02-29"},{"engine_slug":"oracle","sql":"SELECT TO_DATE(2024 || LPAD(60, 3, '0'), 'YYYYDDD') AS leap_day FROM dual;  -- 2024-02-29"}],"faqs":[{"question":"How do I build a date from month and day in MySQL?","answer":"Not with MAKEDATE alone. STR_TO_DATE(CONCAT_WS('-', y, m, d), '%Y-%m-%d') works, or MAKEDATE(y, 1) + INTERVAL (m - 1) MONTH + INTERVAL (d - 1) DAY. That arithmetic does not return NULL for an impossible date: 2023-02-29 becomes 2023-03-01, while STR_TO_DATE returns NULL, so validate first."},{"question":"What does MAKEDATE return for day 0?","answer":"NULL. Day numbering starts at 1; watch for computed day-of-year values that can hit zero."}],"related":["maketime","datefromparts","str-to-date"],"novel_uses":[{"body":"Day 366 stays inside a leap year and spills to January 1 of the next year otherwise, so YEAR(MAKEDATE(y, 366)) = y is a leap-year check with no calendar table.","sql":"SELECT YEAR(MAKEDATE(2023, 366)) <> 2023 AS not_leap,\n       YEAR(MAKEDATE(2024, 366)) = 2024 AS leap;"},{"body":"STR_TO_DATE reads day-of-year through the %j mask, so CONCAT(y, ' ', LPAD(doy, 3, '0')) with '%Y %j' converts the same pair MAKEDATE takes, inside a parse call.","sql":"SELECT STR_TO_DATE(CONCAT(2024, ' ', LPAD(61, 3, '0')), '%Y %j') AS parsed;"}]},"source_url":"https://sqlly.app/sql-functions/makedate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/maketime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MAKETIME function","description":"MySQL's MAKETIME builds a time from hours, minutes and seconds; TIMEFROMPARTS and make_time are the equivalents on SQL Server and PostgreSQL.","body":{"slug":"maketime","name":"MAKETIME","h1":"SQL MAKETIME function","category":"datetime","lede":"Returns a time value from hour and minute integers and a seconds value that can carry a fraction, with an hour range that stretches far past 24 because MySQL's TIME doubles as a duration.","syntax":"MAKETIME(hh, mm, ss)","return_type":"time","support":[{"engine_slug":"sql-server","status":"partial","note":"TIMEFROMPARTS(hh, mm, ss, 0, 0)"},{"engine_slug":"postgresql","status":"partial","note":"make_time(hh, mm, ss)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"printf('%02d:%02d:%02d', hh, mm, ss)"},{"engine_slug":"oracle","status":"no","note":"no direct constructor; compose a date or interval"}],"gotchas":["Minutes or seconds of 60 or more return NULL, but hours up to 838 are accepted: MAKETIME(100, 0, 0) is 100:00:00, and anything larger clamps to 838:59:59 with a warning.","Negative hours work too: MAKETIME(-3, 0, 0) is -03:00:00, which breaks naive parsing that assumes positive clock times.","Fractional seconds pass as a decimal third argument: MAKETIME(9, 30, 10.5) returns 09:30:10.5."],"examples":[{"engine_slug":"mysql","sql":"SELECT MAKETIME(9, 30, 0) AS start_time;"},{"engine_slug":"sql-server","sql":"SELECT TIMEFROMPARTS(9, 30, 0, 0, 0) AS start_time;"},{"engine_slug":"postgresql","sql":"SELECT make_time(9, 30, 15.5) AS start_time;  -- 09:30:15.5"},{"engine_slug":"sqlite","sql":"SELECT time(printf('%02d:%02d:%02d', 9, 30, 15)) AS start_time;  -- 09:30:15"}],"faqs":[{"question":"Can MAKETIME return more than 24 hours?","answer":"Yes, up to 838:59:59. The TIME type stores durations too, so MAKETIME(100,0,0) is legal; cast or validate if you expect clock times."},{"question":"What is the SQL Server equivalent?","answer":"TIMEFROMPARTS(hh, mm, ss, fraction, precision); its fifth argument declares how many fractional digits the fourth argument carries."}],"related":["makedate","timefromparts","time-to-sec"],"novel_uses":[{"body":"Because minutes must stay under 60, convert a total like 150 with DIV and MOD: MAKETIME(150 DIV 60, 150 MOD 60, 0) is 02:30:00. Minutes stay in range only for a non-negative total: MOD keeps the sign of its dividend, so -90 gives a minute of -30 and the result is NULL.","sql":"SELECT MAKETIME(150 DIV 60, 150 MOD 60, 0) AS slot;"},{"body":"Build the 00:00 through 23:00 labels from MAKETIME and LEFT JOIN your facts onto them, so empty hours show as zero rows instead of vanishing from the axis.","sql":"WITH RECURSIVE hrs(n) AS (SELECT 0 UNION ALL SELECT n + 1 FROM hrs WHERE n < 23)\nSELECT n AS hour_of_day, MAKETIME(n, 0, 0) AS slot FROM hrs;"}]},"source_url":"https://sqlly.app/sql-functions/maketime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mask-string","corpus":"sql-functions","engine":null,"language":"en","title":"SQL string masking","description":"Build display masks in SQL: keep the last four, star the rest; REPLICATE, REPEAT and RPAD patterns plus the engines' native masking features.","body":{"slug":"mask-string","name":"Masking strings","h1":"SQL string masking","category":"string","lede":"Turn sensitive values into display-safe form: ****1234. The pattern is length math plus repeat; the gotchas are lengths on multibyte and where the mask runs.","syntax":"REPLICATE('*', LEN(s) - 4) + RIGHT(s, 4)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The recipe: star everything but the tail. SQL Server REPLICATE('*', LEN(s) - 4) + RIGHT(s, 4); PostgreSQL REPEAT and RIGHT; Oracle RPAD('*', LENGTH(s) - 4, '*') || SUBSTR(s, -4).","Guard short values: LEN(s) - 4 goes negative under 4 characters. SQL Server's REPLICATE returns NULL for negative counts, so the mask is NULL; PostgreSQL REPEAT, MySQL REPEAT and SQLite zeroblob return an empty run, so a short value shows unmasked. Clamp the count with GREATEST(... , 0) or an equivalent on every engine.","Width math assumes one unit per character: SQL Server's LEN counts an emoji as 2 under non-SC collations, and MySQL's LENGTH counts bytes. Use CHAR_LENGTH on MySQL and an _SC collation on SQL Server when the data can hold them.","Masks in reports are cosmetic: SQL Server's dynamic data masking and view-based masking protect display, not access; users with query rights can often derive the value."],"examples":[{"engine_slug":"sql-server","sql":"SELECT REPLICATE('*', LEN(number) - 4) + RIGHT(number, 4) AS masked FROM cards;\n-- ************3456"},{"engine_slug":"postgresql","sql":"SELECT CONCAT(REPEAT('*', GREATEST(length(email) - 3, 0)), right(email, 3)) AS masked FROM users;\n-- three tail characters for emails; the card recipe keeps four"},{"engine_slug":"oracle","sql":"SELECT RPAD('*', LENGTH(card) - 4, '*') || SUBSTR(card, -4) AS masked FROM cards;"},{"engine_slug":"mysql","sql":"SELECT CONCAT(REPEAT('*', CHAR_LENGTH(number) - 4), RIGHT(number, 4)) AS masked FROM cards;\n-- ************3456"},{"engine_slug":"sqlite","sql":"SELECT replace(hex(zeroblob(length(number) - 4)), '00', '*') || substr(number, -4) AS masked FROM cards;\n-- ************3456: no repeat(), so hex(zeroblob(n)) builds the star run"}],"faqs":[{"question":"Why did my mask return NULL?","answer":"A negative repeat count: values shorter than the keep-length make LEN(s) - 4 negative, and SQL Server's REPLICATE returns NULL. Clamp with IIF/GREATEST."},{"question":"Is SQL Server's dynamic data masking secure?","answer":"It hides values from unmasked users' results but is not a security boundary; users can often infer values through queries. Real protection is permissions and encryption."},{"question":"Should I mask stored data or at query time?","answer":"Store the real value, mask in views or at read time; masking on write destroys the data. Only hashed or tokenized replacements should ever be stored in place."}],"related":["replicate","substring","right","emoji-length"],"novel_uses":[{"body":"Keeping the first character and the domain, m***@example.com, leaves support tickets useful, since the provider often matters more than the local part.","sql":"SELECT CONCAT(LEFT(email, 1), '***@', SUBSTRING_INDEX(email, '@', -1)) AS masked FROM users;"},{"body":"A generated last4 column keeps WHERE last4 = '3456' working after the full number is masked, because a masked display value is lossy and matches many rows, so lookups need a separately stored searchable tail.","sql":"ALTER TABLE cards ADD COLUMN last4 CHAR(4) AS (RIGHT(number, 4)) STORED;"}]},"source_url":"https://sqlly.app/sql-functions/mask-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/max","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MAX function","description":"How MAX works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the largest value per group on numbers, dates and text, with NULL handling explained.","body":{"slug":"max","name":"MAX","h1":"SQL MAX function","category":"aggregate","lede":"Returns the largest non-null value in a group: the latest date, the highest amount. Like MIN, it returns a value, not the row the value came from.","syntax":"MAX(expression)","return_type":"same type as the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MAX ignores NULLs; MAX over only-NULL values returns NULL.","MAX(created_at) is the usual latest-record lookup, but combine it with a join carefully: two rows can share the same maximum timestamp.","On text columns the column's collation decides the winner. Under a case-insensitive collation, 'apple' and 'APPLE' tie, and either can come back."],"examples":[{"engine_slug":"all","sql":"SELECT MAX(created_at) AS last_order\nFROM orders;"},{"engine_slug":"all","sql":"SELECT customer_id, MAX(amount) AS biggest_order\nFROM orders\nGROUP BY customer_id;"}],"faqs":[{"question":"How do I get the whole row with the maximum value?","answer":"An aggregate collapses the group, so pair MAX with a join, or use a window function: SELECT * FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn FROM orders o) ranked WHERE rn = 1."},{"question":"Does MAX ignore NULL?","answer":"Yes, the same as MIN. NULL values never win the maximum."}],"related":["min","row-number","sum"],"novel_uses":[{"body":"Comparing each row to MAX(at) OVER (PARTITION BY user_id) marks the newest row per user without a CTE or a self join, and every row stays in the result. Ties both get flagged, which is usually what an is_latest column wants.","sql":"SELECT user_id, at,\n       CASE WHEN at = MAX(at) OVER (PARTITION BY user_id) THEN 1 ELSE 0 END AS is_latest\nFROM events;"},{"body":"On an auto-increment id, MAX(id) minus COUNT(*) approximates how many rows were ever removed. The gap also grows from rolled-back inserts, so treat a sudden jump as a hint to investigate, not a ledger.","sql":"SELECT MAX(id) - COUNT(*) AS churn_hint FROM orders;"},{"body":"MAX over a CASE picks one row's value out of a group without a join: MAX(CASE WHEN is_primary THEN phone END) is the customer's primary phone in a single scan, because the CASE turns every non-matching row into NULL and MAX ignores those.","sql":"SELECT customer_id,\n       MAX(CASE WHEN is_primary THEN phone END) AS primary_phone\nFROM customer_phones\nGROUP BY customer_id;"}]},"source_url":"https://sqlly.app/sql-functions/max","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/md5","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MD5 function","description":"How MD5 hashing works in MySQL, PostgreSQL and the HASHBYTES and STANDARD_HASH routes in SQL Server and Oracle: output forms, checksum versus security, and SHA upgrades.","body":{"slug":"md5","name":"MD5","h1":"SQL MD5 function","category":"string","lede":"Returns the 128-bit MD5 hash of a string as a hex digest. Fine for checksums, unsafe for anything an attacker controls.","syntax":"MD5(string)  |  SQL Server: HASHBYTES('MD5', value)  |  Oracle: STANDARD_HASH(value, 'MD5')","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"HASHBYTES('MD5', value) returns 16 raw bytes."},{"engine_slug":"postgresql","status":"yes","note":"md5(text) returns lowercase hex."},{"engine_slug":"mysql","status":"yes","note":"MD5(str) returns lowercase hex."},{"engine_slug":"sqlite","status":"no","note":"No MD5; hash in the application or via an extension."},{"engine_slug":"oracle","status":"partial","note":"STANDARD_HASH(value, 'MD5') returns RAW bytes."}],"gotchas":["MySQL and PostgreSQL return 32 lowercase hex characters. SQL Server's HASHBYTES and Oracle's STANDARD_HASH return 16 raw bytes; CONVERT(varchar(32), ..., 2) and RAWTOHEX render them as uppercase hex.","MD5 has practical collisions, so do not use it where an attacker picks the input: signatures, tamper checks, passwords. Passwords need a slow salted function such as bcrypt or Argon2, computed in the application.","It is still fine as a fast fingerprint for cache keys, change detection, and comparing rows across systems, provided both sides hash the same bytes in the same encoding."],"examples":[{"engine_slug":"mysql","sql":"SELECT MD5('hello') AS digest;  -- 5d41402abc4b2a76b9719d911017c592"},{"engine_slug":"postgresql","sql":"SELECT md5(payload) AS digest\nFROM messages;"},{"engine_slug":"sql-server","sql":"SELECT LOWER(CONVERT(varchar(32), HASHBYTES('MD5', 'hello'), 2)) AS digest;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(STANDARD_HASH('hello', 'MD5')) AS digest\nFROM dual;  -- 5D41402ABC4B2A76B9719D911017C592"}],"faqs":[{"question":"Is MD5 safe for passwords?","answer":"No. MD5 is fast by design, which is exactly wrong for passwords. Use bcrypt, scrypt or Argon2 in application code, never a SQL hash function."},{"question":"What is the difference between MD5 and SHA-256?","answer":"Digest size and collision resistance: MD5 produces 128 bits and has practical collisions; SHA-256 produces 256 bits and has none known."},{"question":"Why does my MD5 result look different in SQL Server?","answer":"HASHBYTES returns binary. CONVERT(varchar(32), HASHBYTES('MD5', v), 2) gives uppercase hex without 0x; wrap it in LOWER() to match MySQL and PostgreSQL. For ASCII text, hash varchar, not nvarchar: nvarchar hashes UTF-16LE bytes, which never match. For non-ASCII text, varchar hashes the database code page (CP1252 with the SQL_Latin1_General_CP1_CI_AS collation used here), so it matches UTF-8 only under a UTF-8 collation such as Latin1_General_100_CI_AS_SC_UTF8."}],"related":["sha2","hashbytes","hex","to-base64"],"novel_uses":[{"body":"Hashing the row's text form gives each row a compact signature, and unlike a separator-joined concatenation it keeps every NULL in its own position, so a value that moves to another column changes the hash. A sync job then compares one small column instead of every field to find what changed.","sql":"SELECT id FROM products\nWHERE md5(ROW(name, price, updated_at)::text) <> stored_hash;"},{"body":"('x' || substr(md5(email), 1, 15))::bit(60)::bigint % 100 < 10 picks a stable ten percent in PostgreSQL: the same email lands in the same bucket on every run, and no extra column is needed.","sql":"SELECT * FROM users\nWHERE ('x' || substr(md5(email), 1, 15))::bit(60)::bigint % 100 < 10;"},{"body":"Hashing the ordered, concatenated ids fingerprints which rows a batch holds: rerun the query and the same digest means the same ids are still there. Only the ids are hashed, so a changed status or amount leaves the digest the same; hash those columns in too when they matter.","sql":"SELECT md5(string_agg(id::text, ',' ORDER BY id)) AS batch_digest\nFROM jobs\nWHERE run_date = '2026-11-26';"}]},"source_url":"https://sqlly.app/sql-functions/md5","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/median","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MEDIAN function","description":"MEDIAN per group: Oracle's built-in, PostgreSQL and SQL Server via PERCENTILE_CONT(0.5) WITHIN GROUP, MySQL window recipes and SQLite's 3.51 percentile support.","body":{"slug":"median","name":"MEDIAN","h1":"SQL MEDIAN function","category":"aggregate","lede":"Returns the middle value of the group, interpolating between the two middle values on even counts.","syntax":"MEDIAN(x) | percentile_cont(0.5) WITHIN GROUP (ORDER BY x)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"no MEDIAN; PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) works as a window function only"},{"engine_slug":"postgresql","status":"partial","note":"use percentile_cont(0.5) WITHIN GROUP (ORDER BY x)"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"partial","note":"median() since 3.51.0 when built with SQLITE_ENABLE_PERCENTILE, or the percentile extension"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Even counts interpolate: the result may be a value that exists in no row; PERCENTILE_DISC never does that.","SQL Server's PERCENTILE_CONT is window-only, so a per-group median needs OVER (PARTITION BY ...) plus DISTINCT or a subquery.","MySQL has neither; the window recipe is averaging the two middle rows found with ROW_NUMBER over the ordered values.","NULLs are skipped by every built-in; the MySQL recipe has to filter WHERE x IS NOT NULL itself, or the NULLs sort first and shift the middle."],"examples":[{"engine_slug":"oracle","sql":"SELECT dept_id, MEDIAN(salary) FROM employees GROUP BY dept_id;"},{"engine_slug":"postgresql","sql":"SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) FROM employees;"},{"engine_slug":"sql-server","sql":"SELECT DISTINCT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY dept_id) FROM employees;"},{"engine_slug":"sqlite","sql":"SELECT median(salary) FROM employees;"}],"faqs":[{"question":"Median vs average?","answer":"The median ignores how extreme the tails are; one huge outlier drags the average but barely moves the median."},{"question":"Why is my median not an actual row value?","answer":"Even counts interpolate between the two middle values; use PERCENTILE_DISC(0.5) to get a real value."},{"question":"What is the median in MySQL?","answer":"No built-in: average the two middle values located with ROW_NUMBER or COUNT over an ordered subquery."}],"related":["percentile-cont","percentile-disc","mode","ordered-set-aggregates","avg"],"novel_uses":[{"body":"PostgreSQL rejects OVER on percentile_cont, so a 30-row trailing median runs it in a LATERAL subquery over the last 30 rows; it tracks the middle of a noisy series where the mean would chase spikes.","sql":"SELECT t.day, m.med FROM timings t CROSS JOIN LATERAL (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY w.ms) AS med FROM (SELECT ms FROM timings w WHERE w.day <= t.day ORDER BY w.day DESC LIMIT 30) w) m;"},{"body":"Oracle's analytic MEDIAN OVER (PARTITION BY dept_id) puts each employee's department median on the same row, no self-join and no GROUP BY collapse.","sql":"SELECT emp_id, dept_id, salary, MEDIAN(salary) OVER (PARTITION BY dept_id) AS dept_median FROM employees;"}]},"source_url":"https://sqlly.app/sql-functions/median","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/metaphone","corpus":"sql-functions","engine":null,"language":"en","title":"SQL METAPHONE function","description":"How PostgreSQL's metaphone and dmetaphone improve on SOUNDEX for name matching: pronunciation rules, double metaphone for accents, and the fuzzystrmatch extension.","body":{"slug":"metaphone","name":"METAPHONE","h1":"SQL METAPHONE function","category":"string","lede":"Encodes a string by its English pronunciation, producing phonetic keys that separate names better than SOUNDEX.","syntax":"metaphone(string, max_length)  |  dmetaphone(string)  |  dmetaphone_alt(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No built-in metaphone."},{"engine_slug":"postgresql","status":"yes","note":"Requires the fuzzystrmatch extension."},{"engine_slug":"mysql","status":"no","note":"No built-in metaphone."},{"engine_slug":"sqlite","status":"no","note":"No built-in metaphone."},{"engine_slug":"oracle","status":"no","note":"No built-in metaphone."}],"gotchas":["metaphone requires a maximum code length: metaphone('telephone', 6) keeps at most six code characters. Shorter codes group more names together. A length of 0 or less fails with the error output cannot be empty string.","Metaphone knows English silent letters and digraphs ('PH' encodes as 'F', initial 'KN' as 'N'), where SOUNDEX maps letters mechanically.","fuzzystrmatch's soundex, metaphone and dmetaphone do not work well with multibyte encodings such as UTF-8, so accented letters are not mapped sensibly. Transliterate first, for example with unaccent."],"examples":[{"engine_slug":"postgresql","sql":"SELECT metaphone('knight', 6) AS code;  -- NFT"},{"engine_slug":"postgresql","sql":"SELECT dmetaphone('Schmidt') AS primary_code,\n       dmetaphone_alt('Schmidt') AS alt_code;  -- XMT, SMT"}],"faqs":[{"question":"Is metaphone better than SOUNDEX?","answer":"For English names, usually: it models pronunciation instead of letter classes, so fewer unrelated names collide. It is still English-centric."},{"question":"What is Double Metaphone for?","answer":"It returns a primary code (dmetaphone) and an alternate (dmetaphone_alt) so that spellings from different languages, such as Germanic and Slavic forms of a name, can still meet on one of the two."},{"question":"Why is metaphone not found in my PostgreSQL?","answer":"It lives in the fuzzystrmatch extension: CREATE EXTENSION fuzzystrmatch; enables metaphone, dmetaphone, levenshtein, soundex and difference together."}],"related":["soundex","difference","similarity","levenshtein"],"novel_uses":[{"body":"fuzzystrmatch's metaphone is immutable, so a stored generated column can hold the code and an index over it turns phonetic lookups into equality searches instead of full scans.","sql":"ALTER TABLE people ADD name_key text\n  GENERATED ALWAYS AS (metaphone(lower(name), 6)) STORED;\nCREATE INDEX ON people (name_key);"},{"body":"Grouping by the code surfaces most spelling variants of the same name, though not all: Smith (SM0) and Smit (SMT) land in different groups. Treat the groups as a first pass before deciding the canonical spelling.","sql":"SELECT metaphone(lower(surname), 6) AS code, COUNT(*) AS n\nFROM people\nGROUP BY code\nHAVING COUNT(*) > 3;"}]},"source_url":"https://sqlly.app/sql-functions/metaphone","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MID function","description":"How MID(str, pos, len) extracts a substring in MySQL and MariaDB, why it is an alias for SUBSTRING, and which functions replace it in other engines.","body":{"slug":"mid","name":"MID","h1":"SQL MID function","category":"string","lede":"Extracts part of a string from a 1-based position. In MySQL it is another name for SUBSTRING.","syntax":"MID(str, start, length)  |  MID(str, start)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"Use SUBSTRING(str, start, length)."},{"engine_slug":"postgresql","status":"partial","note":"Use SUBSTRING or SUBSTR."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"Use SUBSTR."},{"engine_slug":"oracle","status":"partial","note":"Use SUBSTR."}],"gotchas":["MID is exactly SUBSTRING in MySQL: same 1-based positions, same omitted-length behaviour, NULL in gives NULL out.","Position 0 is not clamped to 1: MID('abc', 0) and MID('abc', 0, 2) both return an empty string.","Negative positions count from the end: MID('hello world', -5) is 'world'."],"examples":[{"engine_slug":"mysql","sql":"SELECT MID('hello world', 7) AS tail;  -- world"},{"engine_slug":"mysql","sql":"SELECT MID(iso_code, 1, 2) AS country\nFROM locales;"},{"engine_slug":"sql-server","sql":"SELECT SUBSTRING('hello world', 7, 5) AS tail;  -- world"},{"engine_slug":"postgresql","sql":"SELECT SUBSTRING('hello world' FROM 7) AS tail;  -- world"},{"engine_slug":"sqlite","sql":"SELECT SUBSTR('hello world', 7) AS tail;  -- world"},{"engine_slug":"oracle","sql":"SELECT SUBSTR('hello world', 7) AS tail\nFROM dual;  -- world"}],"faqs":[{"question":"Is MID the same as SUBSTRING in MySQL?","answer":"Yes, argument for argument. SUBSTRING is the spelling PostgreSQL uses too; PostgreSQL and SQLite have no MID at all, so use SUBSTRING or SUBSTR there."},{"question":"Why does MID('abc', 0) return an empty string?","answer":"MySQL positions start at 1 and a start of 0 points before the string, so nothing is returned. Oracle's SUBSTR treats 0 as 1, which is why code ported from Oracle breaks here."}],"related":["substr","substring","left","right"],"novel_uses":[{"body":"ORD(MID(s, n, 1)) reads the code of the nth character in MySQL, which is the inner loop of charset checks and converters written as stored procedures.","sql":"SELECT ORD(MID(code, 1, 1)) AS first_char_code\nFROM items;"},{"body":"A stored generated column built from MID computes the slice once per write; an index over it then serves equality lookups such as WHERE family = 'AB' without repeating the expression in every query.","sql":"ALTER TABLE skus ADD family varchar(2)\n  GENERATED ALWAYS AS (MID(code, 1, 2)) STORED;\nCREATE INDEX idx_skus_family ON skus (family);"}]},"source_url":"https://sqlly.app/sql-functions/mid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/milliseconds","corpus":"sql-functions","engine":null,"language":"en","title":"SQL millisecond function","description":"Sub-seconds: DATEPART(millisecond) on SQL Server, EXTRACT(milliseconds) on PostgreSQL (seconds included; take % 1000), MICROSECOND() on MySQL, strftime('%f') on SQLite.","body":{"slug":"milliseconds","name":"MILLISECOND / MICROSECOND","h1":"SQL millisecond function","category":"datetime","lede":"Returns the sub-second part of a timestamp: SQL Server via DATEPART, MySQL via MICROSECOND(), SQLite via the %f format. PostgreSQL's version keeps the whole seconds.","syntax":"DATEPART(millisecond, ts)  -- SQL Server  |  EXTRACT(milliseconds FROM ts)  -- PostgreSQL  |  MICROSECOND(ts)  -- MySQL","return_type":"integer (SQL Server, MySQL); numeric (PostgreSQL); text (SQLite)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(millisecond | microsecond | nanosecond, ts)"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(milliseconds FROM ts) includes the whole seconds"},{"engine_slug":"mysql","status":"yes","note":"MICROSECOND(ts) returns the fraction in microseconds; divide by 1000 for milliseconds"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%f', ts) returns 'SS.FFF' text"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(SYSTIMESTAMP, 'FF3') for milliseconds"}],"gotchas":["SQL Server's datetime rounds to 1/300 s; DATEPART(millisecond) on it returns 0, 3, 6, 10, 13 and so on (truncated 3.33 ms steps); datetime2 is the precise type.","PostgreSQL's EXTRACT(milliseconds) is the seconds field times 1000, whole seconds included: 31.5 seconds gives 31500. Take it modulo 1000 for the fraction alone.","SQLite's %f is the whole 'seconds.fraction' string like 31.123; the fraction alone needs substr after the dot."],"examples":[{"engine_slug":"sql-server","sql":"SELECT DATEPART(MILLISECOND, SYSDATETIME()) AS ms;"},{"engine_slug":"postgresql","sql":"SELECT FLOOR(EXTRACT(milliseconds FROM ts))::int % 1000 AS ms FROM events;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%f', 'now') AS sec_frac;"},{"engine_slug":"mysql","sql":"SELECT MICROSECOND('2024-01-15 09:30:05.250') AS micros;  -- 250000 = 250 ms"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(SYSTIMESTAMP, 'FF3') AS ms FROM dual;"}],"faqs":[{"question":"Why does SQL Server show .003-style milliseconds?","answer":"The datetime type rounds to 1/300 second. SYSDATETIME() with datetime2 gives true 100-ns precision for sub-second work."},{"question":"How do I store millisecond precision?","answer":"Use datetime2(3) on SQL Server, timestamp(3) on PostgreSQL and Oracle, DATETIME(3) on MySQL, and TEXT ISO strings on SQLite."}],"related":["second","getdate","clock-timestamp"],"novel_uses":[{"body":"TIMESTAMPDIFF(MICROSECOND, start_ts, end_ts) measures the whole span in integer microseconds, so averaging and summing avoid float drift entirely.","sql":"SELECT TIMESTAMPDIFF(MICROSECOND, start_ts, end_ts) AS elapsed_us FROM timings;"},{"body":"Capture SYSDATETIME() into a variable, run the suspect code, and DATEDIFF_BIG(microsecond, @t0, SYSDATETIME()) reports the cost. The BIG form matters once spans pass about 35.8 minutes (2^31 microseconds), where plain DATEDIFF's int overflows with error 535.","sql":"DECLARE @t0 datetime2 = SYSDATETIME();\nWAITFOR DELAY '0:00:00.050';\nSELECT DATEDIFF_BIG(microsecond, @t0, SYSDATETIME()) AS elapsed_us;"}]},"source_url":"https://sqlly.app/sql-functions/milliseconds","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/min","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MIN function","description":"How MIN works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the smallest value per group, on numbers, dates and text, and how NULLs are treated.","body":{"slug":"min","name":"MIN","h1":"SQL MIN function","category":"aggregate","lede":"Returns the smallest non-null value in a group. It works on numbers, dates and strings; for text, the column's collation decides what smallest means.","syntax":"MIN(expression)","return_type":"same type as the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MIN ignores NULLs; MIN of a group whose values are all NULL returns NULL.","On text columns the result follows the column's collation, so case and accent rules decide the smallest value on SQL Server and MySQL.","Booleans do not work everywhere: SQL Server rejects MIN on a bit column (cast it to int), and PostgreSQL has no MIN(boolean); use bool_and instead."],"examples":[{"engine_slug":"all","sql":"SELECT MIN(created_at) AS first_order\nFROM orders;"},{"engine_slug":"all","sql":"SELECT customer_id, MIN(amount) AS smallest_order\nFROM orders\nGROUP BY customer_id;"}],"faqs":[{"question":"Does MIN work on dates?","answer":"Yes. MIN(created_at) returns the earliest timestamp, which is the usual way to find a customer's first order. Text columns compare by collation order."},{"question":"Does MIN ignore NULL?","answer":"Yes. Rows where the expression is NULL never win the minimum. If every value is NULL, MIN returns NULL."}],"related":["max","count","sum"],"novel_uses":[{"body":"MIN on status text follows collation, not process order. Map the stages to numbers first and MIN(CASE ...) returns the earliest stage each customer reached; decode the number with a second CASE in the outer query.","sql":"SELECT customer_id,\n       MIN(CASE status WHEN 'new' THEN 1\n                       WHEN 'paid' THEN 2\n                       WHEN 'shipped' THEN 3 END) AS earliest_stage\nFROM orders\nGROUP BY customer_id;"},{"body":"Group duplicates on the real key, keep MIN(id), and delete everything else in one statement. MySQL refuses a subquery on the target table here (error 1093), so wrap it in a derived table: WHERE id NOT IN (SELECT * FROM (SELECT MIN(id) ...) x).","sql":"DELETE FROM customers\nWHERE id NOT IN (SELECT MIN(id) FROM customers GROUP BY email);"},{"body":"MIN as a window function carries the smallest value so far, so balance minus that running minimum is the worst dip to date. Frame it with 29 PRECEDING for a trailing month instead. Offset window frames need Oracle 12c+, SQL Server 2012+, MySQL 8+, or SQLite 3.25+.","sql":"SELECT day,\n       balance - MIN(balance) OVER (ORDER BY day) AS drawdown\nFROM account_snapshots;"}]},"source_url":"https://sqlly.app/sql-functions/min","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/min-max-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MIN and MAX with OVER","description":"MIN() OVER and MAX() OVER: partition-wide extremes, running maxima and the min-vs-max spread, without losing detail rows.","body":{"slug":"min-max-over","name":"MIN and MAX with OVER","h1":"SQL MIN and MAX with OVER","category":"window","lede":"Finds the smallest or largest value in the frame or partition and attaches it to every row: running maxima for drawdowns, partition extremes for spreads.","syntax":"MAX(x) OVER (PARTITION BY g) | MIN(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MAX(x) OVER (ORDER BY d) is already a running maximum: the default frame ends at the current row (including its peers), which is exactly what a running high needs.","MIN/MAX ignore NULLs entirely; an all-NULL frame returns NULL, not an error.","For whole rows holding the extreme (not just the value), FIRST_VALUE with a matching ORDER BY or a ROW_NUMBER = 1 CTE is cleaner than MIN/MAX + join. FIRST_VALUE returns one column per call, so list each column; exclude NULL sort keys first, because PostgreSQL sorts NULLs first under DESC and returns a NULL row."],"examples":[{"engine_slug":"all","sql":"SELECT day, price,\n       MAX(price) OVER (ORDER BY day) AS running_high,\n       price - MAX(price) OVER (ORDER BY day) AS off_high\nFROM prices;"},{"engine_slug":"all","sql":"SELECT department, salary,\n       MIN(salary) OVER (PARTITION BY department) AS dept_min,\n       MAX(salary) OVER (PARTITION BY department) AS dept_max\nFROM employees;"}],"faqs":[{"question":"How do I get the row with the maximum value?","answer":"Filter with a window: rank rows ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) and keep rn = 1 in an outer query, after filtering out NULL x (WHERE x IS NOT NULL): PostgreSQL sorts NULLs first under DESC and would return a NULL row. MIN/MAX OVER only gives the value, and joining on x = MAX(x) keeps tied rows."},{"question":"Do I need a frame clause for a running MAX?","answer":"Not when the ORDER BY is unique: the default RANGE frame already ends at the current row. With ties it includes the tied rows too, so two rows on the same day both see the day's high. Write ROWS UNBOUNDED PRECEDING plus a tiebreaker if each row must see only the rows up to and including itself."}],"related":["aggregate-over","running-total","first-value"],"novel_uses":[{"body":"MAX minus MIN over a partition is a range-based spread that survives on engines with no STDDEV, and dividing by the average turns it into a scale-free coefficient. Use it for quick comparability checks before committing to real statistics.","sql":"SELECT department, salary,\n       MAX(salary) OVER (PARTITION BY department)\n         - MIN(salary) OVER (PARTITION BY department) AS spread\nFROM employees;"},{"body":"Subtract MIN of the date over the partition from the current date and every row knows its age within the group: cohort day numbers, account tenure, days into a project. On PostgreSQL and Oracle date minus date is days. SQL Server rejects it (use DATEDIFF(day, MIN(d) OVER (...), d)), MySQL does YYYYMMDD arithmetic (use DATEDIFF(d, MIN(d) OVER (...))), and SQLite stores dates as text (use CAST(julianday(d) - julianday(MIN(d) OVER (...)) AS INTEGER)).","sql":"SELECT user_id, activity_day,\n       activity_day - MIN(activity_day) OVER (PARTITION BY user_id) AS day_number\nFROM activity;"}]},"source_url":"https://sqlly.app/sql-functions/min-max-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/min-scale","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MIN_SCALE function","description":"PostgreSQL min_scale(numeric) returns the fewest decimal digits the value needs: 2 for 1.2300, the answer scale() would give after trimming zeros.","body":{"slug":"min-scale","name":"MIN_SCALE","h1":"SQL MIN_SCALE function","category":"math","lede":"Returns the minimum number of decimal digits needed to represent a numeric exactly: min_scale(1.2300) is 2.","syntax":"MIN_SCALE(numeric)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No equivalent"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 13 introduced min_scale and trim_scale together"},{"engine_slug":"mysql","status":"no","note":"No equivalent; normalize a value by rounding to fewer decimals instead"},{"engine_slug":"sqlite","status":"no","note":"No equivalent; REAL values have no decimal scale"},{"engine_slug":"oracle","status":"no","note":"No equivalent; NUMBER values do not keep trailing zeros anyway"}],"gotchas":["min_scale(1.2300) is 2 but scale(1.2300) is 4: min_scale ignores trailing zeros, scale counts them.","For integers the answer is 0: min_scale(42) is 0.","Its main use is storage decisions: if min_scale(x) <= 2 (and the integer part fits), the value survives a cast to DECIMAL(10,2) unchanged."],"examples":[{"engine_slug":"postgresql","sql":"SELECT MIN_SCALE(1.2300::numeric) AS m;  -- 2"},{"engine_slug":"postgresql","sql":"SELECT MIN_SCALE(amount::numeric) AS needed\nFROM rates\nORDER BY needed DESC;"}],"faqs":[{"question":"How is min_scale different from scale?","answer":"scale counts every stored digit after the point, trailing zeros included. min_scale returns the minimum needed to be exact: min_scale(1.2300) is 2 where scale is 4."},{"question":"What is min_scale of an integer?","answer":"0. min_scale(42) is 0 because no fractional digits are required."},{"question":"When would I use it?","answer":"Mostly to check whether a value fits a cheaper column: if MIN_SCALE(x) <= 2 and the integer part has at most 8 digits, the value is exactly representable as DECIMAL(10,2), so casting loses nothing. A larger integer part fails with numeric field overflow instead."}],"related":["scale","trim-scale","numeric-precision-scale"],"novel_uses":[{"body":"MIN_SCALE(x) = 0 is an exact whole-number test for a numeric column, with no float comparison to get wrong. Use it to route rows to an integer path only when the cast loses nothing.","sql":"SELECT COUNT(*) FROM readings WHERE min_scale(value) = 0;"},{"body":"Trailing zeros change scale() but never min_scale(), so min_scale survives round trips through systems that pad values. Comparing it before and after an ETL hop catches changes in precision, but it does not prove the value is intact: 1.2 and 1.3 both have min_scale 1, so pair it with a direct value comparison.","sql":"SELECT id FROM staging\nWHERE min_scale(value) <> min_scale(source_value)\n   OR value <> source_value;"}]},"source_url":"https://sqlly.app/sql-functions/min-scale","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/minute","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MINUTE function","description":"Get the minute 0-59: MINUTE() on MySQL, DATEPART(minute) on SQL Server, EXTRACT(minute FROM ts) on PostgreSQL and Oracle, strftime('%M') on SQLite.","body":{"slug":"minute","name":"MINUTE","h1":"SQL MINUTE function","category":"datetime","lede":"Returns the minutes component of a timestamp, the piece of bucketing that turns raw event times into half-hour or five-minute cohorts.","syntax":"EXTRACT(minute FROM ts)  |  DATEPART(minute, ts)  -- SQL Server  |  MINUTE(ts)  -- MySQL","return_type":"integer (numeric on PostgreSQL, text on SQLite)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(minute, ts); no MINUTE() shorthand"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(minute FROM ts)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%M', ts) returns text"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT needs a TIMESTAMP"}],"gotchas":["Oracle's EXTRACT(minute) fails on plain DATE; cast to TIMESTAMP or use TO_CHAR(d, 'MI').","For sub-hour buckets, floor the division: on PostgreSQL and MySQL EXTRACT(minute ...) / 5 returns 6.8 for minute 34, so wrap it in FLOOR(). PostgreSQL 14+ has date_bin for this.","SQLite's strftime('%M') is minutes; %m is the month, and mixing them is the classic SQLite date bug."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(hour FROM created_at) AS hr,\n       FLOOR(EXTRACT(minute FROM created_at) / 5) AS slot\nFROM events;"},{"engine_slug":"mysql","sql":"SELECT MINUTE(created_at) AS min FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%M', created_at) AS INTEGER) AS min FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(minute, created_at) AS min FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(minute FROM CAST(created_at AS TIMESTAMP)) AS min FROM orders;"}],"faqs":[{"question":"Why does my SQLite query return months?","answer":"strftime('%m') is the month; minutes are %M. Capital and lowercase mean opposite things compared to what you might guess."},{"question":"How do I bucket into 15-minute intervals?","answer":"MySQL: FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(ts) / 900) * 900). PostgreSQL 14+: date_bin('15 minutes', ts, TIMESTAMP '2000-01-01'). SQL Server 2022+: DATE_BUCKET(minute, 15, ts)."}],"related":["extract","hour","date-trunc"],"novel_uses":[{"body":"TIMEDIFF hands back a TIME, so HOUR() and MINUTE() of the difference print a shift as '8:30' style columns without touching SEC_TO_TIME.","sql":"SELECT HOUR(TIMEDIFF(end_at, start_at)) AS hrs,\n       MINUTE(TIMEDIFF(end_at, start_at)) AS mins\nFROM shifts;"},{"body":"DATE_BUCKET needs SQL Server 2022. Before that, count whole minutes from a datetime2 origin and floor the count to the slot width: this drops every timestamp to its five-minute slot, seconds and fractions included. A datetime origin would round 10:29:59.999 up to 10:30, so keep the origin datetime2.","sql":"SELECT DATEADD(minute, DATEDIFF(minute, CAST('1900-01-01' AS datetime2), at) / 5 * 5, CAST('1900-01-01' AS datetime2)) AS slot FROM calls;"}]},"source_url":"https://sqlly.app/sql-functions/minute","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mod","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MOD function","description":"Remainder math with MOD and % in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: where MOD exists, where only % does, and the sign rule.","body":{"slug":"mod","name":"MOD / %","h1":"SQL MOD function","category":"math","lede":"Returns the remainder after division. It is used for sharding keys, every-nth-row sampling and cyclical buckets; the spelling, the sign rule and the divide-by-zero result all vary.","syntax":"MOD(a, b)  |  a % b","return_type":"integer / numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"% operator only, no MOD function"},{"engine_slug":"postgresql","status":"yes","note":"both MOD(a, b) and a % b"},{"engine_slug":"mysql","status":"yes","note":"MOD(a, b), a % b and a MOD b"},{"engine_slug":"sqlite","status":"yes","note":"% operator; MOD(a, b) with the math functions (3.35+)"},{"engine_slug":"oracle","status":"yes","note":"MOD(a, b) only; % is not an operator"}],"gotchas":["The result takes the sign of the dividend: MOD(-7, 3) is -1 on every engine here, not 2. Use MOD(MOD(a, n) + n, n) for an always-positive bucket.","Dividing by zero differs: SQL Server and PostgreSQL raise an error, MySQL and SQLite return NULL, and Oracle's MOD(5, 0) returns 5.","SQL Server only has %, and Oracle only has MOD(). No single spelling works on both."],"examples":[{"engine_slug":"postgresql","sql":"-- also MySQL, SQLite 3.35+ and Oracle\nSELECT id, MOD(id, 4) AS shard FROM users;"},{"engine_slug":"sql-server","sql":"SELECT id, id % 4 AS shard FROM users;"},{"engine_slug":"postgresql","sql":"SELECT MOD(MOD(-7, 3) + 3, 3) AS positive_bucket;  -- 2"},{"engine_slug":"mysql","sql":"SELECT MOD(10, 3) AS rem;  -- 1"},{"engine_slug":"sqlite","sql":"-- mod() is a 3.35+ math function; the % operator also works\nSELECT mod(10, 3) AS rem;  -- 1"},{"engine_slug":"oracle","sql":"SELECT MOD(10, 3) AS rem FROM dual;  -- 1"}],"faqs":[{"question":"What is MOD(-7, 3)?","answer":"-1 on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the remainder follows the dividend's sign. Add the divisor back into a double MOD for an always-positive result."},{"question":"Does SQL Server have a MOD function?","answer":"No, only the % operator: 7 % 3. PostgreSQL, MySQL and SQLite 3.35+ have both MOD() and %. Oracle has MOD() but no % operator."}],"related":["floor","abs","cast"],"novel_uses":[{"body":"user_id % 2 = 0 puts half your users in bucket A, consistently across every query, day and environment, because the remainder never changes. Wrap it as MOD(MOD(id, n) + n, n) when ids can be negative, since the remainder follows the dividend's sign.","sql":"SELECT COUNT(*) FROM users WHERE id % 2 = 0;"},{"body":"WHERE id % 100 = 0 pulls a fixed one-percent slice that is identical on every run and in every environment, unlike RANDOM(). Every hundredth id also spreads the sample evenly across insertion order.","sql":"SELECT * FROM orders WHERE id % 100 = 0;"}]},"source_url":"https://sqlly.app/sql-functions/mod","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mod-sign","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MOD sign of the result","description":"MOD(-7, 3) is -1 on every engine with MOD() (all but SQL Server, which uses -7 % 3). Both take the dividend's sign. A floored modulo returning 2 needs ((x % n) + n) % n.","body":{"slug":"mod-sign","name":"MOD sign","h1":"SQL MOD sign of the result","category":"math","lede":"Covers the sign of the modulo result: every engine truncates the quotient, so -7 % 3 (MOD(-7, 3) on Oracle) is -1, not the 2 that Python, Ruby or a floored modulo would give.","syntax":"MOD(-7, 3)  |  -7 % 3  (T-SQL: % only)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":"-7 % 3 is -1: sign of the dividend; no MOD() function"},{"engine_slug":"postgresql","status":"yes","note":"-7 % 3 is -1: sign of the dividend"},{"engine_slug":"mysql","status":"yes","note":"MOD(-7, 3) is -1: sign of the dividend"},{"engine_slug":"sqlite","status":"yes","note":"-7 % 3 is -1: sign of the dividend"},{"engine_slug":"oracle","status":"yes","note":"MOD(-7, 3) is -1; Oracle's documentation contrasts MOD with the floored 'classical modulus' n2 - n1 * FLOOR(n2/n1)"}],"gotchas":["It matters for bucketing: id % 4 on a negative id gives -1, -2 or -3, so a CASE over 0..3 misses those rows. ((x % n) + n) % n maps every result into 0..n-1.","Ports from Python or Ruby break here: their -7 % 3 is 2. All five SQL engines follow C's truncating rule instead, and none offers a floored variant.","Oracle's REMAINDER is the odd one: it rounds the quotient, so REMAINDER(-7, 3) is -1 but REMAINDER(-8, 3) is 1, a different sign from MOD(-8, 3) = -2."],"examples":[{"engine_slug":"oracle","sql":"SELECT MOD(-7, 3) AS oracle_mod FROM dual;  -- -1"},{"engine_slug":"mysql","sql":"SELECT MOD(-7, 3) AS mysql_mod;  -- -1"},{"engine_slug":"postgresql","sql":"SELECT ((-7) % 3 + 3) % 3 AS floored;  -- 2; on Oracle write MOD(MOD(-7, 3) + 3, 3)"},{"engine_slug":"sql-server","sql":"SELECT -7 % 3 AS tsql_mod;  -- -1: sign of the dividend"},{"engine_slug":"sqlite","sql":"SELECT -7 % 3 AS sqlite_mod;  -- -1: sign of the dividend"}],"faqs":[{"question":"What is MOD(-7, 3) in SQL?","answer":"-1 on all five engines. SQL Server has no MOD() function, so write -7 % 3 there. SQL Server, PostgreSQL, MySQL, SQLite and Oracle all take the sign of the dividend. Python and Ruby return 2, which is the usual source of confusion."},{"question":"How do I get a positive modulo everywhere?","answer":"Use the double-mod trick: ((x % n) + n) % n maps any result into 0..n-1 for positive n. On Oracle, which has no %, write MOD(MOD(x, n) + n, n)."},{"question":"Does Oracle's MOD use floor semantics?","answer":"No. Oracle's documentation says MOD differs from the floored classical modulus, n2 - n1 * FLOOR(n2/n1), whenever the operands have opposite signs, so MOD(-7, 3) is -1 as on the other engines. Oracle's MOD(x, 0) returning x is its real quirk."}],"related":["mod","remainder","modulo-operator","mod-zero"],"novel_uses":[{"body":"Emulating a circular buffer in SQL, ((idx % 8) + 8) % 8 wraps negative offsets into 0..7, so reads before the start land on the right slot. The bare % would return -1 and read nothing.","sql":"SELECT ((idx % 8) + 8) % 8 AS slot FROM cursors;"},{"body":"((days_since_epoch % 7) + 7) % 7 gives a stable 0..6 weekday index for pre-epoch dates, where the bare modulo goes negative. Custom calendars over old data need the double mod.","sql":"SELECT ((days_since_epoch % 7) + 7) % 7 AS weekday_idx FROM history;"}]},"source_url":"https://sqlly.app/sql-functions/mod-sign","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mod-zero","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MOD with a zero divisor","description":"MOD(x, 0) errors on PostgreSQL, is NULL on MySQL and SQLite, returns x on Oracle. SQL Server has no MOD; x % 0 raises divide-by-zero. NULLIF(y, 0) gives NULL everywhere.","body":{"slug":"mod-zero","name":"MOD(x, 0)","h1":"SQL MOD with a zero divisor","category":"math","lede":"What a zero divisor does to a remainder: an error on two engines, NULL on two, and on Oracle MOD(7, 0) quietly returns 7.","syntax":"MOD(x, 0)  |  x % 0  |  MOD(x, NULLIF(y, 0))","return_type":"error or NULL","support":[{"engine_slug":"sql-server","status":"partial","note":"% with 0 raises the divide-by-zero error"},{"engine_slug":"postgresql","status":"yes","note":"ERROR: division by zero"},{"engine_slug":"mysql","status":"yes","note":"MOD(x, 0) is NULL"},{"engine_slug":"sqlite","status":"partial","note":"x % 0 is NULL; mod(x, 0) on 3.35+ likewise"},{"engine_slug":"oracle","status":"yes","note":"MOD(x, 0) returns x by definition; REMAINDER(x, 0) raises ORA-01476"}],"gotchas":["The NULLIF guard works identically for modulo: x % NULLIF(y, 0) degrades the error into a NULL.","Oracle documents MOD(x, 0) = x, so a zero divisor passes the dividend straight through with no error. REMAINDER(x, 0) does raise ORA-01476.","Zero-divisor checks matter in sharding: id % shard_count with a zero shard_count raises an error on SQL Server and PostgreSQL and yields all-NULL keys on MySQL and SQLite; a config table with no row yields all-NULL keys on every engine; on Oracle every id becomes its own shard."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 7 % NULLIF(0, 0) AS safe_mod;  -- NULL"},{"engine_slug":"oracle","sql":"SELECT MOD(7, 0) AS mod_zero FROM dual;  -- 7"},{"engine_slug":"postgresql","sql":"SELECT 7 % 0 AS mod_zero;  -- ERROR: division by zero"},{"engine_slug":"mysql","sql":"SELECT MOD(7, 0) AS mod_zero;  -- NULL"},{"engine_slug":"sql-server","sql":"SELECT 7 % 0 AS mod_zero;  -- Msg 8134, divide by zero error"},{"engine_slug":"sqlite","sql":"SELECT 7 % 0 AS mod_zero;  -- NULL"}],"faqs":[{"question":"What does MOD(x, 0) return?","answer":"Depends on the engine: MySQL and SQLite return NULL; PostgreSQL raises a division-by-zero error; SQL Server has no MOD function, so x % 0 raises one there; Oracle returns x. Use NULLIF(y, 0) in the divisor for predictable NULLs."},{"question":"Does the NULLIF trick work for modulo?","answer":"Yes: x % NULLIF(y, 0) returns NULL instead of erroring, exactly as it does for division. On Oracle write MOD(x, NULLIF(y, 0)), which also stops MOD from returning x."},{"question":"Why did my sharding query return all NULLs?","answer":"The shard count was 0: on MySQL or SQLite, id % 0 yields NULL for every row with no error, so nothing matches. Validate the divisor or use the error-raising engines to catch it."}],"related":["division-by-zero","mod","modulo-operator","nullif"],"novel_uses":[{"body":"A CHECK (shard_count > 0) on the config table means every query can use bare % without a NULLIF guard, because zero is rejected. CHECK still accepts NULL, which gives NULL keys rather than an error, so add NOT NULL to shard_count as well. Fixing the divisor once beats guarding it in every query that reads it.","sql":"ALTER TABLE shard_config ADD CONSTRAINT ck_shards CHECK (shard_count > 0);"},{"body":"A matrix of SELECT 7 % 0, MOD(7, 0) and friends records each engine's zero-divisor stance in a single compatibility test. It documents the split that otherwise surprises a port mid-project.","sql":"SELECT MOD(7, 0) AS oracle_returns_7 FROM dual;  -- 7, quietly"}]},"source_url":"https://sqlly.app/sql-functions/mod-zero","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mode","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MODE function","description":"MODE finds the most common value per group: PostgreSQL's mode() WITHIN GROUP (ORDER BY ...), Oracle's STATS_MODE, how ties resolve, and the GROUP BY recipe.","body":{"slug":"mode","name":"MODE","h1":"SQL MODE function","category":"aggregate","lede":"Returns the most frequent non-NULL value in the group.","syntax":"mode() WITHIN GROUP (ORDER BY col) | STATS_MODE(col)","return_type":"same as input","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"ordered-set form: mode() WITHIN GROUP (ORDER BY col)"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"no MODE; STATS_MODE(x) does the job"}],"gotchas":["Ties resolve by the ORDER BY: PostgreSQL returns the first value in that order among the tied ones. Oracle's STATS_MODE picks one of the tied values with no ordering control.","NULLs are excluded; an all-NULL or empty group returns NULL.","PostgreSQL's form takes no argument to the function itself: the column lives in the WITHIN GROUP (ORDER BY ...).","MySQL, SQL Server and SQLite: GROUP BY the column, ORDER BY COUNT(*) DESC and keep the top row, or ROW_NUMBER over the counts for one mode per group."],"examples":[{"engine_slug":"postgresql","sql":"SELECT mode() WITHIN GROUP (ORDER BY status) FROM orders;"},{"engine_slug":"oracle","sql":"SELECT STATS_MODE(status) FROM orders;"},{"engine_slug":"mysql","sql":"SELECT status FROM orders GROUP BY status ORDER BY COUNT(*) DESC LIMIT 1;"}],"faqs":[{"question":"What happens with ties?","answer":"In PostgreSQL the first tied value in the WITHIN GROUP order wins, so mode() WITHIN GROUP (ORDER BY x DESC) returns the largest tied value. Oracle's STATS_MODE gives no such guarantee."},{"question":"How do I get the mode in MySQL?","answer":"GROUP BY the column, ORDER BY COUNT(*) DESC and take the first row."},{"question":"Does MODE ignore NULLs?","answer":"Yes, both PostgreSQL's mode() and Oracle's STATS_MODE skip them. The GROUP BY recipe does not: add WHERE col IS NOT NULL or NULL can win."}],"related":["ordered-set-aggregates","percentile-disc","count-distinct","median"],"novel_uses":[{"body":"The WITHIN GROUP order takes any expression, so ordering by date_trunc finds the most common hour bucket without materializing one.","sql":"SELECT mode() WITHIN GROUP (ORDER BY date_trunc('hour', created_at)) FROM signups;"},{"body":"Inside a GROUP BY it answers per-department questions like the typical job title, one row per group with no count-sort-limit dance.","sql":"SELECT dept_id, mode() WITHIN GROUP (ORDER BY job_title) FROM employees GROUP BY dept_id;"}]},"source_url":"https://sqlly.app/sql-functions/mode","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/modulo-operator","corpus":"sql-functions","engine":null,"language":"en","title":"SQL % modulo operator","description":"The % remainder operator: the same as MOD where both exist, missing from Oracle, no floats on SQL Server, and a zero divisor errors on two engines.","body":{"slug":"modulo-operator","name":"%","h1":"SQL % modulo operator","category":"math","lede":"Returns the remainder of a division: 7 % 3 is 1, the same math as MOD(), written as an operator on four of the five engines.","syntax":"7 % 3  |  dividend % divisor","return_type":"integer (decimal where supported)","support":[{"engine_slug":"sql-server","status":"yes","note":"% accepts integer, money and decimal operands (7.5 % 2 is 1.5); float operands raise an error"},{"engine_slug":"postgresql","status":"yes","note":"% is an operator; mod(n, d) also exists"},{"engine_slug":"mysql","status":"yes","note":"% and MOD(n, d) are interchangeable"},{"engine_slug":"sqlite","status":"yes","note":"% casts both operands to integers (7.5 % 2 is 1.0); mod(n, d) on 3.35+ keeps fractions (1.5)"},{"engine_slug":"oracle","status":"partial","note":"No % operator; the MOD function is the only spelling"}],"gotchas":["Fractions differ by engine: 7.5 % 2 is 1.5 on SQL Server, PostgreSQL and MySQL, but 1.0 on SQLite, whose % truncates both operands to integers first. SQL Server rejects float operands outright.","A zero divisor raises an error on SQL Server and PostgreSQL; MySQL and SQLite return NULL; Oracle's MOD(7, 0) returns 7.","The result takes the sign of the dividend on all five engines: -7 % 3 is -1, and Oracle's MOD(-7, 3) is -1 too."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 7 % 3 AS remainder, 7.5 % 2 AS dec_rem;  -- 1, 1.5"},{"engine_slug":"oracle","sql":"SELECT MOD(7, 3) AS remainder FROM dual;  -- 1; Oracle has no %"},{"engine_slug":"postgresql","sql":"SELECT id % 2 = 0 AS is_even\nFROM rows;"},{"engine_slug":"mysql","sql":"SELECT 7 % 3 AS remainder, 7.5 % 2 AS dec_rem;  -- 1, 1.5"},{"engine_slug":"sqlite","sql":"SELECT 7.5 % 2 AS op, mod(7.5, 2) AS fn;  -- 1.0, 1.5"}],"faqs":[{"question":"Is % the same as MOD?","answer":"Yes wherever both exist: MySQL, PostgreSQL and SQLite accept both spellings and agree on integers. With decimals they split on SQLite: % truncates to integers (7.5 % 2 is 1.0) while mod() keeps the fraction (1.5). SQL Server only has %, Oracle only has MOD()."},{"question":"Does % work on decimals?","answer":"On SQL Server, PostgreSQL and MySQL, yes: 7.5 % 2 is 1.5. SQL Server refuses float operands ('The data types float and int are incompatible in the modulo operator'), and SQLite's % truncates to integers, so use mod() there."},{"question":"What happens with a zero divisor?","answer":"SQL Server and PostgreSQL raise a division-by-zero error; MySQL and SQLite return NULL; Oracle's MOD(x, 0) returns x. Guard with NULLIF(d, 0) to get NULL everywhere."}],"related":["mod","mod-zero","mod-sign","integer-division"],"novel_uses":[{"body":"IBAN and similar schemes validate reference numbers with a mod 97 remainder. Store the IBAN digits after the standard rearrangement (letters mapped to 10 to 35) in a NUMERIC(30,0) column, since a 28-digit value overflows BIGINT. One WHERE clause then finds the rows that fail the check.","sql":"SELECT * FROM payments WHERE reference % 97 <> 1;"},{"body":"epoch_seconds % 60 gives seconds, % 3600 the seconds into the hour, % 86400 the seconds into the day, all without a date function, for UTC epoch seconds at or after 1970 (earlier values give negative remainders). It works on any engine, including ones with weak date math.","sql":"SELECT epoch_seconds % 86400 AS second_of_day FROM events;"},{"body":"id % 10 puts a stable tenth of rows in a sample that every rerun and every worker agrees on, unlike RAND(). The bucketing is reproducible from the id alone.","sql":"SELECT * FROM users WHERE id % 10 = 0;"}]},"source_url":"https://sqlly.app/sql-functions/modulo-operator","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/month","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MONTH function","description":"Get the month as 1-12: MONTH() on SQL Server and MySQL, EXTRACT(month FROM d) on PostgreSQL and Oracle, strftime('%m', d) on SQLite, which returns text '01'-'12'.","body":{"slug":"month","name":"MONTH","h1":"SQL MONTH function","category":"datetime","lede":"Returns the month number from a date, the grouping key for monthly reporting, before you reach for TO_CHAR or DATE_FORMAT for names.","syntax":"MONTH(d)  |  EXTRACT(month FROM d)  |  strftime('%m', d)  -- SQLite, zero-padded text","return_type":"integer on MySQL and SQL Server; numeric on PostgreSQL; text on SQLite","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(month FROM d)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%m', d) returns '01'-'12' text"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT(month FROM d); there is no MONTH() function"}],"gotchas":["SQLite's zero-padded text sorts fine but compares as text: strftime('%m', d) = 1 is never true. CAST to INTEGER first.","Month numbers are calendar months: grouping by MONTH on data spanning years mixes Januaries of 2023 and 2024 into one bucket; group by year and month together.","Oracle has no MONTH() function; EXTRACT(month FROM d) works on DATE and TIMESTAMP, and TO_CHAR(d, 'MM') returns the zero-padded text form."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(year FROM created_at) AS yr,\n       EXTRACT(month FROM created_at) AS mon,\n       COUNT(*) FROM orders GROUP BY 1, 2;"},{"engine_slug":"sql-server","sql":"SELECT YEAR(created_at) AS yr, MONTH(created_at) AS mon, COUNT(*)\nFROM orders GROUP BY YEAR(created_at), MONTH(created_at);"},{"engine_slug":"mysql","sql":"SELECT MONTH(created_at) AS mon FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%m', created_at) AS INTEGER) AS mon FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(month FROM created_at) AS mon FROM orders;"}],"faqs":[{"question":"How do I get the month name instead?","answer":"DATENAME(month, d) on SQL Server, MONTHNAME(d) on MySQL, TO_CHAR(d, 'FMMonth') on PostgreSQL and Oracle; SQLite has no month-name format."},{"question":"Why do my monthly totals look too big?","answer":"You grouped by month without year, so Januaries from every year collapse together. Group by the year-month pair or a date-truncated column."}],"related":["extract","monthname","quarter"],"novel_uses":[{"body":"Match MONTH and DAY together to find people whose birthday is today. February 29 people only match on the leap day itself, so add a March 1 fallback if you celebrate it then.","sql":"SELECT * FROM people\nWHERE MONTH(born_on) = MONTH(CURDATE())\n  AND DAY(born_on) = DAY(CURDATE());"},{"body":"strftime('%m-%d', d) builds a zero-padded month-day text that groups the same calendar slot across years and sorts correctly without any casts.","sql":"SELECT strftime('%m-%d', d) AS month_day, COUNT(*) AS n\nFROM events GROUP BY month_day ORDER BY month_day;"}]},"source_url":"https://sqlly.app/sql-functions/month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/monthname","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MONTHNAME function","description":"Get the month as a word: MONTHNAME() on MySQL, DATENAME(month) on SQL Server, TO_CHAR(d, 'Month') on PostgreSQL and Oracle; SQLite has none.","body":{"slug":"monthname","name":"MONTHNAME","h1":"SQL MONTHNAME function","category":"datetime","lede":"Returns the month name in the session language: a display concern, which is why SQLite's format codes skip it entirely.","syntax":"MONTHNAME(d)  -- MySQL  |  DATENAME(month, d)  -- SQL Server  |  TO_CHAR(d, 'Month')  -- PostgreSQL, Oracle","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"DATENAME(month, d)"},{"engine_slug":"postgresql","status":"partial","note":"TO_CHAR(d, 'FMMonth') to trim padding"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no month-name format; map with CASE"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'FMMonth'); follows NLS_DATE_LANGUAGE"}],"gotchas":["PostgreSQL and Oracle pad the name to nine characters: TO_CHAR(d, 'Month') gives 'January  '. The FM prefix ('FMMonth') trims it on both.","Names follow the session language: MySQL's lc_time_names, Oracle's NLS_DATE_LANGUAGE and SQL Server's LANGUAGE flip 'January' to other words per connection.","Do not sort or join on names: 'April' sorts before 'January'. Keep the number and format at the edge."],"examples":[{"engine_slug":"mysql","sql":"SELECT MONTHNAME(created_at) AS mon FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATENAME(month, created_at) AS mon FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(created_at, 'FMMonth') AS mon FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'FMMonth') AS mon FROM orders;"}],"faqs":[{"question":"Why is my month name padded with spaces?","answer":"PostgreSQL and Oracle pad to the longest month name (nine characters) for alignment. The FM modifier, as in TO_CHAR(d, 'FMMonth'), removes it on both."},{"question":"How do I get month names in SQLite?","answer":"There is no format code for names; CASE the month number or map it in the application."}],"related":["datename","month","dayname"],"novel_uses":[{"body":"MySQL's '%b' mask gives the three-letter month ('Jan', 'Feb'), the shape chart axes want and MONTHNAME never returns.","sql":"SELECT DATE_FORMAT(d, '%b') AS mon FROM orders;"},{"body":"TO_CHAR takes an NLS parameter: TO_CHAR(d, 'FMMonth', 'NLS_DATE_LANGUAGE=ENGLISH') returns English in any session, so one export never depends on who runs it.","sql":"SELECT TO_CHAR(created_at, 'FMMonth', 'NLS_DATE_LANGUAGE=ENGLISH') AS mon FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/monthname","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/months-between","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MONTHS_BETWEEN function","description":"Months between two dates: MONTHS_BETWEEN in Oracle and its equivalents on SQL Server, PostgreSQL and MySQL: fractional results and argument order explained.","body":{"slug":"months-between","name":"MONTHS_BETWEEN","h1":"SQL MONTHS_BETWEEN function","category":"datetime","lede":"Returns the number of months from one date to another. Oracle's version returns a fraction; on the other engines you build it from DATEDIFF, age() or TIMESTAMPDIFF.","syntax":"MONTHS_BETWEEN(later, earlier)  -- Oracle","return_type":"numeric (fractional on Oracle)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(month, a, b) counts boundaries, not fractions"},{"engine_slug":"postgresql","status":"partial","note":"age(b, a) plus arithmetic, or EXTRACT(year/month)"},{"engine_slug":"mysql","status":"partial","note":"PERIOD_DIFF or TIMESTAMPDIFF(month, a, b)"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Oracle returns a fraction when the days of the month differ, always dividing the leftover days by 31: MONTHS_BETWEEN(DATE '2026-03-15', DATE '2026-01-31') is 1.4839. SQL Server's DATEDIFF(month, ...) for the same dates is 2, and MySQL's TIMESTAMPDIFF(MONTH, ...) is 1.","Argument order: Oracle is (later, earlier) and returns positive forward; flip them and get a negative. DATEDIFF(month, a, b) on SQL Server is (start, end).","PostgreSQL's age(b, a) gives years and months as separate fields, which is friendlier for billing periods."],"examples":[{"engine_slug":"oracle","sql":"SELECT MONTHS_BETWEEN(SYSDATE, hire_date) AS tenure_months\nFROM employees;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(month, hire_date, SYSDATETIME()) AS tenure_months\nFROM employees;"},{"engine_slug":"postgresql","sql":"SELECT (EXTRACT(year FROM age(now(), hired_at)) * 12\n       + EXTRACT(month FROM age(now(), hired_at))) AS tenure_months\nFROM employees;"},{"engine_slug":"mysql","sql":"-- TIMESTAMPDIFF counts whole months\nSELECT TIMESTAMPDIFF(MONTH, hire_date, NOW()) AS tenure_months\nFROM employees;"}],"faqs":[{"question":"Why does MONTHS_BETWEEN return a decimal?","answer":"Oracle counts whole months, then adds the leftover days divided by 31, whatever the month's real length: 15 leftover days add 0.48. If both dates fall on the same day of the month, or both on a month's last day, the result is a whole number. TRUNC it for completed months."},{"question":"What is MONTHS_BETWEEN in SQL Server?","answer":"No direct match. DATEDIFF(month, a, b) counts month boundaries crossed: January 31 to February 1 is 1. That equals whole months only when both dates are on the same day of the month."}],"related":["datediff","dateadd","last-day"],"novel_uses":[{"body":"FLOOR of the month count is completed years and MOD of the same number is the leftover months, which is the tenure display HR wants without string parsing. FLOOR is safe here because Oracle's fraction only ever appears after the completed months.","sql":"SELECT name,\n       FLOOR(MONTHS_BETWEEN(SYSDATE, hired_on) / 12) AS yrs,\n       MOD(FLOOR(MONTHS_BETWEEN(SYSDATE, hired_on)), 12) AS mos\nFROM employees;"},{"body":"Oracle's MONTHS_BETWEEN returns a whole number exactly when the two dates share the day of month (and both times agree, so truncate them), which makes a fraction-zero test an anniversary check that also treats January 31 and February 28 as a matched pair.","sql":"SELECT account_id\nFROM subscriptions\nWHERE MOD(MONTHS_BETWEEN(TRUNC(SYSDATE), TRUNC(started_on)), 1) = 0;"}]},"source_url":"https://sqlly.app/sql-functions/months-between","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/moving-average","corpus":"sql-functions","engine":null,"language":"en","title":"SQL moving average","description":"Trailing and centred moving averages with AVG() OVER and ROWS frames: the 7-row window, shorter windows at the edges and ROWS versus date-based windows.","body":{"slug":"moving-average","name":"Moving Average","h1":"SQL moving average","category":"window","lede":"AVG over a ROWS frame of n preceding rows gives a trailing moving average of n+1 rows; the first n rows see a shorter window and average what exists.","syntax":"AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is 7 rows only when 7 rows exist; early rows average fewer.","Centred frames (BETWEEN 3 PRECEDING AND 3 FOLLOWING) need future rows, so today's value changes once tomorrow's data arrives. Use trailing frames for anything published daily.","Frame size is row count, not time: gaps in dates stretch the average across them. For calendar windows use RANGE with an interval on PostgreSQL, MySQL and Oracle; SQLite can use RANGE 6 PRECEDING over julianday(day); SQL Server needs a calendar spine."],"examples":[{"engine_slug":"all","sql":"-- 7-row trailing average\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7\nFROM prices;"},{"engine_slug":"postgresql","sql":"-- calendar-based: 7 days, not 7 rows\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS ma7d\nFROM prices;"}],"faqs":[{"question":"Why is my moving average shorter at the start?","answer":"The frame cannot reach before the first row, so early rows average the rows that exist. To blank them, wrap it: CASE WHEN COUNT(*) OVER (same frame) = 7 THEN AVG(...) OVER (same frame) END."},{"question":"Moving average over days or over rows?","answer":"ROWS counts observations (right when data is dense and regular); RANGE with an interval counts time (right when dates have gaps). Same query shape, different frame clause."}],"related":["avg-over","moving-sum","range-interval-frame"],"novel_uses":[{"body":"Put a 7-row and a 28-row average in the same SELECT and their order is a trend flag: short above long means momentum up. Both frames ride one sort when the ORDER BY matches.","sql":"SELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) AS ma28\nFROM prices;"},{"body":"A frame that reaches into the future is wrong for a daily published number and right for retrospective work: last month's values will never change, so smoothing them from both sides is fair. Use centered frames on closed periods and trailing frames on anything still moving.","sql":"SELECT week, rides,\n       AVG(rides) OVER (ORDER BY week ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING) AS centered_ma7\nFROM weekly_rides;"}]},"source_url":"https://sqlly.app/sql-functions/moving-average","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/moving-sum","corpus":"sql-functions","engine":null,"language":"en","title":"SQL moving sum","description":"SUM() OVER a bounded frame: trailing 30-row sums, sliding windows over time, and why a frame that runs ahead needs FOLLOWING.","body":{"slug":"moving-sum","name":"Moving Sum","h1":"SQL moving sum","category":"window","lede":"Sums only the rows inside the frame: a trailing n-row (or n-day) window that slides with the current row.","syntax":"SUM(x) OVER (ORDER BY d ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) | SUM(x) OVER (ORDER BY d ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["FOLLOWING bounds look ahead: with one row per week, the current and next two weeks is ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING, and the last rows of the partition see a shorter window.","A window sum is not a total: with a bounded frame it deliberately excludes older rows. Check the frame before assuming a 'SUM OVER' is a grand total.","ROWS is positional: with duplicate ORDER BY values the engine picks which tied row falls just inside the frame, so the sum can change between runs. Add a unique tiebreaker."],"examples":[{"engine_slug":"all","sql":"-- trailing 30-row sum per store\nSELECT store_id, day, units,\n       SUM(units) OVER (PARTITION BY store_id ORDER BY day\n                        ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS sum30\nFROM daily_sales;"}],"faqs":[{"question":"How do I sum the next N rows instead of the previous ones?","answer":"Use FOLLOWING as the end boundary: SUM(x) OVER (ORDER BY d ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING). Boundaries can mix one PRECEDING and one FOLLOWING."},{"question":"Why not just write SUM(x) OVER (ORDER BY d)?","answer":"That uses the default frame, RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: a running total from the first row, not a sliding window. A moving sum needs an explicit bounded frame: ROWS for n rows, or RANGE with an offset for an n-unit value span (PostgreSQL, MySQL and SQLite accept it; SQL Server rejects RANGE offsets, so use a calendar spine there)."}],"related":["sum-over","moving-average","rows-vs-range"],"novel_uses":[{"body":"Divide stock by the trailing 7-row sum scaled to a daily rate, per store, and every row from the seventh day on reports how long inventory lasts if sales keep this pace. One window and one division replace the spreadsheet everyone maintains by hand.","sql":"WITH s AS (\n  SELECT store_id, day, stock_qty,\n         SUM(units) OVER (PARTITION BY store_id ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS sold7,\n         COUNT(*) OVER (PARTITION BY store_id ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS n7\n  FROM daily_sales\n)\nSELECT store_id, day, stock_qty,\n       CASE WHEN n7 = 7 THEN stock_qty * 7.0 / NULLIF(sold7, 0) END AS days_of_supply\nFROM s;"},{"body":"A COUNT over a one-minute RANGE frame is a rate limiter in a query: flag rows where the count passes your cap. PostgreSQL and MySQL accept interval offsets (the SQL below is PostgreSQL; MySQL spells the offset INTERVAL 1 MINUTE); SQL Server rejects RANGE offsets and needs the calendar-spine or self-join rewrite.","sql":"SELECT request_id, called_at,\n       COUNT(*) OVER (ORDER BY called_at\n         RANGE BETWEEN INTERVAL '1 minute' PRECEDING AND CURRENT ROW) AS calls_last_minute\nFROM api_calls;"}]},"source_url":"https://sqlly.app/sql-functions/moving-sum","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/mysql-8-window","corpus":"sql-functions","engine":null,"language":"en","title":"MySQL 8.0 window functions","description":"MySQL 5.7 has no window functions at all; 8.0 added most of them. The version gate, what is still missing in 8.x, and the 5.7 migration path.","body":{"slug":"mysql-8-window","name":"MySQL 8.0 Window Functions","h1":"MySQL 8.0 window functions","category":"window","lede":"Window functions require MySQL 8.0 or newer: ROW_NUMBER, RANK, LAG, ROWS/RANGE frames and the WINDOW clause all arrived in the 8.0 series.","syntax":"ROW_NUMBER() OVER (PARTITION BY g ORDER BY d)  -- MySQL 8.0+","return_type":"n/a (version gate)","support":[{"engine_slug":"sql-server","status":"yes","note":"ranking since 2005; frames and LAG/LEAD since 2012"},{"engine_slug":"postgresql","status":"yes","note":"since 8.4"},{"engine_slug":"mysql","status":"yes","note":"8.0+; nothing in 5.7"},{"engine_slug":"sqlite","status":"yes","note":"since 3.25"},{"engine_slug":"oracle","status":"yes","note":"analytic functions since 8i"}],"gotchas":["Still missing in MySQL 8: GROUPS frames, EXCLUDE, FILTER, NULLS FIRST/LAST, IGNORE NULLS, NTH_VALUE ... FROM LAST, DISTINCT in window aggregates and GROUP_CONCAT as a window function. Several of these parse and then fail with 'This version of MySQL doesn't yet support'. RANGE frames with INTERVAL offsets do work.","The 5.7-era workaround, user variables (@rownum := @rownum + 1), relies on evaluation order MySQL never guaranteed, and setting variables inside expressions is deprecated since 8.0.13. Replace it with ROW_NUMBER() when you upgrade.","MariaDB split from MySQL before 8.0 and ships window functions from 10.2; 'MySQL-compatible' does not mean the same version gate."],"examples":[{"engine_slug":"mysql","sql":"SELECT department, salary,\n       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn,\n       SUM(salary) OVER (PARTITION BY department ORDER BY hire_date) AS running_payroll\nFROM employees;"}],"faqs":[{"question":"Do window functions work on MySQL 5.7?","answer":"No, 5.7 errors on any OVER clause. The user-variable emulation depends on evaluation order MySQL does not guarantee; correlated subqueries or self-joins are slower but correct."},{"question":"Which window features does MySQL 8.0 lack?","answer":"GROUPS frames, EXCLUDE, FILTER, NULLS FIRST/LAST, IGNORE NULLS, FROM LAST, DISTINCT inside window aggregates and GROUP_CONCAT over windows. Ranking, LAG/LEAD, FIRST/LAST/NTH_VALUE, ROWS and RANGE frames (including INTERVAL offsets) and the WINDOW clause all work."}],"related":["window-versions","listagg-window","distinct-in-window"],"novel_uses":[{"body":"Top one per group needs no window at all: GROUP BY the key, MAX the value, join back, and the query runs on 5.7 unchanged. Top N beyond one, offsets and running totals are where the 5.7 fallbacks (correlated subqueries, self-joins) get slow enough to justify the 8.0 upgrade.","sql":"SELECT c.customer_id, c.name, big.max_amount\nFROM customers c\nJOIN (\n  SELECT customer_id, MAX(amount) AS max_amount\n  FROM orders\n  GROUP BY customer_id\n) big ON big.customer_id = c.customer_id;"},{"body":"Read version(), compare the major, and send window queries only to connections that can run them: one code path for 8.0 and a fallback for anything older. MariaDB reports its own version line, so detect it before trusting the major number.","sql":"SELECT version() AS server_version;"}]},"source_url":"https://sqlly.app/sql-functions/mysql-8-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nan-check","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NaN check","description":"No engine ships ISNAN. Oracle has the IS NAN predicate, PostgreSQL compares x = 'NaN', and the IEEE x <> x trick fails on both, since they treat NaN as equal.","body":{"slug":"nan-check","name":"ISNAN","h1":"SQL NaN check","category":"math","lede":"Detects not-a-number values. Only PostgreSQL and Oracle can store NaN at all, and both treat NaN as equal to itself, so the test is an explicit comparison or predicate.","syntax":"x = 'NaN'::float8  -- PostgreSQL  |  x IS NAN  -- Oracle","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"No NaN values exist: operations that would produce one raise an error (SQRT, LOG and POWER raise an invalid floating point operation; 0.0E0/0.0E0 raises divide by zero)"},{"engine_slug":"postgresql","status":"yes","note":"Compare directly: x = 'NaN'::float8. x <> x is false for every non-NULL value, because PostgreSQL defines NaN = NaN as true; for NULL it is NULL"},{"engine_slug":"mysql","status":"no","note":"NaN is not storable; operations that would produce it raise an error or return NULL"},{"engine_slug":"sqlite","status":"partial","note":"NaN becomes NULL on storage; check IS NULL instead, which also matches genuine NULLs. A quoted 'NaN' string is not converted and is stored as TEXT"},{"engine_slug":"oracle","status":"yes","note":"IS NAN predicate: SELECT 1 FROM dual WHERE CAST('NaN' AS BINARY_DOUBLE) IS NAN"}],"gotchas":["IEEE says NaN is unequal to itself, which is why x <> x detects it in C or Python. PostgreSQL and Oracle deliberately break that rule so NaN can be sorted, grouped and indexed, so x <> x finds nothing there.","On SQLite the check is IS NULL: a computed NaN never survives storage, so the NaN question becomes a NULL question, and genuine NULLs match too. A quoted 'NaN' string is not converted and stays TEXT.","Oracle's IS NAN works only on BINARY_FLOAT/BINARY_DOUBLE; NUMBER cannot hold NaN at all."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'NaN'::float8 <> 'NaN'::float8 AS ieee_trick;  -- false: the trick does not work"},{"engine_slug":"oracle","sql":"SELECT * FROM sensor_data WHERE measurement IS NAN;"},{"engine_slug":"postgresql","sql":"SELECT COUNT(*) FROM readings WHERE value = 'NaN'::float8;  -- NaN rows"},{"engine_slug":"sqlite","sql":"SELECT * FROM readings WHERE value IS NULL;  -- NaN rows land here with genuine NULLs: NaN becomes NULL on storage"}],"faqs":[{"question":"Does SQL have an ISNAN function?","answer":"Not by that name. Oracle has the IS NAN predicate for binary float types and PostgreSQL compares against 'NaN'::float8. SQL Server, MySQL and SQLite cannot store NaN, so there is nothing to test."},{"question":"Does the x <> x trick work in SQL?","answer":"Not on the engines that store NaN. IEEE 754 makes NaN unequal to itself, but PostgreSQL and Oracle define NaN = NaN as true so it can be sorted and indexed, so x <> x is false for every non-NULL value (it is NULL for NULL). Use x = 'NaN'::float8 or x IS NAN."},{"question":"How do I check for NaN in SQLite?","answer":"SQLite converts a computed NaN to NULL on storage, so the NaN itself is gone and IS NULL also matches genuine NULLs. Use IS NULL only if the column cannot hold genuine NULLs, and fix the producer of the NaN upstream."}],"related":["nan-infinity","nanvl","null-arithmetic","float-equality"],"novel_uses":[{"body":"A table fed by engines that map NaN to NULL can hold either form. WHERE x = 'NaN'::float8 OR x IS NULL finds both in one pass on PostgreSQL, and the split tells you which producer to fix.","sql":"SELECT COUNT(*) FROM readings WHERE value = 'NaN'::float8 OR value IS NULL;"},{"body":"Oracle separates IS NAN (0d / 0d style results) from IS INFINITE (overflow). Triage queries that count them separately point at a divide bug versus a range bug immediately.","sql":"SELECT COUNT(*) FROM sensor_data WHERE measurement IS NAN;"}]},"source_url":"https://sqlly.app/sql-functions/nan-check","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nan-infinity","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NaN and Infinity handling","description":"PostgreSQL floats and Oracle BINARY_DOUBLE store NaN and Infinity; SQLite keeps Inf but turns NaN into NULL; SQL Server and MySQL have neither.","body":{"slug":"nan-infinity","name":"NaN / Infinity","h1":"SQL NaN and Infinity handling","category":"math","lede":"How the engines represent IEEE not-a-number and infinity: storable values on PostgreSQL and Oracle binary types, infinity only on SQLite, neither on SQL Server or MySQL.","syntax":"'NaN'::float8  -- PostgreSQL  |  BINARY_DOUBLE_NAN, BINARY_DOUBLE_INFINITY  -- Oracle  |  9e999  -- SQLite Inf","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No NaN or Infinity: float overflow raises an error, and there is no literal for either"},{"engine_slug":"postgresql","status":"yes","note":"float accepts 'NaN', 'Infinity', '-Infinity' as literals; NaN sorts above every other value"},{"engine_slug":"mysql","status":"no","note":"Neither value exists: 1e308 * 10 raises 'DOUBLE value is out of range', and there are no literals"},{"engine_slug":"sqlite","status":"partial","note":"Stores IEEE inf (try 9e999), but NaN becomes NULL on storage"},{"engine_slug":"oracle","status":"yes","note":"BINARY_FLOAT/BINARY_DOUBLE support NAN and BINARY_DOUBLE_INFINITY literals with IS NAN / IS INFINITE predicates"}],"gotchas":["SQLite cannot store NaN at all: an IEEE NaN becomes NULL the moment it lands in a column, so a NaN check there is a NULL check.","PostgreSQL sorts NaN above every non-NaN value (in ORDER BY ASC it lands after every number, with NULL after it), a real gotcha for top-N queries.","PostgreSQL treats NaN as equal to NaN, unlike IEEE, so that sorting and indexes work: 'NaN'::float8 = 'NaN'::float8 is true. Oracle does the same for BINARY_DOUBLE."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'NaN'::float8 AS nan, 'Infinity'::float8 AS inf;"},{"engine_slug":"oracle","sql":"SELECT BINARY_DOUBLE_INFINITY AS inf, CAST('NaN' AS BINARY_DOUBLE) AS nan FROM dual;"},{"engine_slug":"sqlite","sql":"SELECT 9e999 AS inf;  -- Inf; a NaN value would come back as NULL"}],"faqs":[{"question":"Can SQL columns hold NaN or Infinity?","answer":"PostgreSQL float and Oracle BINARY_FLOAT/BINARY_DOUBLE can, with literals like 'NaN'::float8 and BINARY_DOUBLE_INFINITY. SQLite stores infinity but turns NaN into NULL. SQL Server and MySQL raise an error instead of producing either."},{"question":"Why did my NaN become NULL in SQLite?","answer":"SQLite maps IEEE NaN to NULL as soon as it is produced (9e999 - 9e999 already returns NULL), so nothing reaches storage as NaN: the value is not representable in its type system, so a NaN check there is really a NULL check."},{"question":"How does NaN sort in PostgreSQL?","answer":"Above every other value, Infinity included: ORDER BY x DESC puts NaN rows first, ahead of every number, so a top-10 report can be all NaN (NULLs still sort ahead of NaN under DESC). Filter x <> 'NaN' explicitly."}],"related":["nan-check","nanvl","infinity","double-precision"],"novel_uses":[{"body":"On PostgreSQL, NULL means never computed and 'NaN'::float8 means computed but invalid. Scoring tables that keep both get a much cheaper postmortem than a table that collapses them into one NULL.","sql":"SELECT COUNT(*) FILTER (WHERE score IS NULL) AS never_run, COUNT(*) FILTER (WHERE score = 'NaN'::float8) AS ran_bad FROM scores;"},{"body":"SQL Server rejects infinite floats, so the source-side query clamps with LEAST and GREATEST before the INSERT. The rows arrive finite, and distance from the clamp marks how extreme they were. NULL and NaN are guarded to stay NULL, because GREATEST skips NULL and PostgreSQL sorts NaN above every number, so an unguarded clamp turns them into the extremes.","sql":"SELECT CASE WHEN x IS NULL OR x = 'NaN'::float8 THEN NULL ELSE LEAST(1.79e308, GREATEST(-1.79e308, x)) END AS clamped FROM staged;"}]},"source_url":"https://sqlly.app/sql-functions/nan-infinity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nanvl","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NANVL function","description":"NANVL(x, default) substitutes a value when x is NaN (Oracle-only, for BINARY_FLOAT/BINARY_DOUBLE columns that can legally carry NaN).","body":{"slug":"nanvl","name":"NANVL","h1":"SQL NANVL function","category":"math","lede":"Returns the second argument when the first is NaN, otherwise the first: NANVL(measurement, 0) turns NaN readings into zero.","syntax":"NANVL(n, default)","return_type":"same type as the input","support":[{"engine_slug":"sql-server","status":"no","note":"No NaN representation, so no NANVL; ISNULL covers missing values"},{"engine_slug":"postgresql","status":"no","note":"No NANVL; CASE WHEN x = 'NaN'::float8 THEN default ELSE x END"},{"engine_slug":"mysql","status":"no","note":"No NANVL and no storable NaN; COALESCE covers NULL"},{"engine_slug":"sqlite","status":"no","note":"No NANVL; NaN never survives storage; COALESCE(x, default) covers the NULL it becomes"},{"engine_slug":"oracle","status":"yes","note":"NANVL(n, default) is built in for BINARY_FLOAT/BINARY_DOUBLE input"}],"gotchas":["NANVL only fires on NaN: NULL passes through untouched, so combine with NVL/COALESCE when both are possible: NVL(NANVL(x, 0), 0).","It exists because Oracle's binary float types can hold NaN from computations such as POWER(-8d, 1/3) or 0d / 0d; NUMBER columns cannot, so NANVL is pointless there.","Elsewhere the emulation is a CASE: PostgreSQL CASE WHEN x = 'NaN'::float8 THEN d ELSE x END; SQLite COALESCE(x, d) after the NaN-to-NULL conversion."],"examples":[{"engine_slug":"oracle","sql":"SELECT NANVL(CAST('NaN' AS BINARY_DOUBLE), 0) AS cleaned FROM dual;  -- 0"},{"engine_slug":"oracle","sql":"SELECT NANVL(measurement, -1) AS flag_bad\nFROM sensor_data;"},{"engine_slug":"sql-server","sql":"SELECT ISNULL(measurement, -1) AS filled\nFROM sensor_data;  -- no NaN on SQL Server; NULL is the only missing value"}],"faqs":[{"question":"What is the PostgreSQL equivalent of NANVL?","answer":"A CASE: CASE WHEN x = 'NaN'::float8 THEN 0 ELSE x END. PostgreSQL has no NANVL function, but its float can hold NaN so the comparison works."},{"question":"Does NANVL also replace NULL?","answer":"No. NULL passes through. Chain NVL(NANVL(x, 0), 0) in Oracle when a column can hold both NaN and NULL."},{"question":"Why is NANVL useless on NUMBER columns?","answer":"Oracle NUMBER cannot represent NaN (only BINARY_FLOAT and BINARY_DOUBLE can), so there is never a NaN for NANVL to catch in a NUMBER column."}],"related":["nan-check","nan-infinity","coalesce","nullif"],"novel_uses":[{"body":"A single NaN poisons SUM and AVG over BINARY_DOUBLE columns to NaN. NANVL(measurement, 0) at the read edge keeps every downstream aggregate alive without hunting the producer first.","sql":"SELECT SUM(NANVL(measurement, 0)) AS safe_total FROM sensor_data;"},{"body":"NANVL(measurement, -1) marks invalid readings with a sentinel instead of erasing them, so counting the -1 rows reports the failure rate. Dropping them to 0 hides a broken sensor behind a clean average.","sql":"SELECT NANVL(measurement, -1) AS flagged FROM sensor_data;"}]},"source_url":"https://sqlly.app/sql-functions/nanvl","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/negation","corpus":"sql-functions","engine":null,"language":"en","title":"SQL unary minus","description":"The - sign in -x flips the sign of a value with the highest precedence of the math operators, and collides with the floor of the integer range at the extremes.","body":{"slug":"negation","name":"-","h1":"SQL unary minus","category":"math","lede":"Negates a numeric value: -x is 0 - x for numbers, and binds tighter than the binary + and - on every engine, and tighter than ^ on PostgreSQL. SQL Server can apply it after * at the BIGINT boundary; see the FAQ.","syntax":"-x  |  +x  |  -(a * b)","return_type":"same type as the input on PostgreSQL and SQLite; SQL Server widens tinyint to smallint, and MySQL returns signed BIGINT for an unsigned input","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Unary minus binds before every binary operator, including PostgreSQL's ^: -x ^ 2 is (-x) ^ 2, so it gives 4 for x = 2. Write -(x ^ 2) for -4.","The smallest BIGINT, -9223372036854775808, has no positive counterpart, so negating it or taking ABS raises 'bigint out of range' on PostgreSQL and an arithmetic overflow on SQL Server. SQLite's ABS raises 'integer overflow', while its unary minus quietly returns a float.","Double unary minus is legal: SELECT -(-5) returns 5. A unary minus before a column or a parenthesized expression negates it."],"examples":[{"engine_slug":"all","sql":"SELECT -5 AS neg, -(-5) AS double_neg, +5 AS plus;  -- -5, 5, 5"},{"engine_slug":"sql-server","sql":"SELECT -balance AS debit_view\nFROM ledger;"},{"engine_slug":"postgresql","sql":"SELECT -2 ^ 2 AS four, -(2 ^ 2) AS minus_four;  -- 4, -4: unary minus binds first"},{"engine_slug":"oracle","sql":"SELECT -5 AS neg, -(-5) AS double_neg FROM dual;  -- -5, 5"}],"faqs":[{"question":"What does unary minus do to a column?","answer":"Negates every non-null value: SELECT -balance flips the sign column-wide. NULL stays NULL, because negation of unknown is unknown."},{"question":"Why does ABS of the smallest bigint overflow?","answer":"Two's-complement integers hold one more negative than positive value: ABS(-9223372036854775808) has no representable positive counterpart, so SQL Server, PostgreSQL, MySQL and SQLite raise an overflow error."},{"question":"Does unary minus bind before or after multiplication?","answer":"Before on PostgreSQL and SQLite: -2 * 3 is (-2) * 3, and the sign also applies first at the BIGINT boundary. SQL Server does not: -CAST(4611686018427387904 AS bigint) * 2 raises an overflow, while (-CAST(4611686018427387904 AS bigint)) * 2 returns -9223372036854775808, so parenthesize the negation there. PostgreSQL's ^ also binds after unary minus, which is why -2 ^ 2 is 4 there."}],"related":["arithmetic-operators","operator-precedence","integer-overflow","abs"],"novel_uses":[{"body":"A ledger that marks each row as debit or credit sums cleanly once credits flip sign: CASE WHEN side = 'C' THEN -amount ELSE amount END. One expression replaces the per-side bookkeeping in every total.","sql":"SELECT SUM(CASE WHEN side = 'C' THEN -amount ELSE amount END) AS balance FROM entries;"},{"body":"The smallest BIGINT has no positive twin, so -x overflows where ABS(x) does on PostgreSQL and SQL Server. SQLite quietly returns a float for -x, and MySQL returns 9223372036854775808, so the guard matters on every engine. NULLIF first, then negate, keeps the query alive when a sentinel row sneaks in.","sql":"SELECT -NULLIF(x, -9223372036854775808) AS safe_neg FROM big_ints;"}]},"source_url":"https://sqlly.app/sql-functions/negation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/new-time","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NEW_TIME function","description":"NEW_TIME in Oracle: convert a DATE between a short list of legacy three-letter zones. What still works, what it cannot do, and the modern replacement.","body":{"slug":"new-time","name":"NEW_TIME","h1":"SQL NEW_TIME function","category":"datetime","lede":"Converts a DATE between a hard-coded list of GMT and North American zone abbreviations (EST, PST, HST...); it predates Oracle's real time zone types.","syntax":"NEW_TIME(date, 'from_zone', 'to_zone')","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"AT TIME ZONE chains"},{"engine_slug":"postgresql","status":"partial","note":"ts AT TIME ZONE chains"},{"engine_slug":"mysql","status":"partial","note":"CONVERT_TZ with offsets, or names once mysql.time_zone is loaded"},{"engine_slug":"sqlite","status":"no","note":"none for named zones; only the host zone through the 'utc' and 'localtime' modifiers"},{"engine_slug":"oracle","status":"yes","note":"this, or TIMESTAMP WITH TIME ZONE arithmetic"}],"gotchas":["The zone list is fixed: AST/ADT, BST/BDT (Bering, not British), CST/CDT, EST/EDT, GMT, HST/HDT, MST/MDT, NST (Newfoundland), PST/PDT and YST/YDT. Anything else, CET included, raises ORA-01857.","It works on DATE, which has second precision: sub-second and historical DST rules are silently out of scope; modern code should use TIMESTAMP WITH TIME ZONE and AT TIME ZONE.","DST handling is naive: pass 'EST' and you get standard time all year; pass 'EDT' and you claim daylight all year. NEW_TIME never decides for you."],"examples":[{"engine_slug":"oracle","sql":"SELECT NEW_TIME(TO_DATE('2026-08-01 14:30', 'YYYY-MM-DD HH24:MI'), 'PST', 'GMT') FROM dual;  -- 2026-08-01 22:30"},{"engine_slug":"oracle","sql":"SELECT NEW_TIME(SYSDATE, 'EST', 'CET') FROM dual;  -- ORA-01857: not a valid time zone"},{"engine_slug":"sql-server","sql":"SELECT CAST('2026-01-15 14:30' AS datetime2) AT TIME ZONE 'Pacific Standard Time' AT TIME ZONE 'GMT Standard Time';  -- 2026-01-15 22:30:00 +00:00"},{"engine_slug":"postgresql","sql":"SELECT TIMESTAMP '2026-01-15 14:30' AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'UTC';  -- 2026-01-15 22:30:00"},{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ('2026-01-15 14:30:00', '-08:00', '+00:00');  -- 2026-01-15 22:30:00"}],"faqs":[{"question":"Is NEW_TIME deprecated?","answer":"Not formally, but superseded: FROM_TZ plus AT TIME ZONE on TIMESTAMP WITH TIME ZONE covers arbitrary IANA zones with real DST history. Keep NEW_TIME for legacy column data only."},{"question":"What is the PostgreSQL equivalent?","answer":"ts AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'UTC': any IANA zone, from the tz database PostgreSQL ships with (or the OS copy, depending on how it was built)."}],"related":["from-tz","at-time-zone","convert-tz","timestamp-with-time-zone"],"novel_uses":[{"body":"Old tables that stored Eastern standard time all year feed UTC pipelines through one wrapper call per column, no backfill required. Rows written during daylight time come out an hour late, so confirm the write path stored standard time before relying on it.","sql":"SELECT NEW_TIME(logged_at, 'EST', 'GMT') FROM legacy_logs;"},{"body":"NEW_TIME applied twice through GMT returns the original value, a cheap test that a zone pair still resolves after upgrades.","sql":"SELECT NEW_TIME(NEW_TIME(TO_DATE('2026-08-01 14:30', 'YYYY-MM-DD HH24:MI'), 'PST', 'GMT'), 'GMT', 'PST') FROM dual;  -- 2026-08-01 14:30"}]},"source_url":"https://sqlly.app/sql-functions/new-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/newid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NEWID function","description":"SQL Server's NEWID() generates a random GUID (uniqueidentifier) per call, with NEWSEQUENTIALID() as the index-friendlier default-constraint twin.","body":{"slug":"newid","name":"NEWID","h1":"SQL NEWID function","category":"conversion","lede":"SELECT NEWID() returns a random version 4 uniqueidentifier. It is also behind the ORDER BY NEWID() random-sample idiom.","syntax":"NEWID()","return_type":"uniqueidentifier","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"gen_random_uuid() is the twin"},{"engine_slug":"mysql","status":"partial","note":"UUID() is the twin, but v1"},{"engine_slug":"sqlite","status":"partial","note":"no built-in; hex(randomblob(16))"},{"engine_slug":"oracle","status":"partial","note":"SYS_GUID() returns raw bytes"}],"gotchas":["Random GUIDs fragment clustered indexes: NEWSEQUENTIALID() (allowed only in DEFAULT constraints) grows more monotonically for hot-insert tables.","ORDER BY NEWID() is the classic random sample, but it scans and sorts every row; TABLESAMPLE samples pages faster and coarser.","uniqueidentifier sorts by its last six bytes first, not left to right, so ORDER BY on a GUID column does not match the order of the text form. This is why NEWSEQUENTIALID output looks unordered as text."],"examples":[{"engine_slug":"sql-server","sql":"SELECT NEWID() AS guid;"},{"engine_slug":"sql-server","sql":"CREATE TABLE sessions (\n  id uniqueidentifier PRIMARY KEY DEFAULT NEWID(),\n  token nvarchar(200)\n);"},{"engine_slug":"sql-server","sql":"SELECT TOP 5 name FROM users ORDER BY NEWID();"},{"engine_slug":"postgresql","sql":"SELECT * FROM users ORDER BY random() LIMIT 5;"},{"engine_slug":"mysql","sql":"SELECT * FROM users ORDER BY RAND() LIMIT 5;"},{"engine_slug":"sqlite","sql":"SELECT * FROM users ORDER BY random() LIMIT 5;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(SYS_GUID()) AS guid FROM dual;"}],"faqs":[{"question":"How do I sample random rows?","answer":"ORDER BY NEWID() with TOP is simple and slow on big tables: it sorts everything. TABLESAMPLE picks pages instead; or pre-generate a random column and index it."},{"question":"NEWID or NEWSEQUENTIALID?","answer":"NEWID for values handed out anywhere; NEWSEQUENTIALID for clustered-index DEFAULTs: sequential GUIDs land closer together and fragment less."}],"related":["gen-random-uuid","uuid-function","sys-guid","randomblob"],"novel_uses":[{"body":"NEWID is for identifiers, not secrets. CRYPT_GEN_RANDOM(n) draws n bytes from the cryptographic generator, which is what an API key or token column should be built from.","sql":"SELECT CRYPT_GEN_RANDOM(32) AS key_bytes;"},{"body":"ABS(CHECKSUM(NEWID()) % 4) turns each call into a 0-3 shard, so an UPDATE can split rows into A/B groups or hash buckets without a separate random column. CHECKSUM returns a signed int, so a bare % 4 also yields -3 to -1; take ABS after the modulo, because ABS(CHECKSUM(...)) overflows on -2147483648.","sql":"SELECT name, ABS(CHECKSUM(NEWID()) % 4) AS bucket FROM users;"}]},"source_url":"https://sqlly.app/sql-functions/newid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/newline-literal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL newlines in strings","description":"Embed line breaks in SQL strings per engine: CHAR(13)/CHAR(10), CHR(10), E'\\n' and backslash escapes, plus the CRLF two-character trap.","body":{"slug":"newline-literal","name":"Newlines in string literals","h1":"SQL newlines in strings","category":"string","lede":"A newline inside a string literal is engine-specific. The portable route is building it from code points; the fast route is knowing your engine's escape.","syntax":"'line1' + CHAR(13) + CHAR(10) + 'line2'  |  E'line1\\nline2'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Windows line breaks are two characters (CR + LF): a single CHR(10) or '\\n' leaves carriage returns behind in Windows-sourced data.","Engine spellings: CHAR(13)+CHAR(10) on SQL Server, CHR(10) on Oracle, char(10) on SQLite, E'\\n' on PostgreSQL (plain strings keep the backslash literal), '\\n' on MySQL (unless NO_BACKSLASH_ESCAPES).","A literal line break typed inside the quotes in your editor is legal SQL on every engine, but it is invisible and fragile in diffs and copy-paste.","Strip them again with REPLACE and the same codes; see remove-newlines for the reverse operation."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 'line1' + CHAR(13) + CHAR(10) + 'line2' AS two_lines;"},{"engine_slug":"postgresql","sql":"SELECT E'line1\\nline2' AS two_lines;"},{"engine_slug":"oracle","sql":"SELECT 'line1' || CHR(10) || 'line2' AS two_lines FROM dual;"},{"engine_slug":"sqlite","sql":"SELECT 'line1' || char(10) || 'line2' AS two_lines;"},{"engine_slug":"mysql","sql":"SELECT 'line1\\nline2' AS two_lines;  -- MySQL reads \\n inside quotes as a newline"}],"faqs":[{"question":"What is the most portable way to write a newline?","answer":"Build it from code points: CHAR(10) on SQL Server, MySQL and SQLite, CHR(10) on Oracle and PostgreSQL. The function name and the concatenation syntax differ ('+' on SQL Server, '||' on PostgreSQL and SQLite, CONCAT() on MySQL), so the snippet is per engine."},{"question":"Why do my newlines show as \\n in the output?","answer":"You are on PostgreSQL with a plain string: backslash escapes are literal there. Prefix the literal with E, or use chr(10)."},{"question":"Does a real line break inside the quotes work?","answer":"Yes. A literal newline inside a string literal is valid on all major engines. It survives execution but tends to get mangled by formatters, diffs and copy-paste."}],"related":["chr","remove-newlines","backslash-escapes"],"novel_uses":[{"body":"Counting rows with CRLF pairs, lone CRs and lone LFs separately tells you which normalization pass a column needs instead of guessing. The chr() spelling below runs on PostgreSQL; SQL Server, MySQL and SQLite reject chr() and need CHAR(13) and CHAR(10).","sql":"SELECT SUM(CASE WHEN body LIKE '%' || chr(13) || chr(10) || '%' THEN 1 ELSE 0 END) AS crlf,\n       SUM(CASE WHEN body LIKE '%' || chr(13) || '%'\n                 AND body NOT LIKE '%' || chr(13) || chr(10) || '%' THEN 1 ELSE 0 END) AS lone_cr\nFROM notes;"},{"body":"A real line break inside the quotes is the one spelling every engine accepts, where E'\\n' is PostgreSQL-only; keep fixture files out of formatters so the break survives.","sql":"INSERT INTO notes (body) VALUES ('first line\nsecond line');  -- a real break inside the quotes, legal on every engine"}]},"source_url":"https://sqlly.app/sql-functions/newline-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/next-day","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NEXT_DAY function","description":"NEXT_DAY in Oracle: the date of the next Monday, Friday or any weekday after a date, and how to build it in engines without the function.","body":{"slug":"next-day","name":"NEXT_DAY","h1":"SQL NEXT_DAY function","category":"datetime","lede":"Returns the first date strictly after the given date that falls on the named weekday.","syntax":"NEXT_DAY(date, 'DAYNAME')","return_type":"date","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The result is strictly after the input: NEXT_DAY(DATE '2026-08-03', 'MONDAY') with Aug 3 a Monday returns the following week, not today.","The weekday string is resolved in the session's NLS_DATE_LANGUAGE: 'LUNES' fails on an English session. Set the session language or use the English name consistently.","Time of day is preserved from the input date; TRUNC the input if you want a midnight result."],"examples":[{"engine_slug":"oracle","sql":"SELECT NEXT_DAY(DATE '2026-08-01', 'MONDAY') FROM dual;  -- 2026-08-03"},{"engine_slug":"postgresql","sql":"SELECT d + (8 - EXTRACT(ISODOW FROM d)::int) FROM (VALUES (DATE '2026-08-01')) v(d);  -- 2026-08-03"}],"faqs":[{"question":"How do I find the next Monday in PostgreSQL or MySQL?","answer":"PostgreSQL: d + (8 - EXTRACT(ISODOW FROM d)::int) on a date column. MySQL: d + INTERVAL (7 - WEEKDAY(d)) DAY. Both add 1 to 7 days, so a Monday input moves to the following Monday, matching NEXT_DAY."},{"question":"Does the weekday name depend on language?","answer":"Yes, it matches the session's NLS_DATE_LANGUAGE. An English install wants 'MONDAY'; a Spanish one may expect 'LUNES'."}],"related":["day-of-week","trunc-date","dayname","adddate"],"novel_uses":[{"body":"NEXT_DAY skips the input date itself, so subtract seven days first when today should count. NEXT_DAY(d - 7, 'FRIDAY') returns the most recent Friday on or before d, which is d itself when d is a Friday.","sql":"SELECT NEXT_DAY(DATE '2026-08-07' - 7, 'FRIDAY') FROM dual;  -- 2026-08-07"},{"body":"Step the input back a week to walk deadlines onto earlier weekdays: the Monday of a Friday deadline's week lands four days before the deadline.","sql":"SELECT NEXT_DAY(DATE '2026-08-07' - 7, 'MONDAY') FROM dual;  -- 2026-08-03"}]},"source_url":"https://sqlly.app/sql-functions/next-day","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/next-value-for-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server NEXT VALUE FOR with OVER","description":"SQL Server's sequence-with-OVER: generating sequence numbers in SELECT order without an identity column, plus its strict placement rules.","body":{"slug":"next-value-for-over","name":"NEXT VALUE FOR OVER","h1":"SQL Server NEXT VALUE FOR with OVER","category":"window","lede":"NEXT VALUE FOR seq OVER (ORDER BY x) hands out sequence values in the requested order; none of the other four engines has a windowed sequence call.","syntax":"NEXT VALUE FOR dbo.Seq OVER (ORDER BY x)","return_type":"bigint (sequence type)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"nextval() has no OVER form; call it from a query already sorted by the wanted order"},{"engine_slug":"mysql","status":"no","note":"no sequence objects; AUTO_INCREMENT on INSERT ... SELECT ... ORDER BY, or ROW_NUMBER()"},{"engine_slug":"sqlite","status":"no","note":"no sequence objects; INTEGER PRIMARY KEY on insert, or ROW_NUMBER()"},{"engine_slug":"oracle","status":"no","note":"seq.NEXTVAL has no OVER form and is not allowed in a query with ORDER BY; number with ROW_NUMBER first"}],"gotchas":["OVER takes ORDER BY only ('NEXT VALUE FOR function does not support the PARTITION BY clause'), and NEXT VALUE FOR is refused in views, subqueries, CTEs, derived tables and functions. A top-level SELECT or INSERT ... SELECT is where it works.","The values are consumed: re-running the query burns numbers. For repeatable numbering, ROW_NUMBER() OVER (ORDER BY x) is free and side-effect free.","Gaps happen like with any sequence (rollbacks, restarts); never treat NEXT VALUE FOR output as gap-free data."],"examples":[{"engine_slug":"sql-server","sql":"SELECT NEXT VALUE FOR dbo.OrderSeq OVER (ORDER BY created_at) AS seq_no,\n       order_id, created_at\nFROM staging_orders;"}],"faqs":[{"question":"When is NEXT VALUE FOR OVER the right tool?","answer":"When you must persist real sequence numbers (foreign keys, order numbers) in a bulk load's order: ROW_NUMBER gives the order but cannot hand out durable sequence values."},{"question":"Why does my NEXT VALUE FOR OVER error in a view or CTE?","answer":"SQL Server refuses NEXT VALUE FOR in views, subqueries, CTEs, derived tables and functions (error 11719). Put it in the outer SELECT or in INSERT ... SELECT, or number into a temp table first."}],"related":["row-number","over-order-by","sql-server-frame-support"],"novel_uses":[{"body":"NEXT VALUE FOR keeps counting across statements, so a re-run of the load takes the next block of numbers instead of colliding with the first. ROW_NUMBER restarts at 1 per query, which is exactly wrong for anything persisted.","sql":"INSERT INTO archive_orders (seq_no, order_id)\nSELECT NEXT VALUE FOR dbo.ArchiveSeq OVER (ORDER BY created_at), order_id\nFROM staging_orders;"},{"body":"Hand out sequence values over an ORDER BY priority and the ticket numbers reflect the queue's own order at insert time. One INSERT ... SELECT does the numbering and the loading together.","sql":"INSERT INTO tickets (ticket_no, customer_id, priority)\nSELECT NEXT VALUE FOR dbo.TicketSeq OVER (ORDER BY priority DESC, created_at),\n       customer_id, priority\nFROM inbound_requests;"}]},"source_url":"https://sqlly.app/sql-functions/next-value-for-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nextval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL sequences: NEXTVAL and NEXT VALUE FOR","description":"Draw numbers from a sequence: nextval('seq') in PostgreSQL, seq.NEXTVAL in Oracle, NEXT VALUE FOR in SQL Server. MySQL and SQLite have no sequence objects.","body":{"slug":"nextval","name":"NEXTVAL / NEXT VALUE FOR","h1":"SQL sequences: NEXTVAL and NEXT VALUE FOR","category":"system","lede":"A sequence hands out increasing numbers independent of any table, so several tables or an application can share one counter.","syntax":"nextval('seq')  |  seq.NEXTVAL  |  NEXT VALUE FOR seq","return_type":"bigint (NUMBER on Oracle)","support":[{"engine_slug":"sql-server","status":"partial","note":"NEXT VALUE FOR seq; sequences exist from 2012"},{"engine_slug":"postgresql","status":"yes","note":"nextval('seq'), currval('seq'), setval"},{"engine_slug":"mysql","status":"no","note":"no sequences; AUTO_INCREMENT columns"},{"engine_slug":"sqlite","status":"no","note":"no sequences; INTEGER PRIMARY KEY or AUTOINCREMENT"},{"engine_slug":"oracle","status":"partial","note":"seq.NEXTVAL and seq.CURRVAL"}],"gotchas":["Sequence values are not rolled back. A failed or rolled-back insert leaves a gap, so never rely on sequences being gapless.","currval('seq') in PostgreSQL and seq.CURRVAL in Oracle fail until nextval has been called for that sequence in the same session.","Oracle and SQL Server increment a sequence once per row: two references to seq.NEXTVAL or NEXT VALUE FOR seq in the same row return the same number. PostgreSQL's nextval advances on every call."],"examples":[{"engine_slug":"postgresql","sql":"CREATE SEQUENCE invoice_no START 1000;\nSELECT nextval('invoice_no') AS a, nextval('invoice_no') AS b;  -- 1000, 1001\nSELECT currval('invoice_no');  -- 1001"},{"engine_slug":"sql-server","sql":"CREATE SEQUENCE invoice_no START WITH 1000;\nSELECT NEXT VALUE FOR invoice_no AS a;  -- 1000\nSELECT NEXT VALUE FOR invoice_no AS b;  -- 1001"},{"engine_slug":"oracle","sql":"CREATE SEQUENCE invoice_no START WITH 1000;\nSELECT invoice_no.NEXTVAL AS a, invoice_no.NEXTVAL AS b FROM dual;  -- 1000, 1000\nDROP SEQUENCE invoice_no;"}],"faqs":[{"question":"How do I emulate a sequence in MySQL?","answer":"Use a one-row counter table: UPDATE counter SET id = LAST_INSERT_ID(id + 1); then SELECT LAST_INSERT_ID(). The value is per connection, so concurrent sessions each get their own number."},{"question":"Sequence or identity column?","answer":"An identity column (IDENTITY, GENERATED AS IDENTITY, AUTO_INCREMENT) is tied to one table and is simpler. A sequence suits numbers shared across tables or needed before the insert."}],"related":["last-insert-id","next-value-for-over","generate-series"],"novel_uses":[{"body":"A hand-made sequence outlives its table because nothing links them. ALTER SEQUENCE seq OWNED BY orders.id on PostgreSQL ties the sequence to its column, so DROP TABLE takes the sequence along; SERIAL columns get this link for free and hand-made sequences do not.","sql":"CREATE SEQUENCE orders_id_seq START 1000;\nALTER SEQUENCE orders_id_seq OWNED BY orders.id;\nDROP TABLE orders;  -- the sequence goes with it"},{"body":"Binding a sequence into a column default, DEFAULT NEXT VALUE FOR invoice_no on SQL Server 2012 and later, gives identity-style keys while keeping the sequence's INCREMENT and CACHE tuning and letting several tables share one counter.","sql":"CREATE SEQUENCE order_ids START WITH 1000;\nCREATE TABLE orders (id BIGINT DEFAULT NEXT VALUE FOR order_ids, note VARCHAR(50));\nINSERT INTO orders (note) OUTPUT inserted.id VALUES ('a');  -- 1000"},{"body":"A sequence with CACHE 100 (Oracle, PostgreSQL, SQL Server) hands out a block of numbers at a time, and a restart throws the unused part away. PostgreSQL caches per session, so every disconnect also drops that session's unused numbers. Keep the cache small when auditors ask about gaps, large when the insert rate matters.","sql":"CREATE SEQUENCE hot_ids CACHE 100;  -- up to 99 numbers can vanish on a restart, or on PostgreSQL when a session ends"}]},"source_url":"https://sqlly.app/sql-functions/nextval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nls-date-format","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NLS_DATE_FORMAT parameter","description":"Oracle's NLS_DATE_FORMAT decides how bare strings and DATEs convert implicitly: the session setting behind date-does-not-match-format errors.","body":{"slug":"nls-date-format","name":"NLS_DATE_FORMAT","h1":"SQL NLS_DATE_FORMAT parameter","category":"datetime","lede":"Returns and sets the session's implicit date mask; TO_DATE with an explicit mask or a DATE literal is how to avoid depending on it.","syntax":"SELECT VALUE FROM NLS_SESSION_PARAMETERS\nWHERE PARAMETER = 'NLS_DATE_FORMAT'  |  ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEFORMAT and LANGUAGE settings play this role"},{"engine_slug":"postgresql","status":"partial","note":"DateStyle sets the output format and the DMY/MDY order for ambiguous input"},{"engine_slug":"mysql","status":"no","note":"fixed ISO-ish expectations for implicit casts"},{"engine_slug":"sqlite","status":"no","note":"no implicit parsing beyond ISO-8601 text"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Comparing a DATE column to a bare string parses the string with NLS_DATE_FORMAT: under the American default DD-MON-RR, '01-JAN-24' works and '2024-01-01' raises ORA-01861.","The default comes from NLS_TERRITORY, and clients can override it through NLS_LANG or their own settings, so the same query works in SQL Developer and fails in a scheduler job. Explicit TO_DATE masks end that class of bug.","NLS_DATE_FORMAT covers whole seconds but not fractional or zone-aware values; NLS_TIMESTAMP_FORMAT and NLS_TIMESTAMP_TZ_FORMAT are the siblings."],"examples":[{"engine_slug":"oracle","sql":"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';"},{"engine_slug":"oracle","sql":"SELECT VALUE FROM NLS_SESSION_PARAMETERS\nWHERE PARAMETER = 'NLS_DATE_FORMAT';"},{"engine_slug":"oracle","sql":"SELECT COUNT(*) FROM orders\nWHERE created_at >= TO_DATE('2024-01-01', 'YYYY-MM-DD');"},{"engine_slug":"sql-server","sql":"SET DATEFORMAT dmy;\nSELECT CONVERT(date, '15/01/2024') AS parsed;  -- 2024-01-15"},{"engine_slug":"postgresql","sql":"SET DateStyle TO 'Postgres, DMY';\nSELECT '15/01/2024'::date AS parsed;  -- stored as 2024-01-15, displays 15-01-2024"}],"faqs":[{"question":"Why does my date query work locally but fail in production?","answer":"The sessions have different NLS_DATE_FORMAT values. Implicit string-to-date conversion depends on it; use TO_DATE with an explicit mask everywhere."},{"question":"Does NLS_DATE_FORMAT affect TO_DATE?","answer":"Only when you leave the mask out: TO_DATE('2024-01-01') uses the session mask. TO_DATE('2024-01-01', 'YYYY-MM-DD') never does."}],"related":["to-date","parse","session-timezone"],"novel_uses":[{"body":"DATE '2024-01-01' never consults NLS_DATE_FORMAT, so code that must run under any territory keeps typed literals and reserves TO_DATE for runtime values.","sql":"SELECT COUNT(*) FROM orders WHERE created_at >= DATE '2024-01-01';"},{"body":"NLS_CALENDAR changes how dates render without touching stored values: set it to 'Persian', read, then set it back to 'GREGORIAN'.","sql":"ALTER SESSION SET NLS_CALENDAR = 'Persian';\nSELECT SYSDATE FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/nls-date-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nls-initcap","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NLS_INITCAP function","description":"Oracle's NLS_INITCAP title-cases a string using a linguistic sort you name, so i-I and other locale pairs come out right, not just binary-correct.","body":{"slug":"nls-initcap","name":"NLS_INITCAP","h1":"SQL NLS_INITCAP function","category":"string","lede":"INITCAP with an explicit NLS_SORT: title-cases per a language's rules instead of the session default.","syntax":"NLS_INITCAP(string [, 'NLS_SORT=sort_name'])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without the second argument it uses the collation Oracle derives for the function, which may not match the data's language.","Linguistic sorts handle special pairs: NLS_INITCAP('istanbul', 'NLS_SORT=XTurkish') starts with a dotted capital I.","Sisters NLS_UPPER and NLS_LOWER take the same parameter; plain INITCAP ignores locale rules entirely.","Oracle only. Other engines reach for per-expression COLLATE clauses (PostgreSQL, SQL Server) instead."],"examples":[{"engine_slug":"oracle","sql":"SELECT NLS_INITCAP('istanbul') AS plain FROM dual;  -- Istanbul"},{"engine_slug":"oracle","sql":"SELECT NLS_INITCAP('istanbul', 'NLS_SORT=XTurkish') AS tr FROM dual;"}],"faqs":[{"question":"How is NLS_INITCAP different from INITCAP?","answer":"INITCAP uses the binary mapping of the character set and ignores linguistic rules; NLS_INITCAP lets you name a linguistic sort per call, so mixed-language data can be cased correctly in one query."},{"question":"What NLS_SORT values can I use?","answer":"BINARY plus the linguistic sorts Oracle ships: XTurkish, XGerman, XDanish and dozens more. XGerman expands ß to SS in NLS_UPPER (Oracle reference example)."},{"question":"Does PostgreSQL need this?","answer":"PostgreSQL picks casing rules per expression with COLLATE, e.g. lower('I' COLLATE \"tr-TR-x-icu\"), so there is no separate function."}],"related":["initcap","nls-upper-lower","turkish-i"],"novel_uses":[{"body":"NLS_INITCAP(name, 'NLS_SORT=BINARY') forces plain case mapping no matter whose session runs the batch, so ETL output does not drift when the job moves to another NLS locale.","sql":"SELECT NLS_INITCAP(name, 'NLS_SORT=BINARY') AS fixed_case FROM staged_names;"},{"body":"Names cased by a Latin session come out Istanbul instead of İstanbul with the dotted I; re-running NLS_INITCAP with XTurkish repairs the column in place.","sql":"SELECT NLS_INITCAP(city, 'NLS_SORT=XTurkish') AS tr FROM branches WHERE country = 'TR';"}]},"source_url":"https://sqlly.app/sql-functions/nls-initcap","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nls-upper-lower","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NLS_UPPER / NLS_LOWER function","description":"Locale-aware casing: Oracle's NLS_UPPER and NLS_LOWER take an NLS_SORT, and PostgreSQL's upper() and lower() follow a COLLATE clause.","body":{"slug":"nls-upper-lower","name":"NLS_UPPER / NLS_LOWER","h1":"SQL NLS_UPPER / NLS_LOWER function","category":"string","lede":"Upper- and lowercase a string under named linguistic rules, for the cases where plain UPPER('i') answers the wrong language.","syntax":"NLS_UPPER(string [, 'NLS_SORT=sort'])  |  lower(string COLLATE \"collation\")","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"plain upper()/lower() with a COLLATE clause; ICU collations from PG 10"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Plain UPPER in Oracle leaves ß alone: UPPER('straße') is STRAßE, while NLS_UPPER('straße', 'NLS_SORT=XGerman') expands it to STRASSE.","PostgreSQL has no extra function: lower('I' COLLATE \"tr-TR-x-icu\") gives the dotless ı, while plain lower('I') gives i under most database locales.","MySQL's UPPER/LOWER follow the argument's collation casing tables but expose no per-call locale override.","SQL Server picks casing per column/expression collation: UPPER('i' COLLATE Turkish_CI_AS); no separate function."],"examples":[{"engine_slug":"oracle","sql":"SELECT NLS_UPPER('straße', 'NLS_SORT=XGerman') AS de, UPPER('straße') AS plain FROM dual;\n-- STRASSE, STRAßE"},{"engine_slug":"postgresql","sql":"SELECT lower('I' COLLATE \"tr-TR-x-icu\") AS tr;  -- ı"}],"faqs":[{"question":"When do I need NLS_UPPER instead of UPPER?","answer":"When the data is in a language whose casing has extra rules: Turkish dotted I, German sharp s. Plain UPPER applies one mapping for every language."},{"question":"What is the PostgreSQL equivalent?","answer":"An expression COLLATE on the ordinary functions: lower('I' COLLATE \"tr-TR-x-icu\"). PostgreSQL has no two-argument lower(); the collation carries the locale."},{"question":"Does this affect WHERE comparisons too?","answer":"Casing in comparisons comes from the collation, not these functions; a case-insensitive collation can make the functions unnecessary for matching."}],"related":["upper","lower","nls-initcap","turkish-i"],"novel_uses":[{"body":"Downstream formats that cannot carry the lowercase sharp s, such as embossed cards and old mainframe feeds, need STRASSE rather than STRAßE, and NLS_UPPER with XGerman expands it on Oracle; on PostgreSQL, upper() under an ICU collation such as \"de-x-icu\" expands it too.","sql":"UPDATE parts SET code = NLS_UPPER(code, 'NLS_SORT=XGerman') WHERE land = 'DE';"},{"body":"A PostgreSQL expression index over lower(name COLLATE \"de-x-icu\") makes the collation part of the index, so every query that folds with the same COLLATE finds it.","sql":"CREATE INDEX people_name_lc ON people (lower(name COLLATE \"de-x-icu\"));"}]},"source_url":"https://sqlly.app/sql-functions/nls-upper-lower","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/normalize","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NORMALIZE function","description":"How PostgreSQL's normalize composes Unicode text into a canonical form: NFC versus NFD, why é compares unequal to e plus an accent, and the IS NORMALIZED predicate.","body":{"slug":"normalize","name":"NORMALIZE","h1":"SQL NORMALIZE function","category":"string","lede":"Converts a string to a canonical Unicode normalization form so visually equal text compares equal.","syntax":"normalize(string [, form])  |  forms: NFC (default), NFD, NFKC, NFKD","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No normalize function; normalize in the application or CLR."},{"engine_slug":"postgresql","status":"yes","note":"Built in since PostgreSQL 13; needs a UTF8 database."},{"engine_slug":"mysql","status":"no","note":"No normalize function; some collations compare the forms as equal."},{"engine_slug":"sqlite","status":"no","note":"No normalize function; normalize in the application."},{"engine_slug":"oracle","status":"partial","note":"COMPOSE gives NFC; DECOMPOSE gives NFD, or NFKD with 'COMPATIBILITY'."}],"gotchas":["'café' can be stored two ways: the single character é, or e followed by a combining accent. They look identical and compare unequal until both are normalized to the same form.","NFC composes characters into the fewest code points and is what most systems expect; NFD decomposes them, as older macOS HFS+ file names did. NFKC and NFKD also fold compatibility characters such as ligatures and full-width letters.","The predicate str IS [NOT] [NFC | NFD | NFKC | NFKD] NORMALIZED tests a value's form without converting it, which is how you find unnormalized rows."],"examples":[{"engine_slug":"postgresql","sql":"SELECT normalize(U&'cafe\\0301', NFC) = 'café' AS same;  -- true"},{"engine_slug":"postgresql","sql":"SELECT count(*) FROM users\nWHERE display_name IS NOT NFC NORMALIZED;"},{"engine_slug":"oracle","sql":"SELECT COMPOSE('e' || UNISTR('\\0301')) AS nfc\nFROM dual;  -- é"}],"faqs":[{"question":"Why do two identical-looking strings compare unequal?","answer":"They are probably in different Unicode forms: composed versus decomposed accents. Apply normalize(col, NFC) to both sides, or better, normalize when writing."},{"question":"Which normalization form should I use?","answer":"NFC for almost everything: it is what the web, JSON APIs and most input methods produce. Use NFKC only when you deliberately want compatibility characters folded, for example for search keys."},{"question":"How do I find rows that are not normalized?","answer":"WHERE col IS NOT NFC NORMALIZED (PostgreSQL 13+), then UPDATE ... SET col = normalize(col, NFC)."}],"related":["upper","lower","translate","unistr"],"novel_uses":[{"body":"Japanese keyboards send full-width letters such as ＡＢＣ, and NFKC folds them to plain ABC, which is the difference between a lookup that matches and one that silently misses. The U& string escapes build the wide letters from ASCII source.","sql":"SELECT normalize(U&'\\FF21\\FF22\\FF23', NFKC) AS folded;  -- ABC"},{"body":"A unique index over normalize(email, NFC) treats composed and decomposed forms of the same address as one value, so the duplicate cannot be inserted at all.","sql":"CREATE UNIQUE INDEX ux_users_email_nfc\n  ON users (normalize(email, NFC));"}]},"source_url":"https://sqlly.app/sql-functions/normalize","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/not-equal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL not-equal operators","description":"<> is the standard not-equal operator, and all five engines accept != as well. Both give NULL against NULL, so WHERE col <> 'x' silently drops NULL rows.","body":{"slug":"not-equal","name":"<> and !=","h1":"SQL not-equal operators","category":"conditional","lede":"a <> b and a != b mean the same thing on every engine here. The trap is NULL: neither form is true when one side is NULL.","syntax":"a <> b  |  a != b","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":"both; IS DISTINCT FROM from 2022"},{"engine_slug":"postgresql","status":"yes","note":"both; IS DISTINCT FROM for NULL-safe tests"},{"engine_slug":"mysql","status":"yes","note":"both; NOT (a <=> b) for NULL-safe tests"},{"engine_slug":"sqlite","status":"yes","note":"both; IS NOT for NULL-safe tests"},{"engine_slug":"oracle","status":"yes","note":"both, plus ^="}],"gotchas":["col <> 'closed' is UNKNOWN when col is NULL, so those rows disappear. Add OR col IS NULL, or use IS DISTINCT FROM (PostgreSQL, SQL Server 2022+), IS NOT (SQLite) or NOT (col <=> 'closed') on MySQL.","There is no performance difference: the parser treats != as <>.","A not-equal filter rarely uses an index seek, because most rows usually qualify and a scan is cheaper."],"examples":[{"engine_slug":"postgresql","sql":"SELECT status FROM (VALUES ('open'), ('closed'), (NULL)) AS t(status)\nWHERE status <> 'closed';  -- open only; the NULL row is dropped"},{"engine_slug":"postgresql","sql":"SELECT status FROM (VALUES ('open'), ('closed'), (NULL)) AS t(status)\nWHERE status IS DISTINCT FROM 'closed';  -- open, NULL"},{"engine_slug":"mysql","sql":"SELECT 1 <> 2 AS a, 1 != 2 AS b, NULL <> 1 AS c;  -- 1, 1, NULL"},{"engine_slug":"sql-server","sql":"SELECT status FROM (VALUES ('open'), ('closed'), (NULL)) AS t(status)\nWHERE status <> 'closed';  -- open only; the NULL row is dropped"},{"engine_slug":"sqlite","sql":"SELECT 1 <> 2 AS a, 1 != 2 AS b, NULL <> 1 AS c;  -- 1, 1, NULL"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN 1 ^= 2 THEN 'ne' END AS caret_form FROM dual;  -- ne"}],"faqs":[{"question":"Should I write <> or !=?","answer":"<> is the SQL standard and works everywhere. != also works on all five engines; pick one and use it consistently."},{"question":"Why does <> leave out NULL rows?","answer":"Comparing anything with NULL yields UNKNOWN, and WHERE keeps only rows where the condition is TRUE. Use IS DISTINCT FROM (NOT (col <=> 'x') on MySQL), or add OR col IS NULL."}],"related":["distinct-from","null-safe-equal","three-valued-logic","is-null"],"novel_uses":[{"body":"NULL keys never join with = or <>, which silently drops rows where the key is unknown on both sides. ON a.key IS NOT DISTINCT FROM b.key matches NULL to NULL: PostgreSQL, SQL Server 2022 and SQLite 3.39+ spell it that way; SQLite also accepts a IS b, and MySQL writes a <=> b.","sql":"SELECT a.id\nFROM a JOIN b ON a.code IS NOT DISTINCT FROM b.code;  -- NULL codes pair up"},{"body":"EXCEPT treats NULLs as equal, so the query below reports rows that differ, including a change into or out of NULL, where col1 <> col2 filters would drop those rows.","sql":"SELECT status, note FROM v1\nEXCEPT\nSELECT status, note FROM v2;  -- NULL changes show up here"}]},"source_url":"https://sqlly.app/sql-functions/not-equal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/not-exists","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NOT EXISTS operator","description":"NOT EXISTS finds rows with no match and never trips on NULLs: the correlated anti-join pattern, why it beats NOT IN, and the LEFT JOIN ... IS NULL alternative.","body":{"slug":"not-exists","name":"NOT EXISTS","h1":"SQL NOT EXISTS operator","category":"conditional","lede":"True when no row in the subquery matches: the standard anti-join.","syntax":"NOT EXISTS (SELECT 1 FROM t WHERE ...) | LEFT JOIN ... WHERE t.id IS NULL","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULLs in the subquery cannot empty the result: NOT EXISTS compares rows, not membership, so there is no NOT IN trap.","The LEFT JOIN ... WHERE right IS NULL anti-join is only correct when the IS NULL test is on a column that is never NULL in a matched row, such as the right table's primary key; test a nullable column and matched rows leak through, once per match.","PostgreSQL, MySQL 8 and SQL Server plan NOT EXISTS as an anti-join (hash, merge or nested-loop, chosen by cost); SQLite runs it as a correlated subquery per outer row, so index the inner join column there."],"examples":[{"engine_slug":"all","sql":"SELECT c.id FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);"},{"engine_slug":"all","sql":"SELECT c.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;"}],"faqs":[{"question":"NOT EXISTS vs NOT IN?","answer":"NOT EXISTS is NULL-safe and usually planned better for anti-joins; NOT IN empties out on a single NULL."},{"question":"NOT EXISTS vs LEFT JOIN IS NULL?","answer":"Same result, duplicates included, as long as the IS NULL test is on a column that is never NULL in a matched row, such as the right table's primary key; test a nullable column instead and matched rows leak through, once per match."},{"question":"Does the subquery need LIMIT 1?","answer":"No. EXISTS short-circuits at the first row on every modern engine."}],"related":["exists","not-in","null-safe-join","in"],"novel_uses":[{"body":"A DELETE guarded by NOT EXISTS removes child rows whose parent never existed, the sweep an absent foreign key makes necessary.","sql":"DELETE FROM order_items WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = order_items.order_id);"},{"body":"INSERT plus NOT EXISTS makes setup scripts idempotent: rerunning adds nothing. The FROM-less SELECT ... WHERE runs as-is on SQL Server, PostgreSQL, MySQL 8 and SQLite; Oracle before 23ai needs FROM DUAL.","sql":"INSERT INTO settings (k, v) SELECT 'theme', 'dark' WHERE NOT EXISTS (SELECT 1 FROM settings WHERE k = 'theme');"}]},"source_url":"https://sqlly.app/sql-functions/not-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/not-in","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NOT IN operator","description":"NOT IN returns zero rows when the subquery yields one NULL: the three-valued logic behind it, NOT EXISTS and JOIN fixes, and when NOT IN is still fine.","body":{"slug":"not-in","name":"NOT IN","h1":"SQL NOT IN operator","category":"conditional","lede":"True when the value matches no member, and silently true for no rows when a NULL sneaks in.","syntax":"x NOT IN (1, 2, 3) | x NOT IN (SELECT ...)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["One NULL in the list or subquery makes the comparison against it UNKNOWN, so NOT IN is FALSE or UNKNOWN for every row, never TRUE, and the result is empty without any error.","Safe rewrites: NOT EXISTS correlated on the join key, or NOT IN (SELECT y FROM t WHERE y IS NOT NULL); they differ on outer rows whose key is NULL, which NOT EXISTS keeps and NOT IN drops.","Literal lists are safe because you can see there is no NULL in them.","LEFT JOIN ... WHERE right.key IS NULL is a third anti-join; matched rows are filtered out, so it returns each unmatched outer row once even when keys match many rows."],"examples":[{"engine_slug":"all","sql":"SELECT * FROM customers c WHERE c.id NOT IN (SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL);"},{"engine_slug":"all","sql":"SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);"}],"faqs":[{"question":"Why does NOT IN return zero rows?","answer":"The subquery contains a NULL: x NOT IN (...) needs every comparison FALSE, and the NULL one is UNKNOWN instead."},{"question":"NOT IN or NOT EXISTS?","answer":"NOT EXISTS: NULL-safe, and PostgreSQL, SQL Server and MySQL plan it as an anti-join; SQLite runs it as a correlated subquery, so index the inner key."},{"question":"When is NOT IN fine?","answer":"With literal lists, or a subquery over a NOT NULL column: visible, no NULL, no trap."}],"related":["exists","not-exists","in","three-valued-logic","null-safe-join"],"novel_uses":[{"body":"PostgreSQL never turns NOT IN into an anti-join, even when both columns are NOT NULL: EXPLAIN shows a hashed SubPlan, which degrades to a per-row SubPlan scan once the set outgrows work_mem, while NOT EXISTS gets a Hash Anti Join.","sql":"EXPLAIN SELECT * FROM customers c WHERE c.id NOT IN (SELECT o.customer_id FROM orders o);"},{"body":"NOT IN inside a CHECK keeps junk states out at the schema level on every engine, no trigger required; a NULL status still passes, so add NOT NULL if it must be set.","sql":"CREATE TABLE jobs (status VARCHAR(20) CHECK (status NOT IN ('void', 'test')));"}]},"source_url":"https://sqlly.app/sql-functions/not-in","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/now","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NOW / CURRENT_TIMESTAMP function","description":"Get the current timestamp in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: NOW, CURRENT_TIMESTAMP, GETDATE and SYSDATE, plus precision and time-zone traps.","body":{"slug":"now","name":"NOW / CURRENT_TIMESTAMP","h1":"SQL NOW / CURRENT_TIMESTAMP function","category":"datetime","lede":"Returns the current date and time. CURRENT_TIMESTAMP is the standard spelling and works on all five engines; NOW(), GETDATE() and SYSDATE are dialect names that differ in precision and in when they are evaluated.","syntax":"CURRENT_TIMESTAMP  |  NOW()  |  GETDATE() / SYSDATETIME()  |  SYSTIMESTAMP  |  datetime('now')","return_type":"timestamp (text on SQLite)","support":[{"engine_slug":"sql-server","status":"yes","note":"CURRENT_TIMESTAMP or GETDATE() (datetime); SYSDATETIME() for datetime2; no NOW()"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"NOW() and CURRENT_TIMESTAMP give the statement start; SYSDATE() the moment of the call"},{"engine_slug":"sqlite","status":"yes","note":"CURRENT_TIMESTAMP or datetime('now'); returns UTC text, no NOW()"},{"engine_slug":"oracle","status":"yes","note":"CURRENT_TIMESTAMP (session zone), SYSTIMESTAMP and SYSDATE (server clock); no NOW()"}],"gotchas":["PostgreSQL's now() and CURRENT_TIMESTAMP are the transaction start time, frozen for the whole transaction; clock_timestamp() keeps moving.","SQLite's CURRENT_TIMESTAMP and datetime('now') return UTC text like '2026-08-01 14:30:00', not local time. datetime('now', 'localtime') converts.","Precision differs: SQL Server's GETDATE() and CURRENT_TIMESTAMP are datetime, accurate to about 3 ms; SYSDATETIME() is datetime2 with 100 ns. MySQL's NOW() has whole seconds unless you ask for NOW(6).","Oracle's SYSDATE and SYSTIMESTAMP read the database server's clock and time zone; CURRENT_TIMESTAMP uses the session time zone, so two clients in different zones see different values."],"examples":[{"engine_slug":"all","sql":"SELECT CURRENT_TIMESTAMP AS loaded_at;"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIME() AS loaded_at;"},{"engine_slug":"sqlite","sql":"SELECT datetime('now', 'localtime') AS loaded_at;"}],"faqs":[{"question":"Is NOW() the time the statement ran?","answer":"On PostgreSQL it is the time the transaction started, so every statement in the transaction sees the same value. MySQL's NOW() is the time the statement started; its SYSDATE() changes even within one statement. SQL Server evaluates GETDATE() once per reference in a query, not per row."},{"question":"Why is SQLite's datetime('now') in the wrong time zone?","answer":"It is UTC by design. Add 'localtime' as a modifier to get the machine's local time, or keep storing UTC and convert for display, which survives daylight-saving changes and servers moving zones."}],"related":["current-date","dateadd","datediff"],"novel_uses":[{"body":"Reading everything newer than the last watermark can still miss rows whose commits landed after your NOW() snapshot. Stopping a few seconds short and letting the next run pick up the remainder makes incremental exports correct even with in-flight transactions.","sql":"SELECT * FROM orders\n-- the cutoff is the previous run's watermark\nWHERE updated_at > TIMESTAMP '2026-08-01 00:00:00'\n  AND updated_at < NOW() - INTERVAL '5 seconds';"},{"body":"MySQL's plain NOW() has one-second resolution, so rows inserted in the same second tie and ORDER BY created_at cannot recover the write order. Column defaults of NOW(6) keep microseconds, and the ordering comes back for debugging.","sql":"CREATE TABLE events (\n  id BIGINT PRIMARY KEY AUTO_INCREMENT,\n  note VARCHAR(200),\n  created_at DATETIME(6) DEFAULT NOW(6)\n);\nSELECT note FROM events ORDER BY created_at;"}]},"source_url":"https://sqlly.app/sql-functions/now","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nth-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NTH_VALUE function","description":"NTH_VALUE in PostgreSQL, MySQL, SQLite and Oracle: pull the second, third or Nth value of the frame, plus the frame trap and the missing SQL Server story.","body":{"slug":"nth-value","name":"NTH_VALUE","h1":"SQL NTH_VALUE function","category":"window","lede":"Returns the expression evaluated on the Nth row of the window frame, counting from 1; NULL when the frame has fewer than N rows so far.","syntax":"NTH_VALUE(expr, n) OVER (ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"no","note":"no NTH_VALUE; emulate with ROW_NUMBER in a subquery and join it back"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Same default-frame trap as LAST_VALUE: with only ORDER BY, the frame ends at the current row, so NTH_VALUE(..., 3) stays NULL until row 3 and never looks past it. Stretch the frame explicitly.","N counts from 1 and must be a positive integer; N = 0 or a negative N is an error, not NULL.","Of the engines here, only Oracle implements FROM LAST (count from the frame end) and IGNORE NULLS on NTH_VALUE. MySQL parses both and refuses them ('doesn't yet support'); PostgreSQL and SQLite reject them as syntax errors."],"examples":[{"engine_slug":"postgresql","sql":"SELECT day, price,\n       NTH_VALUE(price, 2) OVER (\n         ORDER BY day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_price\nFROM prices;"},{"engine_slug":"all","sql":"-- SQL Server emulation: the 2nd value per partition\nWITH n AS (\n  SELECT p0.*, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY day) AS rn\n  FROM prices p0\n)\nSELECT p.grp, p.day, p.price, n.price AS second_price\nFROM prices p\nLEFT JOIN n ON n.grp = p.grp AND n.rn = 2;"}],"faqs":[{"question":"Why does NTH_VALUE return NULL for early rows?","answer":"Two reasons stack: the frame has fewer than N rows in the first place, and the default frame ends at the current row so later rows are invisible. With ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING every row sees the whole partition, so NULL then only appears when the partition has fewer than N rows (or the Nth value is itself NULL)."},{"question":"How do I get the Nth value in SQL Server?","answer":"No NTH_VALUE exists. Number rows with ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) in a CTE, keep the row where rn = N, and join it back."}],"related":["first-value","last-value","ignore-nulls"],"novel_uses":[{"body":"With a full frame and descending order, NTH_VALUE(score, 2) carries the second score of the partition onto every row, so the gap between leader and chasing pack is one subtraction. SQL Server has no NTH_VALUE; use the ROW_NUMBER join shown in the examples.","sql":"SELECT name, score,\n       FIRST_VALUE(score) OVER (ORDER BY score DESC\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS top_score,\n       NTH_VALUE(score, 2) OVER (ORDER BY score DESC\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_score\nFROM players;"},{"body":"Under descending order the first and second rows hold equal values exactly when the lead is tied, so FIRST_VALUE = NTH_VALUE(x, 2) flags a tied lead in one comparison, and the flag lands on every row, not just the tied leaders. A NULL second value means a one-row partition, not a tie.","sql":"SELECT name, score,\n       CASE WHEN FIRST_VALUE(score) OVER (ORDER BY score DESC\n                  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)\n                 = NTH_VALUE(score, 2) OVER (ORDER BY score DESC\n                  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)\n            THEN 1 ELSE 0 END AS tie_at_top\nFROM players;"}]},"source_url":"https://sqlly.app/sql-functions/nth-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ntile","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NTILE function","description":"NTILE in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: divide ordered rows into equal buckets (quartiles, deciles and percentiles by rank).","body":{"slug":"ntile","name":"NTILE","h1":"SQL NTILE function","category":"window","lede":"Distributes ordered rows into n numbered buckets as evenly as possible: NTILE(4) gives quartiles, NTILE(100) percentiles, by position rather than by value.","syntax":"NTILE(buckets) OVER (PARTITION BY g ORDER BY x)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Buckets are by row count, not by value: NTILE(2) over 1, 2, 3, 1000 puts 3 and 1000 in the same top bucket, and two equal values can land in different buckets. For value-based cut points use PERCENTILE_CONT or PERCENTILE_DISC.","When rows do not divide evenly, earlier buckets get the extras: 10 rows in NTILE(4) sizes 3, 3, 2, 2.","With fewer rows than buckets, some buckets are empty: NTILE(100) over 40 rows uses only buckets 1 to 40."],"examples":[{"engine_slug":"all","sql":"SELECT name, spend,\n       NTILE(4) OVER (ORDER BY spend DESC) AS spend_quartile\nFROM customers;"},{"engine_slug":"all","sql":"SELECT region, spend,\n       NTILE(4) OVER (PARTITION BY region ORDER BY spend DESC) AS quartile\nFROM customers;"}],"faqs":[{"question":"What is the difference between NTILE and PERCENTILE_CONT?","answer":"NTILE buckets by row position: every bucket gets the same number of rows. PERCENTILE_CONT finds the value at a fraction of the ordered values. Uneven data gives different answers."},{"question":"What happens when the rows do not divide evenly?","answer":"Earlier buckets absorb the remainder: 10 rows into 4 buckets sizes them 3, 3, 2, 2."}],"related":["rank","percentile-cont","dense-rank"],"novel_uses":[{"body":"NTILE(10) over an order unrelated to the label (a hash of the key works) tags every row with a fold number, and each training run excludes one fold. The data never leaves the warehouse to get shuffled.","sql":"SELECT id, NTILE(10) OVER (ORDER BY MD5(id::text)) AS fold\nFROM training_rows;"},{"body":"Hashing keys into buckets balances keys, not volume. NTILE over a cost ordering spreads the estimated work itself: sorted biggest first, the heavy items alternate across buckets and every worker gets a comparable load.","sql":"SELECT job_id,\n       NTILE(4) OVER (ORDER BY estimated_cost DESC) AS worker\nFROM jobs;"}]},"source_url":"https://sqlly.app/sql-functions/ntile","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ntile-percentile","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NTILE for percentile buckets","description":"NTILE(4), NTILE(10) and NTILE(100) give quartiles, deciles and percentiles on MySQL and SQLite, where PERCENTILE_CONT and PERCENTILE_DISC are missing or optional.","body":{"slug":"ntile-percentile","name":"NTILE for Percentiles","h1":"SQL NTILE for percentile buckets","category":"window","lede":"NTILE(n) distributes partition rows as evenly as possible into n numbered buckets, a cheap percentile approximation that works everywhere window functions do.","syntax":"NTILE(4) OVER (ORDER BY x) | NTILE(10) OVER (PARTITION BY g ORDER BY x)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["When rows do not divide evenly, earlier buckets get the extra row: 7 rows into 4 buckets is 2, 2, 2, 1. Do not assume equal bucket sizes.","NTILE buckets are by position, not by value: two rows with the same ORDER BY value can land in different buckets. For value-based percentiles use CUME_DIST or PERCENTILE_DISC.","SQL Server rejects NTILE without ORDER BY. PostgreSQL, MySQL and SQLite accept it and bucket rows in whatever order the engine returns them, so the buckets are arbitrary."],"examples":[{"engine_slug":"all","sql":"SELECT customer_id, spend,\n       NTILE(4) OVER (ORDER BY spend DESC) AS spend_quartile\nFROM customers;"},{"engine_slug":"all","sql":"-- deciles per region, then averages per bucket\nWITH d AS (\n  SELECT c.*, NTILE(10) OVER (PARTITION BY region ORDER BY spend DESC) AS decile\n  FROM customers c\n)\nSELECT region, decile, AVG(spend) AS avg_spend\nFROM d GROUP BY region, decile\nORDER BY region, decile;"}],"faqs":[{"question":"How is NTILE(100) different from a real percentile?","answer":"It ranks rows by position into 100 nearly-equal buckets, so a bucket can contain tied values and sizes differ by one. PERCENTILE_CONT/DISC answer 'what value is the median?'; NTILE answers 'which bucket is this row in?'."},{"question":"Can the bucket count come from a variable or a column?","answer":"A variable or bind parameter works on all five. A column is where they split: SQL Server and MySQL reject it, Oracle accepts it only if it is a function of the PARTITION BY expressions (constant per partition), and PostgreSQL and SQLite accept it. Keep it constant per partition or the bucketing is meaningless."}],"related":["ntile","cume-dist","percentile-disc"],"novel_uses":[{"body":"NTILE(10) over a table hands out fold ids that differ by at most one row, which is the balance fold splitting wants when the row count does not divide by 10. Order by the primary key for stable, reproducible folds.","sql":"WITH f AS (\n  SELECT patient_id, NTILE(10) OVER (ORDER BY patient_id) AS fold\n  FROM patients\n)\nSELECT fold, COUNT(*) AS rows_in_fold\nFROM f\nGROUP BY fold\nORDER BY fold;"},{"body":"Bucket customers once in a CTE, then join later events back to the decile to watch retention per bucket. The decile becomes a stable cohort key as long as every report recomputes it from the same snapshot.","sql":"WITH d AS (\n  SELECT customer_id, spend,\n         NTILE(10) OVER (ORDER BY spend DESC) AS decile\n  FROM customer_spend\n)\nSELECT decile, COUNT(*) AS customers\nFROM d\nGROUP BY decile\nORDER BY decile;"}]},"source_url":"https://sqlly.app/sql-functions/ntile-percentile","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULL value","description":"NULL means unknown, not zero or empty string: never equal to itself, three-valued logic, IS NULL testing, aggregates skipping it and per-engine empty-string twists.","body":{"slug":"null","name":"NULL","h1":"SQL NULL value","category":"conditional","lede":"The marker for a missing or unknown value, and the source of most SQL surprises.","syntax":"x IS NULL | x IS NOT NULL","return_type":"no type","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL = NULL is UNKNOWN; nothing equals NULL, including another NULL.","'' and NULL are different in PostgreSQL, MySQL, SQL Server and SQLite, but Oracle treats a zero-length string AS NULL.","Aggregates skip NULLs: AVG and SUM over an empty or all-NULL group return NULL; COUNT(col) returns 0, while COUNT(*) still counts the all-NULL rows.","String concatenation splits: CONCAT('a', NULL) is 'a' in PostgreSQL, SQL Server, SQLite and Oracle but NULL in MySQL; 'a' || NULL is NULL in PostgreSQL, SQLite and SQL Server 2025 but 'a' in Oracle, which treats the NULL as an empty string."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CASE WHEN NULL = NULL THEN 'equal' ELSE 'unknown' END AS result;"},{"engine_slug":"all","sql":"SELECT * FROM users WHERE deleted_at IS NULL;"}],"faqs":[{"question":"Is NULL zero or empty string?","answer":"Neither: it is 'unknown'. Zero and '' are values; NULL is the absence of one, with its own logic."},{"question":"How do I test for NULL?","answer":"IS NULL and IS NOT NULL; = NULL is always UNKNOWN under default settings (SQL Server's deprecated SET ANSI_NULLS OFF is the one exception)."},{"question":"Why does my AVG ignore rows?","answer":"AVG skips NULL values by design; use COALESCE(col, 0) if missing should count as zero."}],"related":["is-null","three-valued-logic","empty-string-null","coalesce","distinct-from"],"novel_uses":[{"body":"One NULL operand turns the whole arithmetic expression NULL, so decide per term whether missing means zero or unknown before the formula, not after it.","sql":"SELECT total * 0.9 + COALESCE(bonus, 0) AS payout FROM settlements;"},{"body":"SQL Server, PostgreSQL, MySQL and Oracle make primary-key columns NOT NULL implicitly, but SQLite accepts NULL (even several) in a non-INTEGER primary key unless the table is STRICT or WITHOUT ROWID, so spell out NOT NULL. A nullable deleted_at then marks soft deletes: NULL means live. On SQL Server use DATETIME2, because TIMESTAMP there is rowversion and is never NULL.","sql":"CREATE TABLE users (id BIGINT NOT NULL PRIMARY KEY, deleted_at TIMESTAMP NULL);"}]},"source_url":"https://sqlly.app/sql-functions/null","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null-arithmetic","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULL in arithmetic","description":"Any arithmetic with NULL yields NULL on every engine (5 + NULL is NULL, not 5), and the fixes are COALESCE for defaults and NULLIF for guards.","body":{"slug":"null-arithmetic","name":"NULL math","h1":"SQL NULL in arithmetic","category":"math","lede":"Explains three-valued logic in math expressions: unknown propagates through + - * / and functions, with the COALESCE and NULLIF patterns that tame it.","syntax":"5 + NULL  |  COALESCE(x, 0) + 5  |  x / NULLIF(y, 0)","return_type":"NULL / numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL is contagious by design: 5 + NULL and NULL * 10 are NULL on every engine, and so is LN(NULL) wherever LN exists (SQL Server spells it LOG, and LOG(NULL) is NULL there), because an unknown operand makes the result unknown.","COALESCE supplies the default, but think first: COALESCE(bonus, 0) changes an unknown bonus into no bonus; only do that when zero is truly the meaning.","Aggregates are the exception: SUM, AVG, MIN and MAX skip NULL inputs rather than returning NULL, though SUM over zero rows is still NULL."],"examples":[{"engine_slug":"all","sql":"SELECT 5 + NULL AS unknown;  -- NULL"},{"engine_slug":"all","sql":"SELECT COALESCE(bonus, 0) + salary AS total_comp\nFROM employees;"},{"engine_slug":"all","sql":"SELECT x / NULLIF(y, 0) AS safe_div FROM t;  -- NULL instead of an error"}],"faqs":[{"question":"What does 5 + NULL return in SQL?","answer":"NULL, on every engine. SQL's three-valued logic says an unknown operand makes the whole expression unknown. Wrap operands in COALESCE(x, 0) only when zero genuinely matches the meaning."},{"question":"Why did my AVG ignore NULLs but my + did not?","answer":"Aggregates skip NULL inputs before computing; scalar arithmetic propagates them. AVG(bonus) divides by the non-null count, while bonus + salary is NULL whenever either side is NULL."},{"question":"How do I turn division-by-zero into NULL instead of an error?","answer":"NULLIF in the divisor: x / NULLIF(y, 0). The zero becomes NULL, the division returns NULL, and the query survives: the NULL-propagation rule working for you. SQL Server and PostgreSQL raise an error on a plain x / 0, while MySQL (in a SELECT) and SQLite already return NULL, so NULLIF gives every engine the same result."}],"related":["arithmetic-operators","coalesce","nullif","division-by-zero"],"novel_uses":[{"body":"SUM(rev) / COUNT(y) divides by the rows where y is known; SUM(rev) / COUNT(*) divides by everything. Rate reports that disagree between teams usually picked different COUNTs without noticing.","sql":"SELECT SUM(rev) / NULLIF(COUNT(y), 0) AS per_known, SUM(rev) / NULLIF(COUNT(*), 0) AS per_row FROM t;"},{"body":"CHECK (x > 0) lets NULL through, because unknown is not false. CHECK (x > 0 OR x IS NULL) is the same behavior made explicit, and CHECK (x IS NOT NULL AND x > 0) is how you actually forbid NULL. SQLite has no ALTER TABLE ... ADD CONSTRAINT, so declare that CHECK inside CREATE TABLE there.","sql":"ALTER TABLE t ADD CONSTRAINT ck_positive CHECK (x IS NOT NULL AND x > 0);"}]},"source_url":"https://sqlly.app/sql-functions/null-arithmetic","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null-safe-equal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULL-safe equality","description":"Compare values so NULL equals NULL: MySQL's <=>, SQLite's IS, IS NOT DISTINCT FROM in PostgreSQL and SQL Server 2022, the INTERSECT trick and Oracle's DECODE.","body":{"slug":"null-safe-equal","name":"NULL-safe","h1":"SQL NULL-safe equality","category":"conditional","lede":"Equality tests that report TRUE or FALSE even when NULLs are involved.","syntax":"a <=> b | a IS NOT DISTINCT FROM b | a IS b","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":"IS NOT DISTINCT FROM since SQL Server 2022"},{"engine_slug":"postgresql","status":"yes","note":"IS NOT DISTINCT FROM"},{"engine_slug":"mysql","status":"yes","note":"<=> operator"},{"engine_slug":"sqlite","status":"yes","note":"IS / IS NOT; IS NOT DISTINCT FROM since 3.39"},{"engine_slug":"oracle","status":"partial","note":"no operator; DECODE(a, b, 1, 0) = 1"}],"gotchas":["Plain = returns UNKNOWN when either side is NULL; the null-safe forms return a definite TRUE or FALSE.","The portable recipe on engines with none of the syntax: EXISTS (SELECT a INTERSECT SELECT b), since INTERSECT treats NULLs as equal. Oracle needs FROM dual on both halves.","Oracle's DECODE(a, b, 1, 0) = 1 works because DECODE, unlike CASE, treats two NULLs as equal.","MySQL's <=> returns 1/0 including NULL pairs; SQLite's IS does the same as a wordier operator."],"examples":[{"engine_slug":"mysql","sql":"SELECT 1 <=> 1 AS t, NULL <=> NULL AS t2, NULL <=> 1 AS f;"},{"engine_slug":"sqlite","sql":"SELECT NULL IS NULL AS t, NULL IS 1 AS f;"},{"engine_slug":"postgresql","sql":"SELECT NULL IS NOT DISTINCT FROM NULL AS t;"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN EXISTS (SELECT a INTERSECT SELECT b) THEN 1 ELSE 0 END AS eq FROM t;"},{"engine_slug":"oracle","sql":"SELECT DECODE(a, b, 1, 0) AS eq FROM t;"}],"faqs":[{"question":"How do I test NULL = NULL?","answer":"You cannot with =; use IS NULL on both sides, <=> in MySQL, IS in SQLite or IS NOT DISTINCT FROM."},{"question":"What works on every engine?","answer":"EXISTS (SELECT a INTERSECT SELECT b): INTERSECT defines NULLs as equal by standard."},{"question":"Why does DECODE help in Oracle?","answer":"DECODE's NULL-equality rule: two NULL arguments compare equal, unlike CASE expressions."}],"related":["distinct-from","three-valued-logic","is-null","null-safe-join","decode"],"novel_uses":[{"body":"Grouping, DISTINCT and UNION treat NULLs as one value on every engine, so the null-safe problem exists only for =, joins and set lookups.","sql":"SELECT color, COUNT(*) FROM products GROUP BY color;"},{"body":"IF NOT (OLD.x <=> NEW.x) writes the audit row only when the value really changed, NULLs included in the comparison.","sql":"IF NOT (OLD.mgr_id <=> NEW.mgr_id) THEN INSERT INTO audit(emp_id, at) VALUES (NEW.id, NOW()); END IF"}]},"source_url":"https://sqlly.app/sql-functions/null-safe-equal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null-safe-join","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULL-safe joins","description":"Equality joins silently drop rows whose key is NULL on either side: IS NOT DISTINCT FROM and <=> joins, COALESCE recipes and why NULL keys mean 'no match' in SQL.","body":{"slug":"null-safe-join","name":"JOIN","h1":"SQL NULL-safe joins","category":"conditional","lede":"Join patterns for keys that can be NULL on either side.","syntax":"ON a.k IS NOT DISTINCT FROM b.k | ON a.k <=> b.k | ON COALESCE(a.k, -1) = COALESCE(b.k, -1)","return_type":"joined rows","support":[{"engine_slug":"sql-server","status":"yes","note":"IS NOT DISTINCT FROM since SQL Server 2022; else COALESCE"},{"engine_slug":"postgresql","status":"yes","note":"IS NOT DISTINCT FROM"},{"engine_slug":"mysql","status":"yes","note":"<=>"},{"engine_slug":"sqlite","status":"yes","note":"IS (or IS NOT DISTINCT FROM since 3.39)"},{"engine_slug":"oracle","status":"partial","note":"DECODE(a.k, b.k, 1, 0) = 1"}],"gotchas":["ON a.k = b.k never matches NULL keys: NULL = NULL is UNKNOWN, and joins keep only TRUE rows. That is the relational definition of match.","COALESCE(a.k, sentinel) = COALESCE(b.k, sentinel) is the classic fix but collides when a real key equals the sentinel.","Decide the semantics first: usually a NULL key means 'no relationship' and dropping those rows is correct; these recipes are for when NULL means the same unknown value."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM a JOIN b ON a.k IS NOT DISTINCT FROM b.k;"},{"engine_slug":"mysql","sql":"SELECT * FROM a JOIN b ON a.k <=> b.k;"},{"engine_slug":"oracle","sql":"SELECT * FROM a JOIN b ON DECODE(a.k, b.k, 1, 0) = 1;"},{"engine_slug":"sql-server","sql":"SELECT * FROM a JOIN b ON COALESCE(a.k, -1) = COALESCE(b.k, -1);"},{"engine_slug":"sqlite","sql":"SELECT * FROM a JOIN b ON a.k IS b.k;"}],"faqs":[{"question":"Why do NULL keys never join?","answer":"Equality with NULL is UNKNOWN and joins keep only TRUE rows; matching NULLs needs a null-safe predicate."},{"question":"Is COALESCE on join keys safe?","answer":"Only if the sentinel cannot be a real key value; IS NOT DISTINCT FROM or <=> avoids the collision entirely."},{"question":"Does this affect performance?","answer":"It depends on the engine: PostgreSQL's IS NOT DISTINCT FROM cannot use a b-tree index, while SQL Server 2022's IS NOT DISTINCT FROM, MySQL's <=> and SQLite's IS still seek. COALESCE on the key defeats a plain index everywhere; measure, index the COALESCE expression, or use the two-step join."}],"related":["distinct-from","null-safe-equal","not-exists","three-valued-logic","null"],"novel_uses":[{"body":"Match non-NULL keys with plain equality, then a second pass over NULL-key rows on both sides; the hot path keeps its index seeks.","sql":"SELECT * FROM a JOIN b ON a.k = b.k UNION ALL SELECT * FROM a JOIN b ON a.k IS NULL AND b.k IS NULL;"},{"body":"After a null-safe merge, count how many matches came from NULL keys so the sync report can say how much of the join rode on unknowns; PostgreSQL's FILTER keeps it one query.","sql":"SELECT COUNT(*) FILTER (WHERE a.k IS NULL) AS unknown_matches FROM a JOIN b ON a.k IS NOT DISTINCT FROM b.k;"}]},"source_url":"https://sqlly.app/sql-functions/null-safe-join","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null-sort-order","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULL sort order","description":"Where NULL rows land in ORDER BY and how to move them: SQL Server and MySQL defaults, NULLS FIRST and NULLS LAST in PostgreSQL, Oracle and SQLite 3.30+, CASE workarounds.","body":{"slug":"null-sort-order","name":"NULLS FIRST","h1":"SQL NULL sort order","category":"conditional","lede":"Controls whether NULL rows sort at the top or bottom of an ordered result.","syntax":"ORDER BY x NULLS FIRST | ORDER BY x NULLS LAST | ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x","return_type":"ordering modifier","support":[{"engine_slug":"sql-server","status":"no","note":"no NULLS FIRST/LAST; emulate with CASE"},{"engine_slug":"postgresql","status":"yes","note":"NULLs sort last in ASC by default (NULL treated as largest)"},{"engine_slug":"mysql","status":"no","note":"no syntax; NULLs sort first in ASC and last in DESC"},{"engine_slug":"sqlite","status":"yes","note":"3.30+; NULLs sort first in ASC by default"},{"engine_slug":"oracle","status":"yes","note":"NULLs sort last in ASC by default; NULLS FIRST/LAST supported"}],"gotchas":["The defaults disagree: SQL Server, MySQL and SQLite put NULLs first in ASC; PostgreSQL and Oracle put them last. The same query orders differently across engines.","DESC reverses the NULL placement too, unless you pin it with NULLS FIRST or NULLS LAST.","The CASE workaround sorts NULLs into a fixed group first (or last, with 1/0 swapped), then orders the values within each group."],"examples":[{"engine_slug":"postgresql","sql":"SELECT * FROM races ORDER BY finish_time NULLS LAST;"},{"engine_slug":"sql-server","sql":"SELECT * FROM races ORDER BY CASE WHEN finish_time IS NULL THEN 1 ELSE 0 END, finish_time;"},{"engine_slug":"sqlite","sql":"SELECT * FROM races ORDER BY finish_time NULLS LAST;"},{"engine_slug":"oracle","sql":"SELECT * FROM races ORDER BY finish_time DESC NULLS FIRST;"}],"faqs":[{"question":"Where do NULLs sort by default?","answer":"Engine-dependent: first in SQL Server, MySQL and SQLite; last in PostgreSQL and Oracle (ascending). Pin it with NULLS FIRST/LAST."},{"question":"Does SQL Server support NULLS LAST?","answer":"No; emulate with ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x."},{"question":"Do NULLS FIRST and DESC combine?","answer":"Yes: NULLS FIRST/LAST always wins over the direction's default placement."}],"related":["null","is-null","coalesce","three-valued-logic"],"novel_uses":[{"body":"NULLS FIRST on processed_at serves never-processed rows before finished ones, the queue order a worker poll wants.","sql":"SELECT job_id FROM jobs ORDER BY processed_at NULLS FIRST, created_at;"},{"body":"NULLS LAST keeps did-not-finish rows at the bottom of a results table whichever direction the times sort.","sql":"SELECT racer_id, finish_time FROM results ORDER BY finish_time NULLS LAST;"}]},"source_url":"https://sqlly.app/sql-functions/null-sort-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/null-unique","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNIQUE constraint with NULLs","description":"Unique indexes treat NULLs as distinct in MySQL, SQLite, PostgreSQL and Oracle, so many can coexist; SQL Server allows only one, and PG 15 adds NULLS NOT DISTINCT.","body":{"slug":"null-unique","name":"UNIQUE","h1":"SQL UNIQUE constraint with NULLs","category":"conditional","lede":"How the unique constraint counts NULL values, engine by engine.","syntax":"CREATE UNIQUE INDEX ... ON t (col) | NULLS NOT DISTINCT","return_type":"constraint behaviour","support":[{"engine_slug":"sql-server","status":"partial","note":"a unique index admits exactly one NULL"},{"engine_slug":"postgresql","status":"yes","note":"multiple NULLs by default; NULLS NOT DISTINCT since PG 15 makes them conflict"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Standard semantics: NULL is not a value, so NULLs never collide. Unlimited NULL rows in a unique index on MySQL, SQLite, PostgreSQL and Oracle.","SQL Server deviates: exactly one NULL is allowed, which surprises porters both ways.","PostgreSQL 15+ offers NULLS NOT DISTINCT to make NULLs collide; MySQL, Oracle and SQLite have no such switch.","Composite unique keys split three ways: PostgreSQL (default), MySQL and SQLite exempt any row with at least one NULL; Oracle exempts only all-NULL keys, so (1, NULL) twice violates the constraint; SQL Server treats NULL as a value, so even (NULL, NULL) is allowed once."],"examples":[{"engine_slug":"postgresql","sql":"CREATE UNIQUE INDEX ON t (email) NULLS NOT DISTINCT;"},{"engine_slug":"sql-server","sql":"CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL;"},{"engine_slug":"sqlite","sql":"CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL;"},{"engine_slug":"mysql","sql":"CREATE TABLE users (email VARCHAR(100) UNIQUE);"},{"engine_slug":"oracle","sql":"CREATE TABLE users (email VARCHAR2(100) UNIQUE);"}],"faqs":[{"question":"How many NULLs can a unique column hold?","answer":"Unlimited on MySQL, SQLite, PostgreSQL (default) and Oracle; exactly one on SQL Server."},{"question":"How do I make NULLs count as duplicates?","answer":"PostgreSQL 15+: add NULLS NOT DISTINCT. SQL Server already does it for a plain unique index. Elsewhere: a unique index on an expression such as COALESCE(col, sentinel)."},{"question":"How do I allow many NULLs on SQL Server?","answer":"Use a filtered unique index: CREATE UNIQUE INDEX ux ON t (email) WHERE email IS NOT NULL."},{"question":"What about multi-column unique keys?","answer":"PostgreSQL, MySQL and SQLite let any row with a NULL in the key through. Oracle rejects a repeated (1, NULL) and only lets all-NULL keys repeat. SQL Server rejects any repeated key, NULLs included."}],"related":["null","empty-string-null","coalesce-index","distinct-from"],"novel_uses":[{"body":"A partial unique index rules one active subscription per user while expired rows pile up freely; PostgreSQL and SQLite write it with WHERE, SQL Server with a filtered index.","sql":"CREATE UNIQUE INDEX ON subs (user_id) WHERE status = 'active';"},{"body":"Without partial indexes, a function-based unique index over a CASE gives the same rule: inactive rows turn NULL and NULLs never collide on Oracle.","sql":"CREATE UNIQUE INDEX ux_active ON subs (CASE WHEN status = 'active' THEN user_id END);"}]},"source_url":"https://sqlly.app/sql-functions/null-unique","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nullif","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULLIF function","description":"NULLIF in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: convert a sentinel like 0 or '' into NULL, with divide-by-zero and default-value patterns.","body":{"slug":"nullif","name":"NULLIF","h1":"SQL NULLIF function","category":"conditional","lede":"Returns NULL when its two arguments are equal, and the first argument otherwise. Where COALESCE replaces NULLs with a value, NULLIF turns a placeholder value back into NULL.","syntax":"NULLIF(value, value_to_null_out)","return_type":"type of the first argument","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["It is shorthand for CASE WHEN a = b THEN NULL ELSE a END, which is why it takes exactly two arguments.","The usual division guard: total / NULLIF(count, 0) returns NULL instead of a divide-by-zero error.","Watch types: on SQL Server NULLIF('abc', 0) fails converting 'abc' to int, because the comparison uses the higher-precedence type. Keep both arguments the same type."],"examples":[{"engine_slug":"all","sql":"SELECT total / NULLIF(order_count, 0) AS avg_order\nFROM summaries;"},{"engine_slug":"all","sql":"SELECT NULLIF(TRIM(alias), '') AS clean_alias FROM users;"}],"faqs":[{"question":"What is NULLIF used for?","answer":"Turning sentinels into NULL: blank strings, zero counts, legacy -1 flags. Most often seen as the divide-by-zero guard total / NULLIF(n, 0)."},{"question":"Does NULLIF compare NULL to NULL?","answer":"No. NULLIF(NULL, x) returns NULL because the first argument is NULL. NULLIF(x, NULL) returns x, because x = NULL is never true, so the values are never treated as equal."}],"related":["coalesce","case","ifnull"],"novel_uses":[{"body":"Legacy feeds use -1 for missing. NULLIF(score, -1) turns the sentinel into NULL, so AVG, MIN and MAX behave as if the row were absent, with no CASE and no filtered subquery. COUNT(NULLIF(x, -1)) counts real values only.","sql":"SELECT AVG(NULLIF(response_ms, -1)) AS real_avg\nFROM pings;"},{"body":"old <> new misses every transition that touches NULL. NULLIF(n.status, o.status) IS NOT NULL catches changes from a value, and the IS NULL pair catches changes to NULL. PostgreSQL and SQLite have IS DISTINCT FROM for exactly this; MySQL has the null-safe <=> operator.","sql":"SELECT COUNT(*) AS changed_rows\nFROM new_t n JOIN old_t o ON o.id = n.id\nWHERE NULLIF(n.status, o.status) IS NOT NULL\n   OR (n.status IS NULL AND o.status IS NOT NULL);"}]},"source_url":"https://sqlly.app/sql-functions/nullif","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/number-format","corpus":"sql-functions","engine":null,"language":"en","title":"SQL MySQL FORMAT function","description":"MySQL's FORMAT(x, d) rounds a number to d decimals and adds thousands separators, locale-aware output as a string, with no .NET format strings.","body":{"slug":"number-format","name":"FORMAT (MySQL)","h1":"SQL MySQL FORMAT function","category":"string","lede":"Rounds and groups a number for display: FORMAT(1234.5, 2) returns '1,234.50'. A third argument picks the locale's separators.","syntax":"FORMAT(number, decimals [, locale])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["A negative decimals value is treated as 0, so FORMAT(1234.5, -1) is '1,235'. Decimal values round half away from zero: FORMAT(2.5, 0) is '3' and FORMAT(-2.5, 0) is '-3'. Double values round half to even: FORMAT(CAST(2.5 AS DOUBLE), 0) is '2' and FORMAT(CAST(3.5 AS DOUBLE), 0) is '4'.","The result is a string with separators; arithmetic on it or storing it re-parses. Keep raw numbers in columns, FORMAT only for display.","Locale strings use an underscore: FORMAT(1234.5, 2, 'de_DE') gives '1.234,50'.","SQL Server's FORMAT is a different function that takes .NET patterns. PostgreSQL's nearest equivalent is TO_CHAR(number, 'FM9,999.00')."],"examples":[{"engine_slug":"mysql","sql":"SELECT FORMAT(1234567.891, 2) AS grouped;  -- 1,234,567.89"},{"engine_slug":"mysql","sql":"SELECT FORMAT(1234.5, 2, 'de_DE') AS german;  -- 1.234,50"}],"faqs":[{"question":"Does MySQL FORMAT return a number?","answer":"No, a string. Separators are not valid in a numeric literal. Casting it back stops at the first comma: CAST(FORMAT(1234.5, 2) AS DECIMAL(12,2)) is 1.00, not 1234.50, so format only at the last step."},{"question":"How is this different from SQL Server FORMAT?","answer":"MySQL's version only does digits-and-separators rounding. SQL Server's takes .NET patterns like 'N2' and 'C' plus a culture, and also formats dates."},{"question":"Can I use FORMAT in a WHERE clause?","answer":"It works but defeats indexes and runs per row. Filter on the raw numeric column instead."}],"related":["format","round","to-char"],"novel_uses":[{"body":"A German-locale sheet reads 1.234,50 as a number and treats 1,234.50 as text, so FORMAT(total, 2, 'de_DE') produces a semicolon CSV that German Excel parses directly.","sql":"SELECT CONCAT(id, ';', FORMAT(total, 2, 'de_DE')) AS de_csv\nFROM orders;"},{"body":"FORMAT(SUM(amount), 0) rounds to a whole number and adds separators in one call, which is the whole job for a dashboard tile.","sql":"SELECT FORMAT(SUM(amount), 0) AS total_label FROM payments;  -- 1,234,568"}]},"source_url":"https://sqlly.app/sql-functions/number-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numeric-coercion","corpus":"sql-functions","engine":null,"language":"en","title":"SQL implicit numeric conversion","description":"'1' + 1 is 2 on all five engines, but 'abc' + 1 is 1 on MySQL and SQLite and an error elsewhere. Text columns in PostgreSQL never coerce.","body":{"slug":"numeric-coercion","name":"coercion","h1":"SQL implicit numeric conversion","category":"math","lede":"How each engine treats string operands in arithmetic: lenient prefix parsing on MySQL and SQLite, strict conversion on SQL Server and Oracle, and no coercion of text-typed values on PostgreSQL.","syntax":"'1' + 1  |  CAST('1' AS INT) + 1","return_type":"numeric or error","support":[{"engine_slug":"sql-server","status":"partial","note":"Converts the string to the number's type: '1' + 1 is 2, but '1.5' + 1 fails because '1.5' is not a valid INT. 'abc' raises Msg 245"},{"engine_slug":"postgresql","status":"partial","note":"An untyped literal '1' resolves to integer, so '1' + 1 is 2; a text column or '1'::text + 1 raises 'operator does not exist: text + integer'"},{"engine_slug":"mysql","status":"yes","note":"Coerces: '1' + 1 is 2; non-numeric text coerces to 0 with a warning"},{"engine_slug":"sqlite","status":"yes","note":"Coerces: '1' + 1 is 2; non-numeric text becomes 0, so 'abc' + 1 is 1"},{"engine_slug":"oracle","status":"partial","note":"Implicit TO_NUMBER on numeric-looking strings: '1' + 1 is 2; non-numeric text raises ORA-01722"}],"gotchas":["MySQL and SQLite are the loosest: text with no leading number becomes 0, so typos become zeros instead of errors, and '12abc' coerces as 12. MySQL at least records a truncation warning.","SQL Server converts the string to the other operand's type, so '1.5' + 1 fails ('1.5' is not an INT) while '1.5' + 1.0 works. PostgreSQL accepts the literal '1' + 1 but rejects text_col + 1; cast explicitly: text_col::int + 1.","Oracle's ORA-01722 on bad data fires mid-query depending on plan order: a WHERE that worked on ten rows can fail on ten thousand."],"examples":[{"engine_slug":"mysql","sql":"SELECT '1' + 1 AS coerced, 'abc' + 1 AS zero_coercion;  -- 2, 1"},{"engine_slug":"sqlite","sql":"SELECT '12abc' + 1 AS prefix_coercion;  -- 13"},{"engine_slug":"postgresql","sql":"SELECT '1' + 1 AS literal_ok, '1'::text::int + 1 AS cast_needed;  -- 2, 2; '1'::text + 1 is a type error"},{"engine_slug":"sql-server","sql":"SELECT '1' + 1 AS ok;  -- 2, while '1.5' + 1 raises Msg 245"},{"engine_slug":"oracle","sql":"SELECT '1' + 1 AS coerced FROM dual;  -- 2; 'abc' + 1 raises ORA-01722"}],"faqs":[{"question":"Is '1' + 1 valid SQL?","answer":"As a literal, yes on all five: it returns 2. The differences start with real data: SQL Server fails on '1.5' + 1, PostgreSQL rejects any text-typed column in arithmetic, Oracle raises ORA-01722 on bad strings, and MySQL and SQLite turn garbage into 0 (MySQL with a warning, SQLite silently). Cast explicitly."},{"question":"What does 'abc' + 1 return on SQLite?","answer":"1: SQLite coerces non-numeric text to 0 (and '12abc' to 12) rather than erroring. Handy for parsing, dangerous for catching bad data."},{"question":"Why does my Oracle query raise ORA-01722 intermittently?","answer":"Implicit TO_NUMBER conversion is applied per row at the plan's whim: a string column holding one non-numeric value fails when the scan order reaches it. Cast explicitly or clean the column."}],"related":["cast","try-cast","to-number","arithmetic-operators"],"novel_uses":[{"body":"col + 0 silently turns garbage into 0, so pair the arithmetic with a REGEXP check that rejects non-numeric text first. The regex is the guard the coercion lacks.","sql":"SELECT * FROM imports WHERE value REGEXP '^-?[0-9]+([.][0-9]+)?$' AND value + 0 > 10;"},{"body":"PostgreSQL refuses text + integer, which is the feature: keep raw strings in staging, cast once into typed tables, and a wrong unit or column fails at the boundary instead of three joins later. The error is cheaper the earlier it fires.","sql":"SELECT raw_value::numeric FROM staging;"}]},"source_url":"https://sqlly.app/sql-functions/numeric-coercion","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numeric-precision-scale","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NUMERIC precision and scale","description":"NUMERIC(p, s): p digits in total, s after the point. Excess scale rounds; excess precision errors on SQL Server, PostgreSQL, strict MySQL (CAST clips). SQLite ignores it.","body":{"slug":"numeric-precision-scale","name":"NUMERIC(p, s)","h1":"SQL NUMERIC precision and scale","category":"math","lede":"Defines the two knobs of an exact decimal column: precision p (total digits, up to 38 on SQL Server and Oracle) and scale s (digits after the point), and what happens past either.","syntax":"NUMERIC(precision, scale)  |  DECIMAL(p, s)","return_type":"exact decimal","support":[{"engine_slug":"sql-server","status":"yes","note":"p up to 38; DECIMAL and NUMERIC are synonyms"},{"engine_slug":"postgresql","status":"yes","note":"Declared p up to 1000; unconstrained numeric holds up to 131072 digits before the point and 16383 after"},{"engine_slug":"mysql","status":"yes","note":"p up to 65, s up to 30"},{"engine_slug":"sqlite","status":"partial","note":"NUMERIC(p, s) is parsed but ignored; NUMERIC affinity stores INTEGER, REAL or TEXT per value"},{"engine_slug":"oracle","status":"yes","note":"NUMBER(p, s), p up to 38; NUMERIC(p, s) and DECIMAL(p, s) are accepted as ANSI aliases. Bare NUMBER keeps up to 38 digits at any scale"}],"gotchas":["NUMERIC(5, 2) holds up to 999.99: five digits total, two after the point, three before. Digits past the second decimal place round (CAST(123.456 AS NUMERIC(5, 2)) gives 123.46); a fourth digit before the point is an error.","One-argument DECIMAL(p) means scale 0, an integer column, not a scale-only declaration. Bare NUMERIC is engine-specific: unconstrained on PostgreSQL, DECIMAL(18,0) on SQL Server, DECIMAL(10,0) on MySQL. Oracle writes NUMBER(*, s) for maximum precision.","SQLite accepts the declaration and then ignores it: column affinity decides storage per value, so a NUMERIC(5,2) column can hold 123456.789 as REAL."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(1234.567 AS NUMERIC(6, 2)) AS rounded;  -- 1234.57 on PostgreSQL; MySQL spells the target DECIMAL(6, 2)"},{"engine_slug":"postgresql","sql":"CREATE TABLE prices (amount NUMERIC(10, 2));  -- up to 99999999.99"},{"engine_slug":"sqlite","sql":"SELECT CAST(1234.567 AS NUMERIC(6, 2)) AS not_rounded;  -- 1234.567: the (6, 2) is ignored"},{"engine_slug":"mysql","sql":"SELECT CAST(1234.567 AS DECIMAL(6, 2)) AS rounded;  -- 1234.57: excess scale digits round"},{"engine_slug":"oracle","sql":"SELECT CAST(123.456 AS NUMBER(5, 2)) AS rounds_to_scale FROM dual;  -- 123.46"}],"faqs":[{"question":"What does NUMERIC(10, 2) hold?","answer":"Values up to 99999999.99: ten significant digits, two of them after the point. The scale costs two of the ten digits, a common miscount when sizing money columns."},{"question":"Is DECIMAL different from NUMERIC?","answer":"The standard lets DECIMAL(p, s) carry more precision than declared while NUMERIC(p, s) must be exactly p. In practice SQL Server, PostgreSQL, MySQL and SQLite treat them as synonyms, and Oracle maps both onto NUMBER."},{"question":"Why does SQLite ignore my NUMERIC(5, 2)?","answer":"SQLite's type system is affinity-based: the declaration only nudges storage class choice per value. Enforce scale with triggers, or keep cents as INTEGER."}],"related":["decimal-overflow","scale","numeric-vs-float","division-scale"],"novel_uses":[{"body":"SQL Server MONEY locks scale at 4 and truncates division to four places: CAST(2 AS money) / 3 returns 0.6666. DECIMAL(19, 4) stores the same values, and its division keeps extra digits: CAST(2 AS DECIMAL(19, 4)) / 3 returns 0.666666.","sql":"CREATE TABLE prices (amount DECIMAL(19, 4));"},{"body":"NUMERIC(25, 0) on PostgreSQL or DECIMAL(25, 0) on MySQL stores integers past the 64-bit range exactly, for payment-provider ids and similar oversized keys. Scale 0 keeps every value integral.","sql":"CREATE TABLE refs (external_id NUMERIC(25, 0));"}]},"source_url":"https://sqlly.app/sql-functions/numeric-precision-scale","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numeric-trunc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRUNCATE numeric function","description":"Truncate decimals without rounding: TRUNCATE in MySQL, TRUNC in PostgreSQL and Oracle, ROUND's third argument on SQL Server, and SQLite's trunc and CAST.","body":{"slug":"numeric-trunc","name":"TRUNCATE / TRUNC (numbers)","h1":"SQL TRUNCATE numeric function","category":"math","lede":"Cuts a number at a given decimal position and discards the rest, without rounding. It moves toward zero, so it differs from FLOOR on negative numbers.","syntax":"TRUNCATE(number, decimals)  -- MySQL  |  TRUNC(number [, decimals])  -- PostgreSQL, Oracle  |  ROUND(number, decimals, 1)  -- SQL Server","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"no TRUNC; ROUND(x, d, 1) truncates via the third argument"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"spelled TRUNCATE(x, d); the decimals argument is required"},{"engine_slug":"sqlite","status":"partial","note":"trunc(x) to a whole number (3.35+ math functions); CAST(x * 100 AS INTEGER) / 100.0 for 2 dp"},{"engine_slug":"oracle","status":"yes","note":"TRUNC(n, d), and the same name truncates dates"}],"gotchas":["TRUNC always discards: TRUNC(2.99, 1) is 2.9, not 3.0.","Negative decimals cut whole positions: TRUNC(1234, -2) is 1200 on PostgreSQL and Oracle, TRUNCATE(1234, -2) on MySQL, ROUND(1234, -2, 1) on SQL Server.","Oracle's TRUNC does double duty: TRUNC(date) cuts the time part, TRUNC(number) cuts decimals. Same name, different overloads."],"examples":[{"engine_slug":"mysql","sql":"SELECT TRUNCATE(123.4567, 2) AS cut;  -- 123.45"},{"engine_slug":"postgresql","sql":"SELECT TRUNC(123.4567, 2) AS cut;  -- 123.45"},{"engine_slug":"sql-server","sql":"SELECT ROUND(123.4567, 2, 1) AS cut;  -- 123.45"},{"engine_slug":"sqlite","sql":"SELECT CAST(123.4567 * 100 AS INTEGER) / 100.0 AS cut;  -- 123.45"},{"engine_slug":"oracle","sql":"SELECT TRUNC(123.4567, 2) AS cut FROM dual;  -- 123.45"}],"faqs":[{"question":"What is the difference between TRUNC and ROUND?","answer":"ROUND considers the dropped digit and may carry; TRUNC never does. TRUNC(-2.9, 0) is -2 (toward zero), while ROUND gives -3."},{"question":"How do I truncate instead of round in SQL Server?","answer":"ROUND takes an optional third argument, the documented function parameter: any non-zero value truncates instead of rounding, so ROUND(123.4567, 2, 1) is 123.4500. The result keeps the input's scale."}],"related":["round","floor","cast"],"novel_uses":[{"body":"Processors truncate fees rather than round them, so ROUND(amount * rate, 2) drifts a cent from the settlement file. TRUNC(amount * rate, 2) matches it exactly; SQL Server's form is ROUND(amount * rate, 2, 1).","sql":"SELECT TRUNC(amount * 0.029, 2) AS processor_fee\nFROM charges;"},{"body":"TRUNC(seconds / 60.0) counts only completed minutes, where CEIL counts started ones. The difference is a pricing policy, not a rounding accident, so choose deliberately and write it down. MySQL needs the .0 or you are truncating an integer that is already truncated.","sql":"SELECT TRUNCATE(duration_seconds / 60.0, 0) AS billed_minutes\nFROM calls;"}]},"source_url":"https://sqlly.app/sql-functions/numeric-trunc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numeric-vs-float","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NUMERIC vs FLOAT","description":"0.1 + 0.2 is exactly 0.3 in NUMERIC and 0.30000000000000004 in a double-precision FLOAT, the one choice that decides whether money and measurements round-trip.","body":{"slug":"numeric-vs-float","name":"NUMERIC vs FLOAT","h1":"SQL NUMERIC vs FLOAT","category":"math","lede":"Compares exact decimal types (NUMERIC, DECIMAL, NUMBER) with binary floats (FLOAT, DOUBLE, BINARY_DOUBLE): storage, speed, and the classic 0.1 + 0.2 mismatch.","syntax":"0.1 + 0.2 = 0.3  -- TRUE on NUMERIC, FALSE on FLOAT","return_type":"numeric or double","support":[{"engine_slug":"sql-server","status":"yes","note":"DECIMAL/NUMERIC exact; FLOAT (defaulting to 53 bits) approximate"},{"engine_slug":"postgresql","status":"yes","note":"numeric exact and arbitrary precision; double precision is IEEE 754 binary"},{"engine_slug":"mysql","status":"yes","note":"DECIMAL exact; DOUBLE approximate"},{"engine_slug":"sqlite","status":"yes","note":"No decimal type: everything non-integer is IEEE REAL; exactness needs INTEGER cents or an extension"},{"engine_slug":"oracle","status":"yes","note":"NUMBER is exact decimal; BINARY_DOUBLE is IEEE float"}],"gotchas":["The literal 0.1 is exact in a NUMERIC column but cannot exist in a float: the stored value is the nearest binary fraction, and adding two such values rounds to 0.30000000000000004.","Floats are fixed-size and computed in hardware; NUMERIC is software arithmetic but keeps decimal values exact. Money goes in NUMERIC/DECIMAL/NUMBER.","SQLite is the outlier: it has no decimal type, so store cents as integers or accept REAL rounding."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 0.1::numeric + 0.2::numeric = 0.3::numeric AS exact, 0.1::float8 + 0.2::float8 = 0.3::float8 AS approx;  -- true, false"},{"engine_slug":"mysql","sql":"SELECT 0.1 + 0.2 = 0.3 AS dec_eq, 0.1e0 + 0.2e0 = 0.3e0 AS dbl_eq;  -- 1, 0"},{"engine_slug":"sql-server","sql":"SELECT price * quantity FROM order_items;  -- DECIMAL math stays exact"},{"engine_slug":"sqlite","sql":"SELECT typeof(0.1) AS stored_as, 0.1 + 0.2 = 0.3 AS exact;  -- real, 0"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN 0.1 + 0.2 = 0.3 THEN 1 ELSE 0 END AS exact FROM dual;  -- 1: NUMBER is decimal-exact"}],"faqs":[{"question":"Why is 0.1 + 0.2 not 0.3 in SQL?","answer":"Because the columns are floats: binary floating point cannot represent 0.1 or 0.2 exactly, and the error compounds. In NUMERIC/DECIMAL columns on SQL Server, PostgreSQL and MySQL the same sum is exactly 0.3; SQLite stores both as REAL, so the sum stays approximate there."},{"question":"When should I use FLOAT instead of NUMERIC?","answer":"Scientific measurements, coordinates and rates, anything where 15-17 significant digits suffice and speed matters. Anything counted in currency or units that must balance: NUMERIC."},{"question":"Does SQLite have a NUMERIC type?","answer":"It has NUMERIC affinity but stores numeric values as INTEGER or IEEE REAL (non-numeric text stays TEXT): there is no true decimal storage. Keep money as integer cents in SQLite."}],"related":["double-precision","float-equality","decimal-literals","numeric-precision-scale"],"novel_uses":[{"body":"Two engines or two plans can produce floats one last bit apart, which splits GROUP BY and joins. Grouping on ROUND(x::numeric, 6) merges the near-identical values into one key.","sql":"SELECT ROUND(reading::numeric, 6) AS key, COUNT(*) FROM merged GROUP BY 1;"},{"body":"Float SUMs depend on the order rows arrive, so parallel plans can return totals that differ in the last cents between identical runs. NUMERIC adds in decimal and lands on the same total every time.","sql":"SELECT SUM(total::numeric) AS reproducible_total FROM invoices;"}]},"source_url":"https://sqlly.app/sql-functions/numeric-vs-float","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numtodsinterval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NUMTODSINTERVAL function","description":"NUMTODSINTERVAL in Oracle: turn a number plus a unit name (DAY, HOUR, MINUTE, SECOND) into a DAY TO SECOND interval, the column-safe literal builder.","body":{"slug":"numtodsinterval","name":"NUMTODSINTERVAL","h1":"SQL NUMTODSINTERVAL function","category":"datetime","lede":"Converts a numeric value in a named unit into an INTERVAL DAY TO SECOND, built for column-driven durations.","syntax":"NUMTODSINTERVAL(n, 'unit')","return_type":"interval day to second","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"make_interval(hours => n, mins => m, secs => s) for the multi-part form; hours and mins take integers, so fractions go in secs"},{"engine_slug":"mysql","status":"partial","note":"INTERVAL n unit keyword"},{"engine_slug":"sqlite","status":"no","note":"modifier strings built with ||"},{"engine_slug":"oracle","status":"yes","note":"this: accepts DAY, HOUR, MINUTE, SECOND"}],"gotchas":["Only four units: DAY, HOUR, MINUTE, SECOND. There is no WEEK unit, so write a week as NUMTODSINTERVAL(7 * n, 'DAY'). Months are year-to-month territory: NUMTOYMINTERVAL's job.","The number can be fractional or a column: NUMTODSINTERVAL(elapsed_seconds / 3600, 'HOUR'). The reason it exists over string-built literals.","Fractional results carry down: NUMTODSINTERVAL(1.5, 'DAY') is 1 day 12:00:00; NUMTODSINTERVAL(90, 'MINUTE') is 00 01:30:00."],"examples":[{"engine_slug":"oracle","sql":"SELECT SYSDATE + NUMTODSINTERVAL(90, 'MINUTE') FROM dual;"},{"engine_slug":"oracle","sql":"SELECT NUMTODSINTERVAL(1.5, 'DAY') FROM dual;  -- +01 12:00:00"},{"engine_slug":"postgresql","sql":"SELECT make_interval(days => 1, hours => 12);  -- same span"},{"engine_slug":"mysql","sql":"SELECT '2026-08-01 12:00:00' + INTERVAL 90 MINUTE;  -- 2026-08-01 13:30:00"}],"faqs":[{"question":"NUMTODSINTERVAL vs adding days numerically?","answer":"On a DATE, d + 90/1440 works in fractions of a day. On a TIMESTAMP, + 90/1440 silently converts the result to DATE and drops fractional seconds, while + NUMTODSINTERVAL(90, 'MINUTE') keeps it a TIMESTAMP."},{"question":"What is the PostgreSQL equivalent?","answer":"make_interval with named parts, or INTERVAL '90 minutes' literals when the value is static."}],"related":["numtoyminterval","make-interval","to-dsinterval","sec-to-time"],"novel_uses":[{"body":"An INTERVAL DAY TO SECOND column keeps elapsed values readable and lets predicates compare spans directly, with no unit convention buried in comments.","sql":"SELECT * FROM runs WHERE elapsed > NUMTODSINTERVAL(5, 'MINUTE');"},{"body":"Scale NUMTODSINTERVAL by LEVEL under CONNECT BY to print a grid of spaced timestamps from one SELECT.","sql":"SELECT SYSDATE + (LEVEL - 1) * NUMTODSINTERVAL(15, 'MINUTE') FROM dual CONNECT BY LEVEL <= 8;"}]},"source_url":"https://sqlly.app/sql-functions/numtodsinterval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/numtoyminterval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NUMTOYMINTERVAL function","description":"NUMTOYMINTERVAL in Oracle: turn a number of years or months into a YEAR TO MONTH interval, month arithmetic from column values.","body":{"slug":"numtoyminterval","name":"NUMTOYMINTERVAL","h1":"SQL NUMTOYMINTERVAL function","category":"datetime","lede":"Converts a numeric value in years or months into an INTERVAL YEAR TO MONTH.","syntax":"NUMTOYMINTERVAL(n, 'YEAR' | 'MONTH')","return_type":"interval year to month","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"make_interval(months => n)"},{"engine_slug":"mysql","status":"partial","note":"INTERVAL n MONTH keyword form"},{"engine_slug":"sqlite","status":"no","note":"n || ' months' modifier; no '+' prefix, which turns a negative n into NULL"},{"engine_slug":"oracle","status":"yes","note":"this, but unlike ADD_MONTHS it raises ORA-01839 when the start day does not exist in the target month"}],"gotchas":["Two units only: YEAR and MONTH. Fractions round to whole months: NUMTOYMINTERVAL(1.5, 'MONTH') is 2 months and NUMTOYMINTERVAL(1.4, 'MONTH') is 1, while NUMTOYMINTERVAL(1.5, 'YEAR') is 1 year 6 months.","Adding from the 29th to 31st to a shorter month errors: DATE '2026-01-31' + NUMTOYMINTERVAL(1, 'MONTH') raises ORA-01839, where ADD_MONTHS(DATE '2026-01-31', 1) returns 2026-02-28.","ADD_MONTHS also promotes month ends (2026-02-28 + 1 month gives 2026-03-31); the interval add gives 2026-03-28. Pick the spelling by the month-end behaviour you need."],"examples":[{"engine_slug":"oracle","sql":"SELECT ADD_MONTHS(SYSDATE, -6) FROM dual;  -- matches SYSDATE + NUMTOYMINTERVAL(-6, 'MONTH') except near month ends"},{"engine_slug":"oracle","sql":"SELECT SYSDATE + NUMTOYMINTERVAL(18, 'MONTH') FROM dual;"},{"engine_slug":"postgresql","sql":"SELECT now() + make_interval(months => 18);"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-08-01', INTERVAL 18 MONTH);  -- 2028-02-01"}],"faqs":[{"question":"Why pick NUMTOYMINTERVAL over ADD_MONTHS?","answer":"It produces an interval value you can store, add, average and compare; ADD_MONTHS only ever returns a shifted date. For contract lengths in columns, the interval is the data model."},{"question":"What about half months?","answer":"Not representable: the type is whole months. Express 15 days as a DAY TO SECOND interval instead, and accept that the two types cannot be added without casting to a finer granularity."}],"related":["numtodsinterval","to-yminterval","add-months","make-interval"],"novel_uses":[{"body":"One UPDATE converts legacy integer month counts into interval columns, after which comparisons and joins use the type instead of a convention.","sql":"UPDATE subs SET term = NUMTOYMINTERVAL(plan_months, 'MONTH');"},{"body":"Same-type intervals subtract directly, so applying elapsed months against the stored term yields the remainder with no EXTRACT arithmetic.","sql":"SELECT term - NUMTOYMINTERVAL(months_used, 'MONTH') FROM subs;"}]},"source_url":"https://sqlly.app/sql-functions/numtoyminterval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nvl","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NVL function","description":"NVL(expr, default) swaps NULL for a value in Oracle: how it differs from COALESCE (no short-circuit, first-argument typing), SQLite's IFNULL and portable alternatives.","body":{"slug":"nvl","name":"NVL","h1":"SQL NVL function","category":"conditional","lede":"Returns the second argument when the first is NULL, otherwise the first.","syntax":"NVL(expr, default) | NVL(commission_pct, 0)","return_type":"same as first argument","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"the only one of the five engines with NVL"}],"gotchas":["NVL evaluates both arguments; COALESCE short-circuits and stops at the first non-NULL, which matters when the default is expensive or has side effects.","NVL converts the second argument to the first argument's type: NVL(number_col, 'n/a') fails with ORA-01722 when it tries to turn 'n/a' into a number. COALESCE refuses mixed type families up front with ORA-00932.","Elsewhere: IFNULL in MySQL and SQLite, ISNULL in SQL Server, COALESCE everywhere."],"examples":[{"engine_slug":"oracle","sql":"SELECT NVL(commission_pct, 0) FROM employees;"},{"engine_slug":"oracle","sql":"SELECT NVL(NULL, 'fallback') FROM dual;"}],"faqs":[{"question":"NVL vs COALESCE in Oracle?","answer":"Two arguments versus many, eager versus short-circuit evaluation, and NVL's implicit conversion of the second argument versus COALESCE's same-type requirement. COALESCE is the standard and safer default."},{"question":"What is NVL in MySQL?","answer":"IFNULL(expr, default). It does the same NULL swap, but it short-circuits and types the result from both arguments, so IFNULL(int_col, 'n/a') returns 'n/a' where Oracle's NVL raises ORA-01722."},{"question":"Does NVL handle more than two values?","answer":"No; nest it or use COALESCE."}],"related":["nvl2","coalesce","ifnull","isnull","decode"],"novel_uses":[{"body":"Oracle reads '' as NULL, so NVL(note, 'no note') fills both missing and empty notes in one call; on the other engines COALESCE and IFNULL only fill true NULLs.","sql":"SELECT NVL(note, 'no note') FROM tasks;"},{"body":"Oracle sorts NULLs last ascending but first descending, so NVL(ship_date, DATE '0001-01-01') holds undelivered rows at the bottom of a newest-first list.","sql":"SELECT order_id FROM orders ORDER BY NVL(ship_date, DATE '0001-01-01') DESC;"}]},"source_url":"https://sqlly.app/sql-functions/nvl","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/nvl2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NVL2 function","description":"NVL2(expr, if_not_null, if_null) picks between two values based on whether expr is NULL: Oracle-only among the five, CASE and IIF equivalents, and argument-order gotchas.","body":{"slug":"nvl2","name":"NVL2","h1":"SQL NVL2 function","category":"conditional","lede":"Returns the second argument when the first is not NULL, the third when it is.","syntax":"NVL2(expr, r1, r2)","return_type":"type of r1 or r2","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"the only one of the five engines with NVL2"}],"gotchas":["Argument order trips people up: the not-NULL branch is the second argument, the NULL branch the third.","Only the NULL-ness of expr matters: its value is discarded, so NVL2 is a boolean branch, not a fallback chain.","The portable spelling is CASE WHEN expr IS NOT NULL THEN r1 ELSE r2 END; on SQL Server and SQLite, IIF(expr IS NOT NULL, r1, r2) is shorter."],"examples":[{"engine_slug":"oracle","sql":"SELECT NVL2(phone, 'listed', 'missing') FROM contacts;"},{"engine_slug":"oracle","sql":"SELECT NVL2(discount, price * discount, price) FROM orders;"}],"faqs":[{"question":"Which branch fires when expr is NULL?","answer":"The third argument; the second fires only when expr is not NULL."},{"question":"What is NVL2 in MySQL?","answer":"Nothing native: IF(expr IS NOT NULL, r1, r2) or CASE WHEN expr IS NOT NULL THEN r1 ELSE r2 END."},{"question":"NVL vs NVL2?","answer":"NVL substitutes a default for NULL; NVL2 chooses between two results based on NULL-ness."}],"related":["nvl","coalesce","case","decode","iif"],"novel_uses":[{"body":"The expression shows up in the second branch only, so a prefix and the value concatenate in one call and NULL rows stay NULL instead of 'tel: '.","sql":"SELECT NVL2(phone, 'tel: ' || phone, NULL) FROM contacts;"},{"body":"NVL2(approved_by, 'reviewed', 'pending') computes the status for a report from the data already there, one less column to keep in sync.","sql":"SELECT doc_id, NVL2(approved_by, 'reviewed', 'pending') AS status FROM documents;"}]},"source_url":"https://sqlly.app/sql-functions/nvl2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/object-id","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server OBJECT_ID function","description":"Use OBJECT_ID to test whether a table, view or procedure exists in SQL Server, plus the to_regclass, information_schema and sqlite_schema checks on other engines.","body":{"slug":"object-id","name":"OBJECT_ID","h1":"SQL Server OBJECT_ID function","category":"system","lede":"OBJECT_ID('dbo.orders', 'U') returns the table's object id, or NULL when no such table exists. It is the usual existence check in SQL Server scripts.","syntax":"OBJECT_ID('[database.][schema.]name' [, 'type'])","return_type":"int, or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"to_regclass('schema.name') returns NULL when missing"},{"engine_slug":"mysql","status":"no","note":"no function; query information_schema.tables"},{"engine_slug":"sqlite","status":"no","note":"no function; query sqlite_schema"},{"engine_slug":"oracle","status":"no","note":"no function; query user_objects or all_objects"}],"gotchas":["OBJECT_ID('orders') looks in the current database, in your default schema first and then in dbo. Qualify the name, OBJECT_ID('dbo.orders'), and pass a type ('U' table, 'V' view, 'P' procedure) so a view or procedure called orders does not pass for the table.","Temporary tables live in tempdb: OBJECT_ID('tempdb..#work') finds #work, while OBJECT_ID('#work') run from another database returns NULL.","For drop-if-exists, DROP TABLE IF EXISTS (SQL Server 2016+, PostgreSQL, MySQL, SQLite, Oracle 23ai) replaces the OBJECT_ID check.","PostgreSQL's to_regclass('orders') returns NULL for a missing table, while the cast 'orders'::regclass raises an error."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CASE WHEN OBJECT_ID('dbo.orders', 'U') IS NULL THEN 'missing' ELSE 'exists' END AS orders_table;"},{"engine_slug":"sql-server","sql":"CREATE TABLE #work (id INT);\nSELECT CASE WHEN OBJECT_ID('tempdb..#work') IS NULL THEN 0 ELSE 1 END AS in_tempdb;  -- 1"},{"engine_slug":"postgresql","sql":"SELECT to_regclass('public.orders') IS NOT NULL AS orders_exists;"},{"engine_slug":"sqlite","sql":"SELECT count(*) AS orders_exists FROM sqlite_schema WHERE type = 'table' AND name = 'orders';"}],"faqs":[{"question":"How do I check if a table exists in MySQL?","answer":"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'orders'."},{"question":"How do I check if a table exists in Oracle?","answer":"SELECT COUNT(*) FROM user_tables WHERE table_name = 'ORDERS'. Oracle stores unquoted names in upper case, so a lower-case literal finds nothing."}],"related":["current-schema","identifier-quoting","exists"],"novel_uses":[{"body":"Constraint names are schema-scoped objects, so OBJECT_ID finds them with a type letter: 'F' for a foreign key, 'PK' for a primary key, 'D' for a default. SQL Server 2016+ also has ALTER TABLE ... DROP CONSTRAINT IF EXISTS. The OBJECT_ID check is for older servers, or for branching on whether the constraint exists without dropping it.","sql":"IF OBJECT_ID('dbo.fk_orders_customer', 'F') IS NOT NULL\n  ALTER TABLE dbo.orders DROP CONSTRAINT fk_orders_customer;"},{"body":"to_regclass returns a regclass, which is an oid alias, so its result joins pg_class directly: one query goes from a name string to the relation's relkind and storage row without a name-lookup step.","sql":"SELECT c.relname, c.relkind\nFROM pg_class c\nWHERE c.oid = to_regclass('public.orders');"},{"body":"SQLite stores a table's name exactly as written and sqlite_schema comparisons are case-sensitive, so WHERE name = 'orders' misses a table created as Orders. Compare lower(name) = 'orders' in the existence check.","sql":"SELECT count(*) AS found\nFROM sqlite_schema\nWHERE type = 'table' AND lower(name) = 'orders';"}]},"source_url":"https://sqlly.app/sql-functions/object-id","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/octet-length","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OCTET_LENGTH function","description":"OCTET_LENGTH returns a string's size in bytes, the UTF-8 and encoding counterpart of character length, spelled DATALENGTH or LENGTHB elsewhere.","body":{"slug":"octet-length","name":"OCTET_LENGTH","h1":"SQL OCTET_LENGTH function","category":"string","lede":"Counts bytes, not characters. The number that matters for storage limits, index key lengths and wire size, and it diverges from CHAR_LENGTH on any accent.","syntax":"OCTET_LENGTH(string)  |  DATALENGTH(string)  |  LENGTHB(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATALENGTH is the byte counter; no OCTET_LENGTH"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"octet_length() from SQLite 3.43"},{"engine_slug":"oracle","status":"partial","note":"LENGTHB is the byte counter"}],"gotchas":["'héllo' is 5 characters and 6 bytes in UTF-8; an emoji is 1 character and 4 bytes. CHAR_LENGTH for display, OCTET_LENGTH for byte limits.","SQL Server's LEN ignores trailing spaces while DATALENGTH does not, and for nvarchar DATALENGTH counts 2 bytes per UTF-16 code unit: 2 for é or 中, but 4 for an emoji, a surrogate pair that LEN reports as 2 under the default collation.","Oracle's LENGTHB reflects the database charset: AL32UTF8 gives true UTF-8 byte counts; older single-byte charsets count 1 per character they can store.","MySQL's OCTET_LENGTH is an exact synonym of LENGTH, which is why MySQL's LENGTH surprises people who expect characters."],"examples":[{"engine_slug":"postgresql","sql":"SELECT OCTET_LENGTH('héllo') AS bytes, CHAR_LENGTH('héllo') AS chars;\n-- 6, 5"},{"engine_slug":"oracle","sql":"SELECT LENGTHB('é') AS bytes FROM dual;  -- 2"},{"engine_slug":"sql-server","sql":"SELECT LEN(N'ab') AS chars, DATALENGTH(N'ab') AS bytes;\n-- 2, 4"},{"engine_slug":"mysql","sql":"SET NAMES utf8mb4;\nSELECT OCTET_LENGTH('é') AS bytes, CHAR_LENGTH('é') AS chars;  -- 2, 1 (a latin1 connection gives 2, 2)"},{"engine_slug":"sqlite","sql":"SELECT octet_length('é') AS bytes, length('é') AS chars;  -- 2, 1 (octet_length from SQLite 3.43)"}],"faqs":[{"question":"When do I need bytes instead of characters?","answer":"Storage limits, index key lengths, VARCHAR(n) in byte semantics, and wire payloads all count bytes. Display widths and truncation count characters."},{"question":"What is the SQL Server version of OCTET_LENGTH?","answer":"DATALENGTH, but it measures the stored bytes of the value, so nvarchar data counts 2 bytes per UTF-16 code unit (an emoji is 4 bytes) and trailing spaces are included."},{"question":"Is OCTET_LENGTH ever the same as LENGTH?","answer":"Yes, for pure ASCII in a single-byte encoding: 1 byte per character. Accents, CJK and emoji break the equality."}],"related":["length","datalength","bit-length","varchar-char-semantics"],"novel_uses":[{"body":"PostgreSQL caps a b-tree entry near 2700 bytes, about a third of an 8 kB page, and InnoDB allows 3072 bytes per key on declared width. On PostgreSQL, summing OCTET_LENGTH predicts failure for incompressible keys before the CREATE INDEX (compressible values can still index). On InnoDB the sum of stored bytes does not predict it; add the declared column widths at 4 bytes per character for utf8mb4.","sql":"SELECT OCTET_LENGTH(col_a) + OCTET_LENGTH(col_b) AS key_bytes\nFROM t ORDER BY 1 DESC LIMIT 5;"},{"body":"Byte length is what API limits count, so a WHERE on OCTET_LENGTH(body) finds the emoji-heavy rows a 64 kB webhook will bounce even though CHAR_LENGTH looks fine.","sql":"SELECT id FROM payloads WHERE OCTET_LENGTH(body) > 65536;"}]},"source_url":"https://sqlly.app/sql-functions/octet-length","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/openjson","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OPENJSON function","description":"SQL Server's OPENJSON turns a JSON array or object into rows and columns: WITH-schema shredding for arrays of objects, key-value triples without one.","body":{"slug":"openjson","name":"OPENJSON","h1":"SQL OPENJSON function","category":"string","lede":"FROM OPENJSON(@items) WITH (sku nvarchar(40), qty int) reads a JSON array as a table. Use CROSS APPLY to shred a JSON column row by row.","syntax":"OPENJSON(json_doc [, path]) [WITH (column_defs)]","return_type":"rowset","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"jsonb_to_recordset or jsonb_populate_recordset"},{"engine_slug":"mysql","status":"no","note":"JSON_TABLE"},{"engine_slug":"sqlite","status":"no","note":"json_each"},{"engine_slug":"oracle","status":"no","note":"JSON_TABLE"}],"gotchas":["Without WITH you get three columns: key, value (nvarchar) and type (0 null, 1 string, 2 number, 3 boolean, 4 array, 5 object). With WITH, the declared columns and paths take over.","OPENJSON needs database compatibility level 130 or higher; on a database still at 120 it fails with Invalid object name 'OPENJSON' (or a syntax error near WITH) even on a new server.","It is a table-valued function: put it in FROM, or CROSS APPLY it per row to shred a JSON column of the outer table.","The second argument is the path root: OPENJSON(@doc, '$.items') shreds the nested array directly instead of the whole document."],"examples":[{"engine_slug":"sql-server","sql":"DECLARE @items nvarchar(max) = N'[{\"sku\":\"A1\",\"qty\":2},{\"sku\":\"B2\",\"qty\":5}]';\nSELECT *\nFROM OPENJSON(@items)\nWITH (sku nvarchar(40) '$.sku',\n      qty int '$.qty');"},{"engine_slug":"sql-server","sql":"DECLARE @config nvarchar(max) = N'{\"region\":\"eu\",\"tags\":[\"a\"],\"n\":3}';\nSELECT [key], [value], [type]\nFROM OPENJSON(@config);  -- types 1, 4, 2"},{"engine_slug":"sql-server","sql":"SELECT o.id, i.sku, i.qty\nFROM orders o\nCROSS APPLY OPENJSON(o.items)\nWITH (sku nvarchar(40) '$.sku', qty int '$.qty') i;"}],"faqs":[{"question":"OPENJSON or JSON_TABLE?","answer":"The same job in two dialects: OPENJSON is T-SQL, JSON_TABLE is the SQL standard (Oracle, MySQL, PostgreSQL 17). Porting means rewriting the COLUMNS clause either way."},{"question":"Why are all my OPENJSON columns nvarchar?","answer":"You omitted the WITH clause, so OPENJSON returned its generic schema. Add WITH (col type '$.path', ...) to get typed columns."}],"related":["json-table","json-value","json-query","json-each"],"novel_uses":[{"body":"The WITH-less mode is made for this: GROUP BY type over the generic rows shows whether an 'all numbers' array secretly holds strings or nulls. One statement, no parsing logic.","sql":"SELECT [type], COUNT(*) AS n FROM OPENJSON(@doc) GROUP BY [type];"},{"body":"A column declared AS JSON keeps the nested fragment as JSON text, so a second CROSS APPLY OPENJSON shreds it without re-parsing the outer document. Chained applies beat one giant WITH for nested arrays.","sql":"SELECT o.id, i.items, t.sku FROM orders o CROSS APPLY OPENJSON(o.doc) WITH (items nvarchar(max) '$.items' AS JSON) i CROSS APPLY OPENJSON(i.items) WITH (sku nvarchar(40) '$.sku') t;"}]},"source_url":"https://sqlly.app/sql-functions/openjson","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/operator-precedence","corpus":"sql-functions","engine":null,"language":"en","title":"SQL operator precedence","description":"Unary minus binds tightest, then * / %, then + -. PostgreSQL's ^ sits between unary minus and *, so -2 ^ 2 is 4, and ^ runs left to right.","body":{"slug":"operator-precedence","name":"precedence","h1":"SQL operator precedence","category":"math","lede":"The order in which SQL evaluates mixed math operators: unary sign first, then multiply/divide/modulo, then add/subtract, and parentheses beat everything.","syntax":"a + b * c  |  (a + b) * c  |  -2 ^ 2  -- PostgreSQL: 4","return_type":"n/a","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"^ (power) sits below unary minus and above * /, and is left-associative: 2 ^ 3 ^ 2 is 64"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Plain four-operator precedence plus %; no power operator at all"},{"engine_slug":"oracle","status":"yes","note":"No % and no power operator in SQL; MOD and POWER are functions, so only + - * / and unary sign apply"}],"gotchas":["* / % always beat + -: SELECT 2 + 3 * 4 returns 14, not 20, on every engine.","PostgreSQL's ^ breaks schoolbook order: unary minus binds first, so -2 ^ 2 is 4 (Python's ** gives -4), and 2 ^ 3 ^ 2 is (2 ^ 3) ^ 2 = 64 rather than 512.","Division and modulo share one level and evaluate left to right: 100 / 10 % 3 is (100 / 10) % 3 = 1."],"examples":[{"engine_slug":"all","sql":"SELECT 2 + 3 * 4 AS fourteen, (2 + 3) * 4 AS twenty;  -- 14, 20"},{"engine_slug":"postgresql","sql":"SELECT -2 ^ 2 AS four, -(2 ^ 2) AS minus_four, 2 ^ 3 ^ 2 AS sixty_four;  -- 4, -4, 64"},{"engine_slug":"sql-server","sql":"SELECT 100 / 10 % 3 AS left_to_right;  -- 1"},{"engine_slug":"oracle","sql":"SELECT 2 + 3 * 4 AS fourteen, (2 + 3) * 4 AS twenty FROM dual;  -- 14, 20"}],"faqs":[{"question":"What is the order of operations in SQL?","answer":"Unary minus/plus, then PostgreSQL's ^ where it applies, then * / %, then + -, all left-to-right within a level. Parentheses override everything and cost nothing."},{"question":"Does ^ bind tighter than unary minus?","answer":"No, not on PostgreSQL: -2 ^ 2 is 4 because the minus applies to 2 first. Write -(2 ^ 2) when you mean -4. On SQL Server, ^ is XOR and shares a level with + and -, left to right. On MySQL, ^ is also XOR but binds tighter than * and +, so 1 + 3 ^ 1 is 3."},{"question":"Is it safe to rely on precedence?","answer":"For a * b + c, yes: every reader knows it. For expressions mixing power, negation and division across engines, add parentheses: they document intent and prevent cross-dialect surprises."}],"related":["arithmetic-operators","exponent-operator","integer-division"],"novel_uses":[{"body":"9 / 2 * 3 is 12 on SQL Server, PostgreSQL and SQLite, because 9 / 2 truncates first. Writing 9 * 3 / 2 gives 13 and keeps more of the value; reorder integer chains so multiplication runs first.","sql":"SELECT 9 / 2 * 3 AS loses, 9 * 3 / 2 AS keeps;  -- 12, 13"},{"body":"T-SQL binds & ^ | at the same level as + and -, so 12 & 1 + 2 parses as (12 & 1) + 2, not the 12 & 3 a C programmer expects. Parentheses cost nothing and remove the whole class of bug.","sql":"SELECT 12 & 1 + 2 AS tsql_reading, 12 & (1 + 2) AS intended;  -- 2, 0"}]},"source_url":"https://sqlly.app/sql-functions/operator-precedence","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/oracle-analytic-functions","corpus":"sql-functions","engine":null,"language":"en","title":"Oracle analytic window functions","description":"Oracle shipped window functions as 'analytic functions' in 8i (1999) and has the widest clause support of the five, plus the quirks to know.","body":{"slug":"oracle-analytic-functions","name":"Oracle Analytic Functions","h1":"Oracle analytic window functions","category":"window","lede":"Oracle's analytic functions are window functions by another name, with ROWS/RANGE/GROUPS frames, IGNORE NULLS and Oracle-only extras such as KEEP and RATIO_TO_REPORT.","syntax":"SUM(x) OVER (PARTITION BY g ORDER BY d RANGE BETWEEN INTERVAL '1' DAY PRECEDING AND CURRENT ROW)","return_type":"per-partition value","support":[{"engine_slug":"sql-server","status":"partial","note":"OVER windows yes; KEEP and RATIO_TO_REPORT no"},{"engine_slug":"postgresql","status":"partial","note":"OVER windows yes; KEEP and RATIO_TO_REPORT no"},{"engine_slug":"mysql","status":"partial","note":"OVER windows yes; KEEP and RATIO_TO_REPORT no"},{"engine_slug":"sqlite","status":"partial","note":"OVER windows yes; KEEP and RATIO_TO_REPORT no"},{"engine_slug":"oracle","status":"yes","note":"analytic clauses on most aggregates; keyword orders differ from other engines (x IGNORE NULLS, LISTAGG ... WITHIN GROUP)"}],"gotchas":["Oracle treats NULL as larger than any value: last ascending, first descending. PostgreSQL does the same; SQL Server, MySQL and SQLite do the opposite.","Oracle accepts IGNORE NULLS inside the parentheses, FIRST_VALUE(x IGNORE NULLS), as well as after them; LISTAGG takes WITHIN GROUP (ORDER BY ...) before an OVER that may hold only PARTITION BY.","RANGE frames accept INTERVAL literals and NUMTODSINTERVAL for calendar windows. GROUPS, EXCLUDE and the WINDOW clause need 21c or later, so 19c code cannot use them."],"examples":[{"engine_slug":"oracle","sql":"SELECT department, employee_name, salary,\n       SUM(salary) OVER (PARTITION BY department ORDER BY hire_date) AS running_payroll,\n       RATIO_TO_REPORT(salary) OVER (PARTITION BY department) AS salary_share\nFROM employees;"}],"faqs":[{"question":"What is the difference between aggregate and analytic in Oracle?","answer":"Only whether OVER is present: SUM(x) collapses rows, SUM(x) OVER (...) keeps them. Oracle's analytic forms include the KEEP aggregates, which none of the others have. PERCENTILE_CONT also works OVER on SQL Server but not on PostgreSQL, MySQL or SQLite, and COUNT(DISTINCT x) OVER is rejected by all four others."},{"question":"Why do my Oracle windows sort NULLs differently?","answer":"Oracle sorts NULLs last when ascending and first when descending, treating NULL as larger than everything. SQL Server, MySQL and SQLite treat it as smaller, so the same query puts NULLs at the other end. PostgreSQL and SQLite accept NULLS FIRST/LAST, but SQL Server and MySQL reject it; there, use ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x to put NULLs last."}],"related":["window-nulls-order","ratio-to-report","oracle-keep-dense-rank"],"novel_uses":[{"body":"NUMTODSINTERVAL reaches below one second, so a RANGE frame of half a second counts the ticks clustered around each trade: burst detection for market data feeds. PostgreSQL, MySQL and SQLite also take sub-second RANGE offsets (INTERVAL '0.5 second' on PostgreSQL, INTERVAL 0.5 SECOND on MySQL, a plain 0.5 on SQLite and MySQL); only SQL Server cannot.","sql":"SELECT trade_ts, price,\n       COUNT(*) OVER (ORDER BY trade_ts\n         RANGE BETWEEN NUMTODSINTERVAL(0.5, 'SECOND') PRECEDING\n                   AND CURRENT ROW) AS ticks_last_half_second\nFROM trades;"},{"body":"The analytic form of KEEP puts the winner's value on every row of the partition: MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) OVER (PARTITION BY department) is the veteran's salary next to each employee. No CTE, no join, no FIRST_VALUE gymnastics.","sql":"SELECT department, employee_name, salary,\n       MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date)\n         OVER (PARTITION BY department) AS veteran_salary\nFROM employees;"}]},"source_url":"https://sqlly.app/sql-functions/oracle-analytic-functions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/oracle-keep-dense-rank","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Oracle KEEP DENSE_RANK","description":"Oracle's KEEP clause: a value from the first or last row by some other ordering, as an aggregate or analytic, Oracle's arg_min and arg_max.","body":{"slug":"oracle-keep-dense-rank","name":"KEEP DENSE_RANK","h1":"SQL Oracle KEEP DENSE_RANK","category":"window","lede":"KEEP (DENSE_RANK FIRST/LAST ORDER BY ...) keeps only the tie-winning rows of a group and aggregates over them: arg_min/arg_max as a first-class clause.","syntax":"MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) OVER (PARTITION BY g)","return_type":"type of the aggregate","support":[{"engine_slug":"sql-server","status":"no","note":"no equivalent; ROW_NUMBER = 1 in a CTE"},{"engine_slug":"postgresql","status":"no","note":"no equivalent; DISTINCT ON or ROW_NUMBER"},{"engine_slug":"mysql","status":"no","note":"no equivalent; ROW_NUMBER in a CTE"},{"engine_slug":"sqlite","status":"no","note":"no equivalent; ROW_NUMBER in a CTE"},{"engine_slug":"oracle","status":"yes","note":"Oracle-only clause, aggregate and analytic forms"}],"gotchas":["The aggregate inside KEEP supplies the value: MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) is 'the salary of the earliest hire', FIRST_VALUE without keeping rows, and it composes with GROUP BY.","DENSE_RANK is mandatory wording (KEEP FIRST/LAST alone is invalid). When several rows tie for first, all of them feed the outer aggregate, so MAX and MIN can return different answers; that is how ties are made explicit.","Elsewhere, FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY hire_date) gives the same value on every row, or ROW_NUMBER() = 1 in a CTE gives one row per group. PostgreSQL can also use DISTINCT ON."],"examples":[{"engine_slug":"oracle","sql":"-- salary of the earliest and latest hire per department\nSELECT department,\n       MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) AS veteran_salary,\n       MAX(salary) KEEP (DENSE_RANK LAST ORDER BY hire_date) AS newest_salary\nFROM employees\nGROUP BY department;"},{"engine_slug":"all","sql":"-- portable equivalent of the first column (ties broken arbitrarily)\nSELECT department, salary AS veteran_salary\nFROM (\n  SELECT department, salary,\n         ROW_NUMBER() OVER (PARTITION BY department ORDER BY hire_date) AS rn\n  FROM employees\n) t\nWHERE rn = 1;"}],"faqs":[{"question":"What is Oracle's equivalent of arg_min?","answer":"MAX(value) KEEP (DENSE_RANK FIRST ORDER BY sort_col): the value that goes with the smallest sort key. FIRST_VALUE gives the same answer over a window when the sort key has no ties; with ties it returns one of the tied rows, while KEEP aggregates over all of them. KEEP also works in plain GROUP BY queries."},{"question":"Why DENSE_RANK and not RANK in the KEEP clause?","answer":"The clause is defined as KEEP (DENSE_RANK FIRST|LAST ORDER BY ...), and DENSE_RANK keeps every tied row, so all of them feed the outer aggregate."}],"related":["first-value","oracle-analytic-functions","top-n-per-group"],"novel_uses":[{"body":"MIN(updated_by) KEEP (DENSE_RANK LAST ORDER BY updated_at) names whoever made the most recent update, with the MIN tiebreak picking alphabetically when two edits share a timestamp. Arg-max over audit columns is what this clause was built for.","sql":"SELECT record_key,\n       MIN(updated_by) KEEP (DENSE_RANK LAST ORDER BY updated_at) AS latest_editor,\n       MAX(updated_at) AS last_change\nFROM revisions\nGROUP BY record_key;"},{"body":"Add a second ORDER BY column inside KEEP and the winner is defined even when the primary key ties: ORDER BY score DESC, created_at takes the earliest among equals. The equivalent ROW_NUMBER query needs the same tiebreak anyway, so KEEP is the shorter spelling.","sql":"SELECT contestant_id,\n       MAX(entry_time) KEEP (DENSE_RANK FIRST ORDER BY score DESC, created_at) AS winning_entry_time\nFROM entries\nGROUP BY contestant_id;"}]},"source_url":"https://sqlly.app/sql-functions/oracle-keep-dense-rank","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ord","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ORD function","description":"How ORD returns a character's code in MySQL: multi-byte characters combined byte by byte, the difference from ASCII, and how to get a real code point with utf32.","body":{"slug":"ord","name":"ORD","h1":"SQL ORD function","category":"string","lede":"Returns the code of the leftmost character of a string, combining all of its bytes for multi-byte characters.","syntax":"ORD(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No ORD; UNICODE returns the code point for BMP characters, but only the high surrogate for emoji (55357 for \uD83D\uDE00)."},{"engine_slug":"postgresql","status":"no","note":"No ORD; ascii() returns the code point."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No ORD; unicode() returns the code point."},{"engine_slug":"oracle","status":"partial","note":"ASCII returns the same byte-combined value."}],"gotchas":["For a multi-byte character ORD combines the bytes: (first byte × 256) + second byte, and so on. ORD('é') in utf8mb4 is 50089 (0xC3A9), not the code point 233.","For single-byte characters ORD equals ASCII. It reads only the first character; pair it with SUBSTR to step through a string.","ORD('') is 0 and ORD(NULL) is NULL, like ASCII."],"examples":[{"engine_slug":"mysql","sql":"SELECT ORD('A') AS code, ORD('é') AS utf8_code;  -- 65, 50089"},{"engine_slug":"mysql","sql":"SELECT ORD(CONVERT(SUBSTR(col, 1, 1) USING utf32)) AS code_point\nFROM items;"},{"engine_slug":"oracle","sql":"SELECT ASCII('é') AS code\nFROM dual;  -- 50089"}],"faqs":[{"question":"How is ORD different from ASCII in MySQL?","answer":"ASCII returns only the first byte (195 for é); ORD combines all the bytes of the first character (50089). Neither is the code point. ORD(CONVERT(c USING utf32)) returns 233, because UTF-32 stores the code point directly."},{"question":"What is the equivalent in other engines?","answer":"UNICODE() in SQLite and ascii() in PostgreSQL return code points. SQL Server's UNICODE() returns the code point only for characters in the Basic Multilingual Plane; for emoji it returns the high surrogate (55357 for \uD83D\uDE00). Oracle's ASCII returns the same byte-combined value as ORD."}],"related":["ascii","unicode","chr","substr"],"novel_uses":[{"body":"In utf8mb4 any multi-byte first character pushes ORD above 127, so one comparison finds rows whose values start outside ASCII, usually an import or encoding problem.","sql":"SELECT id FROM products\nWHERE ORD(name) > 127;"},{"body":"ORD between 48 and 57 proves the first character is a digit. It reads only the first character, so pair it with a length or pattern check before trusting the rest.","sql":"SELECT id FROM parts\nWHERE ORD(code) BETWEEN 48 AND 57;"}]},"source_url":"https://sqlly.app/sql-functions/ord","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ordered-set-aggregates","corpus":"sql-functions","engine":null,"language":"en","title":"SQL WITHIN GROUP clause","description":"WITHIN GROUP (ORDER BY ...) feeds ordered-set aggregates like PERCENTILE_CONT, PERCENTILE_DISC and mode(): PostgreSQL and Oracle support, SQL Server's mix, MySQL gap.","body":{"slug":"ordered-set-aggregates","name":"WITHIN GROUP","h1":"SQL WITHIN GROUP clause","category":"aggregate","lede":"The clause that hands an aggregate a sorted input, powering percentiles, modes and hypothetical ranks.","syntax":"PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) | mode() WITHIN GROUP (ORDER BY x)","return_type":"depends on the aggregate","support":[{"engine_slug":"sql-server","status":"partial","note":"PERCENTILE_CONT and PERCENTILE_DISC need OVER; STRING_AGG and APPROX_PERCENTILE_CONT/DISC (2022+) take WITHIN GROUP as plain aggregates"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no WITHIN GROUP; emulate with window functions"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The syntax is function(args) WITHIN GROUP (ORDER BY col): the ordering lives outside the parentheses, unlike every normal aggregate.","Percentiles and mode() take exactly one ORDER BY expression; the function's own arguments carry parameters like the fraction. LISTAGG and STRING_AGG accept a multi-column ORDER BY.","Hypothetical-set forms (RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST with arguments) also use WITHIN GROUP.","MySQL has no ordered-set aggregates. SQLite 3.51 builds with SQLITE_ENABLE_PERCENTILE offer median(x) and percentile_cont(x, p) as plain functions, without WITHIN GROUP."],"examples":[{"engine_slug":"postgresql","sql":"SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY ms) FROM requests;"},{"engine_slug":"oracle","sql":"SELECT PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY ms) FROM requests;"},{"engine_slug":"postgresql","sql":"SELECT mode() WITHIN GROUP (ORDER BY status) FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT APPROX_PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ms) FROM requests;"}],"faqs":[{"question":"Why does WITHIN GROUP exist?","answer":"Some aggregates need their input sorted first; the clause says which column to sort, separate from the function's own arguments."},{"question":"Which engines support it?","answer":"PostgreSQL and Oracle fully. SQL Server for STRING_AGG and the APPROX_PERCENTILE functions as plain aggregates, and for PERCENTILE_CONT/DISC only with OVER. MySQL and SQLite not at all."},{"question":"Can I put multiple columns in the ORDER BY?","answer":"Not for percentiles or mode(), which need exactly one sort expression. String aggregates such as LISTAGG and STRING_AGG accept several, and hypothetical-set functions take one per argument."}],"related":["percentile-cont","percentile-disc","median","mode","hypothetical-set"],"novel_uses":[{"body":"STRING_AGG in SQL Server and LISTAGG in Oracle take WITHIN GROUP (ORDER BY ...) for sorted concatenation, no subquery wrapped around the aggregate.","sql":"SELECT dept_id, STRING_AGG(name, ',') WITHIN GROUP (ORDER BY name) FROM employees GROUP BY dept_id;"},{"body":"SQL Server pairs WITHIN GROUP with OVER so each row carries its partition's median; PostgreSQL rejects OVER on ordered-set aggregates, so compute the median per group and join it back.","sql":"SELECT emp_id, dept_id, salary, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY dept_id) AS dept_median FROM employees;"}]},"source_url":"https://sqlly.app/sql-functions/ordered-set-aggregates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/over-clause","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OVER clause","description":"The OVER clause decoded: empty, PARTITION BY, ORDER BY and frame, the four building blocks every window function is made of.","body":{"slug":"over-clause","name":"OVER Clause","h1":"SQL OVER clause","category":"window","lede":"OVER defines which rows a window function sees: an empty OVER () covers the whole result, PARTITION BY splits it, ORDER BY orders each split, and a frame bounds it further.","syntax":"fn() OVER () | fn() OVER (PARTITION BY g) | fn() OVER (PARTITION BY g ORDER BY d [frame])","return_type":"per-row aggregate or rank","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; full frames since 3.28"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The three shapes mean different things: no ORDER BY and no frame gives the whole partition; ORDER BY without a frame gives the default RANGE frame to the current row; an explicit frame overrides both.","The named WINDOW clause (WINDOW w AS (...), then OVER w) works on all five current engines, but arrived late on two: SQL Server 2022 and Oracle 21c. Older versions of both need every OVER written inline.","An aggregate with OVER keeps every row; the same aggregate without OVER collapses them. The only syntactic difference is the OVER clause itself."],"examples":[{"engine_slug":"all","sql":"SELECT employee_id, department, salary,\n       COUNT(*) OVER () AS total_employees,\n       COUNT(*) OVER (PARTITION BY department) AS dept_employees,\n       SUM(salary) OVER (PARTITION BY department ORDER BY salary) AS running_dept\nFROM employees;"}],"faqs":[{"question":"What does an empty OVER () mean?","answer":"The frame is the entire result set: every row sees every row. COUNT(*) OVER () is the total row count, SUM(x) OVER () the grand total (handy for shares and percentages)."},{"question":"Do I always need ORDER BY inside OVER?","answer":"For ROW_NUMBER, RANK and LAG/LEAD, SQL Server and Oracle require it; PostgreSQL, MySQL and SQLite accept ROW_NUMBER() OVER () but number rows in whatever order they arrive. Aggregates accept it optionally, and adding it changes the default frame from the whole partition to a running one."}],"related":["partition-by","over-order-by","window-default-frame"],"novel_uses":[{"body":"One SELECT can carry a month-partitioned total and a day-ordered running total side by side; the two OVER clauses describe two different windows over the same rows. This is how day reports show context without a self-join. PostgreSQL spelling for the month bucket.","sql":"SELECT day, amount,\n       SUM(amount) OVER (PARTITION BY DATE_TRUNC('month', day)) AS month_total,\n       SUM(amount) OVER (ORDER BY day) AS running_total\nFROM daily_sales;"},{"body":"Compare a windowed total against the number the ledger claims and stamp each row with ok or drift. The flag costs one window and turns reconciliation into a filterable column.","sql":"SELECT entry_id, amount,\n       CASE WHEN SUM(amount) OVER () = 15000 THEN 'ok' ELSE 'drift' END AS recon\nFROM entries;"}]},"source_url":"https://sqlly.app/sql-functions/over-clause","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/over-order-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ORDER BY inside OVER","description":"ORDER BY inside OVER ranks rows and turns aggregates into running ones, a different sort from the query's final ORDER BY.","body":{"slug":"over-order-by","name":"ORDER BY in OVER","h1":"SQL ORDER BY inside OVER","category":"window","lede":"Orders rows within each partition: it defines ROW_NUMBER sequence, tie behaviour and the default frame for aggregates.","syntax":"ROW_NUMBER() OVER (ORDER BY d) | SUM(x) OVER (ORDER BY d)","return_type":"per-row value","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Adding ORDER BY to an aggregate changes its meaning: SUM(x) OVER (PARTITION BY g) is the group total, SUM(x) OVER (PARTITION BY g ORDER BY d) is a running total; the frame appears silently.","With ORDER BY and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes peers (the root of the LAST_VALUE surprise).","Multiple window functions in one SELECT can each carry a different ORDER BY; each distinct ordering usually costs its own sort."],"examples":[{"engine_slug":"all","sql":"SELECT day, price,\n       ROW_NUMBER() OVER (ORDER BY day) AS rn,\n       MAX(price) OVER (ORDER BY day) AS running_max\nFROM prices;"}],"faqs":[{"question":"Is ORDER BY required inside OVER?","answer":"On SQL Server and Oracle, yes for ranking functions and LAG/LEAD ('must have an OVER clause with ORDER BY', ORA-30485). PostgreSQL, MySQL and SQLite run them without it, in an arbitrary order, which is rarely what you want. Aggregates work without it and then cover the whole partition."},{"question":"Does OVER (ORDER BY ...) replace the outer ORDER BY?","answer":"No. The inner one orders the window logic only; the final result order is undefined unless the query ends with its own ORDER BY."}],"related":["over-vs-order-by","window-default-frame","deterministic-window-order"],"novel_uses":[{"body":"Order the window descending and the default frame covers the current row through the end: MIN(closing_price) OVER (ORDER BY day DESC) is the smallest close from today onward. A later day lower than today shows up as min_close_onward below the current close, with no self-join and no LEAD.","sql":"SELECT day, closing_price,\n       MIN(closing_price) OVER (ORDER BY day DESC) AS min_close_onward\nFROM prices;"},{"body":"The OVER ORDER BY takes expressions, so ROW_NUMBER can rank on score * weight without materializing the blend. Keep the expression identical everywhere you need the same order, or store it in a CTE column first.","sql":"SELECT contestant_id,\n       ROW_NUMBER() OVER (ORDER BY score * weight DESC) AS rank_by_blend\nFROM contestants;"}]},"source_url":"https://sqlly.app/sql-functions/over-order-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/over-vs-order-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OVER ORDER BY vs outer ORDER BY","description":"Two ORDER BYs, two jobs: one orders rows inside each window, the other sorts the result set; mixing them up produces wrong ranks or shuffled output.","body":{"slug":"over-vs-order-by","name":"OVER ORDER BY vs Outer ORDER BY","h1":"SQL OVER ORDER BY vs outer ORDER BY","category":"window","lede":"OVER (ORDER BY x) defines the logical order within partitions for window computation; the query's ORDER BY sorts the final rows. Neither implies the other.","syntax":"SELECT ..., ROW_NUMBER() OVER (ORDER BY x) AS rn FROM t ORDER BY other_col","return_type":"n/a (clause semantics)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["A window function such as ROW_NUMBER can appear in a query level's SELECT list and ORDER BY, but not in that level's WHERE, GROUP BY or HAVING; to filter on a rank, compute it in a derived table and filter in the outer WHERE.","Removing the outer ORDER BY means the result can come back in any order, even though ROW_NUMBER was computed over an order. Ranks are values, not a row guarantee.","If the outer ORDER BY matches the window's PARTITION BY and ORDER BY, PostgreSQL, SQL Server and SQLite reuse the window's sort instead of sorting twice; MySQL 8.4 sorts the window output again either way."],"examples":[{"engine_slug":"all","sql":"SELECT department, employee_id, salary,\n       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank\nFROM employees\nORDER BY department, dept_rank;"}],"faqs":[{"question":"Why are my ranked rows not in rank order?","answer":"You ranked inside OVER but never sorted the result: window ORDER BY does not order output. Add an outer ORDER BY on the rank (or the base column) to display in order."},{"question":"Can the two ORDER BYs differ?","answer":"Yes, and sometimes should: rank by amount descending but present alphabetically. The window order controls the numbers; the outer order controls the rows you see."}],"related":["over-order-by","deterministic-window-order","window-clause"],"novel_uses":[{"body":"Ordering by a partitioned COUNT sorts detail rows into group blocks, biggest block first, while every row survives. It is a presentation trick GROUP BY cannot do because it would delete the rows you are presenting.","sql":"SELECT department, employee_id,\n       COUNT(*) OVER (PARTITION BY department) AS dept_size\nFROM employees\nORDER BY dept_size DESC, department, employee_id;"},{"body":"The final ORDER BY may read a window column, so amount minus LAG(amount) ordered descending puts the biggest day-over-day jumps on top with no CTE. The first day has no previous row, so its move is NULL, and PostgreSQL sorts NULL first under DESC; the CASE key pushes it below the real moves on every engine. Ordering by the bare alias moves is the portable spelling.","sql":"SELECT day, amount, move\nFROM (\n  SELECT day, amount,\n         amount - LAG(amount) OVER (ORDER BY day) AS move\n  FROM daily_sales\n) t\nORDER BY CASE WHEN move IS NULL THEN 1 ELSE 0 END, move DESC;"}]},"source_url":"https://sqlly.app/sql-functions/over-vs-order-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/over-with-group-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OVER combined with GROUP BY","description":"Window functions run after GROUP BY, so they aggregate the groups: SUM(SUM(x)) OVER () and running group totals in a single query.","body":{"slug":"over-with-group-by","name":"OVER with GROUP BY","h1":"SQL OVER combined with GROUP BY","category":"window","lede":"When a query has GROUP BY, window functions see the grouped rows: one pass for group aggregates plus totals or trends across groups.","syntax":"SELECT g, SUM(x), SUM(SUM(x)) OVER () FROM t GROUP BY g","return_type":"per-group rows with window values","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The nested-looking SUM(SUM(x)) is correct: the inner SUM(x) is the GROUP BY aggregate, the outer one windows over the group results. SUM(x) OVER () fails here because x is neither grouped nor aggregated on PostgreSQL, SQL Server and MySQL (ONLY_FULL_GROUP_BY, the default). SQLite accepts it and returns an arbitrary x per group, so the total is wrong (4 here, not 6).","PARTITION BY / ORDER BY in the window must reference grouped columns or aggregates of them; referencing a raw non-grouped column errors on PostgreSQL, SQL Server and MySQL (ONLY_FULL_GROUP_BY). SQLite accepts it silently and picks an arbitrary value per group.","This ordering (WHERE, then GROUP BY, then windows, then outer ORDER BY) is also why HAVING cannot filter window results."],"examples":[{"engine_slug":"postgresql","sql":"SELECT department, SUM(salary) AS payroll,\n       SUM(SUM(salary)) OVER (ORDER BY department) AS cumulative_payroll,\n       100.0 * SUM(salary) / SUM(SUM(salary)) OVER () AS payroll_share\nFROM employees\nGROUP BY department\nORDER BY department;"},{"engine_slug":"sql-server","sql":"SELECT department, SUM(salary) AS payroll,\n       SUM(SUM(salary)) OVER (ORDER BY department) AS cumulative_payroll\nFROM employees\nGROUP BY department\nORDER BY department;"},{"engine_slug":"mysql","sql":"SELECT department, SUM(salary) AS payroll,\n       100.0 * SUM(salary) / SUM(SUM(salary)) OVER () AS payroll_share\nFROM employees\nGROUP BY department;"},{"engine_slug":"sqlite","sql":"SELECT department, SUM(salary) AS payroll,\n       RANK() OVER (ORDER BY SUM(salary) DESC) AS payroll_rank\nFROM employees\nGROUP BY department;"},{"engine_slug":"oracle","sql":"SELECT department, ROUND(AVG(salary)) AS dept_avg,\n       ROUND(AVG(AVG(salary)) OVER ()) AS company_avg\nFROM employees\nGROUP BY department;"}],"faqs":[{"question":"Why SUM(SUM(x)) OVER () and not SUM(x) OVER ()?","answer":"After GROUP BY, the rows the window sees are groups, and a raw x no longer exists in them; SUM(x) OVER () is rejected for the same reason SELECT x would be on PostgreSQL, SQL Server and MySQL. SQLite accepts both and returns an arbitrary x per group. The double SUM is idiomatic, not a typo."},{"question":"Can I window over groups and filter groups too?","answer":"HAVING filters groups before windows compute, so HAVING sees SUM(x) but not window results. Wrap in a CTE to filter on the windowed values."}],"related":["window-vs-group-by","percent-of-total","running-total"],"novel_uses":[{"body":"RANK over an aggregated SUM ranks the groups in the same query that computes them: months, departments or regions come out ordered by their own totals. The inner SUM belongs to GROUP BY; the RANK reads it after grouping.","sql":"SELECT department, SUM(salary) AS payroll,\n       RANK() OVER (ORDER BY SUM(salary) DESC) AS payroll_rank\nFROM employees\nGROUP BY department;"},{"body":"After HAVING, the window sees only the surviving groups, so the division measures share of the qualifying pool, not of the company. Decide which denominator the report promises and keep this trick to the first one.","sql":"SELECT department, SUM(salary) AS payroll,\n       100.0 * SUM(salary) / SUM(SUM(salary)) OVER () AS share_of_pool\nFROM employees\nGROUP BY department\nHAVING SUM(salary) > 50000;"}]},"source_url":"https://sqlly.app/sql-functions/over-with-group-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/overlaps","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OVERLAPS operator","description":"PostgreSQL's (start1, end1) OVERLAPS (start2, end2) treats ranges as half-open. The portable test start1 < end2 AND start2 < end1 works on every engine.","body":{"slug":"overlaps","name":"OVERLAPS","h1":"SQL OVERLAPS operator","category":"datetime","lede":"Booking clashes, shift conflicts and validity windows all reduce to one question: do two time ranges overlap?","syntax":"(start1, end1) OVERLAPS (start2, end2)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"no; start1 < end2 AND start2 < end1"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no; start1 < end2 AND start2 < end1"},{"engine_slug":"sqlite","status":"no","note":"no; start1 < end2 AND start2 < end1"},{"engine_slug":"oracle","status":"partial","note":"accepted by 23ai but not in the SQL Language Reference; use the comparison"}],"gotchas":["Ranges are half-open: (Jan 1, Jan 10) and (Jan 10, Jan 20) share only an endpoint, and OVERLAPS returns false.","A zero-length range is the exception: (Jan 5, Jan 5) overlaps (Jan 5, Jan 6), while the hand-written start1 < end2 AND start2 < end1 returns false for it.","If a pair is written end first, OVERLAPS swaps it. The hand-written comparison does not, so validate start <= end on input.","In PostgreSQL, range types do the same job with index support: daterange(a, b) && daterange(c, d), backed by a GiST index."],"examples":[{"engine_slug":"postgresql","sql":"SELECT (DATE '2026-01-01', DATE '2026-01-10') OVERLAPS (DATE '2026-01-10', DATE '2026-01-20') AS touching,\n       (DATE '2026-01-01', DATE '2026-01-10') OVERLAPS (DATE '2026-01-09', DATE '2026-01-20') AS overlapping;  -- f, t"},{"engine_slug":"sql-server","sql":"DECLARE @s1 date = '2026-01-01', @e1 date = '2026-01-10', @s2 date = '2026-01-09', @e2 date = '2026-01-20';\nSELECT CASE WHEN @s1 < @e2 AND @s2 < @e1 THEN 'overlap' ELSE 'none' END AS result;  -- overlap"},{"engine_slug":"postgresql","sql":"SELECT daterange('2026-01-01', '2026-01-10') && daterange('2026-01-10', '2026-01-20') AS touching;  -- f"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN s1 < e2 AND s2 < e1 THEN 'overlap' END AS verdict\nFROM (SELECT DATE '2026-01-01' AS s1, DATE '2026-01-10' AS e1, DATE '2026-01-09' AS s2, DATE '2026-01-20' AS e2 FROM dual);  -- overlap"}],"faqs":[{"question":"How do I find overlapping bookings?","answer":"Self-join on the room: FROM bookings a JOIN bookings b ON a.room = b.room AND a.id < b.id AND a.start_at < b.end_at AND b.start_at < a.end_at."},{"question":"Should the end of a range be inclusive?","answer":"Store half-open ranges (end excluded). Back-to-back bookings then do not clash, and the overlap test needs no +1 adjustments."}],"related":["between","date-minus-date","interval-arithmetic"],"novel_uses":[{"body":"A validity window with no end date is the normal case for current prices and assignments, but PostgreSQL's OVERLAPS does not read a NULL endpoint as unbounded: it shrinks (valid_from, NULL) to the single instant valid_from, so the test is true only when valid_from falls strictly inside the other range and NULL otherwise, including the open window that started earlier. COALESCE the end to 'infinity', or use a range type, where a NULL upper bound really is unbounded.","sql":"SELECT (DATE '2026-01-01', NULL::date) OVERLAPS (DATE '2026-06-01', DATE '2026-06-30') AS raw_null,\n       (DATE '2026-01-01', COALESCE(NULL::date, 'infinity')) OVERLAPS (DATE '2026-06-01', DATE '2026-06-30') AS coalesced,\n       daterange('2026-01-01', NULL) && daterange('2026-06-01', '2026-06-30') AS open_range;  -- NULL, t, t"},{"body":"Asking what was valid at noon is the overlap test with a zero-length range: valid_from <= :t AND (valid_to IS NULL OR :t < valid_to). The half-open convention from this page is what keeps a row valid at exactly its start and invalid at exactly its end.","sql":"SELECT * FROM price_history\nWHERE valid_from <= TIMESTAMP '2026-06-15 12:00'\n  AND (valid_to IS NULL OR TIMESTAMP '2026-06-15 12:00' < valid_to);"}]},"source_url":"https://sqlly.app/sql-functions/overlaps","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/overlay","corpus":"sql-functions","engine":null,"language":"en","title":"SQL OVERLAY function","description":"How OVERLAY PLACING ... FROM ... FOR ... replaces a span of a string in PostgreSQL: SQL-standard syntax, omitted FOR clause, and the STUFF and INSERT equivalents.","body":{"slug":"overlay","name":"OVERLAY","h1":"SQL OVERLAY function","category":"string","lede":"Replaces part of a string with a new substring at a given 1-based position, in one standard-syntax call.","syntax":"OVERLAY(str PLACING new_str FROM start)  |  OVERLAY(str PLACING new_str FROM start FOR count)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"Use STUFF(str, start, len, new)."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"Use INSERT(str, pos, len, new)."},{"engine_slug":"sqlite","status":"no","note":"No OVERLAY; splice with SUBSTR and ||."},{"engine_slug":"oracle","status":"no","note":"No OVERLAY; splice with SUBSTR and ||."}],"gotchas":["FOR defaults to the length of the replacement: OVERLAY('abcdef' PLACING 'XY' FROM 2) replaces two characters and returns 'aXYdef'.","OVERLAY is in the SQL standard, but PostgreSQL is the only engine of these five that implements it. It also works on bytea and bit strings.","FOR 0 is a pure insert: OVERLAY('abc' PLACING 'X' FROM 2 FOR 0) is 'aXbc'."],"examples":[{"engine_slug":"postgresql","sql":"SELECT OVERLAY('abcdef' PLACING 'XY' FROM 2 FOR 3) AS result;  -- aXYef"},{"engine_slug":"postgresql","sql":"SELECT OVERLAY(card PLACING '****' FROM 8 FOR 4) AS masked\nFROM payments;"},{"engine_slug":"sql-server","sql":"SELECT STUFF('abcdef', 2, 3, 'XY') AS result;  -- aXYef"},{"engine_slug":"mysql","sql":"SELECT INSERT('abcdef', 2, 3, 'XY') AS result;  -- aXYef"}],"faqs":[{"question":"What does the FOR clause change?","answer":"How many original characters are removed. Without FOR, the replacement's own length decides; with FOR 4, exactly four characters go, whatever the replacement's length."},{"question":"What is the SQL Server equivalent?","answer":"STUFF(str, start, count, new) does the same delete-and-insert with the same 1-based positions. The edge cases differ: for a start past the end, STUFF returns NULL, while OVERLAY appends the replacement."}],"related":["stuff","replace","substr","translate"],"novel_uses":[{"body":"FOR 0 inserts without deleting, so two stacked OVERLAY calls turn '20261120' into '2026-11-20'. The second offset counts positions in the already-lengthened string.","sql":"SELECT OVERLAY(OVERLAY('20261120' PLACING '-' FROM 5 FOR 0)\n       PLACING '-' FROM 8 FOR 0) AS dashed;"},{"body":"When flags are packed into a string column, OVERLAY(flags PLACING '1' FROM 7 FOR 1) sets one position and leaves the rest of the value alone.","sql":"UPDATE accounts\nSET flags = OVERLAY(flags PLACING '1' FROM 7 FOR 1)\nWHERE id = 42;"},{"body":"A one-position overlay fixes a known wrong character at a known offset, guarded by a check on the same slice so correct rows are left untouched.","sql":"UPDATE codes\nSET code = OVERLAY(code PLACING '0' FROM 3 FOR 1)\nWHERE substr(code, 3, 1) = 'O';"}]},"source_url":"https://sqlly.app/sql-functions/overlay","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/parse","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PARSE function","description":"SQL Server's PARSE converts text to date using a culture name like 'en-GB', and TRY_PARSE returns NULL instead of raising on bad input.","body":{"slug":"parse","name":"PARSE / TRY_PARSE","h1":"SQL PARSE function","category":"datetime","lede":"Returns a typed value parsed by .NET culture rules, so it reads month names in other languages from the USING culture alone; CONVERT reads them only after SET LANGUAGE has changed the session language to match.","syntax":"PARSE('15/01/2024' AS date USING 'en-GB')  |  TRY_PARSE('...' AS date USING 'en-GB')","return_type":"date / datetime2 (requested type)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"to_date / to_timestamp masks"},{"engine_slug":"mysql","status":"partial","note":"STR_TO_DATE masks"},{"engine_slug":"sqlite","status":"no","note":"no culture parsing"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE with an explicit mask"}],"gotchas":["PARSE runs through the .NET CLR and is much slower than CAST or CONVERT; keep it for small imports, not bulk loads. It is not remoted to linked servers either.","Without USING, PARSE falls back to the session language, so the same string parses differently on two servers.","TRY_PARSE swallows the error as NULL, which turns a broken import into silent data loss unless you count the NULLs."],"examples":[{"engine_slug":"sql-server","sql":"SELECT PARSE('15/01/2024' AS date USING 'en-GB') AS parsed;  -- 2024-01-15"},{"engine_slug":"sql-server","sql":"SELECT TRY_PARSE('2024-13-40' AS date USING 'en-US') AS parsed;  -- NULL"},{"engine_slug":"postgresql","sql":"SELECT to_timestamp('15/01/2024 09:30', 'DD/MM/YYYY HH24:MI') AS parsed;"},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('Jan 15, 2024', '%b %e, %Y') AS parsed;  -- 2024-01-15"},{"engine_slug":"oracle","sql":"SELECT TO_DATE('15-Jan-2024', 'DD-Mon-YYYY') AS parsed FROM dual;  -- 2024-01-15"}],"faqs":[{"question":"PARSE or CONVERT: which should I use?","answer":"CONVERT with a style number for known formats and speed; PARSE only when the input format follows a culture you cannot control."},{"question":"Why did TRY_PARSE return NULL on good data?","answer":"The culture mismatched: 15/01/2024 fails under en-US because there is no month 15. Declare USING 'en-GB' explicitly."}],"related":["convert-style","str-to-date","cast"],"novel_uses":[{"body":"PARSE reaches time values too: '9:30 PM' becomes a typed time under en-US, which CONVERT style numbers have no answer for.","sql":"SELECT PARSE('9:30 PM' AS time USING 'en-US') AS t;"},{"body":"Culture parsing covers spelled-out dates: '15 January 2024 09:30' lands as datetime2 in one call, still only worth it for small inputs given the CLR hop.","sql":"SELECT PARSE('15 January 2024 09:30' AS datetime2 USING 'en-GB') AS dt;"}]},"source_url":"https://sqlly.app/sql-functions/parse","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/parsename","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PARSENAME function","description":"How PARSENAME reads the parts of a four-segment dotted name in SQL Server: object, schema, database, server slots, NULL results beyond four parts, and file-path tricks.","body":{"slug":"parsename","name":"PARSENAME","h1":"SQL PARSENAME function","category":"string","lede":"Returns one part of a four-part dotted object name, counting from the right.","syntax":"PARSENAME(name, part)  |  part: 1 = object, 2 = schema, 3 = database, 4 = server","return_type":"string or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"No PARSENAME; SPLIT_PART or parse_ident for qualified names."},{"engine_slug":"mysql","status":"no","note":"No PARSENAME; SUBSTRING_INDEX."},{"engine_slug":"sqlite","status":"no","note":"No PARSENAME; INSTR arithmetic with SUBSTR."},{"engine_slug":"oracle","status":"no","note":"No PARSENAME; REGEXP_SUBSTR with occurrence counts."}],"gotchas":["Parts are counted from the right: PARSENAME('db.dbo.orders', 1) is 'orders', part 2 is 'dbo', part 3 is 'db', and part 4 is NULL.","Five or more dot-separated segments return NULL for every part, so PARSENAME is unreliable for arbitrary strings like a.b.c.d.e.","It understands bracketed parts: PARSENAME('[dbo].[Order Header]', 2) strips the brackets and returns dbo.","A dot inside brackets does not split: PARSENAME('[my.db].dbo.orders', 3) returns my.db."],"examples":[{"engine_slug":"sql-server","sql":"SELECT PARSENAME('db.dbo.orders', 1) AS object_name;  -- orders"},{"engine_slug":"sql-server","sql":"SELECT PARSENAME('10.20.30.40', 4) AS first_octet;  -- 10"}],"faqs":[{"question":"Can PARSENAME split any dotted string?","answer":"Only up to four segments, because it was built for server.database.schema.object names. A fifth segment makes it return NULL; use STRING_SPLIT with the ordinal argument (SQL Server 2022 and later) for general splitting."},{"question":"Why do people use PARSENAME for IP addresses and file names?","answer":"An IPv4 address has exactly four parts, so PARSENAME(ip, 4) through PARSENAME(ip, 1) read the octets. For file names, part 1 is the extension, until a name contains more than three dots."},{"question":"What does PARSENAME('orders', 2) return?","answer":"NULL. With no schema segment present there is no part 2; only part 1 exists."}],"related":["string-split","substring-index","replace","reverse"],"novel_uses":[{"body":"PARSENAME returns NULL the moment a dotted value has five or more segments, so testing the parts IS NOT NULL rejects malformed input before it is spliced into dynamic SQL. Reading the parts back also strips any brackets, so QUOTENAME each part before splicing a name with spaces or keywords into SQL.","sql":"SELECT QUOTENAME(PARSENAME(@input, 2)) + '.' + QUOTENAME(PARSENAME(@input, 1)) AS normalized;"},{"body":"A dotted version is just a four-part name read from the right: part 3 is the major, part 2 the minor, part 1 the patch. A fourth numeric segment would shift the slots, so settle the shape first.","sql":"SELECT PARSENAME(version, 3) AS major,\n       PARSENAME(version, 2) AS minor,\n       PARSENAME(version, 1) AS patch\nFROM releases;"}]},"source_url":"https://sqlly.app/sql-functions/parsename","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/partition-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PARTITION BY in window functions","description":"PARTITION BY in OVER splits rows into independent windows, like GROUP BY that keeps its rows, with resets, NULL groups and multi-column splits.","body":{"slug":"partition-by","name":"PARTITION BY","h1":"SQL PARTITION BY in window functions","category":"window","lede":"Divides the result set into partitions; each window function computes independently per partition and resets at its boundaries.","syntax":"SUM(x) OVER (PARTITION BY g) | ROW_NUMBER() OVER (PARTITION BY g1, g2 ORDER BY d)","return_type":"per-partition value","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PARTITION BY takes expressions, not just columns: date_trunc('month', d) on PostgreSQL (or YEAR(d), MONTH(d) on SQL Server and MySQL) partitions by month with no CTE.","NULLs form their own partition; rows with NULL keys get window values computed among themselves rather than being excluded.","PARTITION BY never changes row count, the closest thing to 'GROUP BY that does not collapse'. Sorting the output still needs an outer ORDER BY."],"examples":[{"engine_slug":"postgresql","sql":"SELECT department, employee_id, salary,\n       AVG(salary) OVER (PARTITION BY department) AS dept_avg,\n       COUNT(*) OVER (PARTITION BY EXTRACT(YEAR FROM hire_date)) AS hires_that_year\nFROM employees;"},{"engine_slug":"sql-server","sql":"SELECT department, employee_id, salary,\n       COUNT(*) OVER (PARTITION BY department) AS dept_headcount,\n       AVG(salary) OVER (PARTITION BY YEAR(hire_date)) AS year_hire_avg\nFROM employees;"},{"engine_slug":"mysql","sql":"SELECT region, rep, revenue,\n       SUM(revenue) OVER (PARTITION BY region) AS region_total,\n       ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS region_rank\nFROM regional_sales;"},{"engine_slug":"sqlite","sql":"SELECT student, cohort, score,\n       MAX(score) OVER (PARTITION BY cohort) AS cohort_top,\n       score - MAX(score) OVER (PARTITION BY cohort) AS below_top\nFROM exam_results;"},{"engine_slug":"oracle","sql":"SELECT employee_id, department, hire_date,\n       COUNT(*) OVER (PARTITION BY EXTRACT(YEAR FROM hire_date)) AS hires_that_year\nFROM employees;"}],"faqs":[{"question":"PARTITION BY or GROUP BY: which do I need?","answer":"GROUP BY when one row per group is the answer; PARTITION BY when every row must stay and carry its group's statistic. They can coexist in one query."},{"question":"Can I PARTITION BY multiple columns?","answer":"Yes, comma-separated, and any expression: PARTITION BY region, EXTRACT(YEAR FROM order_date) (YEAR(order_date) on SQL Server). The partition key is the combination of all of them."}],"related":["over-clause","window-vs-group-by","partition-by-expression"],"novel_uses":[{"body":"The group average minus the overall average is the between-group gap, and the row minus its group average is the within-group gap; together they add up to the row's total deviation from the mean. One SELECT and two windows produce the decomposition that explains where a difference comes from.","sql":"SELECT employee_id, department, salary,\n       AVG(salary) OVER (PARTITION BY department) - AVG(salary) OVER () AS between_gap,\n       salary - AVG(salary) OVER (PARTITION BY department) AS within_gap\nFROM employees;"},{"body":"Subtract the partition's FIRST_VALUE date from the current date and each row knows how far into its group's life it sits: cohort day numbers for retention curves. The SQL shown is PostgreSQL, where date minus date returns days; SQL Server rejects it (use DATEDIFF(day, first_value, current_date)), MySQL subtracts the YYYYMMDD integers (use DATEDIFF(current_date, first_value)), and SQLite returns 0 for text dates (use julianday(current_date) - julianday(first_value)). Order the window by the date so the first value is the real start.","sql":"SELECT user_id, activity_day,\n       activity_day - FIRST_VALUE(activity_day) OVER (\n         PARTITION BY user_id ORDER BY activity_day) AS day_number\nFROM activity;"}]},"source_url":"https://sqlly.app/sql-functions/partition-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/partition-by-expression","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PARTITION BY with expressions","description":"Partitions need not be columns: date truncation, case buckets and derived keys let one query window over months, cohorts or custom groups.","body":{"slug":"partition-by-expression","name":"PARTITION BY Expressions","h1":"SQL PARTITION BY with expressions","category":"window","lede":"Any expression can define a partition: calendar buckets, conditional cohorts or normalized keys, evaluated per row before windows run.","syntax":"SUM(x) OVER (PARTITION BY DATE_TRUNC('month', d)) | COUNT(*) OVER (PARTITION BY CASE WHEN ... END)","return_type":"per-partition value","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+; use DATE_FORMAT / YEAR-MONTH expressions"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; use strftime('%Y-%m', d)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The same expression logic applies in ORDER BY inside OVER: partitioning by month and ordering by day gives a running total per month.","Bucketing with CASE creates cohorts on the fly: PARTITION BY CASE WHEN amount > 1000 THEN 'big' ELSE 'small' END windows over the two tiers.","Keep partition expressions simple enough for the engine to match to an index when performance matters; a function on the partition key generally cannot use a plain index on the column."],"examples":[{"engine_slug":"postgresql","sql":"SELECT order_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY date_trunc('month', order_date)\n                         ORDER BY order_date) AS mtd_amount\nFROM orders;"},{"engine_slug":"sql-server","sql":"SELECT order_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY YEAR(order_date), MONTH(order_date)\n                         ORDER BY order_date) AS mtd_amount\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT order_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY DATE_FORMAT(order_date, '%Y-%m')\n                         ORDER BY order_date) AS mtd_amount\nFROM orders;"},{"engine_slug":"sqlite","sql":"SELECT order_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY strftime('%Y-%m', order_date)\n                         ORDER BY order_date) AS mtd_amount\nFROM orders;"},{"engine_slug":"oracle","sql":"SELECT order_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY TRUNC(order_date, 'MM')\n                         ORDER BY order_date) AS mtd_amount\nFROM orders;"}],"faqs":[{"question":"Can I partition by a column I compute in the same SELECT?","answer":"Not by its alias: all four engines tested reject it with an unknown-column error, because window inputs are the underlying rows. Repeat the expression, or compute it in a CTE first."},{"question":"Does an expression partition defeat indexes?","answer":"It can. On PostgreSQL and SQLite, partitioning on d with ORDER BY d reads the index on d, while partitioning on DATE_TRUNC('month', d) sorts first, so it generally cannot. MySQL 8.4 sorted in both cases on a 200,000-row table, so do not rely on the index there. For hot paths, materialize the bucket column and index it."}],"related":["partition-by","over-clause","window-performance"],"novel_uses":[{"body":"Partition on FLOOR(salary / 10000) and rows fall into 10k bands with no derived table; band counts and band averages come free. The expression is computed per row before the windows run, so it works anywhere expressions do.","sql":"SELECT employee_id, salary,\n       COUNT(*) OVER (PARTITION BY FLOOR(salary / 10000)) AS in_band,\n       AVG(salary) OVER (PARTITION BY FLOOR(salary / 10000)) AS band_avg\nFROM employees;"},{"body":"Partition by the truncated week and order by day: the sum resets every Monday. PostgreSQL writes date_trunc('week', day); MySQL reaches the same Monday-start grouping with YEARWEEK(day, 3); plain YEARWEEK(day) starts its weeks on Sunday, so it resets a day early.","sql":"SELECT day, sales,\n       SUM(sales) OVER (PARTITION BY DATE_TRUNC('week', day) ORDER BY day) AS wtd\nFROM daily_sales;"}]},"source_url":"https://sqlly.app/sql-functions/partition-by-expression","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/patindex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PATINDEX function","description":"How PATINDEX finds the first position matching a LIKE pattern in SQL Server: wildcards, character classes, collation effects and the CHARINDEX and REGEXP alternatives.","body":{"slug":"patindex","name":"PATINDEX","h1":"SQL PATINDEX function","category":"string","lede":"SQL Server search that returns the first position where a LIKE-style wildcard pattern matches inside a string.","syntax":"PATINDEX('%pattern%', string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"regexp_instr (PostgreSQL 15+) takes a regex instead of a LIKE pattern."},{"engine_slug":"mysql","status":"partial","note":"REGEXP_INSTR in MySQL 8.0.4+ takes a regex."},{"engine_slug":"sqlite","status":"no","note":"No PATINDEX; INSTR finds literal substrings only."},{"engine_slug":"oracle","status":"partial","note":"REGEXP_INSTR takes a regex."}],"gotchas":["The pattern usually needs % on both sides. PATINDEX('abc', s) only matches when the whole string is 'abc'; '%abc%' finds it anywhere.","Patterns use LIKE syntax, not regex: % and _ wildcards, [abc] and [a-z] character classes, [^abc] negation. No +, * or alternation. Under Windows collations (the default SQL_Latin1_General_CP1_CI_AS and Latin1_General_CS_AS alike) a range such as [a-z] also matches uppercase and accented letters, so '[^a-z ]' does not flag 'H'. A _BIN2 collation compares code points instead.","Returns 0 for no match and NULL if either argument is NULL. There is no ESCAPE clause as in LIKE; match a literal % or _ by bracketing it: '%[%]%'."],"examples":[{"engine_slug":"sql-server","sql":"SELECT PATINDEX('%[0-9]%', address) AS first_digit\nFROM addresses;"},{"engine_slug":"sql-server","sql":"SELECT PATINDEX('%[^a-z ]%', comment) AS first_bad_char\nFROM comments;"},{"engine_slug":"postgresql","sql":"SELECT regexp_instr(address, '[0-9]') AS first_digit\nFROM addresses;"},{"engine_slug":"mysql","sql":"SELECT REGEXP_INSTR(address, '[0-9]') AS first_digit\nFROM addresses;"},{"engine_slug":"oracle","sql":"SELECT REGEXP_INSTR(address, '[0-9]') AS first_digit\nFROM addresses;"}],"faqs":[{"question":"What is the difference between PATINDEX and CHARINDEX?","answer":"CHARINDEX searches for a literal substring and accepts a start position; PATINDEX searches for a LIKE pattern and always starts at 1. Use PATINDEX when you need the first character that matches a class such as [0-9]."},{"question":"Does PATINDEX support full regular expressions?","answer":"No, only the LIKE wildcard set: %, _ and bracketed character classes. SQL Server 2025 and Azure SQL Database add REGEXP_INSTR for real regex; on older versions the options are CLR functions or the application."},{"question":"Why does PATINDEX return 0 when the substring is clearly there?","answer":"Without % wildcards the pattern must match the whole string. Write PATINDEX('%abc%', col), not PATINDEX('abc', col)."}],"related":["charindex","regexp-instr","substring","replace"],"novel_uses":[{"body":"PATINDEX('%[0-9]%', col) finds where the digits start, and STUFF drops everything before them, which turns 'SKU-1234' into '1234' in SQL Server. A value with no digits returns NULL because the length goes negative, which you can filter on.","sql":"SELECT STUFF(code, 1, PATINDEX('%[0-9]%', code) - 1, '') AS digits\nFROM items;"},{"body":"PATINDEX('[0-9]%', col) = 1 is true when the value begins with an ASCII digit, because the pattern must match at position 1. Under Windows collations a full-width digit such as '９' also matches [0-9]; a _BIN2 collation does not. Chained in a CASE it classifies rows by shape without splitting anything.","sql":"SELECT CASE WHEN PATINDEX('[0-9]%', tracking) = 1 THEN 'numeric'\n            WHEN PATINDEX('[A-Z]%', tracking) = 1 THEN 'alpha'\n            ELSE 'other' END AS shape\nFROM shipments;"},{"body":"LEFT(s, PATINDEX('%[^a-zA-Z0-9]%', s + ' ') - 1) keeps the leading run of safe characters. Under a Windows collation such as the default, accented letters also count as safe, so 'café-bar' yields 'café'; use a _BIN2 collation for strict ASCII. Appending a space guarantees the pattern always matches, so the length never goes negative even for a clean string.","sql":"SELECT LEFT(title, PATINDEX('%[^a-zA-Z0-9]%', title + ' ') - 1) AS slug\nFROM articles;"}]},"source_url":"https://sqlly.app/sql-functions/patindex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percent-of-total","corpus":"sql-functions","engine":null,"language":"en","title":"SQL percent of total","description":"Dividing each row by its group or grand total: SUM() OVER as the denominator, integer division traps and per-partition shares.","body":{"slug":"percent-of-total","name":"Percent of Total","h1":"SQL percent of total","category":"window","lede":"Row divided by SUM(x) OVER (partition or empty) gives the share: group percentages without a separate totals query or join.","syntax":"x * 100.0 / SUM(x) OVER (PARTITION BY g)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Multiply by 100.0 (or cast) before dividing: on SQL Server, PostgreSQL and SQLite, integer / integer truncates and a share of 0 is the usual symptom. MySQL and Oracle return a decimal.","Guard the denominator with NULLIF when the total can be 0: SQL Server, PostgreSQL and Oracle raise a division-by-zero error, while MySQL and SQLite return NULL.","The empty OVER () is the grand total across all rows of the result after WHERE; filters shrink the denominator, which may or may not be the percentage you mean."],"examples":[{"engine_slug":"all","sql":"SELECT region, amount,\n       100.0 * amount / NULLIF(SUM(amount) OVER (), 0) AS share_of_all,\n       100.0 * amount / NULLIF(SUM(amount) OVER (PARTITION BY region), 0) AS share_of_region\nFROM sales;"}],"faqs":[{"question":"Why is my percentage always 0 or 100?","answer":"Integer division: amount / total with both integers truncates on SQL Server, PostgreSQL and SQLite. Make the numerator decimal (amount * 1.0) before dividing."},{"question":"Can I get percent of total with GROUP BY in the same query?","answer":"Yes: window functions run after grouping, so SELECT dim, SUM(x), 100.0 * SUM(x) / SUM(SUM(x)) OVER () FROM t GROUP BY dim works; the inner SUM is the group's, the outer one the grand total."}],"related":["sum-over","cumulative-share","over-with-group-by"],"novel_uses":[{"body":"Compute each category's share per month in a CTE, then subtract LAG of the share inside the category: positive numbers are categories gaining mix. Shares move even when everything grows, and this is the number that shows it. PostgreSQL spelling for the month bucket.","sql":"WITH monthly AS (\n  SELECT category, DATE_TRUNC('month', order_date) AS month, SUM(total) AS v\n  FROM orders GROUP BY 1, 2\n), share AS (\n  SELECT category, month, 100.0 * v / SUM(v) OVER (PARTITION BY month) AS pct\n  FROM monthly\n)\nSELECT category, month, pct,\n       pct - LAG(pct) OVER (PARTITION BY category ORDER BY month) AS mix_shift\nFROM share\nORDER BY month, category;"},{"body":"Swap the numerator for revenue times margin rate and the percentage ranks products by profit contribution instead of volume. High-share low-margin products stop looking like winners.","sql":"SELECT product_id, amount, margin_rate,\n       100.0 * amount * margin_rate / SUM(amount * margin_rate) OVER () AS pct_of_margin\nFROM sales;"}]},"source_url":"https://sqlly.app/sql-functions/percent-of-total","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percent-rank","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERCENT_RANK function","description":"PERCENT_RANK in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: each row's rank as a fraction from 0 to 1, with the tie and edge cases.","body":{"slug":"percent-rank","name":"PERCENT_RANK","h1":"SQL PERCENT_RANK function","category":"window","lede":"Returns the relative rank of a row: (RANK - 1) / (partition rows - 1), a fraction between 0 and 1 where the first row is always 0.","syntax":"PERCENT_RANK() OVER (PARTITION BY g ORDER BY x)","return_type":"double precision / float","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The first row in every partition is exactly 0, and the last row is exactly 1 unless it ties with the row before it: with 4 untied rows the fractions are 0, 0.333, 0.667, 1.","Tied ORDER BY values share the same PERCENT_RANK because they share the same RANK; use ROW_NUMBER when ties must break differently.","A single-row partition returns 0, not a division-by-zero error: the denominator (rows - 1) is guarded."],"examples":[{"engine_slug":"all","sql":"SELECT name, points,\n       PERCENT_RANK() OVER (ORDER BY points DESC) AS pct\nFROM players;"},{"engine_slug":"all","sql":"-- top 10% by spend within each region\nWITH r AS (\n  SELECT c.*, PERCENT_RANK() OVER (PARTITION BY region ORDER BY spend DESC) AS pct\n  FROM customers c\n)\nSELECT * FROM r WHERE pct <= 0.1;"}],"faqs":[{"question":"What is the difference between PERCENT_RANK and CUME_DIST?","answer":"PERCENT_RANK is (RANK - 1) / (rows - 1): the first row is 0. CUME_DIST is peers-at-or-below / total rows: the first row is above 0 and the last is exactly 1. For cutoffs like 'top 10%', both work, but CUME_DIST counts ties together."},{"question":"Does PERCENT_RANK return 0 or 1 for the best row?","answer":"0 for the first row in ORDER BY direction, and 1 for the last row when that row is untied. If you want the leader to be 1, use 1 - PERCENT_RANK(), which also gives 1 to a tied leader; ordering ascending gives a tied leader less than 1."}],"related":["rank","cume-dist","ntile"],"novel_uses":[{"body":"PERCENT_RANK puts incomparable metrics on one 0 to 1 scale, so a blended score like 0.6 * spend_p + 0.4 * recency_p ranks customers on two axes at once without picking units. Blend the two window columns in an outer query; raw spend and raw days cannot be mixed because they mean different things.","sql":"SELECT customer_id,\n       PERCENT_RANK() OVER (ORDER BY spend) AS spend_p,\n       PERCENT_RANK() OVER (ORDER BY last_visit) AS recency_p\nFROM customers;"},{"body":"Rows with PERCENT_RANK between 0.45 and 0.55 are the middle band by rank, a median-neighbourhood filter that never needs a median function and runs on every window-capable engine.","sql":"SELECT name, score\nFROM (\n  SELECT name, score, PERCENT_RANK() OVER (ORDER BY score) AS pr\n  FROM players\n) t\nWHERE pr BETWEEN 0.45 AND 0.55;"},{"body":"Rank = PERCENT_RANK * (rows - 1) + 1, so a report that stored only the fraction can reproduce the integer rank it came from. Handy when auditing exports where the rank column was dropped.","sql":"SELECT customer_id,\n       ROUND(CAST(pr * (cnt - 1) AS DECIMAL(18, 6)), 0) + 1 AS rank_restored\nFROM (\n  SELECT customer_id,\n         PERCENT_RANK() OVER (ORDER BY spend DESC) AS pr,\n         COUNT(*) OVER () AS cnt\n  FROM customers\n) t;"}]},"source_url":"https://sqlly.app/sql-functions/percent-rank","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percent-rank-vs-cume-dist","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERCENT_RANK vs CUME_DIST","description":"Two relative-rank functions that look interchangeable and are not: different formulas, different treatment of ties, different ranges at the edges.","body":{"slug":"percent-rank-vs-cume-dist","name":"PERCENT_RANK vs CUME_DIST","h1":"SQL PERCENT_RANK vs CUME_DIST","category":"window","lede":"PERCENT_RANK positions a row by its rank over (rows - 1); CUME_DIST positions it by the share of rows at or below it, so ties land at the top of their group.","syntax":"PERCENT_RANK() OVER (ORDER BY x) | CUME_DIST() OVER (ORDER BY x)","return_type":"double precision / float","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Edge behaviour differs: PERCENT_RANK is 0 on the first row and 1 only on a last row that is not tied; CUME_DIST is never 0 and is exactly 1 for every row of the last tie group.","With duplicate ORDER BY values, PERCENT_RANK gives all peers the value of the first peer's position, CUME_DIST the value through the last peer. For scores 70, 80, 90, 90, 95 the two 90s get 0.5 and 0.8.","Both give tied rows identical values, so neither splits a tie group. They still put the cutoff in different places: pct <= 0.5 keeps both 90s under PERCENT_RANK and neither under CUME_DIST."],"examples":[{"engine_slug":"all","sql":"SELECT name, score,\n       PERCENT_RANK() OVER (ORDER BY score) AS pr,\n       CUME_DIST()   OVER (ORDER BY score) AS cd\nFROM players;\n-- scores 70, 80, 90, 90, 95:\n-- pr = 0, 0.25, 0.5, 0.5, 1\n-- cd = 0.2, 0.4, 0.8, 0.8, 1"}],"faqs":[{"question":"Which should I use for a 'bottom N percent' filter?","answer":"CUME_DIST <= 0.25 keeps rows whose whole tie group fits inside the first 25% of rows, so the result never exceeds 25%. PERCENT_RANK <= 0.25 keeps every row whose first peer is at or under 0.25 on the 0-to-1 scale, so a tie group straddling the line comes in whole and the result can exceed 25%. CUME_DIST matches how PERCENTILE_DISC picks its value."},{"question":"Can both be 0 or 1 on the same row?","answer":"Never 0: the first row has PERCENT_RANK 0 but CUME_DIST of at least 1/N. Both can be 1: the last row has CUME_DIST 1, and PERCENT_RANK is also 1 there unless it ties with an earlier row."}],"related":["percent-rank","cume-dist","rank"],"novel_uses":[{"body":"CUME_DIST is the share of customers at or below a given customer, the honest number for percentile claims aimed at the customer. One minus it is the share strictly above; with ties the strictly-below share sits lower than the at-or-below share by exactly the tie group's own share of rows, so quote the at-or-below figure when the audience includes the customer.","sql":"SELECT customer_id, spend,\n       CUME_DIST() OVER (ORDER BY spend) AS at_or_below\nFROM customers;"},{"body":"The same curve answers where a candidate value would land: count the rows at or below it and divide by the total, no window needed. On PostgreSQL and Oracle, PERCENT_RANK(v) WITHIN GROUP answers where the threshold would rank, inside the engine.","sql":"SELECT SUM(CASE WHEN size <= 42 THEN 1 ELSE 0 END) * 1.0 / COUNT(*)\n       AS share_at_or_below\nFROM sizes;"}]},"source_url":"https://sqlly.app/sql-functions/percent-rank-vs-cume-dist","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percentile-cont","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERCENTILE_CONT function","description":"Compute percentiles in SQL: PERCENTILE_CONT in SQL Server, PostgreSQL and Oracle, what MySQL and SQLite offer instead, and the window-function form.","body":{"slug":"percentile-cont","name":"PERCENTILE_CONT","h1":"SQL PERCENTILE_CONT function","category":"aggregate","lede":"Returns the value at a given fraction of the ordered group, interpolating between the two nearest values. PERCENTILE_CONT(0.5) is the median.","syntax":"PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)  -- aggregate form","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":"window form only: it always needs an OVER clause"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no PERCENTILE_CONT; emulate with window functions"},{"engine_slug":"sqlite","status":"partial","note":"percentile_cont(x, 0.5) and median(x) in 3.47+ builds with the percentile extension enabled, as in the sqlite3 shell"},{"engine_slug":"oracle","status":"yes","note":"aggregate or analytic; MEDIAN(x) as a shortcut"}],"gotchas":["SQL Server requires the window form: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g). It returns the value on every row, so add DISTINCT or a GROUP BY around it to get one row per group.","PostgreSQL only has the aggregate form: PERCENTILE_CONT cannot be used as a window function there, so compute one group per query or wrap it in a grouped subquery.","0.5 gives the median. For p95 use 0.95; the result interpolates between the two nearest rows when no row lands exactly on the fraction."],"examples":[{"engine_slug":"postgresql","sql":"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms) AS median\nFROM pings;"},{"engine_slug":"sql-server","sql":"SELECT DISTINCT\n       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms)\n           OVER () AS median\nFROM pings;"},{"engine_slug":"oracle","sql":"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms) AS median\nFROM pings;"},{"engine_slug":"sqlite","sql":"-- two-argument percentile_cont comes from the percentile extension:\n-- in the CLI since 3.47, or compiled in with SQLITE_ENABLE_PERCENTILE\nSELECT percentile_cont(response_ms, 0.5) AS median FROM pings;"}],"faqs":[{"question":"How do I compute a median in SQL?","answer":"PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) on PostgreSQL and Oracle (Oracle also has MEDIAN(x)), the same expression with an OVER () clause on SQL Server. On MySQL, number the rows with ROW_NUMBER and COUNT and average the middle one or two. SQLite builds with the percentile extension have median(x)."},{"question":"What is the difference between PERCENTILE_CONT and PERCENTILE_DISC?","answer":"CONT interpolates between neighbouring values and can return a value that exists in no row; DISC returns an actual row value, skipping interpolation."}],"related":["avg","row-number","stddev"],"novel_uses":[{"body":"PostgreSQL accepts an array of fractions, so PERCENTILE_CONT(ARRAY[0.25, 0.5, 0.75]) returns all three quartiles in one pass. The 1.5 IQR rule then marks outliers: anything below q1 - 1.5 * (q3 - q1) or above q3 + 1.5 * (q3 - q1). Other engines compute the two quartiles separately.","sql":"SELECT percentile_cont(ARRAY[0.25, 0.5, 0.75]) WITHIN GROUP (ORDER BY response_ms) AS quartiles\nFROM pings;"},{"body":"A fixed cutoff misfires when groups sit at different levels. Computing each group's median and comparing every row to twice its own group's median flags outliers relative to their peers, which is fairer than one global number.","sql":"WITH med AS (\n  SELECT region,\n         PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY spend) AS med_spend\n  FROM customers GROUP BY region\n)\nSELECT c.*\nFROM customers c JOIN med m USING (region)\nWHERE c.spend > 2 * m.med_spend;"}]},"source_url":"https://sqlly.app/sql-functions/percentile-cont","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percentile-cont-vs-disc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERCENTILE_CONT vs PERCENTILE_DISC","description":"Interpolated versus discrete percentiles: when PERCENTILE_CONT invents a value, when PERCENTILE_DISC keeps a real one, and which engines support each.","body":{"slug":"percentile-cont-vs-disc","name":"PERCENTILE_CONT vs PERCENTILE_DISC","h1":"SQL PERCENTILE_CONT vs PERCENTILE_DISC","category":"window","lede":"Both compute a percentile from an ordered set, but CONT interpolates between neighbouring values while DISC snaps to an actual value from the data.","syntax":"PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) | PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x)","return_type":"float or double precision (CONT) / type of x (DISC)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"neither exists; use CUME_DIST or NTILE"},{"engine_slug":"sqlite","status":"no","note":"neither exists; use CUME_DIST or NTILE"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["With an even row count, the median differs: CONT averages the two middle values, DISC returns the lower one. Salaries of 40k and 50k give a 45k median under CONT, 40k under DISC.","CONT needs a type it can interpolate: numerics everywhere, plus interval in PostgreSQL and date/timestamp in Oracle. DISC accepts any orderable type, so it is the only option for a median of text values.","SQL Server allows both only with an OVER clause (OVER () or OVER (PARTITION BY ...)); PostgreSQL allows them only as aggregates (no OVER); Oracle allows either form."],"examples":[{"engine_slug":"postgresql","sql":"SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY price) AS p25,\n       PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY price) AS p25_disc\nFROM products;"},{"engine_slug":"sql-server","sql":"-- both run only as window functions on SQL Server\nSELECT DISTINCT region,\n       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY price)\n         OVER (PARTITION BY region) AS cont_median,\n       PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price)\n         OVER (PARTITION BY region) AS disc_median\nFROM products;"},{"engine_slug":"oracle","sql":"-- Oracle runs both as plain aggregates, the form SQL Server rejects\nSELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY price) AS cont_median,\n       PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price) AS disc_median\nFROM products;"}],"faqs":[{"question":"Which one should I use for a median?","answer":"CONT when the median of an even count should average the middle two (financial convention); DISC when the answer must be a value that actually exists, or when the column is not numeric."},{"question":"Why does PERCENTILE_CONT error on a date column?","answer":"Interpolating between two dates needs arithmetic on the type. SQL Server accepts only numerics, PostgreSQL only double precision and interval (no function matches a date argument); Oracle does interpolate DATE and TIMESTAMP values. DISC works on dates everywhere it exists."}],"related":["percentile-disc","percentile-cont","cume-dist"],"novel_uses":[{"body":"For latency or capacity questions the honest answer usually sits between two observations, so PERCENTILE_CONT fits: a p95 request time can be a value no request ever recorded. Use PERCENTILE_DISC when the reported number must be a real data point, such as an actual invoice amount.","sql":null},{"body":"Neither engine has either function, but the interpolated median falls out of row numbers: average the rows whose doubled rank lies from the count up to the count plus two. Even counts average two rows and odd counts return the middle row unchanged, so one expression covers both parities.","sql":"WITH r AS (\n  SELECT price, ROW_NUMBER() OVER (ORDER BY price) AS rn,\n         COUNT(*) OVER () AS n\n  FROM products\n)\nSELECT AVG(price) AS cont_median\nFROM r\nWHERE 2 * rn BETWEEN n AND n + 2;"}]},"source_url":"https://sqlly.app/sql-functions/percentile-cont-vs-disc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/percentile-disc","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERCENTILE_DISC function","description":"PERCENTILE_DISC in SQL Server, PostgreSQL and Oracle: the actual value at a percentile, via WITHIN GROUP, and why MySQL and SQLite cannot run that form.","body":{"slug":"percentile-disc","name":"PERCENTILE_DISC","h1":"SQL PERCENTILE_DISC function","category":"window","lede":"Returns the ordered value at which the cumulative distribution first reaches the given fraction: a real value from the data, not an interpolation.","syntax":"PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) | PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g)","return_type":"type of the ORDER BY expression","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2012+; window form only: OVER (PARTITION BY ...) is mandatory"},{"engine_slug":"postgresql","status":"yes","note":"ordered-set aggregate only; OVER is rejected"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"aggregate and analytic (OVER) forms"}],"gotchas":["Syntax is inverted from other functions: the fraction goes first and the column is declared inside WITHIN GROUP (ORDER BY ...). Swapping them fails on PostgreSQL and SQL Server.","MySQL has no PERCENTILE_DISC, and SQLite has none in WITHIN GROUP form (the sqlite3 shell on macOS 3.51.0 also registers a non-standard two-argument percentile_disc(x, fraction); the 3.44.4 build lacks it). The exact emulation is the first row, in ORDER BY order, whose CUME_DIST() is at least the fraction.","The two server engines disagree on form: PostgreSQL rejects OVER ('OVER is not supported for ordered-set aggregate'), SQL Server rejects the plain aggregate ('must have an OVER clause'). Oracle accepts both, so no single PERCENTILE_DISC query runs unchanged on every engine."],"examples":[{"engine_slug":"postgresql","sql":"SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price) AS median\nFROM products;"},{"engine_slug":"sql-server","sql":"SELECT DISTINCT region,\n       PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price)\n         OVER (PARTITION BY region) AS median_price\nFROM products;"},{"engine_slug":"oracle","sql":"-- Oracle alone runs both forms; here the analytic one\nSELECT DISTINCT region,\n       PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price)\n         OVER (PARTITION BY region) AS median_price\nFROM products;"}],"faqs":[{"question":"What is the difference between PERCENTILE_DISC and PERCENTILE_CONT?","answer":"DISC returns an actual row's value (the smallest value whose cumulative share reaches the fraction); CONT interpolates between the two surrounding values and can return a value that appears nowhere in the data. DISC works on any orderable type, including text and dates."},{"question":"Does PERCENTILE_DISC work in MySQL or SQLite?","answer":"No, not in WITHIN GROUP form (the sqlite3 shell on macOS 3.51.0 also has a non-standard two-argument percentile_disc). Compute CUME_DIST() OVER (PARTITION BY g ORDER BY x) in a CTE, then take MIN(x) per group among rows where the CUME_DIST is >= the fraction. That returns exactly what PERCENTILE_DISC would."}],"related":["percentile-cont","percentile-cont-vs-disc","cume-dist"],"novel_uses":[{"body":"The aggregate form pairs with GROUP BY, so PostgreSQL and Oracle return a median per department without any CTE or window scaffolding. SQL Server cannot run this shape, and MySQL has no function at all, and SQLite has none in WITHIN GROUP form.","sql":"SELECT department,\n       PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary\nFROM employees\nGROUP BY department;"},{"body":"On SQL Server the window form computes the median per partition in a CTE, and a join back gives each row its gap to the department median in one statement. Keep the DISTINCT shape the plain median query needs.","sql":"WITH m AS (\n  SELECT DISTINCT department,\n         PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary)\n           OVER (PARTITION BY department) AS median_salary\n  FROM employees\n)\nSELECT e.employee_id, e.salary,\n       e.salary - m.median_salary AS vs_median\nFROM employees e\nJOIN m ON m.department = e.department;"}]},"source_url":"https://sqlly.app/sql-functions/percentile-disc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/period-add-diff","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PERIOD_ADD function","description":"PERIOD_ADD and PERIOD_DIFF in MySQL: add months to, or diff, compact YYYYMM period numbers, and why day values break them.","body":{"slug":"period-add-diff","name":"PERIOD_ADD / PERIOD_DIFF","h1":"SQL PERIOD_ADD function","category":"datetime","lede":"Arithmetic on month-period integers in the YYYYMM form, with no day or time component at all.","syntax":"PERIOD_ADD(period, n)  |  PERIOD_DIFF(period1, period2)","return_type":"integer (YYYYMM / months)","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Arguments are integers like 202608, not dates: PERIOD_ADD(202608, 3) gives 202611. A full YYYYMMDD value is not rejected: PERIOD_ADD(20260801, 1) returns 20260802, which looks plausible and is wrong.","Two-digit years are accepted with MySQL's 70-99 / 00-69 pivot (1970-1999, 2000-2069); four-digit years are safer.","For real dates use DATE_ADD(d, INTERVAL n MONTH) and TIMESTAMPDIFF(MONTH, a, b); PERIOD functions exist for accounting-style period columns."],"examples":[{"engine_slug":"mysql","sql":"SELECT PERIOD_ADD(202608, 3);  -- 202611"},{"engine_slug":"mysql","sql":"SELECT PERIOD_DIFF(202608, 202601);  -- 7"}],"faqs":[{"question":"How do I convert a date to a period?","answer":"EXTRACT(YEAR_MONTH FROM d) returns 202608 for any August 2026 date. DATE_FORMAT(d, '%Y%m') + 0 does the same through a string."},{"question":"Does PERIOD_DIFF count month boundaries like DATEDIFF?","answer":"No. It is a true month difference of period numbers: PERIOD_DIFF(202601, 202512) is 1 regardless of days."}],"related":["adddate","timestampdiff","date-format"],"novel_uses":[{"body":"Concatenate a day and parse with STR_TO_DATE when a period key must join real date columns, keeping the accounting period and the transaction calendar connected.","sql":"SELECT STR_TO_DATE(CONCAT(202608, '01'), '%Y%m%d');  -- 2026-08-01"},{"body":"PERIOD_DIFF normalizes through year and month fields, so it counts months across year boundaries correctly where raw integer subtraction would not.","sql":"SELECT PERIOD_DIFF(202701, 202511);  -- 14"}]},"source_url":"https://sqlly.app/sql-functions/period-add-diff","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/period-over-period","corpus":"sql-functions","engine":null,"language":"en","title":"SQL period over period with LAG","description":"Month-over-month and year-over-year growth without self-joins: aggregate to periods first, then LAG across the period rows.","body":{"slug":"period-over-period","name":"Period Over Period Comparison","h1":"SQL period over period with LAG","category":"window","lede":"Aggregate to one row per period, apply LAG over the period ordering, and compute the ratio, the clean replacement for double self-joins on the fact table.","syntax":"SELECT ... FROM (SELECT period, SUM(x) AS v ... GROUP BY period) t | v / LAG(v) OVER (ORDER BY period) - 1","return_type":"numeric ratio","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["LAG must run over period rows, not raw fact rows: LAG over the fact table mixes rows inside the same month and returns intra-month deltas, not MoM.","Gaps in periods break the arithmetic: LAG steps back one row, so a missing month makes 'previous' two months ago. Generate the period spine (calendar table or generate_series) and LEFT JOIN facts onto it first.","Integer division kills growth rates: with integer columns, v / LAG(v) truncates on SQL Server, PostgreSQL and SQLite (MySQL and Oracle return a decimal). Multiply by 100.0 or cast one side first; on SQLite, CAST to DECIMAL or NUMERIC still truncates, so cast to REAL instead."],"examples":[{"engine_slug":"postgresql","sql":"WITH monthly AS (\n  SELECT date_trunc('month', order_date) AS month, SUM(total) AS revenue\n  FROM orders\n  GROUP BY 1\n)\nSELECT month, revenue,\n       LAG(revenue) OVER (ORDER BY month) AS prev_month,\n       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))\n             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_pct\nFROM monthly\nORDER BY month;"},{"engine_slug":"sql-server","sql":"WITH monthly AS (\n  SELECT YEAR(order_date) AS yr, MONTH(order_date) AS mo, SUM(total) AS revenue\n  FROM orders\n  GROUP BY YEAR(order_date), MONTH(order_date)\n)\nSELECT yr, mo, revenue,\n       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY yr, mo))\n             / LAG(revenue) OVER (ORDER BY yr, mo), 1) AS mom_pct\nFROM monthly\nORDER BY yr, mo;"},{"engine_slug":"mysql","sql":"WITH monthly AS (\n  SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue\n  FROM orders\n  GROUP BY month\n)\nSELECT month, revenue,\n       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))\n             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_pct\nFROM monthly\nORDER BY month;"},{"engine_slug":"sqlite","sql":"WITH monthly AS (\n  SELECT strftime('%Y-%m', order_date) AS month, SUM(total) AS revenue\n  FROM orders\n  GROUP BY month\n)\nSELECT month, revenue,\n       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))\n             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_pct\nFROM monthly\nORDER BY month;"},{"engine_slug":"oracle","sql":"WITH monthly AS (\n  SELECT TRUNC(order_date, 'MM') AS month, SUM(total) AS revenue\n  FROM orders\n  GROUP BY TRUNC(order_date, 'MM')\n)\nSELECT month, revenue,\n       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))\n             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_pct\nFROM monthly\nORDER BY month;"}],"faqs":[{"question":"Why use LAG instead of a self-join for YoY?","answer":"A self-join needs date arithmetic to find 'same month last year' and scans the fact table twice or more. LAG over monthly aggregates reads each period once, and LAG(revenue, 12) over a month spine gives YoY in the same pass."},{"question":"How do I handle months with no sales?","answer":"Include them in the spine (zero-fill) before LAG, otherwise LAG skips them and, with November missing, December is compared against October."}],"related":["difference-from-previous","lag","date-trunc"],"novel_uses":[{"body":"Subtract LAG of the growth rate from the growth rate and positive numbers mean speeding up. A month can grow while decelerating, which is the number that warns about next quarter.","sql":"WITH monthly AS (\n  SELECT date_trunc('month', order_date) AS month, SUM(total) AS revenue\n  FROM orders GROUP BY 1\n), rates AS (\n  SELECT month, revenue,\n         100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))\n           / NULLIF(LAG(revenue) OVER (ORDER BY month), 0) AS mom_pct\n  FROM monthly\n)\nSELECT month, mom_pct,\n       mom_pct - LAG(mom_pct) OVER (ORDER BY month) AS accel\nFROM rates\nORDER BY month;"},{"body":"Run the same LAG delta inside a category partition, then sort each month's deltas: the top rows name the categories behind the month's move. Totals hide this; only the per-category delta assigns credit.","sql":"WITH monthly AS (\n  SELECT category, date_trunc('month', order_date) AS month, SUM(total) AS v\n  FROM orders GROUP BY 1, 2\n)\nSELECT category, month,\n       v - LAG(v) OVER (PARTITION BY category ORDER BY month) AS delta\nFROM monthly\nORDER BY month, delta DESC;"}]},"source_url":"https://sqlly.app/sql-functions/period-over-period","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/pg-cast-operator","corpus":"sql-functions","engine":null,"language":"en","title":"SQL :: cast operator","description":"PostgreSQL's expression::type cast shorthand: how it binds, why the other four engines reject it, and when to write CAST instead.","body":{"slug":"pg-cast-operator","name":"::","h1":"SQL :: cast operator","category":"conversion","lede":"x::int is PostgreSQL shorthand for CAST(x AS int). It is the shortest cast in SQL, and no other engine here parses it.","syntax":"expression::type","return_type":"the target type","support":[{"engine_slug":"sql-server","status":"no","note":"no :: cast (:: only calls static methods, as in hierarchyid::GetRoot()); use CAST or CONVERT"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no ::; use CAST or CONVERT"},{"engine_slug":"sqlite","status":"no","note":"no ::; use CAST"},{"engine_slug":"oracle","status":"no","note":"no ::; use CAST"}],"gotchas":["The shorthand is PostgreSQL-only: MySQL, SQL Server, SQLite and Oracle reject the syntax at parse time, so SQL that must travel between engines needs CAST.",":: binds tighter than arithmetic: a + b::numeric casts only b, while (a + b)::numeric casts the sum. With integer division the difference shows: 7 / 2::numeric is 3.5, (7 / 2)::numeric is 3.","The type name after :: is a PostgreSQL name: nvarchar, datetime and tinyint do not exist there, so casts copied from SQL Server fail on the type, not the operator."],"examples":[{"engine_slug":"postgresql","sql":"SELECT created_at::date AS day FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT '3.14'::numeric(10, 2) AS price;"},{"engine_slug":"postgresql","sql":"SELECT id::text || '-' || label FROM items;"}],"faqs":[{"question":"Is :: faster than CAST?","answer":"No. Both spellings resolve to the same cast operation; :: is purely shorthand. Pick by readability and by whether the query may ever run elsewhere."},{"question":"Why does '13/01/2026'::date fail?","answer":"Text-to-date casts read field order from the DateStyle setting, which defaults to MDY, so 13 is taken as the month and the cast errors with 'date/time field value out of range'. For a known non-ISO format, use TO_DATE('13/01/2026', 'DD/MM/YYYY')."}],"related":["cast","convert","to-char-numeric","implicit-conversion"],"novel_uses":[{"body":"string_to_array returns text[], so its elements stay strings until you cast the whole array. One ::int[] converts every element in a single step, which beats unnest-cast-reaggregate when a stored CSV column feeds an ANY() probe.","sql":"SELECT * FROM shipments WHERE 7 = ANY (string_to_array(StopIds, ',')::int[]);"},{"body":"The regclass cast resolves a table reference, errors if the table does not exist, and re-emits it in canonical quoted form: '\"my table\"'::regclass::text is \"my table\" with the quotes included. The input must already follow identifier rules, so 'my table' unquoted fails with invalid name syntax and 'MyTable' folds to mytable; for a raw name from config or user input, quote it with format('%I', name) or quote_ident first.","sql":"SELECT format('SELECT count(*) FROM %s', '\"my table\"'::regclass::text);"},{"body":"Text-to-boolean casts accept yes, no, on, off, y, n, t, f, 1 and 0 case-insensitively, so survey and form answers load without a CASE ladder. Any other spelling raises an error instead of guessing.","sql":"SELECT answer::bool AS opted_in FROM survey_answers;"}]},"source_url":"https://sqlly.app/sql-functions/pg-cast-operator","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/pi","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PI function","description":"PI() returns the circle constant as a double on four engines. Oracle has no PI(), even in 23ai, so ACOS(-1) stands in. MySQL shows only six decimals.","body":{"slug":"pi","name":"PI","h1":"SQL PI function","category":"math","lede":"Returns an approximation of pi, about 3.141592653589793, as a floating point value.","syntax":"PI()","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"Displays 3.141593 (six decimals) by default, but the value used in arithmetic is the full double"},{"engine_slug":"sqlite","status":"yes","note":"On 3.35+ when the library is compiled with SQLITE_ENABLE_MATH_FUNCTIONS; the sqlite.org CLI ships with it, some distro and embedded builds do not"},{"engine_slug":"oracle","status":"no","note":"No PI() in any release, 23ai included (ORA-00904); use ACOS(-1)"}],"gotchas":["PI() is a double: 15-17 significant digits, so it is close to but not exactly pi. Formulas inherit that precision.","TAN(PI()/2) is not an error or infinity: PI()/2 is only approximately a right angle in floats, so the tangent is a huge finite number.","MySQL prints PI() as 3.141593, which looks like a truncated constant. Only the display is short: PI() + 0.0000000000 shows 3.1415926536, and formulas use the full double."],"examples":[{"engine_slug":"postgresql","sql":"SELECT PI() AS pi;  -- 3.141592653589793"},{"engine_slug":"mysql","sql":"SELECT PI() AS shown, PI() + 0.0000000000 AS more_digits;  -- 3.141593, 3.1415926536"},{"engine_slug":"sql-server","sql":"SELECT RADIUS, PI() * SQUARE(RADIUS) AS area\nFROM circles;"},{"engine_slug":"sqlite","sql":"SELECT pi() AS pi;  -- 3.14159265358979 (the sqlite3 shell shows 15 digits)"},{"engine_slug":"oracle","sql":"SELECT ACOS(-1) AS pi FROM dual;  -- Oracle has no PI()"}],"faqs":[{"question":"What does PI() return exactly?","answer":"The double nearest to pi, 3.141592653589793, accurate to about 16 digits. MySQL displays it as 3.141593 but computes with the full value."},{"question":"How do I get pi on Oracle?","answer":"SELECT ACOS(-1) FROM dual. Oracle has no PI() function in any release, 23ai included. ACOS(-1) on NUMBER returns pi to NUMBER precision, about 38 digits, more than a double carries."},{"question":"Why is TAN(PI()/2) a huge number instead of infinity?","answer":"PI()/2 in double precision is not exactly a right angle, it sits about 6.1e-17 below the true pi/2, roughly 0.28 of one unit in the last place, so the tangent is finite and enormous (about 1.6e16) rather than undefined."}],"related":["sin","cos","degrees","double-precision"],"novel_uses":[{"body":"x - FLOOR(x / (2 * PI())) * (2 * PI()) maps any radian value into one turn, 0 to 2 PI (a tiny negative input can round to exactly 2 PI()), the normalization bearing math needs so 370 and 10 degrees name the same bearing. Run it before averaging or diffing angles.","sql":"SELECT -0.5 - FLOOR(-0.5 / (2 * PI())) * (2 * PI()) AS wrapped;  -- 5.783185307179586"},{"body":"When a table stores circle areas, SQRT(area / PI()) gets the radius back for drawing or distance work. Keeping PI() in the expression instead of a rounded 3.14 avoids a systematic bias in every recovered radius.","sql":"SELECT SQRT(area / PI()) AS radius FROM zones;"}]},"source_url":"https://sqlly.app/sql-functions/pi","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/plus-concat","corpus":"sql-functions","engine":null,"language":"en","title":"SQL + concatenation operator","description":"Concatenate strings with the + operator on SQL Server: NULL poisoning, the int-precedence conversion trap, and when CONCAT is the safer call.","body":{"slug":"plus-concat","name":"+ / +=","h1":"SQL + concatenation operator","category":"string","lede":"SQL Server's traditional concatenation operator, also available as += for appending in UPDATE. Two sharp edges: NULLs and implicit casts.","syntax":"'a' + 'b'  |  SET @s += 'more'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"+ is arithmetic or concatenation depending on operand types"},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["NULL + 'a' is NULL. CONCAT and CONCAT_WS skip NULLs instead; CONCAT_NULL_YIELDS_NULL controls the + behaviour but is deprecated.","The higher-precedence type wins: '5' + 1 is 6 (int converts the string), 'Age: ' + 42 throws a conversion error. CONCAT('Age: ', 42) converts cleanly.","'abc' + REPLICATE('x', 9000) silently truncates at 8000 bytes unless the operands are varchar(max)/nvarchar(max).","Other engines do not use + for strings at all: in MySQL and SQLite, 'a' + 1 is arithmetic (and 'a' casts to 0)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 'Order ' + CAST(42 AS varchar(10)) AS label;  -- Order 42"},{"engine_slug":"sql-server","sql":"SELECT NULL + 'a' AS poisoned;  -- NULL"},{"engine_slug":"sql-server","sql":"UPDATE notes SET body += ' (reviewed)' WHERE id = 7;"}],"faqs":[{"question":"Why does NULL + 'text' return NULL?","answer":"That is the SQL Server default: a NULL operand poisons the + result. Use CONCAT, which treats NULL as an empty string, or CONCAT_WS, which skips NULLs without adding a separator, or ISNULL(col, '') each operand."},{"question":"Why does 'Age: ' + 42 fail?","answer":"int has higher type precedence than varchar, so SQL Server tries to convert 'Age: ' to a number. CONCAT('Age: ', 42) or CAST(42 AS varchar) fixes it."},{"question":"Do other databases use + to join strings?","answer":"No. PostgreSQL, Oracle and SQLite use ||, MySQL uses CONCAT. In MySQL and SQLite, + between strings is arithmetic addition."}],"related":["concat-operator","concat-null-yields-null","concat"],"novel_uses":[{"body":"Before STRING_AGG, SELECT @list = @list + name + ', ' FROM t folded rows into one variable; the trick still works on any version, but the order is whatever the plan returns, so add ORDER BY awareness or sort after.","sql":"DECLARE @list varchar(max) = '';\nSELECT @list = @list + name + ', ' FROM sys.databases;\nSELECT @list;"},{"body":"A computed column keeps the expression out of every query: ALTER TABLE ADD full_name AS (first_name + ' ' + last_name) evaluates on read with no trigger or app code.","sql":"ALTER TABLE users ADD display_name AS (first_name + ' ' + last_name);"}]},"source_url":"https://sqlly.app/sql-functions/plus-concat","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/position","corpus":"sql-functions","engine":null,"language":"en","title":"SQL POSITION function","description":"How POSITION(substr IN str) finds a substring in PostgreSQL and MySQL, what it returns for no match or NULL, and the CHARINDEX and INSTR spellings elsewhere.","body":{"slug":"position","name":"POSITION","h1":"SQL POSITION function","category":"string","lede":"Returns the 1-based position of the first occurrence of a substring, or 0 when it is not found. It is the SQL-standard spelling, but only PostgreSQL and MySQL accept it.","syntax":"POSITION(substr IN str)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"No POSITION; use CHARINDEX(substr, str)."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"POSITION(substr IN str) is a synonym for LOCATE(substr, str)."},{"engine_slug":"sqlite","status":"partial","note":"No POSITION; use INSTR(str, substr)."},{"engine_slug":"oracle","status":"partial","note":"No POSITION; use INSTR(str, substr)."}],"gotchas":["Positions are 1-based and 0 means not found, so POSITION(x IN s) > 0 is the containment test.","A NULL argument returns NULL, not 0, so WHERE POSITION('@' IN email) = 0 silently skips rows where email is NULL.","PostgreSQL matches case exactly under its default deterministic collations, but a nondeterministic ICU collation (deterministic = false) makes it ignore case: POSITION('B' IN 'abc') returns 2 there. MySQL follows the collation, and its default utf8mb4_0900_ai_ci ignores case: POSITION('B' IN 'abc') is 2 there."],"examples":[{"engine_slug":"postgresql","sql":"SELECT POSITION('world' IN 'hello world') AS pos;  -- 7"},{"engine_slug":"mysql","sql":"SELECT POSITION('@' IN email) AS at_sign\nFROM users;"},{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('world', 'hello world') AS pos;  -- 7"},{"engine_slug":"sqlite","sql":"SELECT INSTR('hello world', 'world') AS pos;  -- 7"},{"engine_slug":"oracle","sql":"SELECT INSTR('hello world', 'world') AS pos\nFROM dual;"}],"faqs":[{"question":"What does POSITION return if the substring is not found?","answer":"Zero. NULL comes back only when one of the arguments is NULL."},{"question":"Is POSITION the same as CHARINDEX or INSTR?","answer":"Same answer for a non-empty substring, with different spelling and argument order: CHARINDEX(substr, str) in SQL Server, INSTR(str, substr) in SQLite, Oracle and MySQL. For an empty substring, CHARINDEX returns 0 where PostgreSQL, MySQL and SQLite return 1. Only PostgreSQL and MySQL accept the standard POSITION(substr IN str) form."},{"question":"How do I find the second occurrence of a substring?","answer":"POSITION has no start argument. In PostgreSQL search the remainder: POSITION('x' IN SUBSTRING(s FROM p + 1)) + p, remembering that a miss returns p rather than 0. MySQL's LOCATE('x', s, p + 1) and Oracle's INSTR(s, 'x', 1, 2) do it directly."}],"related":["charindex","strpos","instr","locate"],"novel_uses":[{"body":"The match position minus one is exactly the prefix length, so LEFT(sku, POSITION('-' IN sku) - 1) splits the code before the first dash in PostgreSQL or MySQL. When the dash is missing POSITION returns 0 and the subtraction misfires, so filter with POSITION(...) > 0 first.","sql":"SELECT LEFT(sku, POSITION('-' IN sku) - 1) AS prefix\nFROM parts\nWHERE POSITION('-' IN sku) > 0;"},{"body":"In PostgreSQL, ORDER BY NULLIF(POSITION('needle' IN col), 0) puts rows that contain the needle first, ordered by how early it appears. NULLIF turns the 0 of a miss into NULL, and NULLs sort last on an ascending sort.","sql":"SELECT * FROM docs\nORDER BY NULLIF(POSITION('urgent' IN note), 0);"},{"body":"A CHECK constraint built on POSITION enforces shape rules such as no spaces in a username. PostgreSQL enforces it, and MySQL does too from 8.0.16; older MySQL versions parse the constraint and then ignore it.","sql":"ALTER TABLE users ADD CONSTRAINT no_spaces\n  CHECK (POSITION(' ' IN username) = 0);"}]},"source_url":"https://sqlly.app/sql-functions/position","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/postgres-window-features","corpus":"sql-functions","engine":null,"language":"en","title":"PostgreSQL window function features","description":"PostgreSQL's window feature set: FILTER, GROUPS, EXCLUDE, interval RANGE frames and named windows, plus what it still lacks in version 18.","body":{"slug":"postgres-window-features","name":"PostgreSQL Window Features","h1":"PostgreSQL window function features","category":"window","lede":"PostgreSQL 9.4+ has FILTER, 11+ adds GROUPS, EXCLUDE and RANGE offsets, and named windows work too; the notable absences are IGNORE NULLS, FROM LAST and QUALIFY.","syntax":"AVG(x) FILTER (WHERE c) OVER (ORDER BY d GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW EXCLUDE TIES)","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"no","note":"named WINDOW clause on 2022 (verified 16.0.4325.4); no FILTER, GROUPS, EXCLUDE or RANGE offsets"},{"engine_slug":"postgresql","status":"partial","note":"11+ for GROUPS/EXCLUDE/RANGE offsets; 9.4+ for FILTER; no IGNORE NULLS or QUALIFY through PostgreSQL 18"},{"engine_slug":"mysql","status":"partial","note":"named WINDOW and numeric RANGE offsets on 8.4 (verified); no FILTER, GROUPS, EXCLUDE or IGNORE NULLS"},{"engine_slug":"sqlite","status":"partial","note":"FILTER, GROUPS, EXCLUDE, named windows and numeric RANGE offsets on 3.51.0 (verified); no interval RANGE, IGNORE NULLS, FROM LAST or QUALIFY"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Still missing through PostgreSQL 18: IGNORE NULLS and FROM LAST on the offset functions, and QUALIFY. The COUNT/MAX forward fill and the CTE filter replace them.","DISTINCT inside window aggregates and ORDER BY inside a windowed aggregate call (string_agg(x, ',' ORDER BY x) OVER ...) both raise 'not implemented for window functions'.","Named windows can be extended (OVER (w ORDER BY ...)) as long as w has no ORDER BY or frame of its own, and FILTER combines freely with frames and EXCLUDE."],"examples":[{"engine_slug":"postgresql","sql":"SELECT symbol, day, close,\n       AVG(close) FILTER (WHERE volume > 0) OVER w AS avg_active,\n       AVG(close) OVER (w ORDER BY day GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW\n                        EXCLUDE CURRENT ROW) AS ma2_ex_self\nFROM quotes\nWINDOW w AS (PARTITION BY symbol);"}],"faqs":[{"question":"Does PostgreSQL support IGNORE NULLS?","answer":"No, through PostgreSQL 18 it is a syntax error. Forward-fill with the COUNT(expr) OVER (ORDER BY id) grouping trick or a LATERAL last-non-NULL join."},{"question":"Does PostgreSQL implement the whole standard for windows?","answer":"Most of the frame syntax (GROUPS, EXCLUDE, RANGE offsets, named windows) is there. The gaps are IGNORE NULLS, FROM LAST, DISTINCT in window aggregates and aggregate ORDER BY in window form. QUALIFY is not standard, so its absence is not a gap."}],"related":["filter-over","groups-frame","window-versions"],"novel_uses":[{"body":"FILTER inside the aggregate and EXCLUDE CURRENT ROW on the frame compose: the average of the neighbours that actually have readings, with the row itself and its NULLs both out of the way. PostgreSQL runs the full combination; engines missing either clause need the subtraction rewrite.","sql":"SELECT day, temp,\n       AVG(temp) FILTER (WHERE temp IS NOT NULL) OVER (\n         ORDER BY day ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING\n         EXCLUDE CURRENT ROW) AS neighbours_avg\nFROM readings;"},{"body":"PostgreSQL's DISTINCT ON picks one row per key without any window scaffolding; ORDER BY the key then the priority columns and the first row of each group survives. Ties beyond the listed keys are resolved arbitrarily, so end the ORDER BY with a unique column when the choice matters.","sql":"SELECT DISTINCT ON (customer_id) customer_id, order_id, amount\nFROM orders\nORDER BY customer_id, amount DESC, order_id;"}]},"source_url":"https://sqlly.app/sql-functions/postgres-window-features","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/power","corpus":"sql-functions","engine":null,"language":"en","title":"SQL POWER function","description":"Exponentiation with POWER and POW in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: integer versus float results and the compound-interest pattern.","body":{"slug":"power","name":"POWER / POW","h1":"SQL POWER function","category":"math","lede":"Raises a base to an exponent: POWER(2, 10) is 1024. On SQL Server the result takes the base's type, so integer bases can overflow or lose fractions.","syntax":"POWER(base, exponent)  |  POW(base, exponent)  -- MySQL, PostgreSQL, SQLite  |  base ^ exponent  -- PostgreSQL","return_type":"float or numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"POWER, POW and the ^ operator"},{"engine_slug":"mysql","status":"yes","note":"POWER and POW"},{"engine_slug":"sqlite","status":"yes","note":"POWER and POW, math functions from SQLite 3.35+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server returns the base's type: POWER(2, 10) is int, POWER(2, 31) overflows, and POWER(2, -1) is 0. Cast the base: POWER(CAST(2 AS float), 31). PostgreSQL, MySQL and SQLite return double precision for integer inputs.","PostgreSQL's ^ operator is exponentiation, but on SQL Server and MySQL ^ is bitwise XOR: 2 ^ 3 is 8 on PostgreSQL and 1 on the other two.","A negative base with a fractional exponent has no real result: SQLite returns NULL, while SQL Server, PostgreSQL, MySQL and Oracle raise an error for POWER(-8, 0.5)."],"examples":[{"engine_slug":"all","sql":"SELECT POWER(2, 10) AS kilo;  -- 1024"},{"engine_slug":"all","sql":"SELECT principal * POWER(1.05, years) AS compound\nFROM deposits;"}],"faqs":[{"question":"What is the difference between POWER and POW?","answer":"Nothing. PostgreSQL, MySQL and SQLite accept both spellings; SQL Server and Oracle only have POWER."},{"question":"Why does my POWER overflow?","answer":"On SQL Server the result has the base's type, so an int base overflows past 2,147,483,647. Cast the base: POWER(CAST(2 AS FLOAT), 100). Other engines already return double precision and only overflow near 1e308."}],"related":["sqrt","round","floor"],"novel_uses":[{"body":"Legacy feeds pack dates as 20260801; integer division and MOD take them apart: x / 10000 is the year, MOD(x / 100, 100) the month. POWER(10, k) generalizes it to any digit position. Integer division truncates on SQL Server, PostgreSQL and SQLite; MySQL needs DIV instead of /.","sql":"SELECT CAST('20260801' AS integer) / 10000 AS yr,\n       MOD(CAST('20260801' AS integer) / 100, 100) AS mo,\n       MOD(CAST('20260801' AS integer), 100) AS dy;"},{"body":"Storing POWER(2, attempt) on the row itself hands the scheduler its next delay, doubling 2, 4, 8, 16 seconds with no state anywhere else. Cap it with a CASE so a stuck job's fortieth retry does not ask for more seconds than the universe has left.","sql":"SELECT attempt,\n       CASE WHEN POWER(2, attempt) > 3600 THEN 3600 ELSE POWER(2, attempt) END AS wait_seconds\nFROM retries;"}]},"source_url":"https://sqlly.app/sql-functions/power","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/printf","corpus":"sql-functions","engine":null,"language":"en","title":"SQL printf / format function","description":"sprintf-style formatting in SQLite (printf, alias format) and PostgreSQL (format): SQLite takes placeholders like %s and %d, PostgreSQL takes %s, %I and %L.","body":{"slug":"printf","name":"printf / format","h1":"SQL printf / format function","category":"string","lede":"Formats a template with arguments like C's sprintf. SQLite's printf and format and PostgreSQL's format() cover the niche between CONCAT and TO_CHAR.","syntax":"printf(format, args...)  |  format(format, args...)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"format() with %s, %I and %L placeholders"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"yes","note":"printf() from 3.8.3; format() alias from 3.38.0"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["SQLite printf supports the C staples: %d, %s, %f, width and zero-fill like %05d. PostgreSQL's format is simpler: %s, %I (identifier), %L (literal), with %1$s positional reuse.","PostgreSQL's format has no %.1f-style precision; use to_char or round() first, then feed the result in as %s.","SQL Server's nearest tool is FORMATMESSAGE; MySQL and Oracle have no sprintf-style function; CONCAT chains or TO_CHAR do the work.","In SQLite, format() and printf() are the same function. format() only exists from SQLite 3.38.0, so use printf() when older builds are in play."],"examples":[{"engine_slug":"sqlite","sql":"SELECT printf('%05d', 42) AS padded;  -- 00042"},{"engine_slug":"postgresql","sql":"SELECT format('%s (%s)', 'draft', 'v2') AS label;  -- draft (v2)"},{"engine_slug":"postgresql","sql":"SELECT format('%I = %L', 'order details', 'it''s') AS safe;  -- \"order details\" = 'it''s'"}],"faqs":[{"question":"What is the difference between printf and format in SQLite?","answer":"None. They are the same function. printf() came first (3.8.3); SQLite 3.38.0 made format() the primary name and kept printf() as an alias, matching the name PostgreSQL uses."},{"question":"What do %I and %L mean in PostgreSQL's format()?","answer":"%I quotes the value as an identifier (safe for dynamic SQL object names), %L as a literal (quotes and doubles embedded quotes). %s substitutes plain text."},{"question":"Can I zero-pad numbers with printf?","answer":"Yes: printf('%06d', 1234) is 001234 in SQLite. That is also the standard SQLite answer to LPAD-style padding, which SQLite does not have."}],"related":["zero-pad","formatmessage","to-char"],"novel_uses":[{"body":"Width and precision flags give SQLite the LPAD/RPAD layout work it otherwise lacks: %-12s left-aligns text and %8.2f right-aligns money into fixed columns.","sql":"SELECT printf('%-12s| %8.2f', name, total) AS line FROM accounts;"},{"body":"PostgreSQL's format() accepts positional references, so one value can appear twice without passing it again: handy for generated emails and labels.","sql":"SELECT format('%1$s %2$s <%1$s.%2$s@corp.example>', first_name, last_name) AS email FROM users;"},{"body":"SQLite's printf adds %q and %Q beyond C's set: %Q wraps the value in single quotes and doubles embedded ones, and passes NULL through unquoted, ready to paste into generated SQL.","sql":"SELECT printf('INSERT INTO t VALUES (%Q);', note) AS stmt FROM notes;"}]},"source_url":"https://sqlly.app/sql-functions/printf","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/printf-sqlite","corpus":"sql-functions","engine":null,"language":"en","title":"SQLite printf function","description":"How SQLite's printf and format compose strings with % patterns: width and precision, %q and %Q for SQL quoting, thousands separators and the equivalents elsewhere.","body":{"slug":"printf-sqlite","name":"PRINTF","h1":"SQLite printf function","category":"string","lede":"Builds a string from a C-style format pattern and a list of arguments.","syntax":"printf(format, arg, ...)  |  format(format, arg, ...)  -- alias from 3.38","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"FORMATMESSAGE('%s has %d', a, b) takes printf-style placeholders."},{"engine_slug":"postgresql","status":"partial","note":"format() with %s, %I and %L; no %d or %f and no precision. %s takes a width, so format('%5s', 42) pads a number."},{"engine_slug":"mysql","status":"no","note":"No printf-style function; CONCAT and FORMAT."},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"No printf-style SQL function; TO_CHAR and ||."}],"gotchas":["printf has been in SQLite for a long time; format() was added in 3.38.0 as another name for it.","Patterns follow C: %d for integers, %.2f for two decimals, %s for text, %% for a literal percent sign. SQLite adds a ',' flag for thousands separators: printf('%,d', 1234567) is '1,234,567'.","%q doubles single quotes without adding outer quotes; %Q also wraps the value in quotes and turns NULL into the bare word NULL. %w doubles double quotes for identifiers."],"examples":[{"engine_slug":"sqlite","sql":"SELECT printf('%s: %.2f', 'total', 12.5) AS line;  -- total: 12.50"},{"engine_slug":"sqlite","sql":"SELECT printf('%05d', id) AS zero_padded\nFROM invoices;"},{"engine_slug":"sqlite","sql":"SELECT format('%s=%Q', k, v) AS pair\nFROM settings;"},{"engine_slug":"sql-server","sql":"SELECT FORMATMESSAGE('%s has %d items', 'cart', 3) AS line;"},{"engine_slug":"postgresql","sql":"SELECT format('%I = %L', 'user name', 'O''Brien') AS sql;"}],"faqs":[{"question":"Is format() the same as printf() in SQLite?","answer":"Yes. format() arrived in SQLite 3.38.0 as an alias; both accept the same patterns, including %q, %Q and %w."},{"question":"How do I zero-pad a number in SQLite?","answer":"printf('%05d', n) pads to five digits with zeros. The width comes before the type letter, and a leading 0 in the width enables zero fill."},{"question":"What does %Q do that %s does not?","answer":"%Q wraps the text in single quotes and doubles embedded quotes, producing a literal that is safe to embed in generated SQL; %s substitutes the raw text."}],"related":["format","strftime","rpad","quote"],"novel_uses":[{"body":"printf builds one row's VALUES clause and group_concat joins them, which turns a table into an INSERT script without leaving the sqlite3 shell. %Q quotes each text value safely.","sql":"SELECT group_concat(printf('(%Q, %d)', name, qty), ',' || char(10))\nFROM items;"},{"body":"A minus sign before the width (%-16s) left-aligns text, and a width with .2f right-aligns numbers, so printf lays out monospace reports right in the sqlite3 shell.","sql":"SELECT printf('%-16s| %8.2f', name, price) FROM items;"}]},"source_url":"https://sqlly.app/sql-functions/printf-sqlite","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/product","corpus":"sql-functions","engine":null,"language":"en","title":"SQL PRODUCT aggregate","description":"SQL Server 2025 adds PRODUCT() to multiply the values in a group. Elsewhere, EXP(SUM(LN(x))) does it for positive numbers. Overflow, zeros and NULLs explained.","body":{"slug":"product","name":"PRODUCT","h1":"SQL PRODUCT aggregate","category":"aggregate","lede":"PRODUCT(x) is to multiplication what SUM is to addition. Compound growth from a column of rates is the usual reason to want it.","syntax":"PRODUCT([ALL | DISTINCT] expression)  |  PRODUCT([ALL] expression) OVER ([PARTITION BY ...] [ORDER BY ...])","return_type":"int for tinyint, smallint and int; bigint for bigint; decimal(38, 0) or decimal(38, 6) for decimal; money for money and smallmoney; float for float and real","support":[{"engine_slug":"sql-server","status":"yes","note":"PRODUCT() from SQL Server 2025"},{"engine_slug":"postgresql","status":"no","note":"no; EXP(SUM(LN(x))) for positive values"},{"engine_slug":"mysql","status":"no","note":"no; EXP(SUM(LN(x))) for positive values"},{"engine_slug":"sqlite","status":"no","note":"no; exp(sum(ln(x))) where the math functions are compiled in"},{"engine_slug":"oracle","status":"no","note":"no; EXP(SUM(LN(x))) for positive values"}],"gotchas":["PRODUCT ignores NULLs and returns NULL for an empty or all-NULL group.","Integer input gives an int result that overflows fast: two rows of 100000 fail with an arithmetic overflow. Cast to bigint, decimal or float first.","The EXP(SUM(LN(x))) workaround breaks on zero and negative values, where LN is undefined: PostgreSQL raises an error, while MySQL and SQLite return NULL from LN and SUM silently skips that row, so 2, 0 and 4 give 7.999999999999998 instead of 0. It also returns floating-point noise: 2 * 3 * 4 comes back as 23.999999999999993 on PostgreSQL and MySQL.","For compound growth, PRODUCT(1 + rate) - 1 is the cumulative return: rates of 10%, 5% and -2% give 0.1319."],"examples":[{"engine_slug":"sql-server","sql":"SELECT PRODUCT(x) AS all_values, PRODUCT(DISTINCT x) AS distinct_values\nFROM (VALUES (2), (2), (3), (CAST(NULL AS INT))) AS t(x);  -- 12, 6"},{"engine_slug":"sql-server","sql":"SELECT PRODUCT(1 + r) - 1 AS growth\nFROM (VALUES (0.10), (0.05), (-0.02)) AS t(r);  -- 0.131900"},{"engine_slug":"postgresql","sql":"SELECT exp(sum(ln(x))) AS product\nFROM (VALUES (2), (3), (4)) AS t(x);  -- 23.999999999999993"}],"faqs":[{"question":"Which engines have PRODUCT?","answer":"SQL Server 2025, Azure SQL Database, Azure SQL Managed Instance and Microsoft Fabric. None of the other four engines here has a built-in product aggregate."},{"question":"How do I handle zeros and negatives in the LN workaround?","answer":"Multiply the magnitudes and fix the sign separately: CASE WHEN SUM(CASE WHEN x = 0 THEN 1 ELSE 0 END) > 0 THEN 0 ELSE EXP(SUM(LN(ABS(NULLIF(x, 0))))) * (1 - 2 * (SUM(CASE WHEN x < 0 THEN 1 ELSE 0 END) % 2)) END. The NULLIF keeps zeros away from LN, which errors on 0 in PostgreSQL. For -2, 3 and 4 it returns -23.999999999999993."}],"related":["sum","exp","ln","aggregate-nulls"],"novel_uses":[{"body":"A join that returns each rate row twice multiplies it twice, and PRODUCT has no idea the duplication was accidental. PRODUCT(DISTINCT x) collapses exact duplicates; the cleaner fix is to aggregate the rates in a CTE before joining.","sql":"SELECT PRODUCT(DISTINCT r) AS clean\nFROM (VALUES (1.10), (1.10), (1.05)) AS t(r);  -- 1.155, not 1.2705"},{"body":"PRODUCT returns NULL for an empty or all-NULL group, not 1, so a report that joins cohort totals shows blanks for quiet months. COALESCE(PRODUCT(x), 1) keeps the multiplicative identity and lets downstream multiplication stay correct.","sql":"SELECT COALESCE(PRODUCT(x), 1) AS safe_product\nFROM (VALUES (1)) AS t(x)\nWHERE 1 = 0;  -- empty group: 1"}]},"source_url":"https://sqlly.app/sql-functions/product","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/qualify","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUALIFY clause","description":"QUALIFY filters window function results in one clause: native in Snowflake, DuckDB, BigQuery and Oracle AI Database 26ai, absent from the other four engines here.","body":{"slug":"qualify","name":"QUALIFY","h1":"SQL QUALIFY clause","category":"window","lede":"A SELECT-level clause evaluated after windows compute, letting you write WHERE rn = 1 logic without a CTE or subquery.","syntax":"SELECT ... FROM t QUALIFY ROW_NUMBER() OVER (PARTITION BY g ORDER BY d) = 1","return_type":"filtered rows","support":[{"engine_slug":"sql-server","status":"no","note":"no QUALIFY, including SQL Server 2025; wrap the window in a CTE or subquery"},{"engine_slug":"postgresql","status":"no","note":"no QUALIFY through PostgreSQL 18; CTE or subquery required"},{"engine_slug":"mysql","status":"no","note":"no QUALIFY; CTE or subquery required"},{"engine_slug":"sqlite","status":"no","note":"no QUALIFY; CTE or subquery required"},{"engine_slug":"oracle","status":"yes","note":"Oracle AI Database 26ai (release update 23.26.0) and later; earlier 23ai and 19c need the CTE"}],"gotchas":["Of the five engines here only Oracle has QUALIFY, and only from release update 23.26.0 (branded 26ai). It also exists in Teradata, Snowflake, DuckDB, Databricks SQL and BigQuery, so it shows up in code being ported in.","Evaluation order where it exists: WHERE, then GROUP BY/HAVING, then windows, then QUALIFY, then ORDER BY; it is literally WHERE for window results.","The portable replacement is mechanical: compute the same expression as a column in a CTE, then filter on that column outside."],"examples":[{"engine_slug":"oracle","sql":"-- Oracle 26ai, and Snowflake/Teradata/DuckDB/BigQuery\nSELECT * FROM orders\nQUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) = 1;"},{"engine_slug":"postgresql","sql":"-- what the other engines require:\nWITH r AS (\n  SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn\n  FROM orders\n)\nSELECT * FROM r WHERE rn = 1;"}],"faqs":[{"question":"Does PostgreSQL or SQL Server support QUALIFY?","answer":"No, not PostgreSQL 18 and not SQL Server 2025. Both need the CTE or subquery pattern. Oracle added it in release update 23.26.0; Teradata, Snowflake, DuckDB, Databricks and BigQuery have it too."},{"question":"Is QUALIFY part of the SQL standard?","answer":"No. It started in Teradata and spread vendor by vendor, which is why support is patchy. The CTE rewrite gives the same result on any engine with window functions."}],"related":["qualify-alternatives","window-in-cte","top-n-per-group"],"novel_uses":[{"body":"QUALIFY after a COUNT partitioned by the business key leaves only the duplicated rows in the output. NULL keys form one partition, so two rows with a NULL email count as duplicates of each other. The CTE version needs a wrap; here the filter sits next to the window it reads.","sql":"SELECT contact_id, email\nFROM contacts\nQUALIFY COUNT(*) OVER (PARTITION BY email) > 1;"},{"body":"QUALIFY price > AVG(price) OVER () keeps the above-average rows without wrapping the average in a subquery. The condition is ordinary SQL, so thresholds like twice the average work too.","sql":"SELECT product_id, price\nFROM products\nQUALIFY price > AVG(price) OVER ();"}]},"source_url":"https://sqlly.app/sql-functions/qualify","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/qualify-alternatives","corpus":"sql-functions","engine":null,"language":"en","title":"SQL alternatives to QUALIFY","description":"Three shapes that replace QUALIFY: the CTE wrap, the derived table and the LATERAL (or CROSS APPLY) top-N join, with each engine's spelling.","body":{"slug":"qualify-alternatives","name":"QUALIFY Alternatives","h1":"SQL alternatives to QUALIFY","category":"window","lede":"Every QUALIFY query converts to a CTE filter, a derived-table filter, or a lateral top-N join; each shape fits a different case.","syntax":"WITH r AS (... ) WHERE rn = 1 | JOIN LATERAL (...) LIMIT 1","return_type":"filtered rows","support":[{"engine_slug":"sql-server","status":"yes","note":"CROSS APPLY instead of LATERAL"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+; LATERAL since 8.0.14"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; no LATERAL keyword; use correlated subqueries in SELECT"},{"engine_slug":"oracle","status":"yes","note":"LATERAL and CROSS APPLY since 12c"}],"gotchas":["The CTE shape wins for reuse (several filters on window columns) and readability; the subquery shape wins for one-shot rn = 1 filters in ORMs that fight CTEs.","LATERAL top-1 per group scales differently: it loops the outer row count times but touches few rows per iteration, often faster than windowing a huge partition when the outer side is small.","A correlated subquery in SELECT can fetch the top value per row (SELECT MAX(amount) FROM orders o WHERE o.customer_id = c.customer_id) without any window at all; a scalar subquery returns exactly one column, so several columns of the top row need one subquery per column (each repeating the lookup) or a LATERAL / CROSS APPLY join."],"examples":[{"engine_slug":"postgresql","sql":"-- lateral top-1: fastest when groups are small and numerous\nSELECT c.customer_id, top_orders.id, top_orders.amount\nFROM customers c\nCROSS JOIN LATERAL (\n  SELECT o.id, o.amount\n  FROM orders o\n  WHERE o.customer_id = c.customer_id\n  ORDER BY o.amount DESC\n  LIMIT 1\n) top_orders;"},{"engine_slug":"all","sql":"-- inline subquery form\nSELECT *\nFROM (\n  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn\n  FROM orders o\n) ranked\nWHERE rn = 1;"}],"faqs":[{"question":"Which alternative should I default to?","answer":"The CTE wrap: it ports everywhere window functions do, handles multiple window columns, and keeps the window logic in one visible place. Reach for LATERAL only on measured hot paths."},{"question":"Can I emulate QUALIFY without wrapping the query?","answer":"Not in general. Top-1 per group has unwrapped forms: a NOT EXISTS anti-join against a higher-ranked row (every engine), DISTINCT ON in PostgreSQL, and TOP 1 WITH TIES ... ORDER BY ROW_NUMBER() OVER (...) in SQL Server. Any other filter on a window column needs the query wrapped in a CTE or derived table; that wrap is exactly what QUALIFY saves you."}],"related":["qualify","window-in-cte","top-n-per-group"],"novel_uses":[{"body":"OFFSET inside a lateral join pages every group in one statement: rows six through ten per category leave the database in a single result set. PostgreSQL writes LIMIT and OFFSET; SQL Server 2012+ writes OFFSET n ROWS FETCH NEXT m ROWS ONLY inside CROSS APPLY.","sql":"SELECT c.category, p.product_id, p.price\nFROM categories c\nCROSS JOIN LATERAL (\n  SELECT product_id, price\n  FROM products pr\n  WHERE pr.category = c.category\n  ORDER BY price DESC\n  LIMIT 5 OFFSET 5\n) p;"},{"body":"When the question is whether a group contains a qualifying row, EXISTS answers with an index probe and stops at the first hit, while the window path ranks every row of every group first. Reserve windows for when the rank itself is the answer.","sql":"SELECT customer_id\nFROM customers c\nWHERE EXISTS (\n  SELECT 1 FROM orders o\n  WHERE o.customer_id = c.customer_id AND o.amount > 500);"}]},"source_url":"https://sqlly.app/sql-functions/qualify-alternatives","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quarter","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUARTER function","description":"Get the quarter 1-4: QUARTER() on MySQL, DATEPART(quarter) on SQL Server, EXTRACT(quarter) on PostgreSQL, and the workarounds where it is missing.","body":{"slug":"quarter","name":"QUARTER","h1":"SQL QUARTER function","category":"datetime","lede":"Returns the calendar quarter as an integer 1-4. SQLite has no quarter function at all, and Oracle only formats it as text.","syntax":"DATEPART(quarter, d)  -- SQL Server  |  EXTRACT(quarter FROM d)  -- PostgreSQL  |  QUARTER(d)  -- MySQL","return_type":"integer (numeric on PostgreSQL)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(quarter, d)"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(quarter FROM d)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"compute it: (CAST(strftime('%m', d) AS INTEGER) + 2) / 3"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'Q') returns text"}],"gotchas":["Oracle has no EXTRACT(quarter): TO_CHAR(d, 'Q') is the stand-in and returns text, not a number.","Quarters are calendar quarters on every engine; fiscal quarters need your own mapping table or an offset by months.","SQLite needs the arithmetic form: (month + 2) / 3 with integer division gives 1 through 4."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(year FROM created_at) AS yr,\n       EXTRACT(quarter FROM created_at) AS qtr, COUNT(*)\nFROM orders GROUP BY 1, 2;"},{"engine_slug":"mysql","sql":"SELECT QUARTER(created_at) AS qtr FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'Q') AS qtr FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(quarter, created_at) AS qtr FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT (CAST(strftime('%m', created_at) AS INTEGER) + 2) / 3 AS qtr FROM orders;"}],"faqs":[{"question":"How do I get quarters in SQLite?","answer":"No QUARTER function: (CAST(strftime('%m', d) AS INTEGER) + 2) / 3 with integer division returns 1-4."},{"question":"Can I get fiscal quarters?","answer":"Not directly. Shift the date by the fiscal offset in months first (DATEADD(month, -3, d) on SQL Server), then take the calendar quarter."}],"related":["extract","month","date-trunc"],"novel_uses":[{"body":"date_trunc('quarter', ts) returns the quarter start as a real timestamp, no arithmetic and no format codes.","sql":"SELECT date_trunc('quarter', created_at) AS q FROM orders;"},{"body":"SQL Server 2022 and later have DATETRUNC(quarter, d), which returns the quarter start directly. On earlier versions, DATEFROMPARTS(YEAR(d), (DATEPART(quarter, d) - 1) * 3 + 1, 1) builds the same quarter-start date key.","sql":"SELECT DATEFROMPARTS(YEAR(created_at), (DATEPART(quarter, created_at) - 1) * 3 + 1, 1) AS quarter_start\nFROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/quarter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quote","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUOTE function","description":"QUOTE turns a value into a SQL literal on MySQL and SQLite: MySQL escapes with backslashes, SQLite doubles quotes. Parameterized queries make it unnecessary.","body":{"slug":"quote","name":"QUOTE","h1":"SQL QUOTE function","category":"string","lede":"Returns the argument as a quoted SQL string literal, escaping embedded quotes (and, on MySQL, backslashes). Useful for generating SQL text; parameters are better for running it.","syntax":"QUOTE(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"QUOTENAME(s, '''') for strings up to 128 characters; longer input returns NULL"},{"engine_slug":"postgresql","status":"partial","note":"quote_literal(s), or quote_nullable(s) to get the bare word NULL"},{"engine_slug":"mysql","status":"yes","note":"escapes ', \\, NUL (as \\0) and Ctrl-Z (as \\Z); newlines pass through; result is wrapped in single quotes"},{"engine_slug":"sqlite","status":"yes","note":"doubles embedded quotes; numbers come back bare, blobs as X'..' literals"},{"engine_slug":"oracle","status":"no","note":"no equivalent; double the quotes with REPLACE(s, '''', '''''')"}],"gotchas":["The result includes the surrounding quotes: QUOTE('ab') returns 'ab' with quotes included, so it slots straight into a composed statement.","MySQL escapes with a backslash: QUOTE('O''Brien') is 'O\\'Brien', which only parses where backslash escapes are on. SQLite doubles the quote instead and returns 'O''Brien', which parses everywhere.","It is for string literals only, not identifiers. MySQL's identifier helper is sys.quote_identifier() in the sys schema.","Parameterized queries beat QUOTE every time: no escaping logic, no injection surface. QUOTE is for the rare dynamic case you cannot parameterize."],"examples":[{"engine_slug":"mysql","sql":"SELECT QUOTE('O''Brien') AS lit;  -- 'O\\'Brien'"},{"engine_slug":"mysql","sql":"SELECT QUOTE(NULL) AS lit;  -- NULL (unquoted)"},{"engine_slug":"sqlite","sql":"SELECT quote('O''Brien') AS lit, quote(x'ab') AS blob_lit;  -- 'O''Brien', X'AB'"},{"engine_slug":"postgresql","sql":"SELECT quote_literal('O''Brien') AS lit;  -- 'O''Brien'"},{"engine_slug":"sql-server","sql":"SELECT QUOTENAME('O''Brien', '''') AS lit;  -- 'O''Brien', strings up to 128 characters only"}],"faqs":[{"question":"Is QUOTE safe against SQL injection?","answer":"On SQLite it is safe for string literals: quotes are doubled and nothing else needs escaping. On MySQL it is safe only in the default sql_mode. With NO_BACKSLASH_ESCAPES on, QUOTE still backslash-escapes, so a value with a backslash before a quote breaks out of the literal and injects SQL. It does not cover identifiers, numbers from strings, or other engines. Parameters remain the right answer."},{"question":"Why does the output include the quotes?","answer":"QUOTE returns a ready-to-paste literal: quotes and escapes included. QUOTE('ab') yields 'ab', four characters counting the quotes."},{"question":"What is the SQL Server equivalent?","answer":"QUOTENAME, which quotes identifiers with brackets by default. QUOTENAME(s, '''') returns a quoted string literal with embedded quotes doubled, but only for input up to 128 characters; past that it returns NULL, so longer values need '''' + REPLACE(s, '''', '''''') + ''''."}],"related":["quotename","backslash-escapes","identifier-quoting"],"novel_uses":[{"body":"Wrapping each value in quote() and gluing the SQL around it prints runnable INSERT statements from a SELECT, with the escaping already done.","sql":"SELECT 'INSERT INTO tags VALUES (' || quote(tag) || ');' AS stmt FROM tags;  -- SQLite"},{"body":"Quoting a value in a debug SELECT exposes trailing spaces and embedded quotes that result grids trim away, which settles the length looks wrong arguments fast.","sql":"SELECT quote(note) AS shown, LENGTH(note) AS actual FROM notes;"}]},"source_url":"https://sqlly.app/sql-functions/quote","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quote-ident","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUOTE_IDENT function","description":"How PostgreSQL's quote_ident wraps an identifier in double quotes only when needed: case folding, reserved words, and the QUOTENAME and format %I equivalents.","body":{"slug":"quote-ident","name":"QUOTE_IDENT","h1":"SQL QUOTE_IDENT function","category":"string","lede":"Returns a string quoted as a valid SQL identifier, adding double quotes only when required.","syntax":"quote_ident(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"QUOTENAME(name) always adds brackets."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"sys.quote_identifier() wraps a name in backticks and doubles any backticks inside."},{"engine_slug":"sqlite","status":"no","note":"No identifier quoter; printf('%w') escapes double quotes inside a name."},{"engine_slug":"oracle","status":"no","note":"No direct equivalent; DBMS_ASSERT.ENQUOTE_NAME uppercases by default."}],"gotchas":["Valid unquoted identifiers come back unchanged: quote_ident('orders') is orders. Spaces, uppercase letters, a leading digit or a reserved word get double quotes: quote_ident('order') is \"order\".","PostgreSQL folds unquoted identifiers to lowercase, so quote_ident('Orders') returns \"Orders\" to preserve the capital.","Embedded double quotes are doubled, and format('%I.%I', schema, table) applies the same rules to each argument."],"examples":[{"engine_slug":"postgresql","sql":"SELECT quote_ident('order details') AS ident;  -- \"order details\""},{"engine_slug":"postgresql","sql":"SELECT format('SELECT count(*) FROM %I', 'Order Lines') AS sql;"},{"engine_slug":"sql-server","sql":"SELECT QUOTENAME('Order Details') AS ident;  -- [Order Details]"}],"faqs":[{"question":"What is the difference between quote_ident and quote_literal?","answer":"quote_ident is for identifiers (tables, columns) and uses double quotes; quote_literal is for string values and uses single quotes. Swapping them produces invalid or wrong SQL."},{"question":"When does quote_ident actually add quotes?","answer":"When the text is not a valid unquoted identifier: uppercase letters, spaces or punctuation, a leading digit, or a reserved keyword such as order or user."}],"related":["quote-literal","quotename","format","quote"],"novel_uses":[{"body":"When quote_ident(input) comes back different from the input, the text was not a safe plain identifier: it had uppercase, spaces, punctuation or was reserved. Report builders can use that as a cheap rejection test.","sql":"SELECT quote_ident('Order Lines') <> 'Order Lines' AS needs_quoting;"},{"body":"Interpolating a schema name straight into SET would allow injection through configuration, but format with %I quotes it correctly first.","sql":"EXECUTE format('SET search_path = %I', v_schema);"}]},"source_url":"https://sqlly.app/sql-functions/quote-ident","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quote-literal","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUOTE_LITERAL function","description":"How PostgreSQL's quote_literal makes text safe to embed as a SQL literal: quote doubling, backslash handling, NULL results and the format %L shortcut.","body":{"slug":"quote-literal","name":"QUOTE_LITERAL","h1":"SQL QUOTE_LITERAL function","category":"string","lede":"Returns the argument as a correctly quoted SQL string literal with embedded quotes doubled.","syntax":"quote_literal(string)  |  quote_nullable(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"QUOTENAME(s, '''') for strings up to 128 characters."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"Use QUOTE(str)."},{"engine_slug":"sqlite","status":"partial","note":"Use QUOTE(x)."},{"engine_slug":"oracle","status":"partial","note":"DBMS_ASSERT.ENQUOTE_LITERAL."}],"gotchas":["quote_literal(NULL) returns NULL, which silently drops the value from concatenated SQL; quote_nullable(NULL) returns the word NULL. Choose deliberately.","Backslashes are doubled and the literal gets an E prefix: quote_literal(E'a\\\\b') returns E'a\\\\b', which parses the same whatever standard_conforming_strings is set to.","It protects literal values only; identifiers need quote_ident or format's %I."],"examples":[{"engine_slug":"postgresql","sql":"SELECT quote_literal('O''Brien') AS literal;  -- 'O''Brien'"},{"engine_slug":"postgresql","sql":"SELECT format('SELECT * FROM t WHERE name = %L', 'O''Brien') AS sql;"},{"engine_slug":"sql-server","sql":"SELECT QUOTENAME('O''Brien', '''') AS literal;  -- 'O''Brien'"},{"engine_slug":"mysql","sql":"SELECT QUOTE('O''Brien') AS literal;  -- 'O\\'Brien'"},{"engine_slug":"sqlite","sql":"SELECT quote('O''Brien') AS literal;  -- 'O''Brien'"},{"engine_slug":"oracle","sql":"SELECT DBMS_ASSERT.ENQUOTE_LITERAL('O''Brien') AS literal\nFROM dual;  -- 'O''Brien'"}],"faqs":[{"question":"When should I use quote_literal instead of %L?","answer":"When you are concatenating strings rather than calling format(). Inside format(), %L is shorter and handles NULL like quote_nullable."},{"question":"Why did my NULL disappear from the generated SQL?","answer":"quote_literal(NULL) is NULL, and concatenating NULL makes the whole query string NULL. Use quote_nullable, or format() with %L."}],"related":["quote","quote-ident","format","quotename"],"novel_uses":[{"body":"string_agg over quote_literal turns a column into a quoted, comma-joined list ready to paste into another query or migration script.","sql":"SELECT string_agg(quote_literal(tag), ', ') AS in_list\nFROM (SELECT DISTINCT tag FROM imports) s;"},{"body":"The same pairing builds full INSERT statements inside SQL: one quote_nullable per column, joined per row, keeps the quoting rules out of the application and keeps NULLs intact.","sql":"SELECT format('INSERT INTO tag_map (tag) VALUES %s;',\n       string_agg(format('(%s)', quote_nullable(tag)), ', ')) AS stmt\nFROM (SELECT DISTINCT tag FROM imports) s;"}]},"source_url":"https://sqlly.app/sql-functions/quote-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quote-nullable","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUOTE_NULLABLE function","description":"How PostgreSQL's quote_nullable returns the word NULL for NULL input where quote_literal returns NULL: dynamic SQL, format %L and safe literal building.","body":{"slug":"quote-nullable","name":"QUOTE_NULLABLE","h1":"SQL QUOTE_NULLABLE function","category":"string","lede":"Quotes a value as an SQL string literal, and returns the unquoted word NULL when the input is NULL.","syntax":"quote_nullable(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No equivalent; QUOTENAME returns NULL for NULL input."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"QUOTE(NULL) also returns the word NULL."},{"engine_slug":"sqlite","status":"partial","note":"quote(NULL) also returns the word NULL."},{"engine_slug":"oracle","status":"no","note":"No equivalent; DBMS_ASSERT.ENQUOTE_LITERAL plus NVL."}],"gotchas":["quote_literal(NULL) is NULL, so it wipes out a concatenated query string; quote_nullable(NULL) is the text NULL and survives concatenation.","format()'s %L specifier behaves like quote_nullable, which is why format() is the usual way to build dynamic SQL in PL/pgSQL.","It protects values only; identifiers need quote_ident or format's %I."],"examples":[{"engine_slug":"postgresql","sql":"SELECT quote_nullable(NULL) AS literal;  -- NULL"},{"engine_slug":"postgresql","sql":"SELECT format('UPDATE t SET parent = %L', NULL::text) AS sql;"},{"engine_slug":"mysql","sql":"SELECT QUOTE(NULL) AS literal;  -- NULL"},{"engine_slug":"sqlite","sql":"SELECT quote(NULL) AS literal;  -- NULL"}],"faqs":[{"question":"Why choose quote_nullable over quote_literal?","answer":"When the value can be NULL and the generated SQL must still be valid: the literal becomes the keyword NULL instead of nulling the whole string."},{"question":"Does quote_nullable change non-null values?","answer":"No. It doubles embedded quotes and wraps the text exactly as quote_literal does; only the NULL case differs."}],"related":["quote-literal","quote-ident","format","quote"],"novel_uses":[{"body":"Export generation needs the word NULL in the output, not a dropped value: quote_nullable writes NULL unquoted and everything else as a quoted literal, so the generated INSERT round-trips.","sql":"SELECT format('INSERT INTO t (a, b) VALUES (%s, %s);',\n       quote_nullable(name), quote_nullable(parent_id)) AS stmt\nFROM nodes;"},{"body":"quote_nullable renders '' as '' and NULL as the word NULL, which settles in one SELECT whether a mysterious blank column holds an empty string or a NULL.","sql":"SELECT quote_nullable(note) AS shown FROM t WHERE id = 7;"}]},"source_url":"https://sqlly.app/sql-functions/quote-nullable","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/quotename","corpus":"sql-functions","engine":null,"language":"en","title":"SQL QUOTENAME function","description":"SQL Server's QUOTENAME wraps an identifier in brackets (or your chosen delimiter) and doubles embedded closers, the safe builder for dynamic SQL.","body":{"slug":"quotename","name":"QUOTENAME","h1":"SQL QUOTENAME function","category":"string","lede":"Turns a string into a delimited identifier: QUOTENAME('Order Details') gives [Order Details]. Built for dynamic T-SQL, where raw names break parsing.","syntax":"QUOTENAME(name [, quote_character])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"quote_ident(name) adds double quotes when needed"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Embedded closers are doubled, not escaped: QUOTENAME('weird]name') gives [weird]]name], which parses back correctly.","The optional second argument picks the wrapper: ']' (default), '\"', '''' and a few bracket pairs. QUOTENAME(s, '''') builds a string literal, doubling embedded quotes.","Input longer than 128 characters returns NULL, silently. The limit counts UTF-16 code units, so 64 emoji fit and 65 do not. That matches the sysname limit for identifiers, but it also means QUOTENAME cannot quote longer strings for other uses.","It never validates that the object exists; it only makes the name parseable. Permission checks still apply to the dynamic statement."],"examples":[{"engine_slug":"sql-server","sql":"SELECT QUOTENAME('Order Details') AS id;  -- [Order Details]"},{"engine_slug":"sql-server","sql":"SELECT QUOTENAME('weird]name') AS q;  -- [weird]]name]"},{"engine_slug":"sql-server","sql":"DECLARE @table sysname = N'Order Details';\nDECLARE @sql nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(@table) + N' WHERE id = @id';\nEXEC sp_executesql @sql, N'@id int', @id = 7;"},{"engine_slug":"postgresql","sql":"SELECT quote_ident('order details') AS id;  -- \"order details\""}],"faqs":[{"question":"Why use QUOTENAME instead of just adding brackets?","answer":"A name containing ] breaks hand-bracketed dynamic SQL, because the first ] ends the identifier early. QUOTENAME doubles the closers so the name parses back intact. Reserved words are not the problem: [order] works when bracketed by hand."},{"question":"Does QUOTENAME prevent SQL injection?","answer":"For identifiers, yes when paired with typed parameters for values. It only makes names parseable. Never concatenate user input as values; sp_executesql parameters do that."},{"question":"Is there a QUOTENAME in MySQL or PostgreSQL?","answer":"Not by that name. PostgreSQL's quote_ident() does the same job with double quotes, adding them only when needed. MySQL's sys schema has sys.quote_identifier(), which wraps a name in backticks and doubles embedded ones."}],"related":["identifier-quoting","quote","replace"],"novel_uses":[{"body":"STRING_AGG over QUOTENAME(name) builds a safe, comma-separated column list for dynamic PIVOT or SELECT statements straight from sys.columns.","sql":"SELECT STRING_AGG(QUOTENAME(name), ', ') WITHIN GROUP (ORDER BY column_id) AS cols\nFROM sys.columns WHERE object_id = OBJECT_ID('dbo.sales');"},{"body":"QUOTENAME(value, '\"') wraps a field in double quotes and doubles embedded ones, which is the CSV escaping rule, no SSIS required. It returns NULL for a NULL value and for input over 128 characters, so wrap it in COALESCE(..., '') and handle long values separately.","sql":"SELECT COALESCE(QUOTENAME(name, '\"'), '') AS csv_field FROM brands;"}]},"source_url":"https://sqlly.app/sql-functions/quotename","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/radians","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RADIANS function","description":"RADIANS(x) converts degrees to radians, the unit trig functions take. Oracle lacks it, and on SQL Server RADIANS(180) is the integer 3.","body":{"slug":"radians","name":"RADIANS","h1":"SQL RADIANS function","category":"math","lede":"Converts an angle from degrees to radians: RADIANS(180) is PI() (on SQL Server use 180.0, since the integer form gives 3) and RADIANS(90) is about 1.5708.","syntax":"RADIANS(angle_degrees)","return_type":"double; SQL Server returns the input's type","support":[{"engine_slug":"sql-server","status":"yes","note":"Returns the input's type (REAL gives FLOAT): RADIANS(180) is 3, RADIANS(180.0) is 3.141592653589793116"},{"engine_slug":"postgresql","status":"yes","note":"radians(double precision) only"},{"engine_slug":"mysql","status":"yes","note":"RADIANS() is built into MySQL"},{"engine_slug":"sqlite","status":"yes","note":"On 3.35+ with the math functions compiled in"},{"engine_slug":"oracle","status":"no","note":"No RADIANS; use x * ACOS(-1) / 180"}],"gotchas":["It is x * PI() / 180. On Oracle, spell it out: angle * ACOS(-1) / 180.","SQL Server truncates integer input: RADIANS(180) is 3 and RADIANS(30) is 0, so SIN(RADIANS(30)) is 0 there. Write RADIANS(30.0) or RADIANS(CAST(x AS FLOAT)).","The most common trig bug is skipping it: SIN(30) computes 30 radians. RADIANS(30) then SIN gives the intended 0.5 (0.49999999999999994 in doubles)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT RADIANS(180) AS pi_value;  -- 3.141592653589793"},{"engine_slug":"sql-server","sql":"SELECT RADIANS(180) AS int_in, RADIANS(180.0) AS dec_in;  -- 3, 3.141592653589793116"},{"engine_slug":"mysql","sql":"SELECT RADIANS(180) AS pi_value;  -- 3.141592653589793"},{"engine_slug":"sqlite","sql":"SELECT radians(180) AS pi_value;  -- 3.14159265358979"},{"engine_slug":"postgresql","sql":"SELECT SIN(RADIANS(30)) AS half;  -- 0.49999999999999994"},{"engine_slug":"oracle","sql":"SELECT 30 * ACOS(-1) / 180 AS radians FROM dual;"}],"faqs":[{"question":"What is the formula behind RADIANS?","answer":"x * PI() / 180. On Oracle, which lacks the function, write angle * ACOS(-1) / 180."},{"question":"Why do I need RADIANS at all?","answer":"Every SQL trig function takes radians. Passing degrees computes the wrong angle silently: SIN(30) is the sine of 30 radians, about -0.988, not 0.5."},{"question":"Is RADIANS(180) exactly pi?","answer":"It is the closest double to pi, accurate to about 16 digits, which is why SIN(RADIANS(180)) returns 1.2e-16 instead of 0 on PostgreSQL, MySQL and SQLite. On SQL Server, RADIANS(180) with an integer argument is just 3, so SIN gives 0.1411; use RADIANS(180.0) there."}],"related":["degrees","pi","sin","cos"],"novel_uses":[{"body":"Wrap RADIANS(angle_deg) in a view and every downstream query stops repeating the conversion or getting it wrong in one spot. The base table keeps the raw degrees the devices send.","sql":"CREATE VIEW wave_rad AS SELECT id, RADIANS(angle_deg) AS angle_rad FROM wave_samples;"},{"body":"PostgreSQL builds expression indexes on immutable functions, so an index on SIN(RADIANS(lat)) serves north-south band filters directly. The conversion must sit inside the index expression to match the query.","sql":"CREATE INDEX ix_places_lat ON places (SIN(RADIANS(lat)));"}]},"source_url":"https://sqlly.app/sql-functions/radians","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/random","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANDOM function","description":"Random numbers in SQL: RANDOM() in PostgreSQL and SQLite, RAND() in MySQL and SQL Server, DBMS_RANDOM in Oracle (ranges, sampling and ORDER BY pitfalls).","body":{"slug":"random","name":"RANDOM / RAND","h1":"SQL RANDOM function","category":"math","lede":"Returns a random number. The traps are the spelling, SQLite returning an integer instead of a fraction, SQL Server's RAND() giving every row the same value, and the cost of ORDER BY RANDOM() on big tables.","syntax":"RANDOM()  -- PostgreSQL, SQLite  |  RAND()  -- MySQL, SQL Server  |  DBMS_RANDOM.VALUE  -- Oracle","return_type":"float in [0, 1); a 64-bit integer on SQLite","support":[{"engine_slug":"sql-server","status":"partial","note":"RAND(); evaluated once per query, not per row"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"RAND(), evaluated per row"},{"engine_slug":"sqlite","status":"yes","note":"RANDOM() returns a signed 64-bit integer, not a fraction"},{"engine_slug":"oracle","status":"partial","note":"DBMS_RANDOM.VALUE, a PL/SQL package function"}],"gotchas":["SQL Server's RAND() is evaluated once per query, so every row gets the same number. For a per-row value use RAND(CHECKSUM(NEWID())), or ORDER BY NEWID() to shuffle.","SQLite's RANDOM() returns an integer between -9223372036854775808 and 9223372036854775807. For 0..n-1 use ABS(RANDOM()) % n; for a fraction use (RANDOM() / 18446744073709551616.0) + 0.5.","ORDER BY RANDOM() sorts the whole table. For large tables sample instead: TABLESAMPLE SYSTEM (1) on PostgreSQL, TABLESAMPLE (1 PERCENT) on SQL Server, the SAMPLE clause on Oracle, or a WHERE RANDOM() < 0.01 filter on PostgreSQL.","On PostgreSQL, MySQL and Oracle, FLOOR(RANDOM() * n) (or RAND(), DBMS_RANDOM.VALUE) gives an integer from 0 to n-1."],"examples":[{"engine_slug":"postgresql","sql":"SELECT FLOOR(RANDOM() * 100) AS dice;  -- 0..99"},{"engine_slug":"sql-server","sql":"SELECT TOP 10 * FROM orders ORDER BY NEWID();"},{"engine_slug":"postgresql","sql":"SELECT * FROM events WHERE RANDOM() < 0.001;  -- rough 0.1% sample"},{"engine_slug":"mysql","sql":"-- RAND() is re-evaluated per row\nSELECT RAND() AS roll;  -- a float in [0, 1)"},{"engine_slug":"sqlite","sql":"SELECT RANDOM() AS roll;  -- a signed 64-bit integer"},{"engine_slug":"oracle","sql":"-- DBMS_RANDOM is a PL/SQL package\nSELECT DBMS_RANDOM.VALUE AS roll FROM dual;  -- a float in [0, 1)"}],"faqs":[{"question":"Why does RAND() return the same value on every row in SQL Server?","answer":"It is evaluated once for the whole query. RAND(CHECKSUM(NEWID())) gives a new value per row, because NEWID() is evaluated per row and seeds RAND each time."},{"question":"Is ORDER BY RANDOM() okay?","answer":"For small tables, yes. For anything large it reads and sorts every row; use TABLESAMPLE (SQL Server), TABLESAMPLE SYSTEM or BERNOULLI (PostgreSQL), SAMPLE (Oracle), or an indexed random-key column instead."}],"related":["floor","ceil","row-number"],"novel_uses":[{"body":"Seeding the generator makes the shuffle deterministic: MySQL's ORDER BY RAND(42) returns the same order on every run, which is what fixtures, demos and screenshot tests want. Unseeded RAND() reshuffles each execution, and SQL Server's RAND evaluates once per query, so NEWID() is its shuffle.","sql":"SELECT id FROM words ORDER BY RAND(42);"},{"body":"ORDER BY MD5(id) shuffles rows deterministically across engines, sessions and runs with no seed to manage, because the hash of a key never changes. The cost is one hash per row, which is fine for moderate sets.","sql":"SELECT id FROM users ORDER BY MD5(id::text);"}]},"source_url":"https://sqlly.app/sql-functions/random","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/random-bytes","corpus":"sql-functions","engine":null,"language":"en","title":"SQL cryptographic random","description":"Cryptographic random per engine: RANDOM_BYTES on MySQL, CRYPT_GEN_RANDOM on SQL Server, gen_random_bytes via pgcrypto, randomblob on SQLite, DBMS_CRYPTO on Oracle.","body":{"slug":"random-bytes","name":"random bytes","h1":"SQL cryptographic random","category":"math","lede":"Produces unpredictable bytes for tokens and keys; the seeded or plain random() functions are predictable and must never be used for secrets.","syntax":"RANDOM_BYTES(n)  -- MySQL  |  CRYPT_GEN_RANDOM(n)  -- SQL Server  |  randomblob(n)  -- SQLite","return_type":"binary / blob","support":[{"engine_slug":"sql-server","status":"yes","note":"CRYPT_GEN_RANDOM(n) is built in; the optional seed does not make output reproducible and the call returns NULL when the seed is shorter than n"},{"engine_slug":"postgresql","status":"partial","note":"No core function: gen_random_bytes(n) comes from the pgcrypto extension (gen_random_uuid() is core since 13)"},{"engine_slug":"mysql","status":"yes","note":"RANDOM_BYTES(n) since 5.6.17, backed by the TLS library's generator; n from 1 to 1024"},{"engine_slug":"sqlite","status":"partial","note":"randomblob(N) returns N random bytes, not documented as CSPRNG-grade, but widely used for tokens"},{"engine_slug":"oracle","status":"partial","note":"DBMS_CRYPTO.RANDOMBYTES(n) in PL/SQL; DBMS_RANDOM is not cryptographic"}],"gotchas":["RAND(), random() and DBMS_RANDOM are predictable: seeded or weak generators. Tokens and keys come from the crypto functions only.","16 bytes (128 bits) is enough for a session token, 32 for a 256-bit key. RANDOM_BYTES raises an error above 1024 on MySQL, and CRYPT_GEN_RANDOM returns NULL above 8000 on SQL Server rather than raising an error.","On PostgreSQL the pgcrypto extension must be installed first: CREATE EXTENSION pgcrypto; (gen_random_bytes is not core, though gen_random_uuid() became core in 13)."],"examples":[{"engine_slug":"mysql","sql":"SELECT HEX(RANDOM_BYTES(16)) AS token;"},{"engine_slug":"sql-server","sql":"SELECT CRYPT_GEN_RANDOM(16) AS token_bytes;"},{"engine_slug":"sqlite","sql":"SELECT hex(randomblob(16)) AS token;"},{"engine_slug":"postgresql","sql":"SELECT encode(gen_random_bytes(16), 'hex') AS token;  -- after CREATE EXTENSION pgcrypto"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(DBMS_CRYPTO.RANDOMBYTES(16)) AS token FROM dual;  -- 32 hex characters"}],"faqs":[{"question":"Can I use RAND() to generate tokens?","answer":"No. RAND() and random() are predictable, and a seeded sequence is fully reproducible by anyone who learns the seed. Use RANDOM_BYTES (MySQL), CRYPT_GEN_RANDOM (SQL Server), gen_random_bytes (PostgreSQL via pgcrypto) or randomblob (SQLite)."},{"question":"How do I get cryptographic random bytes in PostgreSQL?","answer":"gen_random_bytes(n) from the pgcrypto extension: CREATE EXTENSION pgcrypto first. The core gen_random_uuid() (13+) also draws crypto-grade randomness."},{"question":"Is SQLite's randomblob secure?","answer":"SQLite documents random() and randomblob as pseudo-random, not as a CSPRNG guarantee, fine for shuffling and ids, but check your threat model before using it for secrets."}],"related":["random","random-per-row","setseed"],"novel_uses":[{"body":"TO_BASE64(RANDOM_BYTES(16)) on MySQL yields 24 characters ending in ==; swapping + and / for - and _ and dropping the = padding leaves a 22-character URL-safe token. One expression in the INSERT, no application round trip.","sql":"SELECT REPLACE(REPLACE(REPLACE(TO_BASE64(RANDOM_BYTES(16)), '+', '-'), '/', '_'), '=', '') AS token;"}]},"source_url":"https://sqlly.app/sql-functions/random-bytes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/random-integer-range","corpus":"sql-functions","engine":null,"language":"en","title":"SQL random integer in a range","description":"FLOOR(RAND() * N) + offset recipes per engine: PostgreSQL, MySQL, SQLite, Oracle's VALUE(min, max) and SQL Server's seeded-per-row dance.","body":{"slug":"random-integer-range","name":"random range","h1":"SQL random integer in a range","category":"math","lede":"Generates a random integer between bounds: scale the engine's random float into [min, max+1), floor it, or wrap Oracle's two-argument VALUE in TRUNC.","syntax":"FLOOR(RAND() * N) + 1  |  floor(random() * N)::int  -- PostgreSQL  |  TRUNC(DBMS_RANDOM.VALUE(min, max + 1))  -- Oracle","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"FLOOR(RAND(CHECKSUM(NEWID())) * N) + 1 for per-row values; plain RAND() gives the same integer on every row"},{"engine_slug":"postgresql","status":"yes","note":"floor(random() * N)::int + 1"},{"engine_slug":"mysql","status":"yes","note":"FLOOR(RAND() * N) + 1"},{"engine_slug":"sqlite","status":"yes","note":"Use modulo of the 64-bit random(): ABS(random()) % N + 1"},{"engine_slug":"oracle","status":"yes","note":"TRUNC(DBMS_RANDOM.VALUE(1, N + 1)): VALUE's high bound is excluded, so pass max + 1"}],"gotchas":["The float recipe is [min, min + N): multiply, floor, offset. FLOOR(RAND() * 6) + 1 is a die roll; forgetting the + 1 makes 0 possible and 6 impossible.","SQLite's random() is a signed 64-bit integer, not a float; ABS(random()) % N + 1 is the idiom, and ABS guards the negative half of the range.","Oracle's DBMS_RANDOM.VALUE(low, high) returns a float in [low, high); the high bound is excluded, so TRUNC(DBMS_RANDOM.VALUE(1, 7)) covers 1 through 6."],"examples":[{"engine_slug":"postgresql","sql":"SELECT floor(random() * 6)::int + 1 AS die;"},{"engine_slug":"sqlite","sql":"SELECT ABS(random()) % 6 + 1 AS die;"},{"engine_slug":"oracle","sql":"SELECT TRUNC(DBMS_RANDOM.VALUE(1, 7)) AS die FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT FLOOR(RAND(CHECKSUM(NEWID())) * 6) + 1 AS die FROM sys.objects;"},{"engine_slug":"mysql","sql":"SELECT FLOOR(RAND() * 6) + 1 AS die;  -- 1 through 6"}],"faqs":[{"question":"How do I generate a random integer between 1 and N?","answer":"FLOOR(random_float * N) + 1: floor(random() * 6)::int + 1 on PostgreSQL, FLOOR(RAND() * 6) + 1 on MySQL, ABS(random()) % 6 + 1 on SQLite, TRUNC(DBMS_RANDOM.VALUE(1, 7)) on Oracle."},{"question":"Why does my random integer include 0?","answer":"The offset was dropped: FLOOR(RAND() * 6) alone yields 0 through 5. Add 1 after the floor to shift to 1 through 6."},{"question":"Why do all rows show the same random integer on SQL Server?","answer":"RAND() evaluated once per query. Use RAND(CHECKSUM(NEWID())) so each row reseeds the generator, as plain RAND() shares one value across the whole result set."}],"related":["random","random-per-row","floor","setseed"],"novel_uses":[{"body":"FLOOR(RAND() * 100) + 1 plus a CASE over the ranges 1 to 60, 61 to 90, 91 to 100 implements a weighted loot or routing table with no lookup table. Edit the ranges to retune the weights.","sql":"SELECT CASE WHEN r <= 60 THEN 'common' WHEN r <= 90 THEN 'rare' ELSE 'epic' END FROM (SELECT FLOOR(RAND() * 100) + 1 AS r) t;"},{"body":"For playlists or galleries, ORDER BY (idx + offset) % n with offset = ABS(random()) % n gives a different rotation each run without storing state, and the offset is the only random input. A real shuffle it is not, but it is free.","sql":"SELECT id FROM tracks CROSS JOIN (SELECT ABS(random()) % 5 AS off) o ORDER BY (idx + o.off) % 5;"}]},"source_url":"https://sqlly.app/sql-functions/random-integer-range","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/random-per-row","corpus":"sql-functions","engine":null,"language":"en","title":"SQL random values per row","description":"random() varies per row on four engines. SQL Server's RAND() runs once per query; use CHECKSUM(NEWID()) or a per-row seed like RAND(object_id), not a fixed RAND(42).","body":{"slug":"random-per-row","name":"RAND per row","h1":"SQL random values per row","category":"math","lede":"How to get a different random number on every row: the engines that do it natively and the SQL Server workaround for RAND()'s once-per-query evaluation.","syntax":"random()  -- per row  |  RAND()  -- once per query on SQL Server  |  RAND(CHECKSUM(NEWID()))  -- per row on SQL Server","return_type":"float in [0, 1); SQLite's random() is a signed 64-bit integer","support":[{"engine_slug":"sql-server","status":"partial","note":"RAND() evaluates once per SELECT: every row gets the same value; RAND(CHECKSUM(NEWID())) recomputes per row"},{"engine_slug":"postgresql","status":"yes","note":"random() is evaluated per row"},{"engine_slug":"mysql","status":"yes","note":"RAND() is evaluated per row"},{"engine_slug":"sqlite","status":"yes","note":"random() is evaluated per row"},{"engine_slug":"oracle","status":"yes","note":"DBMS_RANDOM.VALUE is evaluated per row"}],"gotchas":["SQL Server's RAND() is the trap: SELECT RAND() FROM big_table returns the identical value on every row, evaluated once for the statement.","The per-row SQL Server idiom is RAND(CHECKSUM(NEWID())): NEWID() differs per row, its checksum reseeds the generator, and the value varies.","Per-row random values make ORDER BY random() a full shuffle: fine on small tables, a scan and sort of every row on large ones."],"examples":[{"engine_slug":"sql-server","sql":"SELECT RAND(CHECKSUM(NEWID())) AS per_row FROM sys.objects;  -- different on each row"},{"engine_slug":"sql-server","sql":"SELECT RAND() AS same_everywhere FROM sys.objects;  -- one value, every row"},{"engine_slug":"postgresql","sql":"SELECT random() AS per_row FROM generate_series(1, 3);  -- three different values"},{"engine_slug":"mysql","sql":"SELECT id, RAND() AS per_row FROM t;  -- different on each row"},{"engine_slug":"sqlite","sql":"SELECT random() AS per_row FROM wave_samples;  -- different on each row"},{"engine_slug":"oracle","sql":"SELECT DBMS_RANDOM.VALUE AS per_row FROM sensor_data;  -- different on each row"}],"faqs":[{"question":"Why does RAND() return the same value on every row in SQL Server?","answer":"T-SQL evaluates RAND() once per query and shares the value across rows. For per-row randomness use RAND(CHECKSUM(NEWID())), whose seed changes with each row's NEWID()."},{"question":"Does MySQL's RAND() differ per row?","answer":"Yes. Unlike SQL Server, MySQL evaluates RAND() per row, as PostgreSQL's random() and SQLite's random() and Oracle's DBMS_RANDOM.VALUE do."},{"question":"How do I pick n random rows?","answer":"ORDER BY random() LIMIT n on PostgreSQL and SQLite, ORDER BY RAND() LIMIT n on MySQL, SELECT TOP (n) ... ORDER BY NEWID() on SQL Server, and ORDER BY DBMS_RANDOM.VALUE FETCH FIRST n ROWS ONLY on Oracle. All of them sort the whole table; TABLESAMPLE is cheaper on big tables."}],"related":["random","setseed","random-integer-range","random-bytes"],"novel_uses":[{"body":"MySQL has no usable TABLESAMPLE on a plain server (8.4 parses it, then fails with ERROR 3889 unless a HeatWave secondary engine is attached), but WHERE RAND() < 0.01 draws about one percent per run, row by row. Use it for exploratory queries; keep keyed sampling where repeatability matters.","sql":"SELECT * FROM events WHERE RAND() < 0.01;"},{"body":"On SQL Server, DATEADD with RAND(CHECKSUM(NEWID())) * 5000 milliseconds staggers a thundering herd of jobs that failed together. Generated in the batch statement, the spread costs nothing at run time.","sql":"SELECT DATEADD(millisecond, CAST(RAND(CHECKSUM(NEWID())) * 5000 AS INT), base_run) AS jittered_run FROM retry_queue;"}]},"source_url":"https://sqlly.app/sql-functions/random-per-row","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/randomblob","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANDOMBLOB function","description":"SQLite's RANDOMBLOB(N) returns N random bytes: the raw material for UUID-shaped ids, tokens and salts, with RANDOM() for plain integers.","body":{"slug":"randomblob","name":"RANDOMBLOB","h1":"SQL RANDOMBLOB function","category":"conversion","lede":"SELECT hex(randomblob(16)) makes a 32-character random id. The SQLite library has no UUID function, so this is the usual way to build one.","syntax":"RANDOMBLOB(N)","return_type":"blob","support":[{"engine_slug":"sql-server","status":"partial","note":"CRYPT_GEN_RANDOM(n)"},{"engine_slug":"postgresql","status":"partial","note":"gen_random_bytes(n) via pgcrypto"},{"engine_slug":"mysql","status":"partial","note":"RANDOM_BYTES(n)"},{"engine_slug":"sqlite","status":"yes","note":"the native one"},{"engine_slug":"oracle","status":"partial","note":"DBMS_CRYPTO.RANDOMBYTES(n)"}],"gotchas":["hex(randomblob(16)) gives 32 hex characters with no version bits and no dashes. The sqlite3 shell's uuid() extension makes real v4 UUIDs, but applications linking the library do not have it.","It returns a BLOB: store, compare and index as blob, or hex-encode to text first; comparing a blob to a text literal is a type mismatch that quietly never matches.","The twins elsewhere: RANDOM_BYTES (MySQL), CRYPT_GEN_RANDOM (SQL Server), gen_random_bytes (pgcrypto on PostgreSQL) and DBMS_CRYPTO.RANDOMBYTES (Oracle)."],"examples":[{"engine_slug":"sqlite","sql":"SELECT hex(randomblob(16)) AS token;"},{"engine_slug":"sqlite","sql":"INSERT INTO tokens (value)\nVALUES (hex(randomblob(32)));"},{"engine_slug":"sql-server","sql":"SELECT CRYPT_GEN_RANDOM(16) AS salt;"},{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS pgcrypto;\nSELECT gen_random_bytes(16) AS salt;"},{"engine_slug":"mysql","sql":"SELECT HEX(RANDOM_BYTES(16)) AS salt;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(DBMS_CRYPTO.RANDOMBYTES(16)) AS salt FROM dual;"}],"faqs":[{"question":"Is randomblob safe for tokens?","answer":"It uses SQLite's internal pseudo-random generator (ChaCha20, seeded from the OS), which is fine for ids and nonces. For long-lived secrets, generate them with the application's OS-level CSPRNG."},{"question":"Why does my random id repeat?","answer":"It should not within realistic lengths: 16 bytes is 128 bits. Duplicates usually mean the value got truncated after hex-encoding; check for substr() or column-width cuts."}],"related":["zeroblob","gen-random-uuid","newid","random"],"novel_uses":[{"body":"The library has no uuid() function, but the string is just formatted random bytes: hex segments joined with dashes, a 4 in the version slot and an 8/9/a/b variant nibble. One expression, shell included.","sql":"SELECT lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || substr(hex(randomblob(2)), 2) || '-' || substr('89ab', abs(random()) % 4 + 1, 1) || substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6))) AS uuid4;"},{"body":"INSERT with randomblob(1048576) creates a one-megabyte dummy blob without touching the filesystem, which is how you fill a table for load tests or size a page cache.","sql":"INSERT INTO fixtures (content) VALUES (randomblob(1048576));"}]},"source_url":"https://sqlly.app/sql-functions/randomblob","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/range-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANGE frame","description":"RANGE frames bound the window by the ORDER BY value: peers travel together, and numeric or interval offsets define value spans.","body":{"slug":"range-frame","name":"RANGE Frame","h1":"SQL RANGE frame","category":"window","lede":"A RANGE frame includes rows whose ORDER BY value falls within an offset of the current value; ties are always in or out together.","syntax":"SUM(x) OVER (ORDER BY d RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) | RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"partial","note":"RANGE with UNBOUNDED PRECEDING/FOLLOWING and CURRENT ROW only; no value offsets"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; RANGE offsets since 3.28"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["RANGE requires exactly one ORDER BY expression when using offsets (a value span is only defined against one column); UNBOUNDED/CURRENT ROW forms work with multi-key sorts.","The default frame of every ordered window is a RANGE frame, so RANGE semantics are already in your queries even if you never write the word.","Numeric offsets compare values, not rows: RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING on integers covers values v-1 through v+1, peers included."],"examples":[{"engine_slug":"postgresql","sql":"SELECT sensor_id, reading_time, value,\n       AVG(value) OVER (PARTITION BY sensor_id\n                        ORDER BY reading_time\n                        RANGE BETWEEN INTERVAL '5 minutes' PRECEDING\n                                  AND CURRENT ROW) AS avg_5min\nFROM readings;"},{"engine_slug":"mysql","sql":"-- numeric offsets: PostgreSQL, MySQL, SQLite 3.28+ and Oracle, not SQL Server\nSELECT bid, price,\n       COUNT(*) OVER (ORDER BY price RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS nearby_bids\nFROM orderbook;"},{"engine_slug":"sqlite","sql":"-- 3.28+ for RANGE offsets\nSELECT bid, price,\n       COUNT(*) OVER (ORDER BY price RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS nearby_bids\nFROM orderbook;"},{"engine_slug":"oracle","sql":"SELECT product, price,\n       AVG(price) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS band_avg\nFROM products;"},{"engine_slug":"sql-server","sql":"-- RANGE with value offsets is rejected here; only UNBOUNDED and CURRENT ROW ends parse\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day\n           RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS peer_running_avg\nFROM prices;"}],"faqs":[{"question":"When is RANGE required instead of ROWS?","answer":"When the window is defined by value distance (a time interval, a price band, a percentile-like span) or when ties must move together. Row-count windows want ROWS."},{"question":"Why does RANGE reject my two-column ORDER BY?","answer":"Offset boundaries need a single sortable value; with multiple keys there is no total order to measure distance in. Use ROWS, or keep offsets only on the primary key."}],"related":["rows-vs-range","range-numeric-offsets","range-interval-frame"],"novel_uses":[{"body":"An AVG over a RANGE band averages every row within five units of this one. The band is the same width everywhere, so a dense region averages many rows inside it and a sparse one averages only the few rows that fall inside it, with no bucketing table. SQL Server cannot run value offsets; PostgreSQL, MySQL, SQLite 3.28+ and Oracle can.","sql":"SELECT product_id, price,\n       AVG(price) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS band_avg\nFROM products;"},{"body":"MIN and MAX over the same band give a local corridor: the spread of prices near this one rather than across the whole table. The corridor is the spread of values inside the band, not a count of them: a row with no neighbours gets a zero-width corridor, so put COUNT(*) over the same band beside it to see how thin the neighbourhood is.","sql":"SELECT product_id, price,\n       MIN(price) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS band_floor,\n       MAX(price) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS band_ceiling\nFROM products;"}]},"source_url":"https://sqlly.app/sql-functions/range-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/range-interval-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANGE with interval offsets","description":"Trailing time windows with RANGE BETWEEN INTERVAL: calendar windows in PostgreSQL, MySQL and Oracle, and what SQL Server and SQLite do instead.","body":{"slug":"range-interval-frame","name":"RANGE Interval Frames","h1":"SQL RANGE with interval offsets","category":"window","lede":"When the ORDER BY is a date or timestamp, RANGE offsets can be intervals: the frame covers a time span, independent of how many rows exist.","syntax":"AVG(x) OVER (ORDER BY ts RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"RANGE ... INTERVAL ... PRECEDING / FOLLOWING on temporal ORDER BY"},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+ allows interval units in RANGE frames: RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW"},{"engine_slug":"sqlite","status":"no","note":"RANGE offsets are plain numbers (fractions work), no interval type; emulate with date arithmetic and RANGE on julian day or a generated date spine"},{"engine_slug":"oracle","status":"yes","note":"RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW, and NUMTODSINTERVAL forms"}],"gotchas":["Interval frames solve the gap problem: a 7-day window keeps being 7 days when days are missing, whereas ROWS BETWEEN 6 PRECEDING quietly stretches over holes.","SQL Server has no interval offsets (its RANGE has none at all): the standard workaround is a calendar spine joined to the data, or ROWS over a spine with a row for every day (plain ROWS without the spine counts observations, not days).","Interval offsets need a date or timestamp ORDER BY. On PostgreSQL and MySQL a plain number offset on a date or timestamp is an error, and a sub-day interval on a DATE is accepted but only sees rows from that same day. SQLite raises no error for a number offset on a text date and returns wrong frames, so order by julianday(day)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT day, price,\n       AVG(price) OVER (ORDER BY day\n                        RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS ma7d\nFROM prices;"},{"engine_slug":"oracle","sql":"SELECT trade_ts, amount,\n       SUM(amount) OVER (ORDER BY trade_ts\n                         RANGE BETWEEN INTERVAL '1' HOUR PRECEDING AND CURRENT ROW) AS hourly_vol\nFROM trades;"},{"engine_slug":"mysql","sql":"-- MySQL 8.0+ takes interval units straight in the RANGE frame\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day\n                        RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW) AS ma7d\nFROM prices;"}],"faqs":[{"question":"Why prefer an interval frame over ROWS for time data?","answer":"Because ROWS counts observations: a day with no sales shifts the 7-day window into week-old data. RANGE with an interval anchors the window to the clock, giving real 'last 7 days' semantics."},{"question":"How do I do this on SQL Server or SQLite?","answer":"SQLite: order by julianday(day) and use RANGE BETWEEN 6 PRECEDING AND CURRENT ROW, which is a numeric offset in days. SQL Server has no RANGE offsets, so join a calendar table to fill missing days and use ROWS, or use a correlated subquery over the date range."}],"related":["range-frame","moving-average","sql-server-frame-support"],"novel_uses":[{"body":"Count rows over a trailing 29-day interval per customer and any count above 1 is a repeat purchase inside the month. PostgreSQL writes INTERVAL '29 days'; MySQL writes INTERVAL 29 DAY and needs MySQL 8.0+.","sql":"SELECT customer_id, order_day,\n       COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_day\n         RANGE BETWEEN INTERVAL '29 days' PRECEDING AND CURRENT ROW) AS orders_last_30d\nFROM orders;"},{"body":"A COUNT over a one-hour RANGE frame gives each request the traffic around it, which separates one slow caller from a busy minute for everyone. Oracle accepts INTERVAL '1' HOUR and NUMTODSINTERVAL for sub-second spans.","sql":"SELECT call_id, called_at,\n       COUNT(*) OVER (ORDER BY called_at\n         RANGE BETWEEN INTERVAL '1 hour' PRECEDING AND CURRENT ROW) AS calls_last_hour\nFROM api_calls;"}]},"source_url":"https://sqlly.app/sql-functions/range-interval-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/range-numeric-offsets","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANGE with numeric offsets","description":"RANGE BETWEEN n PRECEDING AND n FOLLOWING: value-based bands around each row; peers, one-column rule and where each engine draws the line.","body":{"slug":"range-numeric-offsets","name":"RANGE Numeric Offsets","h1":"SQL RANGE with numeric offsets","category":"window","lede":"Numeric RANGE offsets select rows whose ORDER BY value lies within n of the current value: a value band, not a row count.","syntax":"COUNT(*) OVER (ORDER BY price RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING)","return_type":"per-frame count","support":[{"engine_slug":"sql-server","status":"no","note":"RANGE supports only UNBOUNDED and CURRENT ROW ends; no numeric or interval offsets"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.28+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The ORDER BY expression must be numeric (or a type with engine support for offset arithmetic) and there must be exactly one ORDER BY expression in the window.","Ties are always inside the band: every peer of the current row is included because its value equals the current value, whatever the offset.","SQL Server is the outlier: its RANGE accepts only UNBOUNDED and CURRENT ROW bounds, never numeric offsets, so any value-band window must be rewritten with a self-join or ROWS approximation."],"examples":[{"engine_slug":"postgresql","sql":"SELECT product, price,\n       COUNT(*) OVER (ORDER BY price RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS competing_products\nFROM products;"},{"engine_slug":"mysql","sql":"SELECT player, rating,\n       COUNT(*) OVER (ORDER BY rating RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS pool_size\nFROM players;"},{"engine_slug":"sqlite","sql":"-- 3.28+ for RANGE offsets\nSELECT student, score,\n       COUNT(*) OVER (ORDER BY score RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING) AS score_band\nFROM exam_results;"},{"engine_slug":"oracle","sql":"SELECT product, price,\n       MIN(price) OVER (ORDER BY price RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING) AS band_floor\nFROM products;"}],"faqs":[{"question":"How is a numeric RANGE offset different from ROWS n PRECEDING?","answer":"ROWS counts positions; RANGE measures value distance. With prices 9, 10, 11, 15, the row at 10 with BETWEEN 1 PRECEDING AND 1 FOLLOWING sees 9, 10 and 11 under RANGE; at 15 (the last row), RANGE sees only 15 while ROWS takes 11 and 15."},{"question":"Why does my RANGE offset query error on SQL Server?","answer":"SQL Server's RANGE clause supports only UNBOUNDED and CURRENT ROW boundaries: no offsets at all. Approximate with ROWS, or self-join on the value band."}],"related":["range-frame","sql-server-frame-support","rows-vs-range"],"novel_uses":[{"body":"The ORDER BY must be numeric, so order by the epoch second: strftime returns text, and without the CAST the counts come back wrong. With the epoch in seconds, 300 PRECEDING means five minutes. The offset rule itself needs SQLite 3.28+.","sql":"SELECT request_id, ts,\n       COUNT(*) OVER (ORDER BY CAST(STRFTIME('%s', ts) AS INTEGER)\n         RANGE BETWEEN 300 PRECEDING AND CURRENT ROW) AS calls_last_5min\nFROM api_calls;"},{"body":"COUNT over a rating band of plus or minus 100 is the queue depth for fair matches, recomputed on every row. Widen the band when the pool runs thin instead of rewriting the query.","sql":"SELECT player_id, rating,\n       COUNT(*) OVER (ORDER BY rating RANGE BETWEEN 100 PRECEDING AND 100 FOLLOWING) AS pool_size\nFROM players;"}]},"source_url":"https://sqlly.app/sql-functions/range-numeric-offsets","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rank","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANK function","description":"RANK in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: tie-aware ranking with gaps, versus DENSE_RANK and ROW_NUMBER, in ORDER BY and pagination.","body":{"slug":"rank","name":"RANK","h1":"SQL RANK function","category":"window","lede":"Ranks rows within a partition, giving tied rows the same rank and skipping the subsequent numbers: 1, 2, 2, 4. That gap behaviour is the whole difference from DENSE_RANK.","syntax":"RANK() OVER (PARTITION BY g ORDER BY x)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Ties share a rank and the next rank jumps: scores 10, 10, 9 rank 1, 1, 3. DENSE_RANK gives 1, 1, 2; ROW_NUMBER gives 1, 2, 3.","The ORDER BY inside OVER decides what counts as a tie. Leave it out and every row is a tie, so PostgreSQL, MySQL and SQLite rank every row 1; SQL Server and Oracle (ORA-30485) refuse RANK without ORDER BY.","RANK is also available in a plain aggregate form (RANK(x) WITHIN GROUP (ORDER BY y)) on PostgreSQL and Oracle: the rank a value would get inside the group."],"examples":[{"engine_slug":"all","sql":"-- RANK is a reserved word in MySQL 8, so the alias is not rank\nSELECT name, points,\n       RANK() OVER (ORDER BY points DESC) AS position\nFROM players;"},{"engine_slug":"all","sql":"SELECT department, salary,\n       RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank\nFROM employees;"}],"faqs":[{"question":"What is the difference between RANK and DENSE_RANK?","answer":"Gaps after ties. Scores 10, 10, 9 rank as 1, 1, 3 with RANK and 1, 1, 2 with DENSE_RANK. Both differ from ROW_NUMBER, which never ties."},{"question":"Can RANK be used for pagination?","answer":"Use ROW_NUMBER for pagination. With RANK, tied rows share a number and the next numbers are skipped, so WHERE rank BETWEEN 11 AND 20 can return more or fewer than ten rows. RANK suits leaderboards where sharing a position is correct."}],"related":["dense-rank","row-number","ntile"],"novel_uses":[{"body":"Top ten rows means something different every season; top ten percent scales. Rank the players, carry COUNT(*) OVER () alongside, and compare the rank against a fraction of the total.","sql":"WITH ranked AS (\n  SELECT player, score,\n         RANK() OVER (ORDER BY score DESC) AS rk,\n         COUNT(*) OVER () AS total\n  FROM players\n)\nSELECT player, score\nFROM ranked\nWHERE rk <= CEIL(total * 0.1);"},{"body":"Integer division on the rank pairs players two by two: (rk + 1) / 2 assigns matches 1 versus 2, 3 versus 4 and so on. Integer division truncates on SQL Server, PostgreSQL and SQLite; MySQL needs DIV.","sql":"SELECT player, rk, (rk + 1) / 2 AS match_no\nFROM ranked_players\nORDER BY rk;"}]},"source_url":"https://sqlly.app/sql-functions/rank","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rank-within-group","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RANK WITHIN GROUP","description":"RANK and PERCENT_RANK WITHIN GROUP in PostgreSQL and Oracle: where a given value would fall inside an ordered set, without scanning rows by hand.","body":{"slug":"rank-within-group","name":"RANK WITHIN GROUP","h1":"SQL RANK WITHIN GROUP","category":"window","lede":"The inverse-distribution form of RANK: it returns the rank the given value would have if it were inserted into the ordered set.","syntax":"RANK(42) WITHIN GROUP (ORDER BY score) | PERCENT_RANK(42) WITHIN GROUP (ORDER BY score)","return_type":"bigint / double precision","support":[{"engine_slug":"sql-server","status":"no","note":"no hypothetical-set aggregates; count the rows that sort before the value"},{"engine_slug":"postgresql","status":"yes","note":"RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST all take WITHIN GROUP"},{"engine_slug":"mysql","status":"no","note":"no hypothetical-set aggregates; count the rows that sort before the value"},{"engine_slug":"sqlite","status":"no","note":"no hypothetical-set aggregates; count the rows that sort before the value"},{"engine_slug":"oracle","status":"yes","note":"RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST all take WITHIN GROUP"}],"gotchas":["The argument count must match the ORDER BY list: RANK(10, 'A') WITHIN GROUP (ORDER BY x, y) is valid, and a mismatched count is rejected before the query runs.","This is an aggregate, not a window function: no OVER clause. It answers 'where does this threshold land?' in one pass instead of ranking every row and searching.","SQL Server, MySQL and SQLite emulate it by counting: RANK(v) is 1 + the rows that sort strictly before v, DENSE_RANK(v) is 1 + the distinct values before v, and PERCENT_RANK(v) is the rows before v divided by the total row count."],"examples":[{"engine_slug":"postgresql","sql":"-- the rank a score of 85 would get\nSELECT RANK(85) WITHIN GROUP (ORDER BY score DESC) AS would_be\nFROM scores;"},{"engine_slug":"all","sql":"-- portable emulation: ties share the lower rank\nSELECT COUNT(*) + 1 AS would_be\nFROM scores WHERE score > 85;"}],"faqs":[{"question":"When would I use RANK WITHIN GROUP instead of RANK()?","answer":"When you have a threshold value, not rows to rank: 'which percentile is 85 points?' or 'what rank would this candidate's salary get?' without materializing a ranking of the whole table."},{"question":"Why is my emulated rank off when scores tie?","answer":"Rows equal to the value must not be counted: RANK(85) is 1 + COUNT of scores strictly better than 85, so use > for a DESC ordering, not >=. Counting the ties too gives the rank after them."}],"related":["rank","percent-rank","percentile-disc"],"novel_uses":[{"body":"RANK of a hypothetical price against the live book answers would-it-win without inserting a row: rank 1 means the bid tops the order book as it stands. PostgreSQL and Oracle only.","sql":"SELECT RANK(95.00) WITHIN GROUP (ORDER BY price DESC) AS would_rank\nFROM bids;"},{"body":"PERCENT_RANK with a value instead of a row returns where that threshold sits in the distribution, the number behind claims like 85 points is 94th percentile. It scans the set once and ranks nothing.","sql":"SELECT PERCENT_RANK(85) WITHIN GROUP (ORDER BY score) AS threshold_pct\nFROM scores;"}]},"source_url":"https://sqlly.app/sql-functions/rank-within-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ratio-to-report","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Oracle RATIO_TO_REPORT","description":"Oracle's analytic shortcut for percent-of-total: the row's value divided by its partition's sum, with no divide-by-zero error, in one function call.","body":{"slug":"ratio-to-report","name":"RATIO_TO_REPORT","h1":"SQL Oracle RATIO_TO_REPORT","category":"window","lede":"RATIO_TO_REPORT(x) OVER (partition) returns x / SUM(x) in that partition, the percent-of-total pattern as a built-in analytic.","syntax":"RATIO_TO_REPORT(amount) OVER (PARTITION BY region)","return_type":"NUMBER (a fraction; 0 to 1 for non-negative values)","support":[{"engine_slug":"sql-server","status":"no","note":"use amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY ...), 0)"},{"engine_slug":"postgresql","status":"no","note":"use amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY ...), 0)"},{"engine_slug":"mysql","status":"no","note":"MySQL 8.0+: use amount / SUM(amount) OVER (PARTITION BY ...)"},{"engine_slug":"sqlite","status":"no","note":"use amount * 1.0 / SUM(amount) OVER (PARTITION BY ...)"},{"engine_slug":"oracle","status":"yes","note":"Oracle-only analytic; other engines use the SUM OVER division pattern"}],"gotchas":["NULL behaves as in the hand-rolled division: a NULL x gives a NULL ratio, and NULLs are left out of the partition sum.","A partition whose values sum to 0 yields NULL rather than an error, while x / SUM(x) OVER (...) raises divide-by-zero on Oracle, SQL Server and PostgreSQL (MySQL and SQLite return NULL).","The portable equivalent everywhere is the two-window division: amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY g), 0); see percent-of-total."],"examples":[{"engine_slug":"oracle","sql":"SELECT region, amount,\n       RATIO_TO_REPORT(amount) OVER (PARTITION BY region) AS region_share,\n       RATIO_TO_REPORT(amount) OVER () AS company_share\nFROM sales;"},{"engine_slug":"all","sql":"-- the portable form\nSELECT region, amount,\n       amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY region), 0) AS region_share\nFROM sales;"}],"faqs":[{"question":"What is the portable replacement for RATIO_TO_REPORT?","answer":"Divide the row by its partition sum: amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY g), 0). Watch integer division and the zero-sum guard."},{"question":"How does RATIO_TO_REPORT handle NULL and zero sums?","answer":"NULL inputs give NULL ratios, and a zero-sum partition gives NULL for every row instead of an error. On SQL Server and PostgreSQL the manual division needs NULLIF to match that; MySQL and SQLite already return NULL."}],"related":["percent-of-total","oracle-analytic-functions","oracle-keep-dense-rank"],"novel_uses":[{"body":"On PostgreSQL (DATE_TRUNC), delta each category in a CTE, then take the ratio of each delta to the sum of deltas: positive shares name the categories that drove the month. The portable form divides by NULLIF(SUM(delta) OVER (PARTITION BY month), 0), so months with zero net change return NULL instead of an error.","sql":"WITH monthly AS (\n  SELECT category, DATE_TRUNC('month', sold_at) AS month, SUM(total) AS v\n  FROM orders GROUP BY 1, 2\n), d AS (\n  SELECT category, month,\n         v - LAG(v) OVER (PARTITION BY category ORDER BY month) AS delta\n  FROM monthly\n)\nSELECT category, month, delta,\n       delta * 1.0 / NULLIF(SUM(delta) OVER (PARTITION BY month), 0) AS share_of_change\nFROM d;"},{"body":"Compute the share once in a CTE, then run a running SUM over it ordered by size: the row where the running weight crosses one half is where half the portfolio sits. Concentration reviews start from exactly this line.","sql":"WITH w AS (\n  SELECT position_id, market_value,\n         RATIO_TO_REPORT(market_value) OVER () AS weight\n  FROM portfolio\n)\nSELECT position_id, weight,\n       SUM(weight) OVER (ORDER BY market_value DESC) AS cum_weight\nFROM w;"}]},"source_url":"https://sqlly.app/sql-functions/ratio-to-report","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rawtohex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RAWTOHEX function","description":"Oracle's RAWTOHEX shows a value's bytes as hexadecimal and HEXTORAW decodes them back, the byte-level pair behind Oracle's encoding debugging.","body":{"slug":"rawtohex","name":"RAWTOHEX / HEXTORAW","h1":"SQL RAWTOHEX function","category":"string","lede":"Convert between RAW bytes and hex text. Applied to a string, it exposes the stored encoding byte by byte.","syntax":"RAWTOHEX(raw)  |  HEXTORAW(hex)","return_type":"string / raw","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["On a VARCHAR2, RAWTOHEX implicitly casts to RAW first, so you see the database character set's bytes: on an AL32UTF8 database, RAWTOHEX('café') shows the UTF-8 é as C3A9.","HEXTORAW is the inverse, returning RAW. Compare and store it as binary, not text.","RAW tops out at 2000 bytes under MAX_STRING_SIZE=STANDARD (32767 when it is EXTENDED), and RAWTOHEX rejects BLOBs outright: use DBMS_LOB-level routines or UTL_RAW on chunks.","Other engines: HEX/UNHEX on MySQL, hex() on SQLite, encode/decode on PostgreSQL."],"examples":[{"engine_slug":"oracle","sql":"SELECT RAWTOHEX('ab') AS h FROM dual;  -- 6162"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX('café') AS h FROM dual;  -- 636166C3A9"}],"faqs":[{"question":"Why does RAWTOHEX('café') give 5 bytes for 4 characters?","answer":"It hexes the stored bytes, and AL32UTF8 encodes é as two bytes (C3A9). Four characters, five bytes."},{"question":"How is this different from MySQL's HEX?","answer":"Same concept, different input rule: Oracle hexes the stored bytes of any scalar except LOBs and LONG, so a number shows its internal NUMBER encoding, not its digits. MySQL's HEX(255) returns FF."},{"question":"How do I turn hex back into a string?","answer":"HEXTORAW gives RAW; for readable text, UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW(hex)) under the right charset."}],"related":["hex","unhex","dump"],"novel_uses":[{"body":"RAWTOHEX(SYS_GUID()) turns a RAW(16) system guid into the familiar 32-character string, the standard Oracle recipe for request ids and file names.","sql":"SELECT RAWTOHEX(SYS_GUID()) AS request_id FROM dual;"},{"body":"Snapshotting RAWTOHEX for a few rows before and after a character-set migration shows whether an accent really became its two UTF-8 bytes instead of a substitute.","sql":"SELECT RAWTOHEX(name) FROM customers WHERE id = 17;  -- compare before and after the conversion"}]},"source_url":"https://sqlly.app/sql-functions/rawtohex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-count","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_COUNT function","description":"How REGEXP_COUNT counts pattern matches in Oracle, PostgreSQL 15+ and SQL Server 2025: start and flags arguments, non-overlapping matches, and MySQL workarounds.","body":{"slug":"regexp-count","name":"REGEXP_COUNT","h1":"SQL REGEXP_COUNT function","category":"string","lede":"Counts the non-overlapping matches of a regular expression inside a string.","syntax":"REGEXP_COUNT(str, pattern [, start [, flags]])","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL Database."},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 15 and later."},{"engine_slug":"mysql","status":"no","note":"No REGEXP_COUNT on 8.4. For a literal, (CHAR_LENGTH(s) - CHAR_LENGTH(REPLACE(s, x, ''))) DIV CHAR_LENGTH(x) gives an integer, where plain / gives 3.0000. REPLACE is case-sensitive even under utf8mb4_0900_ai_ci, so wrap s and x in LOWER() for a case-insensitive count."},{"engine_slug":"sqlite","status":"no","note":"No REGEXP_COUNT."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Matches do not overlap: REGEXP_COUNT('aaa', 'aa') is 1, because the first match consumes two characters and the scan continues after it.","Returns 0 when the pattern never matches and NULL when the string is NULL; wrap in COALESCE before summing counts across rows.","Before PostgreSQL 15 the workaround is counting rows: (SELECT count(*) FROM regexp_matches(str, pattern, 'g')), which returns 0 rather than NULL for a NULL string, so guard NULL inputs yourself."],"examples":[{"engine_slug":"oracle","sql":"SELECT REGEXP_COUNT(log_line, 'error', 1, 'i') AS errors\nFROM logs;"},{"engine_slug":"postgresql","sql":"SELECT regexp_count('a1b22c333', '[0-9]+') AS numbers;  -- 3"},{"engine_slug":"sql-server","sql":"SELECT REGEXP_COUNT('a1b22c333', '[0-9]+') AS numbers;  -- 3"}],"faqs":[{"question":"How do I count occurrences of a literal substring instead of a regex?","answer":"Compare lengths: (LENGTH(s) - LENGTH(REPLACE(s, 'ab', ''))) / LENGTH('ab') in PostgreSQL, or (CHAR_LENGTH(s) - CHAR_LENGTH(REPLACE(s, 'ab', ''))) DIV CHAR_LENGTH('ab') in MySQL. SQL Server has no LENGTH function, so use (DATALENGTH(s) - DATALENGTH(REPLACE(s, 'ab', ''))) / DATALENGTH('ab') there, because LEN ignores trailing spaces and miscounts text that ends in a space."},{"question":"Does REGEXP_COUNT count overlapping matches?","answer":"No. 'aa' in 'aaa' counts once. Counting overlaps needs a lookahead pattern such as '(?=aa)' where the engine supports it (PostgreSQL does, SQL Server's RE2 does not) or a manual walk."},{"question":"What is the PostgreSQL equivalent?","answer":"regexp_count(str, pattern) from PostgreSQL 15. On older versions, count the rows of regexp_matches(str, pattern, 'g')."}],"related":["regexp-substr","regexp-instr","regexp-replace","length"],"novel_uses":[{"body":"A well-formed row of four fields holds exactly three separators, so REGEXP_COUNT(line, ',') = 3 becomes a one-line constraint in PostgreSQL and Oracle.","sql":"ALTER TABLE imports ADD CONSTRAINT shape_ok\n  CHECK (REGEXP_COUNT(line, ',') = 3);"},{"body":"Counting the term per row and ordering by the count is term-frequency ranking in plain SQL. The fourth argument takes 'i', so the count stays case-insensitive without wrapping the column in LOWER.","sql":"SELECT title, REGEXP_COUNT(body, 'error', 1, 'i') AS hits\nFROM logs\nORDER BY hits DESC;"}]},"source_url":"https://sqlly.app/sql-functions/regexp-count","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-instr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_INSTR function","description":"How REGEXP_INSTR returns where a regex matches in Oracle, MySQL 8, PostgreSQL 15+ and SQL Server 2025: start, occurrence and return-option arguments compared.","body":{"slug":"regexp-instr","name":"REGEXP_INSTR","h1":"SQL REGEXP_INSTR function","category":"string","lede":"Returns the 1-based position where a regular expression matches a string, or 0 when there is no match.","syntax":"REGEXP_INSTR(str, pattern [, start [, occurrence [, return_opt [, flags [, group]]]]])","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL Database."},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 15 and later."},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0.4 and later; no capture-group argument."},{"engine_slug":"sqlite","status":"no","note":"No REGEXP_INSTR; the REGEXP operator only answers true or false."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Regex flavours differ: Oracle uses POSIX extended syntax with Perl-style shortcuts such as \\d, MySQL uses ICU, PostgreSQL its own ARE engine and SQL Server 2025 RE2. Classes, quantifiers and alternation port; lookarounds and backreferences do not.","return_opt 0 (the default) gives the position of the first matched character, 1 the position just after the match. Oracle, PostgreSQL and SQL Server also take a capture-group number after the flags; MySQL stops at the flags.","Every engine returns 0 for no match and NULL when the string or pattern is NULL; positions count characters from 1."],"examples":[{"engine_slug":"oracle","sql":"SELECT REGEXP_INSTR(phone, '[0-9]{3}') AS first_digits_pos\nFROM contacts;"},{"engine_slug":"mysql","sql":"SELECT REGEXP_INSTR('abc123', '[0-9]+') AS pos;  -- 4"},{"engine_slug":"postgresql","sql":"SELECT regexp_instr('abc123', '[0-9]+', 1, 1, 1) AS after_match;  -- 7"},{"engine_slug":"sql-server","sql":"SELECT REGEXP_INSTR('abc123', '[0-9]+') AS pos;  -- 4"}],"faqs":[{"question":"What is the difference between REGEXP_INSTR and REGEXP_SUBSTR?","answer":"REGEXP_INSTR says where the match is; REGEXP_SUBSTR returns the matched text. They take the same start and occurrence arguments, so you can pair them."},{"question":"How do I get the end position of a regex match?","answer":"Set the return option to 1: REGEXP_INSTR(str, pattern, 1, 1, 1) returns the position just after the first match. The argument order is the same in all four engines."},{"question":"Which regex flavor does each engine use?","answer":"Oracle: POSIX extended plus Perl-style escapes. MySQL 8: ICU. PostgreSQL: its Advanced Regular Expressions. SQL Server 2025: RE2, which has no backreferences or lookarounds. Test anything beyond classes, anchors and quantifiers on each engine."}],"related":["regexp-substr","regexp-count","patindex","charindex"],"novel_uses":[{"body":"A start position of regexp_instr(str, pat, 1, 1, 1) is the character just after the match, so substr from there returns the tail. Every engine that has the function accepts return_opt.","sql":"SELECT substr(log_line, regexp_instr(log_line, '[0-9]+', 1, 1, 1)) AS after_first_number\nFROM lines;"},{"body":"A regex predicate never seeks an index, with or without lower(): MySQL and PostgreSQL scan every row either way. The flags argument (match_type in MySQL) sets case sensitivity without touching the column. On a case-insensitive MySQL collation the default already ignores case, so 'i' changes nothing there; use 'c' to force case-sensitive matching.","sql":"SELECT REGEXP_INSTR(note, 'error', 1, 1, 0, 'i') AS first_error\nFROM logs;"},{"body":"Each call's return_opt 1 result is the next call's start, which walks through matches one at a time in a loop without rescanning the prefix. Here the inner call finds where the first match ends and the outer call resumes there.","sql":"SELECT REGEXP_INSTR('ORA-1 ORA-2', 'ORA-[0-9]+',\n       REGEXP_INSTR('ORA-1 ORA-2', 'ORA-[0-9]+', 1, 1, 1)) AS second_match;"}]},"source_url":"https://sqlly.app/sql-functions/regexp-instr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-like","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_LIKE function","description":"How REGEXP_LIKE tests a string against a regex in Oracle, MySQL 8, PostgreSQL 15+ and SQL Server 2025: condition versus function, case defaults, and the ~ operator.","body":{"slug":"regexp-like","name":"REGEXP_LIKE","h1":"SQL REGEXP_LIKE function","category":"string","lede":"Returns true when the string matches the regular expression, false otherwise.","syntax":"REGEXP_LIKE(str, pattern [, flags])","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL; a predicate, not a value."},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 15+; the ~ operator works in every version."},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0.4 and later."},{"engine_slug":"sqlite","status":"partial","note":"str REGEXP pattern parses, but needs a regexp() function loaded; the sqlite3 shell includes one."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Oracle and SQL Server treat REGEXP_LIKE as a condition for WHERE, CASE WHEN and CHECK constraints; SQL Server rejects it in a SELECT list, and Oracle allows it there only from 23ai. MySQL returns 1 or 0 and PostgreSQL a boolean.","Case defaults differ: MySQL follows the collation, so REGEXP_LIKE('ABC', 'b') is true under the default utf8mb4_0900_ai_ci. Oracle, PostgreSQL and SQL Server match case exactly. Pass 'i' or 'c' instead of relying on the default.","The match is not anchored: REGEXP_LIKE('abc', 'b') is true. Anchor with ^ and $ when you mean a full-string match."],"examples":[{"engine_slug":"mysql","sql":"SELECT * FROM users\nWHERE REGEXP_LIKE(email, '^[a-z0-9.]+@example[.]com$');"},{"engine_slug":"oracle","sql":"SELECT * FROM products\nWHERE REGEXP_LIKE(sku, '^SKU-[0-9]{4}$');"},{"engine_slug":"sql-server","sql":"SELECT * FROM users\nWHERE REGEXP_LIKE(email, '@example[.]com$', 'i');"},{"engine_slug":"postgresql","sql":"SELECT * FROM users\nWHERE regexp_like(email, '^[a-z0-9.]+@example[.]com$');"},{"engine_slug":"sqlite","sql":"SELECT 'jane@example.com' REGEXP '^[^@]+@[^@]+$' AS is_email;  -- 1"}],"faqs":[{"question":"Is REGEXP_LIKE the same as LIKE?","answer":"No. LIKE uses % and _ wildcards and must match the whole string; REGEXP_LIKE evaluates a regular expression that matches anywhere unless you anchor it."},{"question":"What is the PostgreSQL equivalent of REGEXP_LIKE?","answer":"PostgreSQL 15 added regexp_like(str, pattern [, flags]). The ~ operator does the same in every version: email ~ '^[a-z]+$', with ~* for case-insensitive matching."},{"question":"How do I make REGEXP_LIKE case-insensitive?","answer":"Pass the 'i' flag: REGEXP_LIKE(col, 'pattern', 'i'). It works in MySQL, Oracle, PostgreSQL and SQL Server; 'c' forces case-sensitive matching."}],"related":["regexp-instr","regexp-count","regexp-substr","case"],"novel_uses":[{"body":"PostgreSQL 15+ accepts regexp_like as a partial index predicate because it is immutable: an index over just the matching rows serves the common query and ignores the rest of the table.","sql":"CREATE INDEX hot_inbox ON messages (created_at)\nWHERE regexp_like(recipients, '@example[.]com$');"},{"body":"MySQL returns 1 or 0 and Oracle and SQL Server treat the call as a condition, so a CASE WHEN REGEXP_LIKE chain sorts rows into buckets by shape in a single pass.","sql":"SELECT CASE WHEN REGEXP_LIKE(phone, '^[+]') THEN 'international'\n            WHEN REGEXP_LIKE(phone, '^[0-9]+$') THEN 'national'\n            ELSE 'invalid' END AS kind\nFROM contacts;"},{"body":"One anchored pattern with alternation reads better than three LIKE tests ORed together and matches the same rows. Index use differs: on MySQL a single LIKE 'AAPL-%' seeks the index, while the regex and the three-way OR both scan it, and on PostgreSQL with the default collation none of them can use a plain btree.","sql":"SELECT * FROM products\nWHERE REGEXP_LIKE(sku, '^(AAPL|MSFT|GOOG)-');"}]},"source_url":"https://sqlly.app/sql-functions/regexp-like","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-match","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_MATCH function","description":"How PostgreSQL's regexp_match returns capture groups as an array: whole-match versus group output, regexp_matches for all occurrences, and one-row-per-match behaviour.","body":{"slug":"regexp-match","name":"REGEXP_MATCH","h1":"SQL REGEXP_MATCH function","category":"string","lede":"Returns the capture groups of the first regex match in a string as a text array. Available since PostgreSQL 10.","syntax":"regexp_match(string, pattern [, flags])","return_type":"text[] or NULL","support":[{"engine_slug":"sql-server","status":"partial","note":"SQL Server 2025's table-valued REGEXP_MATCHES returns every match, with groups as JSON."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"No array result; REGEXP_SUBSTR returns one whole match."},{"engine_slug":"sqlite","status":"no","note":"No equivalent; the REGEXP operator only checks true or false."},{"engine_slug":"oracle","status":"no","note":"No array result; call REGEXP_SUBSTR once per group with its group argument."}],"gotchas":["Without capture groups regexp_match returns a one-element array holding the whole match; with groups it returns one element per group.","No match returns NULL, not an empty array. A pattern that can match zero characters always matches: regexp_match('abc', 'x*') is {\"\"}.","For every match, not just the first, use regexp_matches with the 'g' flag; it returns one row per match. Passing 'g' to regexp_match is an error, not a silent no-op: regexp_match() does not support the \"global\" option."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regexp_match('2026-11-20', '([0-9]+)-([0-9]+)-([0-9]+)') AS ymd;  -- {2026,11,20}"},{"engine_slug":"postgresql","sql":"SELECT (regexp_match(email, '(.+)@(.+)'))[2] AS domain\nFROM users;"},{"engine_slug":"sql-server","sql":"SELECT match_id, match_value\nFROM REGEXP_MATCHES('abc123def456', '[a-z]+[0-9]+');"}],"faqs":[{"question":"How do I get all matches instead of the first?","answer":"Use regexp_matches(str, pattern, 'g'), which returns one row per match. regexp_match only looks at the first."},{"question":"Why does regexp_match return an array instead of text?","answer":"Because it returns every capture group at once. Subscript the call to pick one: (regexp_match(str, pat))[2]. The parentheses around the call are required."},{"question":"Does regexp_match use PCRE regex?","answer":"No. PostgreSQL uses its own Advanced Regular Expressions: POSIX extended syntax plus Perl-style escapes, so \\d, \\s, \\w, lookahead, lookbehind and backreferences all work. Named groups and possessive quantifiers do not."}],"related":["regexp-substr","regexp-split-to-array","regexp-replace","substring"],"novel_uses":[{"body":"An anchored pattern in PostgreSQL either fails and returns NULL, or succeeds with a fixed array shape, so one call both validates the format and hands back the parts through a lateral alias.","sql":"SELECT m[1]::int AS id\nFROM refs, regexp_match(label, '^id=([0-9]+)$') AS m\nWHERE m IS NOT NULL;"},{"body":"Subscripting regexp_match inside a join extracts an embedded reference, which rescues data that stores ids inside prose. An expression index on the same expression can serve the join, because regexp_match is IMMUTABLE: CREATE INDEX ON comments (((regexp_match(source, 'user=([0-9]+)'))[1])) gives an Index Scan on the join. Without one, compute it once into a column when the table is large.","sql":"SELECT a.*, b.id\nFROM comments a\nJOIN users b ON (regexp_match(a.source, 'user=([0-9]+)'))[1] = b.id::text;"}]},"source_url":"https://sqlly.app/sql-functions/regexp-match","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-replace","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_REPLACE function","description":"Regex replace in SQL: REGEXP_REPLACE on PostgreSQL, MySQL 8, Oracle and SQL Server 2025, the SQLite gap, and how capture groups and flags differ.","body":{"slug":"regexp-replace","name":"REGEXP_REPLACE","h1":"SQL REGEXP_REPLACE function","category":"string","lede":"Replaces text matching a regular expression. The engines that have it disagree on whether it replaces the first match or all of them, and on how to write a capture group.","syntax":"REGEXP_REPLACE(string, pattern, replacement [, flags])  -- PostgreSQL  |  REGEXP_REPLACE(string, pattern, replacement [, start [, occurrence [, flags]]])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL; earlier versions have no regex functions"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+, using the ICU regex library"},{"engine_slug":"sqlite","status":"no","note":"no REGEXP_REPLACE; even the REGEXP operator needs a user function or extension"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["First match or all: PostgreSQL replaces only the first match unless you pass the 'g' flag. MySQL, Oracle and SQL Server 2025 replace every match by default (occurrence 0).","Capture groups in the replacement are \\1 on PostgreSQL, Oracle and SQL Server, but $1 on MySQL: REGEXP_REPLACE('abc', '(b)', '[$1]') is 'a[b]c'.","Case-insensitive matching: the 'i' flag. PostgreSQL takes it as the fourth argument; MySQL, Oracle and SQL Server take it as the sixth, after start position and occurrence.","On MySQL a backslash in a string literal is itself an escape character, so a regex \\s must be written '\\\\s'. POSIX classes such as [[:space:]] avoid the problem."],"examples":[{"engine_slug":"postgresql","sql":"SELECT REGEXP_REPLACE(phone, '[^0-9]', '', 'g') AS digits\nFROM contacts;"},{"engine_slug":"oracle","sql":"-- replaces every match by default\nSELECT REGEXP_REPLACE(phone, '[^0-9]', '') AS digits FROM contacts;"},{"engine_slug":"mysql","sql":"-- start 1, occurrence 0 (all), case-insensitive\nSELECT REGEXP_REPLACE(note, '<br[[:space:]]*/?>', ' ', 1, 0, 'i') AS clean\nFROM notes;"},{"engine_slug":"sql-server","sql":"-- SQL Server 2025\nSELECT REGEXP_REPLACE(phone, '[^0-9]', '') AS digits FROM contacts;"}],"faqs":[{"question":"Does SQL Server have REGEXP_REPLACE?","answer":"From SQL Server 2025 (and in Azure SQL Database), yes, along with REGEXP_LIKE, REGEXP_SUBSTR and the other REGEXP_ functions. Earlier versions have only LIKE and PATINDEX wildcards, so nested REPLACE or a SQL CLR function is the workaround."},{"question":"How do I make REGEXP_REPLACE case-insensitive?","answer":"Pass the 'i' flag. On PostgreSQL it is the fourth argument: REGEXP_REPLACE(s, 'x', '-', 'gi'). On MySQL, Oracle and SQL Server 2025 it is the sixth: REGEXP_REPLACE(s, 'x', '-', 1, 0, 'i'). MySQL also accepts (?i) at the start of the pattern."}],"related":["replace","split-part","instr"],"novel_uses":[{"body":"A view that masks every run of four or more digits turns raw application tables into log-safe ones: short counts stay readable and card- or phone-shaped strings disappear from anything that reads the view.","sql":"SELECT REGEXP_REPLACE(msg, '\\d{4,}', '####') AS safe_msg\nFROM app_log;"},{"body":"Lowercase plus one regex pass converts legacy titles into URL slugs inside an UPDATE, which is the whole migration. PostgreSQL needs the g flag or only the first run of non-URL characters converts; a second pass can trim dashes off the ends.","sql":"UPDATE posts\nSET slug = REGEXP_REPLACE(LOWER(title), '[^a-z0-9]+', '-', 'g');"}]},"source_url":"https://sqlly.app/sql-functions/regexp-replace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-split-to-array","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_SPLIT_TO_ARRAY function","description":"How PostgreSQL's regexp_split_to_array splits a string on a regex pattern: multi-character delimiters, zero-length matches, and string_to_array for plain separators.","body":{"slug":"regexp-split-to-array","name":"REGEXP_SPLIT_TO_ARRAY","h1":"SQL REGEXP_SPLIT_TO_ARRAY function","category":"string","lede":"Splits a string wherever a regular expression matches and returns the pieces as a text array.","syntax":"regexp_split_to_array(string, pattern [, flags])","return_type":"text[]","support":[{"engine_slug":"sql-server","status":"no","note":"No arrays; SQL Server 2025's REGEXP_SPLIT_TO_TABLE returns rows."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"No regex split; JSON_TABLE or SUBSTRING_INDEX chains."},{"engine_slug":"sqlite","status":"no","note":"No regex split."},{"engine_slug":"oracle","status":"no","note":"No direct equivalent; REGEXP_SUBSTR walks."}],"gotchas":["The separator is a regex, so '[,;]\\s*' splits on a comma or semicolon plus any following whitespace. With standard_conforming_strings on (the default), backslashes in a plain literal reach the regex engine unchanged.","Zero-length matches split between characters: regexp_split_to_array('abc', 'x*') is {a,b,c}. Only zero-length matches at the very start or end, or right after a previous match, are ignored.","A leading or trailing delimiter produces an empty first or last element: regexp_split_to_array(',a', ',') is {\"\",a}."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regexp_split_to_array('a, b; c', '[,;][ ]*') AS parts;  -- {a,b,c}"},{"engine_slug":"postgresql","sql":"SELECT unnest(regexp_split_to_array(line, '\\s+')) AS word\nFROM lines;"}],"faqs":[{"question":"When should I use string_to_array instead?","answer":"When the separator is a fixed string. string_to_array is faster and has no regex escaping to get wrong: regexp_split_to_array('a.b', '.') returns {\"\",\"\",\"\",\"\"} because the dot matches any character, where string_to_array('a.b', '.') returns {a,b}. An empty input gives {} from string_to_array but {\"\"} from regexp_split_to_array."},{"question":"How do I split on any whitespace?","answer":"Use '\\s+' or the POSIX class '[[:space:]]+', then unnest the array if you need rows."},{"question":"Why does my array contain empty strings?","answer":"The input had adjacent delimiters or a delimiter at either end. Strip the delimiter from both ends first (btrim(line, ',') for a comma), use a pattern with + so runs of adjacent delimiters count as one separator, or filter empties after unnest."}],"related":["regexp-split-to-table","string-to-array","regexp-match","string-split"],"novel_uses":[{"body":"Two split arrays compared with && share at least one token, which is a tag-overlap test in one expression. It pairs naturally with a GIN index when the split becomes a stored column.","sql":"SELECT a.id, b.id\nFROM docs a JOIN docs b ON a.id < b.id\nWHERE regexp_split_to_array(a.tags, '\\s+') && regexp_split_to_array(b.tags, '\\s+');"},{"body":"A stored generated column holds the tokens computed at write time, and a GIN index over it supports the && overlap and @> containment operators without re-splitting on read.","sql":"ALTER TABLE docs ADD tokens text[]\n  GENERATED ALWAYS AS (regexp_split_to_array(body, '\\s+')) STORED;\nCREATE INDEX ON docs USING gin (tokens);"},{"body":"Subscripting the array reads the nth whitespace-separated token directly, which split_part cannot express because it has no regex separator.","sql":"SELECT (regexp_split_to_array(line, '\\s+'))[2] AS second_word\nFROM lines;"}]},"source_url":"https://sqlly.app/sql-functions/regexp-split-to-array","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-split-to-table","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_SPLIT_TO_TABLE function","description":"How regexp_split_to_table splits a string on a regex into one row per piece in PostgreSQL and SQL Server 2025: ordering, empty pieces, and WITH ORDINALITY positions.","body":{"slug":"regexp-split-to-table","name":"REGEXP_SPLIT_TO_TABLE","h1":"SQL REGEXP_SPLIT_TO_TABLE function","category":"string","lede":"Splits a string wherever a regular expression matches and returns the pieces as a set of rows.","syntax":"regexp_split_to_table(string, pattern [, flags])","return_type":"set of text rows","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL; returns value and ordinal columns."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"No built-in; recursive CTEs or JSON_TABLE fill the gap."},{"engine_slug":"sqlite","status":"no","note":"No built-in split; json_each over a JSON array."},{"engine_slug":"oracle","status":"no","note":"No built-in; REGEXP_SUBSTR with CONNECT BY LEVEL."}],"gotchas":["To keep each piece's position in PostgreSQL, add WITH ORDINALITY in the FROM clause: regexp_split_to_table(s, ',') WITH ORDINALITY AS t(word, n). SQL Server's version returns an ordinal column by itself.","Like regexp_split_to_array, zero-length matches split between characters, and adjacent delimiters produce empty strings.","Call it in the FROM clause (as a lateral function) when you need other columns next to the pieces. In the SELECT list one call returns the same rows, but two set-returning calls there zip together instead of crossing: regexp_split_to_table('a,b,c', ',') next to regexp_split_to_table('1,2', ',') gives three rows, with NULL padding the shorter one."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regexp_split_to_table('one,two,three', ',') AS word;"},{"engine_slug":"postgresql","sql":"SELECT l.id, w.word, w.n\nFROM logs l, regexp_split_to_table(l.message, '[[:space:]]+') WITH ORDINALITY AS w(word, n);"},{"engine_slug":"sql-server","sql":"SELECT value, ordinal FROM REGEXP_SPLIT_TO_TABLE('a1b22c', '[0-9]+');"}],"faqs":[{"question":"How do I keep track of each element's position?","answer":"In PostgreSQL: FROM regexp_split_to_table(str, pat) WITH ORDINALITY AS t(v, n); n is 1-based. In SQL Server 2025, read the ordinal column."},{"question":"What is the difference between the array and table variants?","answer":"regexp_split_to_array returns one array value per input row; regexp_split_to_table returns one row per piece, which is what joins and GROUP BY need."}],"related":["regexp-split-to-array","string-split","string-to-array","substring-index"],"novel_uses":[{"body":"Splitting on a negated character class tokenizes free text: every run of non-letters is the delimiter, and GROUP BY over the rows counts the words. lower comes first so case does not split the counts.","sql":"SELECT word, count(*) AS n\nFROM logs, regexp_split_to_table(lower(message), '[^a-z]+') AS word\nWHERE word <> ''\nGROUP BY word\nORDER BY n DESC\nLIMIT 20;"},{"body":"One UPDATE re-splits, trims every element, drops the empties and rejoins in the original order, because WITH ORDINALITY preserves each element's position. A row whose elements are all empty becomes NULL rather than '', because string_agg over no rows returns NULL.","sql":"UPDATE posts\nSET tags = (SELECT string_agg(btrim(w), ',' ORDER BY n)\n            FROM regexp_split_to_table(posts.tags, ',') WITH ORDINALITY AS t(w, n)\n            WHERE btrim(w) <> '');"}]},"source_url":"https://sqlly.app/sql-functions/regexp-split-to-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regexp-substr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGEXP_SUBSTR function","description":"How REGEXP_SUBSTR extracts the text matching a regex in Oracle, MySQL 8, PostgreSQL 15+ and SQL Server 2025: occurrence and group arguments, NULL results, alternatives.","body":{"slug":"regexp-substr","name":"REGEXP_SUBSTR","h1":"SQL REGEXP_SUBSTR function","category":"string","lede":"Returns the substring that matches a regular expression, or NULL when the pattern does not match.","syntax":"REGEXP_SUBSTR(str, pattern [, start [, occurrence [, flags [, group]]]])","return_type":"string or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL Database."},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 15+; older versions use SUBSTRING(str FROM pattern)."},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0.4+; no capture-group argument."},{"engine_slug":"sqlite","status":"no","note":"No REGEXP_SUBSTR; extract in the application."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["A non-match returns NULL. In Oracle a zero-length match is NULL too, because Oracle treats the empty string as NULL. MySQL and PostgreSQL return the empty string for a zero-length match and NULL only for a non-match or a NULL input.","The occurrence argument extracts later matches: occurrence 2 returns the second match, which is how you walk through repeated tokens.","The group argument (Oracle, PostgreSQL, SQL Server) picks a parenthesised group; 0, the default, is the whole match. MySQL has no group argument, so extracting a group there takes REGEXP_REPLACE with a $1 backreference over the whole string, for example REGEXP_REPLACE(s, '^.*key=(.*)$', '$1'). The pattern must match the entire string, because a non-match returns the input unchanged rather than NULL. The backslash-digit form is not a backreference in MySQL."],"examples":[{"engine_slug":"oracle","sql":"SELECT REGEXP_SUBSTR(path, '[^/]+', 1, 1) AS first_segment\nFROM routes;"},{"engine_slug":"mysql","sql":"SELECT REGEXP_SUBSTR('a1b22', '[0-9]+', 1, 2) AS second_number;  -- 22"},{"engine_slug":"oracle","sql":"SELECT REGEXP_SUBSTR(email, '(.+)@(.+)', 1, 1, NULL, 2) AS domain\nFROM users;"},{"engine_slug":"sql-server","sql":"SELECT REGEXP_SUBSTR('abc123', '[0-9]+') AS digits;  -- 123"},{"engine_slug":"postgresql","sql":"SELECT regexp_substr('abc123', '[0-9]+') AS digits;  -- 123"}],"faqs":[{"question":"How do I extract the second match of a pattern?","answer":"Pass occurrence 2: REGEXP_SUBSTR(str, pattern, 1, 2) starts at position 1 and returns the second match. Increase the occurrence to walk through the rest."},{"question":"What is the PostgreSQL equivalent of REGEXP_SUBSTR?","answer":"PostgreSQL 15 added regexp_substr with the same arguments. On older versions SUBSTRING(str FROM pattern) returns the first parenthesised group, or the whole match when there are no groups, and regexp_match returns the groups of the first match as an array; regexp_matches with the 'g' flag returns one array per match."},{"question":"Why does a successful extraction return NULL in Oracle?","answer":"Oracle stores the empty string as NULL. A pattern that matches zero characters, such as 'x*', yields NULL rather than an empty string."}],"related":["regexp-instr","regexp-count","regexp-match","substring"],"novel_uses":[{"body":"Pairing REGEXP_SUBSTR with LEVEL walks every occurrence in Oracle: LEVEL feeds the occurrence argument and REGEXP_COUNT bounds the walk, which turns one delimited string into rows.","sql":"SELECT REGEXP_SUBSTR('a,b,c', '[^,]+', 1, LEVEL) AS item\nFROM dual\nCONNECT BY LEVEL <= REGEXP_COUNT('a,b,c', '[^,]+');"},{"body":"MySQL has no capture-group argument, but anchoring a class to the end often captures the same piece directly: '[^@]+$' returns everything after the last @ with no group needed.","sql":"SELECT REGEXP_SUBSTR(email, '[^@]+$', 1, 1) AS domain\nFROM users;"}]},"source_url":"https://sqlly.app/sql-functions/regexp-substr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regr-count","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGR_COUNT function","description":"REGR_COUNT(Y, X) counts rows where both inputs are non-NULL: PostgreSQL and Oracle support, why it drives the other REGR_ functions, and a portable COUNT recipe.","body":{"slug":"regr-count","name":"REGR_COUNT","h1":"SQL REGR_COUNT function","category":"aggregate","lede":"Counts the complete input pairs the regression functions actually use.","syntax":"REGR_COUNT(y, x)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"no","note":"COUNT(CASE WHEN y IS NOT NULL AND x IS NOT NULL THEN 1 END)"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"portable recipe: COUNT(*) with both columns non-NULL in WHERE"},{"engine_slug":"sqlite","status":"no","note":"COUNT(CASE WHEN y IS NOT NULL AND x IS NOT NULL THEN 1 END)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["It is the denominator behind every other REGR_ decision: the whole family works on complete pairs only.","Never returns NULL: an empty group yields 0, like COUNT.","The portable recipe is a filtered COUNT: COUNT(CASE WHEN y IS NOT NULL AND x IS NOT NULL THEN 1 END)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regr_count(sales, ad_spend) FROM monthly;"},{"engine_slug":"sql-server","sql":"SELECT COUNT(CASE WHEN sales IS NOT NULL AND ad_spend IS NOT NULL THEN 1 END) FROM monthly;"},{"engine_slug":"oracle","sql":"SELECT REGR_COUNT(sales, ad_spend) FROM monthly;"}],"faqs":[{"question":"REGR_COUNT vs COUNT(*)?","answer":"COUNT(*) counts rows; REGR_COUNT(y, x) counts rows where both y and x are non-NULL."},{"question":"Can it return NULL?","answer":"No, it returns 0 for an empty group like COUNT does."},{"question":"Which engines have it?","answer":"PostgreSQL and Oracle; everywhere else use the filtered COUNT recipe."}],"related":["regr-slope","regr-intercept","count","aggregate-nulls","regr-r2"],"novel_uses":[{"body":"Put the pair count in HAVING so a slope is only reported for groups with enough complete observations to trust it.","sql":"SELECT region, regr_slope(revenue, month_no) FROM monthly GROUP BY region HAVING regr_count(revenue, month_no) >= 6;"},{"body":"regr_count over COUNT(*) is a 0-to-1 score of how much of the table has both columns filled, one row of output per segment.","sql":"SELECT region, regr_count(budget, spend) * 1.0 / COUNT(*) AS pair_fill FROM plans GROUP BY region;"}]},"source_url":"https://sqlly.app/sql-functions/regr-count","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regr-intercept","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGR_INTERCEPT function","description":"REGR_INTERCEPT returns the least-squares line's y-intercept: AVG(y) minus REGR_SLOPE(y,x) times AVG(x) over complete pairs; PostgreSQL and Oracle support, NULL rules.","body":{"slug":"regr-intercept","name":"REGR_INTERCEPT","h1":"SQL REGR_INTERCEPT function","category":"aggregate","lede":"Returns the y-intercept of the least-squares line fitted to the complete (y, x) pairs.","syntax":"REGR_INTERCEPT(y, x) | REGR_INTERCEPT(y, x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"same manual route"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"compute AVG(y) - slope * AVG(x) with the manual slope formula"},{"engine_slug":"sqlite","status":"no","note":"same manual route over complete pairs"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Same pair filtering as the rest of the family: either input NULL drops the row.","NULL whenever REGR_SLOPE is NULL: fewer than two pairs or zero x-variance.","Portable form: REGR_AVGY(y, x) - REGR_SLOPE(y, x) * REGR_AVGX(y, x), or AVG(y) - slope * AVG(x) over rows filtered to complete pairs (WHERE y IS NOT NULL AND x IS NOT NULL) where REGR_ is missing; plain AVG(y) and AVG(x) over all rows give a different answer when one side has NULLs."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regr_intercept(sales, ad_spend) FROM monthly;"},{"engine_slug":"oracle","sql":"SELECT REGR_INTERCEPT(sales, ad_spend) FROM monthly;"}],"faqs":[{"question":"What does the intercept mean here?","answer":"The predicted y when x is 0, for the line fitted by least squares."},{"question":"How do I compute it by hand?","answer":"AVG(y) - slope * AVG(x) over complete pairs only (WHERE y IS NOT NULL AND x IS NOT NULL), with slope = COVAR_POP(y,x) / VAR_POP(x), or (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) on engines without COVAR_POP."},{"question":"Which engines ship it?","answer":"PostgreSQL and Oracle; MySQL, SQL Server and SQLite need the manual formula."}],"related":["regr-slope","regr-count","covar-pop","avg","regr-r2"],"novel_uses":[{"body":"Regress total cost against units produced and the intercept is the cost incurred at zero units, the fixed-cost number accountants estimate by hand.","sql":"SELECT regr_intercept(total_cost, units) AS fixed_cost FROM production_months;"},{"body":"PostgreSQL and Oracle run the regression aggregates as window functions, so a trailing frame shows the fitted baseline moving as the process changes.","sql":"SELECT day, regr_intercept(ms, bytes) OVER (ORDER BY day ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS base_ms FROM timings;"}]},"source_url":"https://sqlly.app/sql-functions/regr-intercept","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regr-r2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGR_R2 function","description":"REGR_R2 returns R squared for a least-squares fit: between 0 and 1, NULL on too few pairs or constant x, PostgreSQL and Oracle support and the CORR relation.","body":{"slug":"regr-r2","name":"REGR_R2","h1":"SQL REGR_R2 function","category":"aggregate","lede":"Returns the coefficient of determination of the least-squares fit, the share of y's variance the line explains.","syntax":"REGR_R2(y, x) | REGR_R2(y, x) OVER (...)","return_type":"numeric (0 to 1)","support":[{"engine_slug":"sql-server","status":"no","note":"same manual route"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"square the manual correlation coefficient"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["NULL on fewer than two complete pairs or when every x is the same. When every y is the same but x varies, it returns 1 (a flat line fits perfectly) even though CORR returns NULL.","Otherwise it is the square of CORR(y, x), so the sign of the relationship is lost; pair it with REGR_SLOPE to read direction.","Only complete (y, x) pairs are used, like the rest of the REGR_ family."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regr_r2(sales, ad_spend) FROM monthly;"},{"engine_slug":"oracle","sql":"SELECT REGR_R2(salary, age) FROM employees;"}],"faqs":[{"question":"What is a good REGR_R2 value?","answer":"Closer to 1 means the line explains more of y's variance; there is no universal cutoff: it depends on the domain."},{"question":"Is REGR_R2 just CORR squared?","answer":"For ordinary data, yes. The exception is a constant y with varying x: CORR is NULL there, REGR_R2 returns 1."},{"question":"Which engines have it?","answer":"PostgreSQL and Oracle; elsewhere square the manual correlation formula."}],"related":["regr-slope","corr","regr-count","var-pop"],"novel_uses":[{"body":"Fitting R squared per segment shows which regions a linear story describes and where it does not; a segment near 0 needs a different shape, not a better line.","sql":"SELECT region, regr_r2(revenue, ad_spend) FROM monthly GROUP BY region;"},{"body":"As a window aggregate in PostgreSQL, a trailing REGR_R2 reveals the fit degrading period by period, an early sign the old model stopped describing the data.","sql":"SELECT week, regr_r2(revenue, ad_spend) OVER (ORDER BY week ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) FROM weekly;"}]},"source_url":"https://sqlly.app/sql-functions/regr-r2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/regr-slope","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REGR_SLOPE function","description":"REGR_SLOPE fits a least-squares line per group: slope = COVAR_POP(y,x) / VAR_POP(x), PostgreSQL and Oracle support, pair filtering and degenerate inputs.","body":{"slug":"regr-slope","name":"REGR_SLOPE","h1":"SQL REGR_SLOPE function","category":"aggregate","lede":"Returns the slope of the least-squares line fitted to the complete (y, x) pairs of a group.","syntax":"REGR_SLOPE(y, x) | REGR_SLOPE(y, x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"same manual formula; cast integers to float"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"manual: (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs"},{"engine_slug":"sqlite","status":"no","note":"same manual formula over complete pairs"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Only complete pairs count: a NULL in y or x drops the row.","The result is NULL when there are fewer than two pairs or when every x is the same (VAR_POP(x) = 0); with fractional x such as 0.1, float rounding can leave a tiny nonzero variance and PostgreSQL returns a huge bogus slope instead of NULL.","The companion intercept is REGR_INTERCEPT(y, x) = AVG(y) - REGR_SLOPE(y, x) * AVG(x).","MySQL, SQL Server and SQLite have no REGR_ functions; slope = (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs (WHERE y IS NOT NULL AND x IS NOT NULL)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT regr_slope(sales, ad_spend) FROM monthly;"},{"engine_slug":"oracle","sql":"SELECT REGR_SLOPE(sales, ad_spend) OVER (PARTITION BY region) FROM monthly;"}],"faqs":[{"question":"What is REGR_SLOPE mathematically?","answer":"COVAR_POP(y, x) / VAR_POP(x) computed over complete (y, x) pairs, the least-squares estimate of dy/dx; on raw columns VAR_POP(x) also counts rows where only y is NULL and gives a different number."},{"question":"Why is my result NULL?","answer":"Fewer than two complete pairs, or every x value identical, leaves the slope undefined."},{"question":"Does MySQL have REGR_SLOPE?","answer":"No; compute (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs."}],"related":["regr-intercept","regr-count","covar-pop","corr","regr-r2"],"novel_uses":[{"body":"One GROUP BY fits a line per region and ORDER BY slope turns the table into a growth ranking, no chart tool in the loop.","sql":"SELECT region, regr_slope(revenue, month_no) AS trend FROM monthly GROUP BY region ORDER BY trend DESC;"},{"body":"Intercept plus slope times the next period number is a naive forecast straight from the aggregates; honest until the series bends, and cheap enough to recompute each run.","sql":"SELECT regr_intercept(revenue, month_no) + regr_slope(revenue, month_no) * 13 AS next_month FROM monthly;"}]},"source_url":"https://sqlly.app/sql-functions/regr-slope","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/remainder","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REMAINDER function","description":"Oracle's REMAINDER rounds the quotient to the nearest integer before subtracting, while MOD takes its floor, so REMAINDER(8, 3) is -1 where MOD(8, 3) is 2.","body":{"slug":"remainder","name":"REMAINDER","h1":"SQL REMAINDER function","category":"math","lede":"Returns n1 - n2 * N, where N is the integer nearest n1/n2 (an exact half goes to the even integer): REMAINDER(8, 3) is -1 because 8/3 rounds to 3, while MOD(8, 3) is 2.","syntax":"REMAINDER(n1, n2)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"No REMAINDER; % truncates the quotient instead"},{"engine_slug":"postgresql","status":"no","note":"No REMAINDER; % follows the dividend's sign"},{"engine_slug":"mysql","status":"no","note":"No REMAINDER; MOD follows the dividend's sign"},{"engine_slug":"sqlite","status":"no","note":"No REMAINDER; % keeps the dividend's sign"},{"engine_slug":"oracle","status":"yes","note":"REMAINDER(n1, n2) is built in; a zero divisor raises ORA-01476 for NUMBER and returns NaN for BINARY_DOUBLE"}],"gotchas":["Oracle's MOD takes the floor of the quotient (n1 - n2 * FLOOR(n1/n2)); REMAINDER rounds it. They differ when rounding and flooring pick different integers, which for positive quotients means a fraction above one half: MOD(8, 3) is 2, REMAINDER(8, 3) is -1.","The REMAINDER result can have either sign regardless of the inputs' signs, and always has magnitude at most half the divisor. On SQL Server, PostgreSQL, MySQL and SQLite, % and MOD take the dividend's sign; Oracle's MOD takes the divisor's sign, so MOD(-8, 3) is 1 there.","Zero divisors flip: MOD(7, 0) returns 7, but REMAINDER(7, 0) raises ORA-01476 (and REMAINDER(7d, 0d) returns NaN)."],"examples":[{"engine_slug":"oracle","sql":"SELECT REMAINDER(8, 3) AS rem, MOD(8, 3) AS mod_result FROM dual;  -- -1, 2"},{"engine_slug":"oracle","sql":"SELECT REMAINDER(7, 3) AS rem FROM dual;  -- 1 (quotient 2.33 rounds to 2)"}],"faqs":[{"question":"How is REMAINDER different from MOD in Oracle?","answer":"REMAINDER rounds the quotient to the nearest integer; MOD takes its floor. REMAINDER(8, 3) is -1 while MOD(8, 3) is 2: the results differ by exactly one divisor whenever they differ."},{"question":"Does any other engine have REMAINDER?","answer":"No. The other four have only truncating % or MOD, which keep the dividend's sign like C's fmod. Emulate with n1 - n2 * ROUND(n1 * 1.0 / n2), which needs decimal division on engines where / truncates integers. Exact halves can differ from Oracle: 15 and 6 give -3 here (2.5 rounds up) but 3 in Oracle, which picks the even integer."},{"question":"What does REMAINDER(7, 0) do?","answer":"Raises ORA-01476: divisor is equal to zero for NUMBER input, and returns NaN for BINARY_DOUBLE input. MOD(7, 0), by contrast, returns 7."}],"related":["mod","mod-sign","modulo-operator","division-by-zero"],"novel_uses":[{"body":"Oracle's REMAINDER rounds the quotient while MOD floors it, so REMAINDER(delta, 7) lands in [-3, 3] for whole-number differences and weekday or phase differences bin symmetrically. MOD gives 0..6 and scatters the near-zero cases across both ends.","sql":"SELECT REMAINDER(day2 - day1, 7) AS centered_diff FROM pairs;"},{"body":"REMAINDER(n1, n2) <> MOD(n1, n2) when rounding and flooring the quotient pick different integers, which is when the quotient sits more than one half above its floor (exact halves depend on parity), so the filter lists every row where the rounding rule matters. A one-line data quality sweep in Oracle.","sql":"SELECT n1, n2 FROM t WHERE REMAINDER(n1, n2) <> MOD(n1, n2);"}]},"source_url":"https://sqlly.app/sql-functions/remainder","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/remove-nbsp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL remove non-breaking spaces","description":"Non-breaking spaces (U+00A0) defeat TRIM, and = on SQL Server, PostgreSQL and SQLite; MySQL's default collation sees a space. Replace them via NCHAR, CHR or UTF-8 bytes.","body":{"slug":"remove-nbsp","name":"Removing non-breaking spaces","h1":"SQL remove non-breaking spaces","category":"string","lede":"Data pasted from Excel, web pages and PDFs carries U+00A0. It renders as a space, fails string comparisons, and TRIM will not touch it.","syntax":"REPLACE(s, NCHAR(160), ' ')","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Default TRIM removes only ordinary spaces, so U+00A0 survives it on every engine. It goes only if you name it in a character-set trim or REPLACE it.","MySQL trap: CHAR(160) is a single binary byte, and CHAR(160 USING utf8mb4) is NULL because 0xA0 alone is not valid UTF-8. Use the two UTF-8 bytes: CHAR(0xC2A0 USING utf8mb4).","SQL Server: use NCHAR(160) against nvarchar data; CHAR(160) depends on the varchar codepage.","Diagnose with bytes, not eyes: Oracle DUMP(col, 16), PostgreSQL encode(convert_to(col, 'utf8'), 'hex') and MySQL HEX(col) show the NBSP as c2a0 in UTF-8 data."],"examples":[{"engine_slug":"sql-server","sql":"SELECT REPLACE(name, NCHAR(160), ' ') AS fixed FROM names;"},{"engine_slug":"mysql","sql":"SELECT REPLACE(name, CHAR(0xC2A0 USING utf8mb4), ' ') AS fixed FROM names;"},{"engine_slug":"oracle","sql":"SELECT REPLACE(name, CHR(160), ' ') AS fixed FROM names;"},{"engine_slug":"postgresql","sql":"SELECT replace(name, chr(160), ' ') AS fixed FROM names;  -- chr(160) is U+00A0 in a UTF8 database"},{"engine_slug":"sqlite","sql":"SELECT replace(name, char(160), ' ') AS fixed FROM names;"}],"faqs":[{"question":"Why does my WHERE clause miss values that look identical?","answer":"One side holds U+00A0 instead of a space: same pixels, different code point, so = fails. Replace the NBSP with ' ' on both sides, or clean on write. MySQL's default utf8mb4_0900_ai_ci collation is the exception: there an NBSP compares equal to a space, so = gives a false match; use utf8mb4_bin or HEX() to see the difference."},{"question":"Why did TRIM not remove it?","answer":"TRIM strips spaces (or an explicit character set). The non-breaking space is a different character; pass it to the character-set form or REPLACE it."},{"question":"How do I find how many are lurking?","answer":"Compare lengths before and after removing them. On SQL Server, use (DATALENGTH(col) - DATALENGTH(REPLACE(col, NCHAR(160), N''))) / 2 for nvarchar. LEN ignores trailing spaces, so LEN(col) - LEN(REPLACE(col, NCHAR(160), '')) reports 2 for N'Ed ' + NCHAR(160), where the true count is 1."}],"related":["trim","remove-newlines","collapse-spaces","empty-string-check"],"novel_uses":[{"body":"A CHECK constraint rejects the character on INSERT, which keeps paste damage out of the table instead of cleaning it after reports go wrong.","sql":"ALTER TABLE notes ADD CONSTRAINT no_nbsp CHECK (note NOT LIKE '%' + NCHAR(160) + '%');"},{"body":"Wrap the replace in TRIM inside the GROUP BY. That merges categories that NBSPs had split into near-identical twins, so one category stops splitting into separate rows with partial totals. Without TRIM, PostgreSQL, MySQL and SQLite keep the replaced value with its trailing space as a separate group.","sql":"SELECT TRIM(REPLACE(category, NCHAR(160), ' ')) AS cat, SUM(amount) AS total\nFROM sales\nGROUP BY TRIM(REPLACE(category, NCHAR(160), ' '));"}]},"source_url":"https://sqlly.app/sql-functions/remove-nbsp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/remove-newlines","corpus":"sql-functions","engine":null,"language":"en","title":"SQL remove newlines","description":"Remove CR, LF and CRLF from text per engine: REPLACE with CHAR/CHR codes or engine escapes, plus the CRLF two-character trap.","body":{"slug":"remove-newlines","name":"Removing newlines","h1":"SQL remove newlines","category":"string","lede":"Flatten multi-line text into one line. The subtlety is that Windows line breaks are two characters, and each engine writes them differently.","syntax":"REPLACE(s, CHAR(13) + CHAR(10), ' ')  |  REPLACE(s, CHR(10), ' ')","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["CRLF is two characters: strip CHAR(13) and CHAR(10) separately or in that order, or Windows-pasted data leaves stray carriage returns.","Plain TRIM removes only spaces, so leading and trailing newlines survive it too; interior newlines survive every TRIM variant.","PostgreSQL writes the escape as E'\\n' (standard strings treat \\ literally); MySQL uses '\\n' unless NO_BACKSLASH_ESCAPES is set; CHR(10)/CHAR(10) is the portable spelling.","Watch for tabs too while you are at it (CHAR(9)/CHR(9)), since pasted data rarely contains only one kind of whitespace."],"examples":[{"engine_slug":"sql-server","sql":"SELECT REPLACE(REPLACE(REPLACE(note, CHAR(13) + CHAR(10), ' '), CHAR(13), ' '), CHAR(10), ' ') AS flat\nFROM notes;"},{"engine_slug":"postgresql","sql":"SELECT REPLACE(REPLACE(REPLACE(note, E'\\r\\n', ' '), E'\\r', ' '), E'\\n', ' ') AS flat FROM notes;"},{"engine_slug":"mysql","sql":"SELECT REPLACE(REPLACE(REPLACE(note, CONCAT(CHAR(13), CHAR(10)), ' '), CHAR(13), ' '), CHAR(10), ' ') AS flat FROM notes;"},{"engine_slug":"oracle","sql":"SELECT REPLACE(note, CHR(10), ' ') AS flat FROM notes;"},{"engine_slug":"sqlite","sql":"SELECT replace(replace(replace(note, char(13) || char(10), ' '), char(13), ' '), char(10), ' ') AS flat\nFROM notes;"}],"faqs":[{"question":"Why do newlines survive my REPLACE?","answer":"Usually the data has CRLF and you replaced only LF; the carriage returns remain. Remove CHAR(13) and CHAR(10) as separate passes."},{"question":"How do I write a newline in a string literal?","answer":"Engine-specific: CHAR(13)/CHAR(10) on SQL Server, CHR(10) on Oracle, E'\\n' on PostgreSQL, '\\n' on MySQL, char(10) on SQLite (which does not process backslash escapes). See the newline-literal page for the full set."},{"question":"Can I just normalize whitespace instead?","answer":"Yes: REGEXP_REPLACE(note, '[[:space:]]+', ' ') collapses newlines, tabs and space runs in one call on MySQL 8+, Oracle and SQL Server 2025. PostgreSQL needs the 'g' flag as a fourth argument or it replaces only the first run. '\\s+' works too, except on MySQL, where the string literal swallows the backslash unless you write '\\\\s+'."}],"related":["newline-literal","trim","remove-nbsp","collapse-spaces"],"novel_uses":[{"body":"Two REPLACE passes turn CRLF and lone CR into plain LF, which is the step that makes hashes, diffs and comparisons of the same text agree across sources.","sql":"UPDATE notes SET body = REPLACE(REPLACE(body, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10));"},{"body":"One LIKE against CHAR(10) and one against CHAR(13) count every row that contains a line break, including lone CR, so you can flatten them on purpose instead of debugging the file later.","sql":"SELECT COUNT(*) FROM notes WHERE body LIKE '%' + CHAR(10) + '%' OR body LIKE '%' + CHAR(13) + '%';"}]},"source_url":"https://sqlly.app/sql-functions/remove-newlines","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/repeat","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REPEAT function","description":"How REPEAT and REPLICATE duplicate a string in each engine: zero and negative counts, NULL results, SQL Server's 8,000-byte cut-off, and workarounds in SQLite and Oracle.","body":{"slug":"repeat","name":"REPEAT","h1":"SQL REPEAT function","category":"string","lede":"Concatenates a string with itself a given number of times.","syntax":"REPEAT(str, count)  |  SQL Server: REPLICATE(str, count)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"Spelled REPLICATE(str, count)."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No REPEAT; replace(hex(zeroblob(n)), '00', str) repeats str n times."},{"engine_slug":"oracle","status":"no","note":"No REPEAT; RPAD(str, LENGTH(str) * n, str)."}],"gotchas":["A count of 0 returns ''. Negative counts differ: PostgreSQL and MySQL return '', SQL Server's REPLICATE returns NULL.","REPLICATE truncates at 8,000 bytes unless the input is varchar(max) or nvarchar(max): LEN(REPLICATE('a', 10000)) is 8000, while REPLICATE(CAST('a' AS varchar(max)), 10000) has all 10,000.","MySQL returns NULL, with a warning, when the result would exceed max_allowed_packet."],"examples":[{"engine_slug":"postgresql","sql":"SELECT REPEAT('ab', 3) AS result;  -- ababab"},{"engine_slug":"sql-server","sql":"SELECT REPLICATE('-', 40) AS divider;"},{"engine_slug":"sqlite","sql":"SELECT replace(hex(zeroblob(3)), '00', 'ab') AS result;  -- ababab"},{"engine_slug":"mysql","sql":"SELECT REPEAT('ab', 3) AS result;  -- ababab"}],"faqs":[{"question":"Is REPEAT the same as REPLICATE?","answer":"Mostly. They differ on negative counts (REPEAT returns an empty string, REPLICATE returns NULL) and on length: REPLICATE stops at 8,000 bytes for non-max input, while PostgreSQL and MySQL (up to max_allowed_packet) do not. MySQL and PostgreSQL say REPEAT, SQL Server says REPLICATE. SQLite and Oracle have neither."},{"question":"How do I repeat a string in Oracle?","answer":"RPAD(str, LENGTH(str) * n, str) repeats the pattern n times; RPAD('=', n, '=') gives exactly n characters."},{"question":"Why did my REPLICATE result stop at 8,000 characters?","answer":"The input was a non-max varchar, so the result was capped at 8,000 bytes (4,000 nvarchar characters). Cast the input to varchar(max) or nvarchar(max)."}],"related":["space","rpad","lpad","concat"],"novel_uses":[{"body":"REPEAT('#', value) turns a number into a bar next to the label, which makes GROUP BY results readable in any client, no charting needed.","sql":"SELECT status, COUNT(*) AS n, REPEAT('#', COUNT(*) * 2) AS bar\nFROM orders\nGROUP BY status;"},{"body":"Repeating spaces by the depth column indents each node under its parent, the cheapest way to render a hierarchy from a recursive query.","sql":"WITH RECURSIVE tree AS (\n  SELECT id, name, 0 AS depth FROM folders WHERE parent_id IS NULL\n  UNION ALL\n  SELECT f.id, f.name, t.depth + 1 FROM folders f JOIN tree t ON f.parent_id = t.id\n)\nSELECT CONCAT(REPEAT('  ', depth), name) AS label FROM tree;"},{"body":"Pairing REPEAT with generate_series produces strings of every length from 1 to n, which exercises length limits and index behavior in one INSERT.","sql":"INSERT INTO samples (payload)\nSELECT REPEAT('x', g) FROM generate_series(1, 10) AS g;"}]},"source_url":"https://sqlly.app/sql-functions/repeat","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/replace","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REPLACE function","description":"Find and replace text with SQL REPLACE in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: literal matches, case sensitivity and why it is not a regex.","body":{"slug":"replace","name":"REPLACE","h1":"SQL REPLACE function","category":"string","lede":"Replaces every occurrence of a literal substring with another string, left to right and non-overlapping. It never treats its arguments as a pattern.","syntax":"REPLACE(string, find, replacement)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The match is literal, not a pattern: REPLACE(s, '%', '') strips percent signs, it does not use wildcards.","Case sensitivity: SQL Server follows the collation (usually case-insensitive). MySQL's REPLACE matches case-sensitively even under a case-insensitive collation, as do PostgreSQL, SQLite and Oracle.","Each call swaps one string. To delete several single characters at once, TRANSLATE works on PostgreSQL and Oracle: TRANSLATE(s, 'x()- ', 'x') drops the brackets, dashes and spaces. Otherwise nest REPLACE calls.","Oracle's third argument is optional: REPLACE(s, '-') deletes every dash."],"examples":[{"engine_slug":"all","sql":"SELECT REPLACE('2026/08/01', '/', '-') AS iso;  -- 2026-08-01"},{"engine_slug":"all","sql":"SELECT REPLACE(REPLACE(phone, '(', ''), ')', '') AS digits\nFROM contacts;"}],"faqs":[{"question":"Is SQL REPLACE case-sensitive?","answer":"On SQL Server it follows the column's collation, which is usually case-insensitive. PostgreSQL, MySQL, SQLite and Oracle match the literal case exactly."},{"question":"Can REPLACE use wildcards or regex?","answer":"No. The search argument is always a literal string. For patterns use REGEXP_REPLACE on PostgreSQL, MySQL 8.0+, Oracle and SQL Server 2025."}],"related":["regexp-replace","trim","instr"],"novel_uses":[{"body":"CAST chokes on 1,234.50, but REPLACE(price_text, ',', '') turns it into castable digits first. Chain a second REPLACE for the currency symbol; the match is literal on every engine, so the same expression ports everywhere.","sql":"SELECT CAST(REPLACE(REPLACE(price_text, ',', ''), '$', '') AS DECIMAL(10, 2)) AS price\nFROM imports;"},{"body":"Doubling each embedded double quote is the CSV escape readers expect: REPLACE the quotes, CONCAT one onto each end, and the cell round-trips through any CSV parser.","sql":"SELECT CONCAT('\"', REPLACE(note, '\"', '\"\"'), '\"') AS safe_cell\nFROM records;"},{"body":"Text pasted from Windows carries CR at the end of every line, which shows up as ^M in exports and breaks line-based parsing. Deleting the CR alone is enough, since LF alone reads fine everywhere: REPLACE(body, CHAR(13), ''), spelled CHR(13) on PostgreSQL and Oracle.","sql":"UPDATE notes\nSET body = REPLACE(body, CHAR(13), '');"}]},"source_url":"https://sqlly.app/sql-functions/replace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/replicate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REPLICATE function","description":"Repeat a string n times: REPLICATE on SQL Server, REPEAT on MySQL and PostgreSQL, RPAD tricks on Oracle, with NULL and length-cap caveats.","body":{"slug":"replicate","name":"REPLICATE / REPEAT","h1":"SQL REPLICATE function","category":"string","lede":"Builds runs of a character or pattern for padding, masking and test data. Three names for one job, and NULL semantics differ between them.","syntax":"REPLICATE(string, n)  |  REPEAT(string, n)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"result is capped by the string type's max length"},{"engine_slug":"postgresql","status":"yes","note":"spelled repeat()"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["SQL Server: REPLICATE('x', -1) returns NULL; PostgreSQL's repeat() and MySQL's REPEAT return '' for n <= 0. Edge inputs do not agree across engines.","The result is bounded by the argument's type: REPLICATE over a varchar literal stops at 8000 bytes silently (4000 characters for nvarchar). Cast to varchar(max) to keep going.","Oracle has no equivalent: RPAD/LPAD repeat a pattern up to a total length (RPAD('ab', 7, 'ab') is 'abababa'), so you compute a length instead of a count.","SQLite has neither function. replace(printf('%*s', n, ''), ' ', 'ab') repeats 'ab' n times: printf builds n spaces, replace swaps each one."],"examples":[{"engine_slug":"sql-server","sql":"SELECT REPLICATE('ab', 3) AS r;  -- ababab"},{"engine_slug":"postgresql","sql":"SELECT repeat('ab', 3) AS r;  -- ababab"},{"engine_slug":"mysql","sql":"SELECT REPEAT('ab', 3) AS r;  -- ababab"}],"faqs":[{"question":"Why did my REPLICATE result get cut off?","answer":"The input was a non-max varchar, so the output capped at 8000 bytes silently. REPLICATE(CAST('x' AS varchar(max)), 10000) keeps the full run."},{"question":"What is Oracle's alternative to REPLICATE?","answer":"RPAD and LPAD repeat a pattern until a total length is reached: RPAD('-', 10, '-') gives a 10-dash rule. There is no repeat-n-times function."},{"question":"Does REPLICATE('x', 0) return NULL or ''?","answer":"Empty string on SQL Server and MySQL. On SQL Server, NULL comes back for negative counts and when either argument is NULL. PostgreSQL's repeat() returns '' for negative counts. MySQL returns '' for 0 and negatives alike."}],"related":["space","zero-pad","mask-string"],"novel_uses":[{"body":"name + REPLICATE('.', 30 - LEN(name)) + value prints the dotted lines of a paper statement from a plain SELECT; MySQL spells the same call REPEAT.","sql":"SELECT name + REPLICATE('.', 30 - LEN(name)) + CAST(bal AS varchar(12)) AS line\nFROM accounts\nWHERE LEN(name) < 30;"},{"body":"STRING_SPLIT(REPLICATE(',', 9), ',') yields ten empty strings, which is the classic trick for turning a quantity into that many rows on SQL Server 2016+.","sql":"SELECT value FROM STRING_SPLIT(REPLICATE(',', 9), ',');  -- 10 rows"}]},"source_url":"https://sqlly.app/sql-functions/replicate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/reverse","corpus":"sql-functions","engine":null,"language":"en","title":"SQL REVERSE function","description":"Reverse a string with REVERSE in SQL Server, PostgreSQL and MySQL, why Oracle's REVERSE is undocumented and byte-based, and what SQLite users do instead.","body":{"slug":"reverse","name":"REVERSE","h1":"SQL REVERSE function","category":"string","lede":"Returns the string with its characters in reverse order. Its everyday use is finding the last occurrence of a character, such as the final slash in a path.","syntax":"REVERSE(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no REVERSE; a recursive CTE or an extension"},{"engine_slug":"oracle","status":"no","note":"REVERSE exists but is undocumented and reverses bytes, so it breaks multi-byte characters"}],"gotchas":["SQLite has no REVERSE. Oracle's works on single-byte text but is undocumented and reverses bytes, which corrupts multi-byte UTF-8 characters.","Emoji: PostgreSQL and MySQL reverse whole characters. SQL Server reverses UTF-16 code units, so an emoji breaks unless the column uses a supplementary-character (_SC) collation.","Combining accents (an e followed by a combining acute mark) come out attached to the wrong letter on every engine, because the mark is a separate character."],"examples":[{"engine_slug":"sql-server","sql":"-- same on PostgreSQL and MySQL\nSELECT REVERSE('stressed') AS dessert;  -- desserts"},{"engine_slug":"mysql","sql":"SELECT REVERSE('stressed') AS dessert;  -- desserts"},{"engine_slug":"postgresql","sql":"SELECT RIGHT(path, POSITION('/' IN REVERSE(path)) - 1) AS file_name\nFROM files;"}],"faqs":[{"question":"Does Oracle have a REVERSE function?","answer":"Not officially. REVERSE('abc') returns 'cba' on Oracle, but the function is undocumented, unsupported, and reverses bytes rather than characters, so multi-byte UTF-8 text comes out corrupted. For real text, write a PL/SQL function."},{"question":"Is REVERSE safe for emoji and accents?","answer":"Not fully. Combining marks end up on the wrong letter on every engine, and SQL Server splits emoji unless the collation is supplementary-character aware (_SC). Use it on codes and identifiers, not prose."}],"related":["left","right","instr"],"novel_uses":[{"body":"The dot's position in the reversed string is the extension's distance from the end, so RIGHT(path, POSITION('.' IN REVERSE(path)) - 1) pulls report.tar.gz apart to gz without loops. Guard the no-dot case first, because a zero position feeds RIGHT a negative length on SQL Server.","sql":"SELECT CASE WHEN POSITION('.' IN REVERSE(path)) > 0\n            THEN RIGHT(path, POSITION('.' IN REVERSE(path)) - 1) END AS ext\nFROM files;"},{"body":"Reversing a domain makes it sort from the significant end, so mail.example.com and lists.example.com land next to each other. Group or order by REVERSE(domain) to see subdomains as one family; REVERSE exists on PostgreSQL, MySQL and SQL Server, not SQLite, and Oracle's is byte-based.","sql":"SELECT REVERSE(email_domain) AS rev, COUNT(*) AS n\nFROM signups\nGROUP BY REVERSE(email_domain)\nORDER BY 1;"}]},"source_url":"https://sqlly.app/sql-functions/reverse","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/right","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RIGHT function","description":"Take the last n characters with SQL RIGHT in SQL Server, PostgreSQL and MySQL, and the SUBSTR forms you need on SQLite and Oracle.","body":{"slug":"right","name":"RIGHT","h1":"SQL RIGHT function","category":"string","lede":"Returns the rightmost n characters of a string: the tail of a filename, the last four digits of a card, the suffix of a code.","syntax":"RIGHT(string, n)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no RIGHT(); use SUBSTR(string, -n)"},{"engine_slug":"oracle","status":"partial","note":"no RIGHT(); use SUBSTR(string, -n)"}],"gotchas":["n larger than the string returns the whole string on the engines that have RIGHT.","The SQLite and Oracle stand-in uses a negative start: SUBSTR(string, -n). They differ when n is longer than the string: SQLite returns the whole string, Oracle returns NULL.","RIGHT assumes a fixed-width suffix. RIGHT(file, 3) is wrong for 'data.json'; for variable-width pieces use SPLIT_PART or a regex."],"examples":[{"engine_slug":"sql-server","sql":"-- same on PostgreSQL and MySQL\nSELECT RIGHT('report_2026.csv', 3) AS ext;  -- csv"},{"engine_slug":"postgresql","sql":"SELECT RIGHT('report_2026.csv', 3) AS ext;  -- csv"},{"engine_slug":"mysql","sql":"SELECT RIGHT('report_2026.csv', 3) AS ext;  -- csv"},{"engine_slug":"sqlite","sql":"SELECT SUBSTR('report_2026.csv', -3) AS ext;  -- csv"},{"engine_slug":"oracle","sql":"SELECT SUBSTR('report_2026.csv', -3) AS ext FROM dual;  -- csv"}],"faqs":[{"question":"Does SQLite have a RIGHT function?","answer":"No. SUBSTR(string, -n) returns the last n characters and is the idiomatic SQLite replacement, since a negative start counts from the end."},{"question":"How do I get the last 4 characters of a string?","answer":"RIGHT(s, 4) on SQL Server, PostgreSQL and MySQL; SUBSTR(s, -4) on SQLite and Oracle. On Oracle, SUBSTR(s, -4) is NULL when s is shorter than 4 characters."}],"related":["left","substring","instr"],"novel_uses":[{"body":"Confirmation screens and logs should show the last four characters only: CONCAT('**** ', RIGHT(card_no, 4)) leaks nothing else. Oracle has no RIGHT; SUBSTR(card_no, -4) is its form.","sql":"SELECT CONCAT('**** ', RIGHT(card_no, 4)) AS masked\nFROM cards;"},{"body":"Payment and meter references often end in a check digit. RIGHT(ref, 1) extracts it so the import can recompute the rest of the number and reject typos at the door instead of at reconciliation time. The modulus 7 in the snippet stands in for whatever scheme your references use.","sql":"SELECT ref\nFROM payments\nWHERE CAST(RIGHT(ref, 1) AS integer) <>\n      MOD(CAST(LEFT(ref, LENGTH(ref) - 1) AS bigint), 7);"}]},"source_url":"https://sqlly.app/sql-functions/right","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rollup","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROLLUP clause","description":"ROLLUP adds per-level subtotals plus a grand total: GROUP BY ROLLUP(...) in PostgreSQL, Oracle, SQL Server and MySQL 8.4, plus MySQL's older GROUP BY ... WITH ROLLUP.","body":{"slug":"rollup","name":"ROLLUP","h1":"SQL ROLLUP clause","category":"aggregate","lede":"Adds a subtotal row for each grouping prefix plus a grand-total row.","syntax":"GROUP BY ROLLUP(a, b) | GROUP BY a, b WITH ROLLUP","return_type":"detail rows plus subtotals","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"GROUP BY a, b WITH ROLLUP; 8.4 also accepts GROUP BY ROLLUP(a, b), but not CUBE or GROUPING SETS"},{"engine_slug":"sqlite","status":"no","note":"no ROLLUP; emulate with UNION ALL of grouped queries"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ROLLUP(a, b) produces (a, b), (a) and () levels: a hierarchy, not every combination; that is CUBE.","Subtotal rows show NULL for the rolled-up columns, colliding with real NULLs unless you add GROUPING().","MySQL's WITH ROLLUP is the same idea in a different position. Before 8.0.12 it could not be combined with ORDER BY; current versions allow it, and ORDER BY a puts the NULL subtotal rows first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT region, city, SUM(amount) FROM sales GROUP BY ROLLUP(region, city);"},{"engine_slug":"mysql","sql":"SELECT region, city, SUM(amount) FROM sales GROUP BY region, city WITH ROLLUP;"},{"engine_slug":"sql-server","sql":"SELECT region, city, SUM(amount) FROM sales GROUP BY ROLLUP(region, city);"},{"engine_slug":"oracle","sql":"SELECT region, SUM(amount) FROM sales GROUP BY ROLLUP(region);"}],"faqs":[{"question":"Which row is the grand total?","answer":"The one with NULL in every rolled-up column; confirm with GROUPING(region) = 1."},{"question":"What is MySQL's syntax?","answer":"GROUP BY a, b WITH ROLLUP, the form every version accepts. MySQL 8.4 also takes the standard GROUP BY ROLLUP(a, b), but not a partial ROLLUP mixed with plain columns, CUBE or GROUPING SETS."},{"question":"ROLLUP vs CUBE?","answer":"ROLLUP rolls up along the listed order only; CUBE computes every subset of the columns."}],"related":["grouping-sets","grouping","grouping-id","sum"],"novel_uses":[{"body":"ROLLUP over extracted year and month adds month rows, year rows and one grand total to a time report in a single scan.","sql":"SELECT EXTRACT(YEAR FROM sold_at) AS yr, EXTRACT(MONTH FROM sold_at) AS mon, SUM(amount) FROM sales GROUP BY ROLLUP(EXTRACT(YEAR FROM sold_at), EXTRACT(MONTH FROM sold_at));"},{"body":"When the per-region subtotal is noise, GROUPING SETS ((region, city), ()) computes exactly the two levels ROLLUP would pad out.","sql":"SELECT region, city, SUM(amount) FROM sales GROUP BY GROUPING SETS ((region, city), ());"}]},"source_url":"https://sqlly.app/sql-functions/rollup","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROUND function","description":"Rounding in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: negative digit positions, decimal versus float rounding modes, and banker's rounding surprises.","body":{"slug":"round","name":"ROUND","h1":"SQL ROUND function","category":"math","lede":"Rounds a number to a given number of decimal places, and to whole tens, hundreds and beyond with a negative digit count. The trap is that the rounding mode depends on the data type.","syntax":"ROUND(number, decimals)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL rounds NUMERIC half away from zero but DOUBLE PRECISION half to even (banker's rounding): ROUND(2.5::numeric) is 3, ROUND(2.5::float8) is 2.","Negative decimals round to powers of ten: ROUND(1234, -2) is 1200 on SQL Server, PostgreSQL, MySQL and Oracle. SQLite treats a negative digit count as 0 and returns 1234.0.","MySQL rounds DOUBLE values half to even too: ROUND(2.5e0) is 2, while ROUND(2.5) on the exact DECIMAL literal is 3. Oracle does the same split: ROUND(2.5d) on a BINARY_DOUBLE is 2, ROUND(2.5) on a NUMBER is 3. SQL Server's ROUND on float rounds 2.5 to 3.","SQL Server's ROUND has a hidden third argument: ROUND(x, 2, 1) truncates instead of rounds."],"examples":[{"engine_slug":"all","sql":"SELECT ROUND(123.4567, 2) AS two_dp;  -- 123.46"},{"engine_slug":"postgresql","sql":"-- also SQL Server, MySQL and Oracle; not SQLite\nSELECT ROUND(1234, -2) AS hundreds;  -- 1200"},{"engine_slug":"postgresql","sql":"SELECT ROUND(2.5::numeric) AS half_up, ROUND(2.5::float8) AS bankers;\n-- 3, 2"}],"faqs":[{"question":"Does SQL round 2.5 up to 3?","answer":"For NUMERIC/DECIMAL, all five round half away from zero, so yes. Floating-point values are different: PostgreSQL, MySQL and Oracle (BINARY_DOUBLE) round a float 2.5 half to even, giving 2. Keep money in DECIMAL columns so ROUND behaves predictably."},{"question":"How do I round to the nearest ten or hundred?","answer":"A negative second argument: ROUND(1234, -2) is 1200 on SQL Server, PostgreSQL, MySQL and Oracle. SQLite ignores negative digits, so divide, round and multiply: ROUND(1234 / 100.0) * 100."}],"related":["numeric-trunc","floor","ceil"],"novel_uses":[{"body":"Sum both sides of the ledger, take the difference, and round it to two decimals before testing for zero: binary float noise disappears and a non-zero result means an entry is genuinely missing. Comparing floats with = instead will flake on invisible digits.","sql":"SELECT ROUND(SUM(debit) - SUM(credit), 2) AS imbalance\nFROM ledger;"},{"body":"GROUP BY ROUND(unit_price, 1) counts sales per dime and shows which price points move volume; negative digit counts widen the buckets where the engine supports them.","sql":"SELECT ROUND(unit_price, 1) AS price_point, COUNT(*) AS sales\nFROM orders\nGROUP BY 1\nORDER BY 1;"}]},"source_url":"https://sqlly.app/sql-functions/round","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROUND date function","description":"ROUND on dates in Oracle: snap to the nearest day, week or month with the noon rule and month-boundary half-way behaviour.","body":{"slug":"round-date","name":"ROUND (date)","h1":"SQL ROUND date function","category":"datetime","lede":"Rounds a date to the nearest boundary of the mask's unit (the only major engine with a date-rounding function).","syntax":"ROUND(date)  |  ROUND(date, fmt)","return_type":"date","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["With no mask, the noon rule applies: times before 12:00 round to that day's midnight, 12:00 and after to the next day's.","ROUND(d, 'MM') rounds up from the 16th day whatever the month's length: 2026-02-15 gives 2026-02-01 and 2026-02-16 gives 2026-03-01. 'YYYY' rounds up from July 1, 'Q' from the 16th day of the quarter's second month.","PostgreSQL, MySQL and SQL Server do not have this: date_trunc and DATETRUNC floor only, and MySQL's ROUND coerces a datetime to a number."],"examples":[{"engine_slug":"oracle","sql":"SELECT ROUND(TO_DATE('2026-08-15 13:00', 'YYYY-MM-DD HH24:MI')) FROM dual;  -- 2026-08-16"},{"engine_slug":"oracle","sql":"SELECT ROUND(TO_DATE('2026-08-15 11:00', 'YYYY-MM-DD HH24:MI')) FROM dual;  -- 2026-08-15"},{"engine_slug":"oracle","sql":"SELECT ROUND(SYSDATE, 'Q') FROM dual;  -- nearest quarter start"}],"faqs":[{"question":"When is ROUND(date) actually useful?","answer":"When a value should count toward the nearest day or month rather than the one it started in, such as a shift starting at 23:40 billed to the next day. For reporting periods, TRUNC is almost always what you meant."},{"question":"How do I replicate ROUND elsewhere?","answer":"TRUNC(d + 0.5) in Oracle does the day case; on PostgreSQL date_trunc('day', d + interval '12 hours')."}],"related":["trunc-date","datetrunc","date-trunc"],"novel_uses":[{"body":"The 'HH' mask rounds to the closest hour with the cutoff at thirty minutes, so support calls land in the hour they gravitate toward.","sql":"SELECT ROUND(TO_DATE('2026-08-01 14:40', 'YYYY-MM-DD HH24:MI'), 'HH') FROM dual;  -- 15:00"},{"body":"Rounding timestamps to the nearest day and grouping on the result folds near-midnight strays into one bucket, which midnight truncation would split.","sql":"SELECT ROUND(ts), COUNT(*) FROM arrivals GROUP BY ROUND(ts);"}]},"source_url":"https://sqlly.app/sql-functions/round-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round-half-even","corpus":"sql-functions","engine":null,"language":"en","title":"SQL banker's rounding","description":"Ties-to-even rounding: 2.5 to 2, 3.5 to 4. Not what ROUND does on exact decimals: where it actually appears, and how to ask for it deliberately.","body":{"slug":"round-half-even","name":"ROUND half-even","h1":"SQL banker's rounding","category":"math","lede":"Banker's rounding sends ties to the even neighbour: 2.5 to 2, 3.5 to 4. Three engines apply it to float input; none applies it to exact decimals.","syntax":"ROUND(2.5, 0)  -- half-up, 3  |  round-to-even, 2","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"ROUND is half away from zero for decimal and float alike; emulate with CASE"},{"engine_slug":"postgresql","status":"partial","note":"round(double precision) rounds ties to even; round(numeric) does not"},{"engine_slug":"mysql","status":"partial","note":"ROUND on DOUBLE rounds ties to even (ROUND(2.5e0) is 2); DECIMAL rounds half away from zero"},{"engine_slug":"sqlite","status":"no","note":"round() is half away from zero; no built-in banker's rounding"},{"engine_slug":"oracle","status":"partial","note":"ROUND on BINARY_DOUBLE/BINARY_FLOAT rounds ties to even; NUMBER does not"}],"gotchas":["Only exact ties are affected, and a float tie is rarer than it looks: 2.5 stores exactly, but 0.285 * 100 computed in doubles is 28.499999999999996, so ROUND sees no tie at all and returns 28.","Casting changes the rule silently: ROUND(x) on a DOUBLE column gives 2 for 2.5, ROUND(CAST(x AS DECIMAL(10,2))) gives 3. Mixed-type reports can disagree by one unit at every tie.","To emulate on exact decimals, test for the tie and pick the even neighbour: CASE WHEN x - FLOOR(x) = 0.5 AND MOD(FLOOR(x), 2) = 0 THEN FLOOR(x) ELSE ROUND(x) END covers non-negative x at 0 decimals."],"examples":[{"engine_slug":"postgresql","sql":"SELECT ROUND(2.5::float8) AS f, ROUND(2.5::numeric) AS n;  -- 2, 3"},{"engine_slug":"mysql","sql":"SELECT ROUND(2.5e0) AS dbl, ROUND(2.5) AS dec_value;  -- 2, 3"},{"engine_slug":"oracle","sql":"SELECT ROUND(2.5d) AS binary_dbl, ROUND(2.5) AS num FROM dual;  -- 2, 3"},{"engine_slug":"mysql","sql":"SELECT CASE\n  WHEN x - FLOOR(x) = 0.5 AND MOD(FLOOR(x), 2) = 0 THEN FLOOR(x)\n  ELSE ROUND(x)\nEND AS banker FROM t;  -- 2.5 gives 2, 3.5 gives 4 (x >= 0)"}],"faqs":[{"question":"Does any SQL ROUND use banker's rounding by default?","answer":"Yes, on approximate floats: PostgreSQL round(double precision), MySQL ROUND on DOUBLE and Oracle ROUND on BINARY_DOUBLE send ties to even. SQL Server and SQLite never do. Exact decimal types (NUMERIC, DECIMAL) round ties away from zero on PostgreSQL, MySQL and SQL Server, and SQLite's NUMERIC, stored as REAL, does too."},{"question":"Why do floats round 2.5 down to 2?","answer":"2.5 is stored exactly, so this is not a storage error: those engines implement float ROUND with the C library's rint-style ties-to-even rule. PostgreSQL shows both side by side: round(2.5::float8) is 2, round(2.5::numeric) is 3."},{"question":"How do I force banker's rounding on exact decimals?","answer":"No engine ships it for NUMERIC/DECIMAL. Emulate it with a CASE: when the value sits exactly on the half (x - FLOOR(x) = 0.5) and FLOOR(x) is even, return FLOOR(x); when it sits on the half and FLOOR(x) is odd, return CEIL(x); otherwise ROUND(x). Scale by 10^d before the CASE and divide by 10^d after to round at d decimals."}],"related":["round","round-half-up","double-precision"],"novel_uses":[{"body":"Half-up on millions of ties pushes totals up by about half a unit per tie. PostgreSQL round(double), MySQL DOUBLE and Oracle BINARY_DOUBLE round ties to even, which cancels that drift across large sets.","sql":"SELECT ROUND(2.5e0) AS even_down, ROUND(3.5e0) AS even_up;  -- 2, 4 on MySQL DOUBLE (PostgreSQL needs ROUND(2.5e0::float8))"},{"body":".NET's Math.Round defaults to ties-to-even, so a C# service and PostgreSQL round(double precision) already agree. Rounding numerics in SQL instead introduces a second rule that disagrees on every tie.","sql":"SELECT ROUND(2.5::float8) AS matches_dotnet, ROUND(2.5::numeric) AS does_not;  -- 2, 3"}]},"source_url":"https://sqlly.app/sql-functions/round-half-even","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round-half-up","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROUND half-up rounding","description":"The default ROUND behaviour on exact decimals: half away from zero on SQL Server, MySQL, Oracle, SQLite and PostgreSQL numeric, and where it changes.","body":{"slug":"round-half-up","name":"ROUND half-up","h1":"SQL ROUND half-up rounding","category":"math","lede":"Documents that every engine's ROUND rounds ties away from zero for exact decimal types (2.5 to 3, -2.5 to -3) and which inputs break that.","syntax":"ROUND(2.5, 0)  |  ROUND(-2.5, 0)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"True for numeric input: round(2.5::numeric) is 3. For double precision, round() follows IEEE ties-to-even instead"},{"engine_slug":"mysql","status":"yes","note":"Half away from zero for exact-value (DECIMAL) arguments; DOUBLE input rounds ties to even, so ROUND(2.5e0) is 2"},{"engine_slug":"sqlite","status":"yes","note":"round(2.5) is 3.0 and round(-2.5) is -3.0"},{"engine_slug":"oracle","status":"yes","note":"NUMBER ROUND is half away from zero; BINARY_DOUBLE follows IEEE"}],"gotchas":["Half-up on stored floats is a coin flip: the literal 2.5 stores exactly, but 2.675 does not, so ROUND(2.675, 2) can give 2.67.","Negative values go away from zero, not up: ROUND(-2.5) is -3, not -2.","The type decides the tie rule on three engines: PostgreSQL double precision, MySQL DOUBLE and Oracle BINARY_DOUBLE round ties to even, so ROUND(2.5e0) is 2 on MySQL. SQL Server rounds float ties away from zero too."],"examples":[{"engine_slug":"all","sql":"SELECT ROUND(2.5, 0) AS up, ROUND(3.5, 0) AS also_up;  -- 3, 4"},{"engine_slug":"all","sql":"SELECT ROUND(-2.5, 0) AS neg;  -- -3 (away from zero)"},{"engine_slug":"postgresql","sql":"SELECT ROUND(2.5::numeric) AS numeric_round, ROUND(2.5::float8) AS float_round;  -- 3, 2"},{"engine_slug":"oracle","sql":"SELECT ROUND(2.5, 0) AS up, ROUND(-2.5, 0) AS neg FROM dual;  -- 3, -3"}],"faqs":[{"question":"Does SQL round 2.5 up to 3?","answer":"Yes on every engine when the value is an exact decimal: ROUND(2.5, 0) is 3 and ROUND(3.5, 0) is 4 (half away from zero). SQL Server requires the second argument; the other four accept ROUND(2.5). The exception is float input on PostgreSQL, MySQL and Oracle, where ties go to the even neighbour and 2.5 becomes 2."},{"question":"Is half-up the same as half-away-from-zero?","answer":"For positive exact decimals yes. For negatives they differ: half-up (toward positive infinity) would send -2.5 to -2, while ROUND on exact decimals sends it to -3 on SQL Server, MySQL, PostgreSQL and SQLite. Float input is the exception: ROUND(-2.5e0) is -2 on MySQL and round(-2.5::float8) is -2 on PostgreSQL."},{"question":"Why did my tie round the wrong way?","answer":"Usually the value is not an exact tie. 2.675 stored as a double sits just below the tie, so ROUND(2.675, 2) gives 2.67 on SQL Server and SQLite. MySQL's DOUBLE rounding returns 2.68 for the same value, and PostgreSQL has no two-argument ROUND for double precision. Keep tie-sensitive data in DECIMAL/NUMERIC."}],"related":["round","round-half-even","numeric-vs-float"],"novel_uses":[{"body":"ROUND per line then SUM can disagree with SUM then ROUND by a cent or two, and contracts usually specify which one rules. Compute the report the same way the invoice does.","sql":"SELECT SUM(ROUND(line_total, 2)) AS lines_rounded, ROUND(SUM(line_total), 2) AS total_rounded FROM order_lines GROUP BY order_id;"},{"body":"Tie behavior only flips between engines for floating types. Casting operands to DECIMAL or NUMERIC before ROUND keeps a report ported between SQL Server, PostgreSQL and MySQL rounding the same way at every tie. SQLite has no DECIMAL type: its CAST returns REAL, so the same tie gives 2.67 there.","sql":"SELECT ROUND(CAST(2.675 AS DECIMAL(10, 3)), 2) AS stable;  -- 2.68 on SQL Server, PostgreSQL and MySQL; 2.67 on SQLite"}]},"source_url":"https://sqlly.app/sql-functions/round-half-up","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round-negative-precision","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROUND to nearest ten or hundred","description":"Negative precision arguments round to whole tens, hundreds or thousands (ROUND(1234, -2) is 1200), and SQLite is the odd engine out.","body":{"slug":"round-negative-precision","name":"ROUND(x, -n)","h1":"SQL ROUND to nearest ten or hundred","category":"math","lede":"Rounds to a position left of the decimal point using a negative second argument, the terse way to bucket numbers into tens, hundreds or thousands.","syntax":"ROUND(number, -1)  |  ROUND(number, -2)  |  ROUND(number, -3)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":"Works on numeric input; cast double precision to numeric first"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"round(X, Y) ignores negative Y; it rounds to 0 digits instead"},{"engine_slug":"oracle","status":"yes","note":"ROUND(n, -m) is standard Oracle practice"}],"gotchas":["ROUND(1234, -2) is 1200 and ROUND(1250, -2) is 1300 on SQL Server, PostgreSQL and MySQL: the same half-up rule as positive digits, applied left of the point.","SQLite returns the value rounded to 0 digits for any negative Y, so round-to-hundreds needs ROUND(x / 100.0) * 100.","It only rounds to powers of ten. For buckets like 5 or 25, divide, round, and multiply back: ROUND(x / 5.0, 0) * 5. Keep the .0, or integer x on SQL Server, PostgreSQL and SQLite is truncated by the division before ROUND runs."],"examples":[{"engine_slug":"sql-server","sql":"SELECT ROUND(1234.56, -2) AS bucket;  -- 1200.00; same on PostgreSQL, MySQL, Oracle; SQLite gives 1235.0"},{"engine_slug":"mysql","sql":"SELECT ROUND(sales, -3) AS sales_k\nFROM monthly_totals;"},{"engine_slug":"sqlite","sql":"SELECT ROUND(amount / 100.0) * 100.0 AS to_hundred\nFROM invoices;"},{"engine_slug":"postgresql","sql":"SELECT ROUND(1234.56::numeric, -2) AS bucket;  -- 1200"},{"engine_slug":"oracle","sql":"SELECT ROUND(1234.56, -2) AS bucket FROM dual;  -- 1200"}],"faqs":[{"question":"How do I round to the nearest ten or hundred?","answer":"Pass a negative digit count: ROUND(1234, -1) is 1230, ROUND(1234, -2) is 1200. SQLite lacks negative precision, so divide by 100, round, and multiply back."},{"question":"Does negative precision work on floats?","answer":"Yes, but the float storage caveat still applies, and on PostgreSQL the two-argument form needs numeric input, so cast first: ROUND(x::numeric, -2)."},{"question":"How do I round to the nearest 5?","answer":"No engine rounds to 5 directly. Divide by 5.0, round to an integer, multiply by 5: ROUND(x / 5.0, 0) * 5. Dividing by a plain 5 truncates integer columns first on SQL Server, PostgreSQL and SQLite, so 13 would land on 10 instead of 15."}],"related":["round","round-precision","numeric-trunc"],"novel_uses":[{"body":"ROUND(headcount, -2) keeps exact values out of a report that leaves the team. Do it in the reporting view so the base tables stay exact.","sql":"SELECT region, ROUND(headcount, -2) AS rounded_headcount FROM staffing;"},{"body":"Rounding to thousands before dividing by 1000.0 gives clean axis ticks and hides float dust: ROUND(revenue, -3) / 1000.0 labels as 12, 13 and 14 instead of 12.478, 12.913 and 13.612. On SQLite the negative argument is ignored and the labels stay at 12.478, 12.913 and 13.612.","sql":"SELECT ROUND(revenue, -3) / 1000.0 AS revenue_k FROM monthly_totals;"}]},"source_url":"https://sqlly.app/sql-functions/round-negative-precision","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/round-precision","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROUND precision argument","description":"ROUND with an explicit number of decimal places: which engines accept it, why PostgreSQL rejects it for double precision, and the SQLite one-argument form.","body":{"slug":"round-precision","name":"ROUND(x, d)","h1":"SQL ROUND precision argument","category":"math","lede":"Rounds a number to d decimal places (ROUND(123.4567, 2) is 123.46) with engine quirks on float input and negative digit counts.","syntax":"ROUND(number, decimals)","return_type":"same type as the input","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"The two-argument form only accepts numeric; round(double precision, int) does not exist; cast to numeric first"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"round(X) and round(X, Y) are core functions on every version, no math extension needed"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL: round(0.285, 2) works on numeric, but round(0.285::float8, 2) is a type error. Cast: round(x::numeric, 2).","d can be negative on SQL Server, PostgreSQL, MySQL and Oracle: ROUND(1234.56, -2) is 1200. SQLite treats a negative Y as 0.","On float input the stored value rules: ROUND(2.675, 2) can be 2.67 on SQL Server FLOAT and SQLite REAL, because the float nearest 2.675 is a hair below it. MySQL DOUBLE gives 2.68 for the same value."],"examples":[{"engine_slug":"all","sql":"SELECT ROUND(123.4567, 2) AS r;  -- 123.46"},{"engine_slug":"postgresql","sql":"SELECT ROUND(AVG(price)::numeric, 2) AS avg_price\nFROM products;"},{"engine_slug":"sqlite","sql":"SELECT ROUND(2.675, 2) AS r;  -- 2.67 (REAL input)"},{"engine_slug":"oracle","sql":"SELECT ROUND(123.4567, 2) AS r FROM dual;  -- 123.46"}],"faqs":[{"question":"Why does PostgreSQL reject ROUND(x, 2) for my column?","answer":"The column is double precision, and PostgreSQL only defines round(numeric, int). Cast once: ROUND(x::numeric, 2). The one-argument round(double) exists but has no digit count."},{"question":"Does the decimals argument accept negative values?","answer":"Yes on SQL Server, PostgreSQL (numeric only), MySQL and Oracle: ROUND(1234.56, -2) rounds to the nearest hundred and gives 1200. SQLite does not: a negative Y behaves like 0."},{"question":"Why is ROUND(2.675, 2) not 2.68?","answer":"2.675 is not exactly representable as a binary float. On FLOAT (SQL Server) or REAL (SQLite) input the stored value sits just below it, so ROUND gives 2.67. A decimal literal such as 2.675 is exact on SQL Server, PostgreSQL and MySQL and gives 2.68. Use a decimal type when the digit boundary matters."}],"related":["round","ceiling","floor","numeric-trunc"],"novel_uses":[{"body":"Rounding every intermediate step compounds error: SUM(ROUND(line_total, 2)) and ROUND(SUM(line_total), 2) can differ by cents on the same rows. Compute with full precision and round once for display or invoicing.","sql":"SELECT ROUND(SUM(line_total), 2) AS invoice_total FROM order_lines GROUP BY order_id;"},{"body":"On SQL Server, ROUND leaves a float a float, so the client still gets a binary double instead of a decimal. CAST(ROUND(x, 2) AS DECIMAL(10, 2)) rounds and shortens the wire type in one step.","sql":"SELECT CAST(ROUND(unit_price * 1.13, 2) AS DECIMAL(10, 2)) AS gross FROM products;"},{"body":"Two-argument ROUND rounds, so ROUND(2.679, 2) gives 2.68. FLOOR(x * 100) / 100 chops the fraction for positive values and works on every engine here. SQL Server also takes a third argument: ROUND(2.679, 2, 1) truncates to 2.670. For negative values FLOOR rounds down, so use ROUND(x, 2, 1) on SQL Server instead.","sql":"SELECT FLOOR(2.679 * 100) / 100 AS truncated;  -- 2.67"}]},"source_url":"https://sqlly.app/sql-functions/round-precision","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/row-count","corpus":"sql-functions","engine":null,"language":"en","title":"SQL @@ROWCOUNT and ROW_COUNT()","description":"Read how many rows the last INSERT, UPDATE or DELETE touched: @@ROWCOUNT, ROW_COUNT(), changes(), GET DIAGNOSTICS and SQL%ROWCOUNT, and what resets them.","body":{"slug":"row-count","name":"@@ROWCOUNT / ROW_COUNT","h1":"SQL @@ROWCOUNT and ROW_COUNT()","category":"system","lede":"Every engine keeps a per-session count of the rows the previous statement changed. The name differs, and so does which statements reset it.","syntax":"@@ROWCOUNT  |  ROW_COUNT()  |  changes()  |  GET DIAGNOSTICS n = ROW_COUNT  |  SQL%ROWCOUNT","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"@@ROWCOUNT; ROWCOUNT_BIG() past 2 billion rows"},{"engine_slug":"postgresql","status":"partial","note":"GET DIAGNOSTICS n = ROW_COUNT inside PL/pgSQL; clients read it from the command tag"},{"engine_slug":"mysql","status":"yes","note":"ROW_COUNT(); -1 after a SELECT"},{"engine_slug":"sqlite","status":"partial","note":"changes(); total_changes() for the whole connection"},{"engine_slug":"oracle","status":"partial","note":"SQL%ROWCOUNT inside PL/SQL"}],"gotchas":["SQL Server resets @@ROWCOUNT after statements such as PRINT, SET options, BEGIN TRANSACTION and COMMIT. Copy it into a variable on the line right after the DML: SELECT @n = @@ROWCOUNT.","MySQL counts rows actually changed: an UPDATE that writes the value a column already has reports 0. Clients that connect with the CLIENT_FOUND_ROWS flag get rows matched instead.","SQLite's changes() counts only rows the statement changed directly. Rows changed by triggers, foreign key actions or REPLACE conflict handling are left out."],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE stock (sku INT, qty INT);\nINSERT INTO stock VALUES (1, 5), (2, 0), (3, 0);\nUPDATE stock SET qty = 10 WHERE qty = 0;\nSELECT @@ROWCOUNT AS updated;  -- 2"},{"engine_slug":"mysql","sql":"CREATE TABLE stock (sku INT, qty INT);\nINSERT INTO stock VALUES (1, 5), (2, 0), (3, 0);\nUPDATE stock SET qty = 10 WHERE qty = 0;\nSELECT ROW_COUNT() AS updated;  -- 2"},{"engine_slug":"sqlite","sql":"CREATE TABLE stock (sku INT, qty INT);\nINSERT INTO stock VALUES (1, 5), (2, 0), (3, 0);\nUPDATE stock SET qty = 10 WHERE qty = 0;\nSELECT changes() AS updated;  -- 2"},{"engine_slug":"postgresql","sql":"CREATE TABLE stock (sku INT, qty INT);\nINSERT INTO stock VALUES (1, 5), (2, 0), (3, 0);\nDO $$\nDECLARE n bigint;\nBEGIN\n  UPDATE stock SET qty = 10 WHERE qty = 0;\n  GET DIAGNOSTICS n = ROW_COUNT;\n  RAISE NOTICE 'updated %', n;  -- updated 2\nEND $$;"},{"engine_slug":"oracle","sql":"CREATE TABLE stock (sku INT, qty INT);\nINSERT INTO stock SELECT 1, 0 FROM dual UNION ALL SELECT 2, 0 FROM dual;\nBEGIN\n  UPDATE stock SET qty = 10 WHERE qty = 0;\n  DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);  -- 2\nEND;\n/"}],"faqs":[{"question":"Why is @@ROWCOUNT 0 when my UPDATE changed rows?","answer":"Another statement ran in between. PRINT, SET options and transaction statements reset it to 0. Capture it immediately after the INSERT, UPDATE or DELETE."},{"question":"Does MySQL's ROW_COUNT() count rows matched or rows changed?","answer":"Rows changed, unless the client connected with CLIENT_FOUND_ROWS. An UPDATE that writes the same value counts 0."}],"related":["last-insert-id","error-message","count"],"novel_uses":[{"body":"In PL/pgSQL every INSERT, UPDATE and DELETE sets the FOUND boolean, so IF FOUND THEN covers the common did-anything-change case without GET DIAGNOSTICS. Read it immediately after the statement, the same freshness rule ROW_COUNT follows.","sql":"DO $$\nBEGIN\n  UPDATE stock SET qty = 0 WHERE qty IS NULL;\n  IF NOT FOUND THEN\n    RAISE NOTICE 'nothing to fix';\n  END IF;\nEND $$;"},{"body":"The first line inside a SQL Server trigger sees @@ROWCOUNT from the statement that fired it, so IF @@ROWCOUNT = 0 RETURN skips zero-row calls before any work. SET NOCOUNT ON below that line is the documented follow-up: it stops the trigger's own statements from sending rows-affected messages to the client.","sql":"IF @@ROWCOUNT = 0 RETURN;\nSET NOCOUNT ON;  -- first lines of a trigger body"},{"body":"The pre-MERGE Oracle upsert runs UPDATE first, then INSERT only when SQL%ROWCOUNT = 0. Two sessions can both see 0 and both insert, so keep a unique constraint and let one side catch DUP_VAL_ON_INDEX, or use MERGE.","sql":"BEGIN\n  UPDATE stock SET qty = qty + 2 WHERE sku = 42;\n  IF SQL%ROWCOUNT = 0 THEN\n    INSERT INTO stock (sku, qty) VALUES (42, 2);\n  END IF;\nEND;\n/"}]},"source_url":"https://sqlly.app/sql-functions/row-count","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/row-number","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROW_NUMBER function","description":"ROW_NUMBER in SQL Server, PostgreSQL, MySQL 8+, SQLite 3.25+ and Oracle: the dedupe, top-N-per-group and pagination workhorse, with determinism traps.","body":{"slug":"row-number","name":"ROW_NUMBER","h1":"SQL ROW_NUMBER function","category":"window","lede":"Numbers rows 1, 2, 3... within a partition, ordered as specified. No gaps, no ties, which is exactly what deduplication and top-N-per-group need.","syntax":"ROW_NUMBER() OVER (PARTITION BY g ORDER BY x)","return_type":"bigint","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without a full tiebreaker in ORDER BY, equal rows can number differently run to run; nondeterministic dedupes are the classic production bug. Add a unique column as the final ORDER BY key.","Window functions cannot appear in WHERE: wrap the query in a CTE or subquery and filter on rn = 1 outside.","ROW_NUMBER vs RANK: ROW_NUMBER never ties; RANK gives tied rows the same number and skips the next ones."],"examples":[{"engine_slug":"all","sql":"SELECT customer_id, amount,\n       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn\nFROM orders;"},{"engine_slug":"all","sql":"-- top order per customer\nWITH ranked AS (\n  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders o\n)\nSELECT * FROM ranked WHERE rn = 1;"}],"faqs":[{"question":"How do I get the latest row per group?","answer":"ROW_NUMBER() OVER (PARTITION BY group ORDER BY updated_at DESC, id) in a CTE, then filter WHERE rn = 1. The id tiebreaker makes it deterministic."},{"question":"Why can't I use ROW_NUMBER in WHERE?","answer":"Window functions evaluate after WHERE. Put them in a subquery or CTE and filter on the computed number outside."}],"related":["rank","dense-rank","lag"],"novel_uses":[{"body":"When no business key exists, order duplicates by the physical row id (ctid on PostgreSQL, rowid on SQLite) and keep rn = 1. SQL Server has no supported physical id, so add an identity column when the table is built.","sql":"WITH d AS (\n  SELECT ctid,\n         ROW_NUMBER() OVER (PARTITION BY email ORDER BY ctid) AS rn\n  FROM subscribers\n)\nDELETE FROM subscribers s USING d\nWHERE s.ctid = d.ctid AND d.rn > 1;"},{"body":"Filtering on ROW_NUMBER ranges pages through any ordered set and needs no OFFSET clause, which some older engines never grew. It stays deterministic as long as the ORDER BY ends in a unique column; wrap in a CTE and filter outside.","sql":"WITH ranked AS (\n  SELECT id, name,\n         ROW_NUMBER() OVER (ORDER BY name, id) AS rn\n  FROM products\n)\nSELECT * FROM ranked\nWHERE rn BETWEEN 101 AND 150;"}]},"source_url":"https://sqlly.app/sql-functions/row-number","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/row-number-pagination","corpus":"sql-functions","engine":null,"language":"en","title":"SQL pagination with ROW_NUMBER","description":"Numbering rows and slicing pages from the numbers, how it compares with OFFSET/LIMIT, and why both get slower on deep pages while keyset paging does not.","body":{"slug":"row-number-pagination","name":"Window Pagination","h1":"SQL pagination with ROW_NUMBER","category":"window","lede":"Number the rows with ROW_NUMBER() OVER (ORDER BY ...) and keep a range of numbers per page; on PostgreSQL and SQL Server it reads about as much as OFFSET, but MySQL reads the whole table on every page, and a COUNT(*) OVER () total also reads the whole table on PostgreSQL and SQL Server.","syntax":"ROW_NUMBER() OVER (ORDER BY id) | WHERE rn BETWEEN 101 AND 120","return_type":"page of rows","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The row numbers exist per query execution; there is no stored ordering. A total ORDER BY (unique tiebreaker) keeps ties in place, but rows still shift between page requests when other rows are inserted or deleted.","Deep OFFSET pages make the engine read and discard all skipped rows. Without a total, the numbered range stops at the page end on PostgreSQL and SQL Server, but MySQL 8.4 materializes every row on every page, and a COUNT(*) OVER () total in the same query forces the full read on PostgreSQL and SQL Server. Keyset pagination (WHERE id > last_id) is the only form that reads just the page.","COUNT(*) OVER () in the same query gives the total rows for page counts without a second query, but it reads every matching row on each page, the same cost as a separate COUNT(*)."],"examples":[{"engine_slug":"all","sql":"WITH p AS (\n  SELECT pr.*, ROW_NUMBER() OVER (ORDER BY created_at DESC, id) AS rn,\n         COUNT(*) OVER () AS total\n  FROM products pr\n)\nSELECT * FROM p WHERE rn BETWEEN 101 AND 120;"}],"faqs":[{"question":"Is ROW_NUMBER pagination better than OFFSET?","answer":"Without a total, PostgreSQL and SQL Server stop at the page end, much like OFFSET, but MySQL reads the whole table on every page. The real win is keyset pagination (WHERE sort_key > last_value), which is an index seek that reads only the page. Compute the total once and cache it rather than asking for COUNT(*) OVER () on every page."},{"question":"Why do rows repeat or vanish between pages?","answer":"Writes between page requests are the usual cause: a row inserted ahead of the page pushes every later row down one number, so the last row of page 1 shows up again at the top of page 2, and a row deleted from page 1 pulls the next row up and skips it. Keyset pagination (WHERE sort_key > last_value) avoids both. If the ORDER BY has ties, also add a unique tiebreaker column, because tied rows can come back in a different order between queries."}],"related":["row-number","rank","running-total"],"novel_uses":[{"body":"Number rows inside each partition and keep a range of numbers, and page two means rows six through ten of every category in a single query. Mobile feeds use this shape to ship a slice of every section per request.","sql":"WITH r AS (\n  SELECT category, product_id, price,\n         ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn\n  FROM products\n)\nSELECT * FROM r\nWHERE rn BETWEEN 6 AND 10\nORDER BY category, rn;"},{"body":"Find the row's number, then integer-divide by the page size: (rn + 19) / 20 puts rows 1 to 20 on page 1 with no CEILING function. On MySQL write DIV instead of the slash, because its slash returns a decimal. Deep-linking a search hit back to its page is the whole use case.","sql":"WITH r AS (\n  SELECT product_id, ROW_NUMBER() OVER (ORDER BY price DESC) AS rn\n  FROM products\n)\nSELECT product_id, rn, (rn + 19) / 20 AS page_no\nFROM r\nWHERE product_id = 1234;"}]},"source_url":"https://sqlly.app/sql-functions/row-number-pagination","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rowid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROWID pseudocolumn","description":"What ROWID means in Oracle and SQLite, PostgreSQL's ctid, and why none makes a stable key. MySQL has no row address; SQL Server's is undocumented.","body":{"slug":"rowid","name":"ROWID","h1":"SQL ROWID pseudocolumn","category":"system","lede":"ROWID is the address of a row: where it is stored (Oracle, PostgreSQL's ctid) or its internal integer key (SQLite). It is fast to look up and not meant to be kept.","syntax":"ROWID  -- Oracle, SQLite  |  ctid  -- PostgreSQL","return_type":"ROWID (Oracle), integer (SQLite), tid (PostgreSQL)","support":[{"engine_slug":"sql-server","status":"no","note":"no documented row address; the undocumented %%physloc%% returns the file, page and slot"},{"engine_slug":"postgresql","status":"partial","note":"ctid (block, tuple); changes on every UPDATE"},{"engine_slug":"mysql","status":"no","note":"none; InnoDB stores rows in primary key order"},{"engine_slug":"sqlite","status":"yes","note":"rowid, also _rowid_ and oid; INTEGER PRIMARY KEY is an alias for it"},{"engine_slug":"oracle","status":"yes","note":"ROWID pseudocolumn"}],"gotchas":["PostgreSQL's ctid changes each time the row is updated, because UPDATE writes a new row version. Never store it.","Oracle ROWIDs change when rows move: ALTER TABLE ... MOVE, partition row movement, or export and reimport.","In SQLite an INTEGER PRIMARY KEY column is the rowid, so SELECT rowid returns the same values under the column's name. Tables created WITHOUT ROWID have none.","The classic use is removing duplicates: keep MIN(rowid) per group in Oracle and SQLite, or MIN(ctid) in PostgreSQL 14 and later. Older PostgreSQL has no min() for tid, so use the ctid self-join below."],"examples":[{"engine_slug":"sqlite","sql":"CREATE TABLE tags (name TEXT);\nINSERT INTO tags VALUES ('a'), ('a'), ('b');\nDELETE FROM tags WHERE rowid NOT IN (SELECT MIN(rowid) FROM tags GROUP BY name);\nSELECT rowid, name FROM tags;  -- 1 a, 3 b"},{"engine_slug":"postgresql","sql":"CREATE TABLE tags (name text);\nINSERT INTO tags VALUES ('a');\nSELECT ctid FROM tags;  -- (0,1)\nUPDATE tags SET name = 'b';\nSELECT ctid FROM tags;  -- (0,2)"},{"engine_slug":"oracle","sql":"CREATE TABLE tags (name VARCHAR2(10));\nINSERT INTO tags (name) SELECT 'a' FROM dual UNION ALL SELECT 'a' FROM dual UNION ALL SELECT 'b' FROM dual;\nDELETE FROM tags WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM tags GROUP BY name);\nSELECT name FROM tags;  -- a, b"}],"faqs":[{"question":"Does SQL Server have ROWID?","answer":"Not as a documented feature. Give the table a key (an IDENTITY column or a natural key) and use ROW_NUMBER() when you need to tell duplicate rows apart."},{"question":"Can I use ROWID as a primary key?","answer":"In SQLite, yes: declare id INTEGER PRIMARY KEY and it is the rowid. In Oracle and PostgreSQL, no, because the address can change."}],"related":["dedupe-rows","rownum","row-number"],"novel_uses":[{"body":"When every column matches, only a row address can tell the copies apart. PostgreSQL's ctid self-join keeps the lowest address per duplicate group; Oracle and SQLite run the same shape with MIN(rowid).","sql":"DELETE FROM tags a\nUSING tags b\nWHERE a.ctid > b.ctid\n  AND ROW(a.name, a.qty) IS NOT DISTINCT FROM ROW(b.name, b.qty);"},{"body":"An update by rowid fetched moments earlier skips the key lookup entirely: UPDATE t SET ... WHERE rowid = :r in Oracle. It is a same-transaction tool only; a row that moved raises ORA-01410 and the statement must fall back to the key.","sql":"DECLARE r ROWID;\nBEGIN\n  SELECT rowid INTO r FROM tags WHERE name = 'a';\n  UPDATE tags SET name = 'a2' WHERE rowid = r;\nEND;\n/"},{"body":"INSERT OR REPLACE deletes the conflicting row and inserts a new one, so the new row gets a new rowid in SQLite. Code that cached the old rowid points at nothing after a replace, which is a classic cause of lost updates in hand-rolled upserts.","sql":"CREATE TABLE kv (k TEXT UNIQUE, v TEXT);\nINSERT INTO kv VALUES ('a', '1');\nSELECT rowid FROM kv;  -- 1\nINSERT OR REPLACE INTO kv VALUES ('a', '2');\nSELECT rowid FROM kv;  -- 2, not 1"}]},"source_url":"https://sqlly.app/sql-functions/rowid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rownum","corpus":"sql-functions","engine":null,"language":"en","title":"Oracle ROWNUM pseudocolumn","description":"Oracle's ROWNUM is assigned before ORDER BY, so WHERE ROWNUM <= 10 ORDER BY x is not a top-10. How to get the right rows in Oracle and on other engines.","body":{"slug":"rownum","name":"ROWNUM","h1":"Oracle ROWNUM pseudocolumn","category":"window","lede":"ROWNUM numbers rows as Oracle fetches them, before sorting. Top-N queries need the sort in a subquery, or FETCH FIRST and ROW_NUMBER().","syntax":"ROWNUM","return_type":"NUMBER","support":[{"engine_slug":"sql-server","status":"partial","note":"ROW_NUMBER() OVER (ORDER BY ...); TOP (n)"},{"engine_slug":"postgresql","status":"partial","note":"ROW_NUMBER() OVER (ORDER BY ...); LIMIT n"},{"engine_slug":"mysql","status":"partial","note":"ROW_NUMBER() OVER (ORDER BY ...) from 8.0; LIMIT n"},{"engine_slug":"sqlite","status":"partial","note":"ROW_NUMBER() OVER (ORDER BY ...); LIMIT n"},{"engine_slug":"oracle","status":"yes","note":"ROWNUM pseudocolumn"}],"gotchas":["ROWNUM is assigned as rows pass the WHERE clause, before ORDER BY. WHERE ROWNUM <= 3 ORDER BY salary DESC sorts three arbitrary rows.","WHERE ROWNUM = 2 and WHERE ROWNUM > 1 return no rows: the first candidate gets ROWNUM 1, fails the test, and the next candidate is numbered 1 again.","From 12c, FETCH FIRST n ROWS ONLY and ROW_NUMBER() say what you mean. If you keep ROWNUM, sort in an inner query and filter in the outer one."],"examples":[{"engine_slug":"oracle","sql":"SELECT x FROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5) WHERE ROWNUM = 2;  -- no rows"},{"engine_slug":"oracle","sql":"SELECT x FROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5 ORDER BY x DESC) WHERE ROWNUM <= 2;  -- 5, 4"},{"engine_slug":"oracle","sql":"SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5 ORDER BY x DESC FETCH FIRST 2 ROWS ONLY;  -- 5, 4"},{"engine_slug":"sql-server","sql":"SELECT TOP (2) x FROM (VALUES (1), (5), (4), (3), (2)) AS t(x) ORDER BY x DESC;  -- 5, 4"},{"engine_slug":"postgresql","sql":"SELECT x FROM (VALUES (1), (5), (4), (3), (2)) AS t(x) ORDER BY x DESC LIMIT 2;  -- 5, 4"},{"engine_slug":"mysql","sql":"SELECT x FROM (SELECT 1 AS x UNION ALL SELECT 5 UNION ALL SELECT 4 UNION ALL SELECT 3 UNION ALL SELECT 2) AS t\nORDER BY x DESC LIMIT 2;  -- 5, 4"},{"engine_slug":"sqlite","sql":"SELECT column1 AS x FROM (VALUES (1), (5), (4), (3), (2)) ORDER BY x DESC LIMIT 2;  -- 5, 4"}],"faqs":[{"question":"How do I page through results with ROWNUM?","answer":"Nest twice: SELECT * FROM (SELECT t.*, ROWNUM AS rn FROM (SELECT ... ORDER BY id) t WHERE ROWNUM <= 20) WHERE rn > 10. On 12c and later, ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY is simpler."},{"question":"Is ROWNUM faster than ROW_NUMBER()?","answer":"Both let Oracle stop early. The plan shows COUNT STOPKEY for a ROWNUM filter and WINDOW SORT PUSHED RANK for a ROW_NUMBER() filter."}],"related":["row-number","row-number-pagination","top-n-per-group","rowid"],"novel_uses":[{"body":"Deleting a million rows in one statement stresses undo and locks every row at once. The Oracle pattern bounds each pass: pick the rowids of the first n matching rows with ROWNUM in a subquery, delete by that rowid list, repeat until no rows.","sql":"DELETE FROM events\nWHERE rowid IN (\n  SELECT rowid FROM events\n  WHERE created < DATE '2025-01-01' AND ROWNUM <= 10000);"},{"body":"A queue table hands each worker a slice when the inner query orders the candidates and ROWNUM caps the slice, and FOR UPDATE SKIP LOCKED lets a second worker take the next rows instead of waiting. Fewer rows than asked can come back when peers hold locks, which is fine for a poller.","sql":"SELECT id FROM (\n  SELECT id FROM jobs WHERE status = 'PENDING' ORDER BY id\n) WHERE ROWNUM <= 10\nFOR UPDATE SKIP LOCKED;"}]},"source_url":"https://sqlly.app/sql-functions/rownum","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rows-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROWS frame","description":"ROWS BETWEEN frames count physical rows (n PRECEDING, CURRENT ROW, n FOLLOWING), giving exact sliding and running windows.","body":{"slug":"rows-frame","name":"ROWS Frame","h1":"SQL ROWS frame","category":"window","lede":"A ROWS frame bounds the window by row count: each boundary is a position relative to the current row, unaffected by ties in the ORDER BY.","syntax":"SUM(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) | ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ROWS is immune to the peers problem: duplicate ORDER BY values each get their own frame end, unlike RANGE. That determinism is why most sliding windows use ROWS.","Early rows see truncated frames: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW averages 1 row on the first row, 2 on the second, and so on.","A frame may not run backwards: ROWS BETWEEN 3 FOLLOWING AND 1 PRECEDING is an error. Start boundary must not come after the end boundary."],"examples":[{"engine_slug":"all","sql":"SELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7,\n       MAX(price) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS high_so_far\nFROM prices;"}],"faqs":[{"question":"ROWS or RANGE: which should I write?","answer":"ROWS when the window is a number of rows (the last 7 observations), RANGE when it is a value span (all peers, or a date interval). ROWS with a unique ORDER BY is the most predictable."},{"question":"How do NULLs affect a ROWS frame?","answer":"They still take up positions: a 7-row frame with two NULLs holds 7 rows, but AVG divides by the 5 non-NULL values and COUNT(x) returns 5 while COUNT(*) returns 7."}],"related":["rows-vs-range","frame-boundary-shorthand","moving-average"],"novel_uses":[{"body":"A ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING average is a local smoother, and a big gap between the raw value and its smoothed self is the spike flag. It runs on every window-capable engine: ROWS frames are core window syntax, and this one uses no EXCLUDE clause.","sql":"SELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS smooth3\nFROM prices;"},{"body":"MIN over a bounded trailing frame drags a support level along under the series, and the current value minus that level is the distance to the recent floor. Early rows see a shorter frame, which is the honest answer for a short history.","sql":"SELECT day, low,\n       MIN(low) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS floor7\nFROM prices;"}]},"source_url":"https://sqlly.app/sql-functions/rows-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rows-n-preceding","corpus":"sql-functions","engine":null,"language":"en","title":"SQL frame offsets n PRECEDING and FOLLOWING","description":"Relative frame offsets: trailing windows that include or exclude the current row, look-ahead frames with FOLLOWING and the non-negative integer rule.","body":{"slug":"rows-n-preceding","name":"n PRECEDING / n FOLLOWING","h1":"SQL frame offsets n PRECEDING and FOLLOWING","category":"window","lede":"Offsets like 3 PRECEDING or 2 FOLLOWING place frame boundaries a fixed distance from the current row, enabling skip-current and lead-style windows.","syntax":"SUM(x) OVER (ORDER BY d ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) | AVG(x) OVER (ORDER BY d ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING)","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"yes","note":"ROWS offsets only; RANGE accepts only UNBOUNDED and CURRENT ROW"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+ for ROWS offsets; RANGE offsets since 3.28"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ROWS offsets must be non-negative integers: SQL Server, MySQL and SQLite reject a fractional offset, but PostgreSQL silently rounds it (1.5 PRECEDING acts as 2). RANGE offsets are not portable: PostgreSQL and MySQL accept interval offsets on date types, SQLite accepts only numeric RANGE offsets, and SQL Server allows RANGE only with UNBOUNDED and CURRENT ROW. Negative offsets are rejected, and only Oracle accepts a column as the offset.","BETWEEN 1 PRECEDING AND 1 PRECEDING is legal: a one-row frame holding exactly the previous row, the aggregate form of LAG for numeric windows.","FOLLOWING-ended frames shrink near the partition's end: CURRENT ROW AND 3 FOLLOWING covers fewer rows on the last rows, same as PRECEDING frames shrink at the start."],"examples":[{"engine_slug":"all","sql":"-- sum of the previous two rows, excluding the current one\nSELECT day, units,\n       SUM(units) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS prev_two\nFROM daily_sales;"}],"faqs":[{"question":"Can the offset be a column?","answer":"Only on Oracle, which evaluates it per row: ROWS BETWEEN g PRECEDING AND CURRENT ROW runs there. PostgreSQL says 'argument of ROWS must not contain variables', SQLite requires a constant non-negative integer, and SQL Server and MySQL accept only a literal (MySQL also a ? parameter). For a per-row window size, use a correlated subquery or a self-join instead."},{"question":"How do I exclude the current row from a running sum?","answer":"End the frame at 1 PRECEDING: ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING. Common for 'total of everything before me' logic. The first row gets NULL, not 0; wrap in COALESCE(..., 0) if you need 0."}],"related":["rows-frame","frame-boundary-shorthand","lag"],"novel_uses":[{"body":"End the frame at 1 PRECEDING and the aggregate never sees the row being decided: a signal computed from everything before today is executable today. Frames that include the current row are how lookahead bias sneaks into backtests.","sql":"SELECT day, px,\n       CASE WHEN AVG(px) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n                 > AVG(px) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 4 PRECEDING)\n            THEN 1 ELSE 0 END AS buy_signal\nFROM prices;"},{"body":"A frame of CURRENT ROW AND 1 FOLLOWING sums exactly the row and its next neighbor, which pairs entries for two-row totals: legs of a relay, sides of a trade, before and after rows. The last row of the partition sees only itself, so plan for the short frame there.","sql":"SELECT entry_id, amount,\n       SUM(amount) OVER (ORDER BY entry_id ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS pair_total\nFROM ledger;"}]},"source_url":"https://sqlly.app/sql-functions/rows-n-preceding","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rows-unbounded-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNBOUNDED PRECEDING and FOLLOWING","description":"ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING spans the full partition: the LAST_VALUE fix and the explicit way to say 'all rows'.","body":{"slug":"rows-unbounded-frame","name":"UNBOUNDED Frame","h1":"SQL UNBOUNDED PRECEDING and FOLLOWING","category":"window","lede":"An unbounded frame stretches from the first to the last row of the partition, making the value functions (FIRST_VALUE, LAST_VALUE, NTH_VALUE) see the whole window.","syntax":"LAST_VALUE(x) OVER (ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)","return_type":"per-partition value","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without it, LAST_VALUE silently returns the current row (or its last tie), and NTH_VALUE returns NULL until the frame reaches row n: the default frame ends at the current row, so neither sees what comes after. This frame is the canonical fix.","One-sided frames are valid: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is the running-total frame; ... AND 1 PRECEDING excludes the current row from its own sum.","Aggregates over a fully unbounded frame equal the same aggregate with no ORDER BY at all; under an ORDER BY the default frame makes the aggregate a running total, so the explicit frame is what turns it into a partition total."],"examples":[{"engine_slug":"postgresql","sql":"SELECT trade_day, tick_time, price,\n       FIRST_VALUE(price) OVER w AS open_price,\n       LAST_VALUE(price) OVER w AS close_price,\n       MAX(price) OVER w AS day_high\nFROM ticks\nWINDOW w AS (PARTITION BY trade_day ORDER BY tick_time\n             ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);"},{"engine_slug":"sql-server","sql":"SELECT trade_day, tick_time, price,\n       FIRST_VALUE(price) OVER (PARTITION BY trade_day ORDER BY tick_time\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS open_price,\n       LAST_VALUE(price) OVER (PARTITION BY trade_day ORDER BY tick_time\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS close_price\nFROM ticks;"},{"engine_slug":"mysql","sql":"SELECT day, price,\n       FIRST_VALUE(price) OVER (ORDER BY day\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_price,\n       LAST_VALUE(price) OVER (ORDER BY day\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_price\nFROM prices;"},{"engine_slug":"sqlite","sql":"SELECT day, price,\n       MIN(price) OVER (ORDER BY day\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS day_low,\n       MAX(price) OVER (ORDER BY day\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS day_high\nFROM prices;"},{"engine_slug":"oracle","sql":"SELECT trade_day, tick_time, price,\n       LAST_VALUE(price) OVER (PARTITION BY trade_day ORDER BY tick_time\n           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS day_close\nFROM ticks;"}],"faqs":[{"question":"Why does FIRST_VALUE work but LAST_VALUE fail by default?","answer":"FIRST_VALUE's target row is always inside the default frame (it is the first); the last row of a frame ending at CURRENT ROW is the current row itself (or its last tie under RANGE), so LAST_VALUE returns that row. Stretch the frame to see the real last row."},{"question":"Is an unbounded frame expensive?","answer":"Not for aggregates: the result is the same for every row of the partition, so engines compute it once. The cost is the sort. Sliding frames are the expensive ones for MIN and MAX, which cannot subtract the row leaving the frame and may rescan it per row."}],"related":["window-default-frame","last-value","rows-frame"],"novel_uses":[{"body":"Over a full-day frame, the current close minus the day's MIN divided by the day's range lands between 0 and 1: where in the day's spread this tick sits. Traders read the extremes as close-to-low or close-to-high; the full frame is what makes MIN and MAX day-wide on every row.","sql":"SELECT trade_day, tick_time, closing_price,\n       (closing_price - MIN(closing_price) OVER (PARTITION BY trade_day ORDER BY tick_time ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) * 1.0\n         / NULLIF(MAX(closing_price) OVER (PARTITION BY trade_day ORDER BY tick_time ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)\n                  - MIN(closing_price) OVER (PARTITION BY trade_day ORDER BY tick_time ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), 0) AS range_position\nFROM ticks\nORDER BY trade_day, tick_time;"},{"body":"Keep the same aggregate twice, once with the frame ending at CURRENT ROW and once unbounded, and every row shows both the value so far and the final total. The gap between the two columns is the remaining work in the partition.","sql":"SELECT day, amount,\n       SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS so_far,\n       SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS partition_total\nFROM daily_sales;"}]},"source_url":"https://sqlly.app/sql-functions/rows-unbounded-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rows-vs-range","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ROWS vs RANGE frames","description":"The same boundaries give different windows: ROWS counts physical rows, RANGE includes value peers, shown side by side on tied data.","body":{"slug":"rows-vs-range","name":"ROWS vs RANGE","h1":"SQL ROWS vs RANGE frames","category":"window","lede":"ROWS treats each row individually; RANGE groups rows with equal ORDER BY values into one frame end. With unique sort keys they coincide.","syntax":"SUM(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) | SUM(x) OVER (ORDER BY d RANGE UNBOUNDED PRECEDING)","return_type":"frame type","support":[{"engine_slug":"sql-server","status":"yes","note":"RANGE takes only UNBOUNDED and CURRENT ROW as offsets; numeric RANGE offsets fail"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["They can differ only when the ORDER BY has ties; tied rows whose values leave the running total unchanged still match. Unique keys make ROWS and RANGE identical, which is why the bug hides until duplicate values appear.","The default frame is RANGE (UNBOUNDED PRECEDING to CURRENT ROW); queries that assume ROWS behaviour without writing it are the classic latent bug.","GROUPS is a third type on PostgreSQL 11+, SQLite 3.28+ and Oracle 21c+: its offsets count tie groups instead of rows or values."],"examples":[{"engine_slug":"all","sql":"-- t holds (day 1, 100), (day 1, 100), (day 2, 50)\nSELECT day, amount,\n       SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS rows_sum,\n       SUM(amount) OVER (ORDER BY day RANGE UNBOUNDED PRECEDING) AS range_sum\nFROM t;\n-- rows_sum: 100, 200, 250   range_sum: 200, 200, 250"}],"faqs":[{"question":"Which frame type is the default?","answer":"RANGE. ORDER BY without a frame clause means RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, peers included; spell out ROWS when you want row-by-row."},{"question":"Do ROWS and RANGE differ in performance?","answer":"Rarely meaningfully; engines optimize both. Choose by semantics first, then measure; the expensive part is usually the sort that feeds the window."}],"related":["rows-frame","range-frame","groups-frame"],"novel_uses":[{"body":"Compute the running total both ways and count the rows where they disagree: that count is how much tie behaviour is already inside your reports. Zero means the ties left every total unchanged, a free pass for these numbers, but it does not prove the keys are unique; anything else is a conversation about which frame you meant. NULL amounts count as zero.","sql":"WITH s AS (\n  SELECT day, amount,\n         SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS by_row,\n         SUM(amount) OVER (ORDER BY day RANGE UNBOUNDED PRECEDING) AS by_peer\n  FROM ledger\n)\nSELECT COUNT(*) AS rows_where_ties_matter\nFROM s\nWHERE COALESCE(by_row, 0) <> COALESCE(by_peer, 0);"},{"body":"With a tiebroken unique ORDER BY the two frame types return identical values, so the default RANGE is safe and the query stays short. Spend the explicit ROWS keyword on the windows that actually face duplicate keys.","sql":"SELECT entry_id, day, amount,\n       SUM(amount) OVER (ORDER BY day, entry_id) AS running_total\nFROM ledger;"}]},"source_url":"https://sqlly.app/sql-functions/rows-vs-range","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rpad","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RPAD function","description":"How RPAD pads a string to a target length on the right in PostgreSQL, MySQL and Oracle: truncation when too long, multi-character pads, and the SQL Server workaround.","body":{"slug":"rpad","name":"RPAD","h1":"SQL RPAD function","category":"string","lede":"Pads a string on the right with a fill pattern until it reaches the requested length.","syntax":"RPAD(str, length [, pad_string])  -- pad_string is required in MySQL","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No RPAD; LEFT(str + REPLICATE(pad, n), n)."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No RPAD; printf('%-10s', str) pads with spaces."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["A target length shorter than the input truncates it: RPAD('abcdef', 4, 'x') is 'abcd', so padding and clipping are the same call.","The pad string repeats and is cut to fit: RPAD('ab', 8, 'xy') is 'abxyxyxy'.","PostgreSQL and Oracle pad with spaces when the third argument is omitted; MySQL requires it. Oracle measures the length in display width, which matches characters except in some multibyte character sets."],"examples":[{"engine_slug":"postgresql","sql":"SELECT RPAD('id-', 6, '0') AS code;  -- id-000"},{"engine_slug":"mysql","sql":"SELECT RPAD(name, 20, '.') AS name_line\nFROM products;"},{"engine_slug":"oracle","sql":"SELECT RPAD('id-', 6, '0') AS code\nFROM dual;  -- id-000"}],"faqs":[{"question":"How do I right-pad in SQL Server?","answer":"There is no RPAD. LEFT(str + REPLICATE(pad, n), n) pads and truncates to n characters; LEFT(str + SPACE(n), n) for spaces."},{"question":"Does RPAD truncate long strings?","answer":"Yes. The result is exactly length characters, so RPAD also works as a fixed-width clip. In PostgreSQL an empty pad string means no padding at all."},{"question":"Is RPAD case-sensitive or collation-aware?","answer":"Neither applies: padding appends the pad pattern verbatim and never compares characters."}],"related":["lpad","repeat","space","printf"],"novel_uses":[{"body":"RPAD(title, 40, '.') fills the gap between label and value with dots, the printed-report leader, in one call.","sql":"SELECT CONCAT(CONCAT(RPAD(name, 40, '.'), ' '), COUNT(*)) AS line\nFROM members\nGROUP BY name;"},{"body":"Padding every column to its width and concatenating produces fixed-width records straight from the query, with no application formatting layer.","sql":"SELECT CONCAT(RPAD(name, 20, ' '), RPAD(sku, 10, ' ')) AS fixed_line\nFROM products;"}]},"source_url":"https://sqlly.app/sql-functions/rpad","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/rtrim","corpus":"sql-functions","engine":null,"language":"en","title":"SQL RTRIM function","description":"How RTRIM strips characters from the end of a string in every major engine: default spaces, character-set arguments, the trailing-zero trap, and LTRIM and TRIM.","body":{"slug":"rtrim","name":"RTRIM","h1":"SQL RTRIM function","category":"string","lede":"Removes the longest run of the given characters (spaces by default) from the end of a string.","syntax":"RTRIM(string [, characters])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"The characters argument needs SQL Server 2022; before that, spaces only."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"One argument only; trims spaces. TRIM(TRAILING x FROM s) strips a repeated string."},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The character-set argument removes any trailing characters from the set: RTRIM('12.000', '0.') is '12', but RTRIM('12.3400', '0.') is '12.34' because trimming stops at the 4.","PostgreSQL, Oracle, SQLite and SQL Server 2022+ accept the set argument; MySQL's RTRIM takes one argument and removes spaces only.","CHAR(n) columns are padded with spaces to full width. SQL Server keeps that padding when you concatenate, so RTRIM is the usual companion there; PostgreSQL drops it during concatenation but keeps it for LIKE."],"examples":[{"engine_slug":"all","sql":"SELECT RTRIM('padded   ') AS trimmed;  -- padded"},{"engine_slug":"postgresql","sql":"SELECT RTRIM('report.pdfxx', 'x') AS trimmed;  -- report.pdf"},{"engine_slug":"mysql","sql":"SELECT TRIM(TRAILING '0' FROM code) AS trimmed\nFROM skus;"}],"faqs":[{"question":"Why does RTRIM('12.000', '0.') also remove the dot?","answer":"The second argument is a set, applied until a character outside it appears. That makes it handy for trailing decimal zeros, but it also turns '120.000' into '12'."},{"question":"Do CHAR columns need RTRIM before comparison?","answer":"Not for = in SQL Server or PostgreSQL, which ignore the padding. Concatenation keeps it in SQL Server but not PostgreSQL. LIKE keeps it in PostgreSQL but not in SQL Server for an unpadded pattern. LEN and length() ignore it; only DATALENGTH and octet_length count it."},{"question":"How is RTRIM different from TRIM?","answer":"TRIM works on both ends, and on PostgreSQL, MySQL and SQL Server 2022+ it can target LEADING or TRAILING; SQLite has only trim(s, chars). RTRIM is the trailing-only form, and every engine spells it the same."}],"related":["ltrim","btrim","translate","replace"],"novel_uses":[{"body":"RTRIM(base_url, '/') keeps one query working whether stored URLs end with a slash or not; MySQL's single-argument RTRIM needs TRIM(TRAILING '/' FROM base_url) instead.","sql":"SELECT RTRIM(base_url, '/') || '/' || path AS full_url\nFROM links;"},{"body":"Unix tools choke on the carriage returns Windows files carry. Trimming the CR and LF set from the right cleans each line during the load in PostgreSQL.","sql":"SELECT RTRIM(line, chr(13) || chr(10)) AS clean\nFROM staging_lines;"}]},"source_url":"https://sqlly.app/sql-functions/rtrim","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/running-total","corpus":"sql-functions","engine":null,"language":"en","title":"SQL running total","description":"Cumulative sums with SUM() OVER (ORDER BY ...): the default frame that makes it work, the peer trap, and reset-per-partition variants.","body":{"slug":"running-total","name":"Running Total","h1":"SQL running total","category":"window","lede":"SUM(x) OVER (ORDER BY d) accumulates from the first row through the current one (under the default RANGE frame, tied peers are included): a cumulative total without a self-join.","syntax":"SUM(x) OVER (ORDER BY d) | SUM(x) OVER (PARTITION BY g ORDER BY d)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ORDER BY is what turns the sum into a running one; with only PARTITION BY you get the partition's grand total on every row.","The default frame is RANGE, so tied ORDER BY values all show the total including every peer. Switch to ROWS UNBOUNDED PRECEDING to total one row at a time: each row sums itself and the rows sorted before it, so tied rows get separate subtotals.","Under a ROWS frame the ORDER BY must be deterministic (add a tiebreaker), or tied rows get running values that depend on row order and can change between runs. The default RANGE frame gives tied rows the same value, so it is not affected."],"examples":[{"engine_slug":"all","sql":"SELECT day, amount,\n       SUM(amount) OVER (ORDER BY day) AS balance\nFROM ledger;"},{"engine_slug":"all","sql":"-- per-account balance, strict row order\nSELECT account_id, day, amount,\n       SUM(amount) OVER (PARTITION BY account_id ORDER BY day, id\n                         ROWS UNBOUNDED PRECEDING) AS balance\nFROM ledger_entries;"}],"faqs":[{"question":"Why is my running total wrong for tied dates?","answer":"The default RANGE frame includes all peers of the current row, so tied rows share one subtotal. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to sum strictly row by row, with a tiebreaker in ORDER BY so the row order is fixed."},{"question":"How do I restart the running total per group?","answer":"PARTITION BY the group inside OVER: SUM(x) OVER (PARTITION BY account_id ORDER BY day). Each partition accumulates from its own first row."}],"related":["sum-over","rows-vs-range","moving-average"],"novel_uses":[{"body":"Accumulate the actuals and multiply the running day count by the daily target, and the difference between the two columns is the ahead or behind line. A flat target needs no second table because COUNT over the same frame counts the days, provided the table holds exactly one row per calendar day; a missing day leaves the target one day short.","sql":"SELECT day, actual,\n       SUM(actual) OVER (ORDER BY day) AS actual_to_date,\n       100 * COUNT(*) OVER (ORDER BY day) AS target_to_date\nFROM daily_sales;"},{"body":"Compute the running balance per account in a CTE, then MIN over it: if an account's minimum dips below zero, that account went negative somewhere in its history. The window over the window needs the wrap, but it turns a visual check into an assertion.","sql":"WITH b AS (\n  SELECT account_id, day, amount,\n         SUM(amount) OVER (PARTITION BY account_id ORDER BY day, entry_id) AS balance\n  FROM ledger\n)\nSELECT account_id, MIN(balance) AS worst_balance\nFROM b\nGROUP BY account_id;"}]},"source_url":"https://sqlly.app/sql-functions/running-total","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/scale","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SCALE function","description":"PostgreSQL scale(numeric) returns how many decimal digits a value carries after the point, trailing zeros included: 4 for 1.2300, 2 for 1.23.","body":{"slug":"scale","name":"SCALE","h1":"SQL SCALE function","category":"math","lede":"Returns the count of digits after the decimal point of a numeric value, including trailing zeros: scale(1.2300) is 4.","syntax":"SCALE(numeric)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No equivalent; SQL_VARIANT_PROPERTY(x, 'Scale') reports the declared scale of the expression's type"},{"engine_slug":"postgresql","status":"yes","note":"scale(numeric) since 9.6; min_scale and trim_scale arrived in 13"},{"engine_slug":"mysql","status":"no","note":"No equivalent; you can approximate with LENGTH of the fractional part of a CAST to text"},{"engine_slug":"sqlite","status":"no","note":"No equivalent; values are stored as REAL and carry no fixed scale"},{"engine_slug":"oracle","status":"no","note":"No direct function; TO_CHAR and string parsing can count the digits"}],"gotchas":["scale counts stored digits, so scale(1.2300) is 4 while scale(1.23) is 2. PostgreSQL numeric keeps trailing zeros, so the two values are equal but report different scales.","It is defined only for numeric: scale(1.5::float8) fails with function scale(double precision) does not exist. Cast first, and expect at most 15 significant digits: 0.1::float8 + 0.2::float8 casts to 0.3 (scale 1), and 1.0000000000000002::float8 casts to 1 (scale 0).","In a NUMERIC(10,2) column every value is coerced to scale 2, so 1.5 is stored as 1.50 and scale() returns 2. Values only differ in scale in unconstrained numeric columns and expressions."],"examples":[{"engine_slug":"postgresql","sql":"SELECT SCALE(1.2300::numeric) AS s;  -- 4"},{"engine_slug":"postgresql","sql":"SELECT amount, SCALE(amount::numeric) AS digits_after_point\nFROM payments;"}],"faqs":[{"question":"What does scale(1.2300) return?","answer":"4. scale() counts the stored digits after the point, trailing zeros included, because numeric keeps them. scale(1.23) would return 2."},{"question":"Is scale() the same as the column's declared scale?","answer":"For a NUMERIC(10,2) column, yes: PostgreSQL pads every value to the declared scale, so 1.5 is stored as 1.50 and scale() returns 2. In an unconstrained numeric column each value keeps its own scale."},{"question":"What is the equivalent outside PostgreSQL?","answer":"There is none built in. Cast to text and count the fractional characters, or carry the scale as data. SQL Server can report the declared scale of an expression's type with SQL_VARIANT_PROPERTY(x, 'Scale'), or of a column through sys.columns."}],"related":["min-scale","trim-scale","numeric-precision-scale"],"novel_uses":[{"body":"WHERE min_scale(amount) > 2 catches values that need more than two decimals to be exact, so padded values like 5.000 are not flagged, common after CSV imports into an unconstrained numeric column. The extra digits survive every SUM silently.","sql":"SELECT * FROM payments WHERE min_scale(amount) > 2;"},{"body":"GROUP BY scale(amount) shows how many fractional digits a column actually carries. A profile that is all 0 and 2 says the data fits DECIMAL(p, 2) even when the column declares something wider.","sql":"SELECT scale(amount) AS digits, COUNT(*) FROM payments GROUP BY 1 ORDER BY 1;"},{"body":"MAX(min_scale(col)) over the whole table gives the scale a fixed-scale target needs before you write the DECIMAL(p, s) DDL for SQL Server or MySQL. MAX(scale(col)) overstates that when the source pads values with trailing zeros. It turns the sizing guess into a query.","sql":"SELECT MAX(min_scale(rate)) AS max_scale, MAX(ABS(rate)) AS max_value FROM fx_rates;"}]},"source_url":"https://sqlly.app/sql-functions/scale","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sec-to-time","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SEC_TO_TIME function","description":"SEC_TO_TIME and TIME_TO_SEC in MySQL: convert between second counts and TIME values, with the interval spellings other engines use.","body":{"slug":"sec-to-time","name":"SEC_TO_TIME / TIME_TO_SEC","h1":"SQL SEC_TO_TIME function","category":"datetime","lede":"Converts a second count to a TIME value and back, the tidiest way to aggregate durations in MySQL.","syntax":"SEC_TO_TIME(seconds)  |  TIME_TO_SEC(time_value)","return_type":"time / integer","support":[{"engine_slug":"sql-server","status":"no","note":"no direct pair; DATEADD(SECOND, ...) and DATEDIFF(SECOND, '00:00:00', t)"},{"engine_slug":"postgresql","status":"partial","note":"make_interval(secs => n) and EXTRACT(EPOCH FROM t)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"NUMTODSINTERVAL(n, 'SECOND') and EXTRACT(SECOND FROM ...) or cast math"}],"gotchas":["TIME_TO_SEC works on clock times and durations alike: TIME_TO_SEC('01:30:00') is 5400, TIME_TO_SEC('-01:30:00') is -5400.","SEC_TO_TIME of values beyond TIME's range (838:59:59) clips; aggregate in seconds, convert only for display.","PostgreSQL's EXTRACT(EPOCH FROM TIME '01:30:00') gives 5400 the same way; Oracle needs interval casts and EXTRACT part by part."],"examples":[{"engine_slug":"mysql","sql":"SELECT SEC_TO_TIME(5400);  -- 01:30:00"},{"engine_slug":"mysql","sql":"SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(duration))) FROM shifts;"},{"engine_slug":"postgresql","sql":"SELECT make_interval(secs => 5400);  -- 01:30:00"},{"engine_slug":"oracle","sql":"SELECT NUMTODSINTERVAL(5400, 'SECOND') FROM dual;  -- +00 01:30:00"}],"faqs":[{"question":"How do I sum a TIME column?","answer":"SUM(TIME_TO_SEC(t)), then SEC_TO_TIME on the total. SUM on a TIME column adds the values as hhmmss numbers: 01:30:00 plus 01:45:00 sums to 27500, not 03:15:00."},{"question":"What is the SQL Server pattern?","answer":"Keep everything in seconds: DATEDIFF(SECOND, '00:00:00', t) to integers, SUM, then DATEADD(SECOND, total, '00:00:00') for display. That literal returns a datetime (1900-01-01 01:30:00.000 for 5400), so wrap it in CAST(... AS time(0)) for a clock value, and only for totals under 24 hours: a time value wraps (90000 gives 01:00:00)."}],"related":["timediff","addtime","extract-epoch","numtodsinterval"],"novel_uses":[{"body":"Divide the second count by 3600.0 to get hours as a decimal, the shape time-tracking exports expect, with rounding applied last.","sql":"SELECT ROUND(TIME_TO_SEC('07:45:00') / 3600.0, 2);  -- 7.75"},{"body":"Floor the second count into 900-second blocks and convert back for labels: a lightweight histogram grid with no calendar arithmetic.","sql":"SELECT SEC_TO_TIME(FLOOR(TIME_TO_SEC('08:07:00') / 900) * 900);  -- 08:00:00"}]},"source_url":"https://sqlly.app/sql-functions/sec-to-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/second","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SECOND function","description":"Get the seconds 0-59: SECOND() on MySQL, DATEPART(second) on SQL Server, EXTRACT(second FROM ts) on PostgreSQL and Oracle, strftime('%S') on SQLite.","body":{"slug":"second","name":"SECOND","h1":"SQL SECOND function","category":"datetime","lede":"Returns the seconds component of a timestamp, usually for dedup keys or measuring sub-minute spreads.","syntax":"EXTRACT(second FROM ts)  |  DATEPART(second, ts)  -- SQL Server  |  SECOND(ts)  -- MySQL","return_type":"integer (fractional on PostgreSQL, text on SQLite)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(second, ts); no SECOND() shorthand"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(second) includes the fraction: 31.5 is valid"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%S', ts) returns text"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT needs a TIMESTAMP; DATE has no sub-second storage"}],"gotchas":["PostgreSQL's EXTRACT(second) includes the fraction (31.500000, not 31) and returns numeric (double precision before version 14). Use FLOOR() if you want whole seconds; a cast to int rounds.","SQL Server's datetime type rounds to 1/300 second, so 10:00:59.999 is stored as 10:01:00.000 and DATEPART(second) returns 0, not 59.","SQLite's %S gives whole seconds as text; %f gives seconds with the fraction, as SS.SSS."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(second FROM created_at) AS s FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(second, created_at) AS s FROM orders;"},{"engine_slug":"mysql","sql":"SELECT SECOND(created_at) AS s FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%S', created_at) AS INTEGER) AS s FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(second FROM CAST(created_at AS TIMESTAMP)) AS s FROM orders;"}],"faqs":[{"question":"Why does EXTRACT(second) return 31.5?","answer":"PostgreSQL folds fractional seconds into the seconds field. EXTRACT(milliseconds) returns the same field times 1000 (31500), not just the fraction."},{"question":"Does Oracle DATE store seconds at all?","answer":"Yes, whole seconds only. Sub-second precision needs TIMESTAMP, and EXTRACT(second) on a DATE works only after casting."}],"related":["extract","milliseconds","minute"],"novel_uses":[{"body":"The midnight idiom DATEADD(second, DATEDIFF(second, 0, ts), 0) overflows: second counts from 1900 exceed the int DATEDIFF returns. Anchor the same pattern near your data instead.","sql":"SELECT DATEADD(second, DATEDIFF(second, '2024-01-01', ts), '2024-01-01') AS sec_bucket FROM clicks;"},{"body":"Subtract date_trunc('day', ts) and take the epoch of the leftover interval: one number from 0 to 86399 that places every event on a single time-of-day axis. On a timestamptz column, cast to timestamp first so the wall clock is used; on DST days a timestamptz difference counts elapsed time, so 12:00 EDT on 2024-03-10 gives 39600 and 23:59:59 on 2024-11-03 gives 89999.","sql":"SELECT EXTRACT(epoch FROM ts::timestamp - date_trunc('day', ts::timestamp)) AS secs_into_day FROM events;"}]},"source_url":"https://sqlly.app/sql-functions/second","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/session-time-zone","corpus":"sql-functions","engine":null,"language":"en","title":"SQL set session time zone","description":"SET TIME ZONE on PostgreSQL, time_zone on MySQL, TIME_ZONE on Oracle: how the session zone re-renders timestamptz data without touching stored values.","body":{"slug":"session-time-zone","name":"Session time zone","h1":"SQL set session time zone","category":"datetime","lede":"Declares the zone in which zone-aware values render for this connection: storage stays UTC, display follows the session.","syntax":"SET TIME ZONE 'Europe/Paris'  |  SET time_zone = 'Europe/Paris'","return_type":"session setting","support":[{"engine_slug":"sql-server","status":"no","note":"no session zone; AT TIME ZONE per query instead, taking Windows zone names such as 'W. Europe Standard Time' from sys.time_zone_info"},{"engine_slug":"postgresql","status":"yes","note":"SET TIME ZONE / SET timezone"},{"engine_slug":"mysql","status":"yes","note":"SET time_zone; offsets work without tz tables, names need them"},{"engine_slug":"sqlite","status":"no","note":"no concept; 'localtime' modifier uses the OS zone"},{"engine_slug":"oracle","status":"yes","note":"ALTER SESSION SET TIME_ZONE"}],"gotchas":["Only display and naive-timestamp interpretation change: a timestamptz column returns different text per session but compares, sorts and indexes identically.","MySQL's SET time_zone with a named zone needs the tz tables loaded, exactly like CONVERT_TZ; otherwise use offsets like '+02:00'.","The session zone also feeds LOCALTIMESTAMP, CURRENT_TIMESTAMP in Oracle, and the parsing of zone-less timestamps into timestamptz; 'naive 14:30' becomes a different instant per session."],"examples":[{"engine_slug":"postgresql","sql":"SET TIME ZONE 'Europe/Paris'; SELECT now();"},{"engine_slug":"mysql","sql":"SET time_zone = '-05:00'; SELECT created_at FROM logs;  -- TIMESTAMP columns shift, DATETIME columns do not"},{"engine_slug":"oracle","sql":"ALTER SESSION SET TIME_ZONE = 'America/New_York';"}],"faqs":[{"question":"Does SET TIME ZONE rewrite my data?","answer":"No. The stored instant is immutable. Only rendering and the interpretation of zone-less input depend on it."},{"question":"How do I set the zone for one query only?","answer":"On PostgreSQL, SET LOCAL TIME ZONE inside a transaction reverts at COMMIT or ROLLBACK. Otherwise convert per expression, with AT TIME ZONE on PostgreSQL, SQL Server and Oracle or CONVERT_TZ on MySQL, which leaves other queries alone."}],"related":["at-time-zone","convert-tz","localtimestamp","timestamp-with-time-zone"],"novel_uses":[{"body":"Each engine exposes the current zone: current_setting('TimeZone') on PostgreSQL, @@session.time_zone on MySQL. Check it before blaming the stored data.","sql":"SELECT current_setting('TimeZone'), now();"},{"body":"Oracle sites can set TIME_ZONE in an AFTER LOGON trigger that looks up each user's zone in a table, so every session renders in its region without application code carrying the mapping.","sql":"CREATE OR REPLACE TRIGGER set_user_tz AFTER LOGON ON DATABASE BEGIN FOR r IN (SELECT tz FROM user_tz_map WHERE username = SYS_CONTEXT('USERENV', 'SESSION_USER')) LOOP EXECUTE IMMEDIATE 'ALTER SESSION SET TIME_ZONE = ''' || r.tz || ''''; END LOOP; END;"}]},"source_url":"https://sqlly.app/sql-functions/session-time-zone","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/session-timezone","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SESSIONTIMEZONE function","description":"Oracle's SESSIONTIMEZONE and DBTIMEZONE show the connection's and the database's zones, and why CURRENT_TIMESTAMP and SYSDATE can disagree.","body":{"slug":"session-timezone","name":"SESSIONTIMEZONE","h1":"SQL SESSIONTIMEZONE function","category":"datetime","lede":"Returns the time zone of the current session. On other engines it is a setting to read: SHOW timezone on PostgreSQL, @@session.time_zone on MySQL.","syntax":"SESSIONTIMEZONE  |  DBTIMEZONE  -- Oracle  |  SHOW timezone  -- PostgreSQL  |  @@session.time_zone  -- MySQL","return_type":"text (zone name or offset)","support":[{"engine_slug":"sql-server","status":"no","note":"no session zone; CURRENT_TIMEZONE() (SQL Server 2022+) reports the server's"},{"engine_slug":"postgresql","status":"partial","note":"SHOW timezone; CURRENT_SETTING('timezone')"},{"engine_slug":"mysql","status":"partial","note":"@@session.time_zone, @@global.time_zone"},{"engine_slug":"sqlite","status":"no","note":"no zones; UTC storage with a 'localtime' modifier"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Oracle has two zones and they can disagree: SESSIONTIMEZONE drives CURRENT_TIMESTAMP and LOCALTIMESTAMP, while DBTIMEZONE only sets how TIMESTAMP WITH LOCAL TIME ZONE columns are stored. SYSDATE and SYSTIMESTAMP follow neither; they use the server OS clock.","On MySQL, named zones like 'Europe/London' fail until the time-zone tables are loaded with mysql_tzinfo_to_sql: SET time_zone raises ERROR 1298 and CONVERT_TZ() returns NULL.","SQL Server has no per-session zone: the server's OS zone applies to everything, so zone logic lives in AT TIME ZONE calls instead."],"examples":[{"engine_slug":"oracle","sql":"SELECT SESSIONTIMEZONE, DBTIMEZONE FROM dual;"},{"engine_slug":"postgresql","sql":"SHOW timezone;"},{"engine_slug":"mysql","sql":"SELECT @@session.time_zone, @@global.time_zone;"}],"faqs":[{"question":"Why do two sessions see different CURRENT_TIMESTAMP values?","answer":"The instant is the same; the rendering follows each session's zone. SESSIONTIMEZONE (Oracle) or SHOW timezone (PostgreSQL) tells you which zone is at play."},{"question":"What is the difference between DBTIMEZONE and SESSIONTIMEZONE?","answer":"DBTIMEZONE is the database's storage zone for TIMESTAMP WITH LOCAL TIME ZONE columns; SESSIONTIMEZONE is the connection's display zone."}],"related":["now","sysdate","localtimestamp"],"novel_uses":[{"body":"SET LOCAL timezone lasts until the transaction ends (COMMIT or ROLLBACK), so a migration batch can write UTC wall-clock values into timestamp columns and every later connection keeps its own zone. On timestamptz columns the zone changes only how values display, not the stored instant.","sql":"BEGIN;\nSET LOCAL timezone = 'UTC';\nUPDATE events SET shown_at = now();\nCOMMIT;"},{"body":"MySQL's @@session.time_zone is just a string, so storing it beside a zone-less timestamp records the zone name. A session on the server default stores 'SYSTEM', so also store @@system_time_zone to say which zone that is.","sql":"INSERT INTO stamps (who, written_in_tz)\nVALUES ('batch-7', @@session.time_zone);"}]},"source_url":"https://sqlly.app/sql-functions/session-timezone","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/setseed","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SETSEED function","description":"setseed() pins PostgreSQL's random sequence for repeatable runs; each engine has a different seeding story, and SQLite cannot be seeded at all.","body":{"slug":"setseed","name":"SETSEED","h1":"SQL SETSEED function","category":"math","lede":"Sets the seed for subsequent random() calls in the session, making a random assignment reproducible: setseed(0.5) then random() gives the same series every run.","syntax":"SETSEED(seed)  -- PostgreSQL, seed in [-1, 1]  |  RAND(seed)  -- SQL Server, MySQL  |  DBMS_RANDOM.SEED  -- Oracle","return_type":"void / none","support":[{"engine_slug":"sql-server","status":"partial","note":"No SETSEED; RAND(seed) reseeds the connection's generator, so the RAND() calls that follow repeat the same sequence"},{"engine_slug":"postgresql","status":"yes","note":"setseed(double precision) takes a value between -1 and 1 and applies to the session; usually called via SELECT setseed(0.42)"},{"engine_slug":"mysql","status":"partial","note":"RAND(N) with a constant N restarts its own series, so each run of the statement returns the same per-row values; a plain RAND() in the same statement is not repeatable"},{"engine_slug":"sqlite","status":"no","note":"random() cannot be seeded; reproducibility is impossible in SQLite"},{"engine_slug":"oracle","status":"partial","note":"DBMS_RANDOM.SEED(value) in PL/SQL, not a plain SQL function"}],"gotchas":["PostgreSQL's setseed takes a double between -1 and 1, not an integer: setseed(42) fails with 'setseed parameter 42 is out of allowed range [-1,1]'.","A seed buys reproducibility, not security: knowing the seed predicts every value. Tokens and keys need the crypto functions, seeded or not.","SQL Server's RAND() is evaluated once per query regardless; seeding changes which value all rows share, it does not make rows differ."],"examples":[{"engine_slug":"postgresql","sql":"SELECT setseed(0.42);\nSELECT random() FROM generate_series(1, 3);  -- same three values every run"},{"engine_slug":"sql-server","sql":"SELECT RAND(42), RAND(), RAND();  -- the same three values every time this runs"},{"engine_slug":"mysql","sql":"SELECT id, RAND(42) AS r FROM t;  -- same per-row values on every run"},{"engine_slug":"oracle","sql":"BEGIN\n  DBMS_RANDOM.SEED(42);\nEND;\n-- DBMS_RANDOM.VALUE now repeats the same series on every run"}],"faqs":[{"question":"How do I make random() reproducible?","answer":"Seed it: SELECT setseed(0.42) on PostgreSQL before the random query, RAND(42) on SQL Server or MySQL. SQLite has no seeding at all, so its random() cannot be seeded; to replay a draw, store the values it produced."},{"question":"Is a seeded random sequence secure?","answer":"No. A seed makes the sequence fully predictable: that is the point. Anything security-related needs engine-provided cryptographic bytes, not seeded RAND."},{"question":"Why does SETSEED affect other sessions?","answer":"It does not: the seed is per-session on PostgreSQL and per-connection for RAND() on SQL Server. Other users' random() streams are unaffected. With connection pooling, though, a seed set by one request can carry over to the next request on that connection."}],"related":["random","random-per-row","random-bytes"],"novel_uses":[{"body":"Set a different seed before each partition's shuffle and each partition gets its own reproducible order: SELECT setseed(0.42) for partition 1, SELECT setseed(0.43) for partition 2, then the random() assignment for that partition. Reusing one seed gives equal-size partitions identical orders. Same input, same assignment, every run.","sql":"SELECT setseed(0.42);"},{"body":"Commit to the seed before the draw, for example by publishing its hash or using a public number that did not exist yet, then reveal it afterwards. Anyone can re-run the seeded query and get the same winner. The draw is checkable without trusting the runner, because the runner could not pick the seed after seeing the result.","sql":"SELECT setseed(0.123456);\nSELECT g AS ticket FROM generate_series(1, 10) g ORDER BY random() LIMIT 1;"}]},"source_url":"https://sqlly.app/sql-functions/setseed","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sha1","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SHA1 function","description":"How SHA1 and SHA hashing work in MySQL, PostgreSQL's digest and HASHBYTES and STANDARD_HASH elsewhere: hex output, deprecation for security and SHA upgrades.","body":{"slug":"sha1","name":"SHA1","h1":"SQL SHA1 function","category":"string","lede":"In MySQL, returns the 160-bit SHA-1 hash of a string as a 40-character hex digest. Other engines return the 20 raw bytes.","syntax":"SHA1(string)  |  SHA(string)  |  HASHBYTES('SHA1', value)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"HASHBYTES('SHA1', value), deprecated since SQL Server 2016."},{"engine_slug":"postgresql","status":"no","note":"No built-in SHA-1; digest(value, 'sha1') from pgcrypto."},{"engine_slug":"mysql","status":"yes","note":"SHA1 and its alias SHA are built in."},{"engine_slug":"sqlite","status":"no","note":"No SHA1 in the SQLite library. The sqlite3 shell (3.51.0) adds sha1(), sha1_query() and sha1b()."},{"engine_slug":"oracle","status":"partial","note":"STANDARD_HASH(value, 'SHA1')."}],"gotchas":["SHA-1 collisions have been demonstrated since 2017, so it is retired for signatures and certificates. For non-adversarial checksums it still works where compatibility requires it.","MySQL returns 40 lowercase hex characters; SQL Server's HASHBYTES and Oracle's STANDARD_HASH return 20 raw bytes that need CONVERT(..., 2) or RAWTOHEX to display.","For new work prefer SHA-256: MySQL's SHA2(str, 256), PostgreSQL's sha256(convert_to(v, 'UTF8')) (sha256 takes bytea, not text), HASHBYTES('SHA2_256', v) and STANDARD_HASH(v, 'SHA256')."],"examples":[{"engine_slug":"mysql","sql":"SELECT SHA1('hello') AS digest;  -- aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"},{"engine_slug":"postgresql","sql":"SELECT encode(digest('hello', 'sha1'), 'hex') AS digest;  -- needs pgcrypto"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(40), HASHBYTES('SHA1', 'hello'), 2) AS digest;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(STANDARD_HASH('hello', 'SHA1')) AS digest\nFROM dual;"}],"faqs":[{"question":"Is SHA1 the same as SHA-1?","answer":"Yes. MySQL names the function SHA1 and also accepts SHA; the algorithm is the 160-bit SHA-1 standard."},{"question":"Should I use SHA1 or SHA2 for new code?","answer":"SHA-2, usually SHA-256. SHA-1 collisions are practical, so anything security-adjacent should move."},{"question":"How do I get SHA1 in PostgreSQL?","answer":"With pgcrypto: CREATE EXTENSION pgcrypto; then encode(digest(value, 'sha1'), 'hex'). PostgreSQL 11+ has sha224, sha256, sha384 and sha512 built in, but not SHA-1."}],"related":["sha2","md5","hashbytes","hex"],"novel_uses":[{"body":"Old systems that keyed rows by SHA-1 keep working: computing the same digest in MySQL lets new tables join against the legacy keys without a backfill.","sql":"SELECT * FROM legacy_index l\nJOIN imports i ON l.key = UPPER(SHA1(i.payload));"},{"body":"The first eight hex characters of a digest make a stable short id in PostgreSQL: same content, same slug, and no sequence to keep in sync across environments. Eight hex characters are 32 bits, so two titles collide with about even odds near 77,000 rows: add a UNIQUE constraint or use a longer prefix.","sql":"SELECT LEFT(encode(digest(title, 'sha1'), 'hex'), 8) AS slug\nFROM articles;"}]},"source_url":"https://sqlly.app/sql-functions/sha1","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sha2","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SHA2 function","description":"How SHA2 hashes with a chosen digest size in MySQL and the SHA-256 equivalents in PostgreSQL, SQL Server and Oracle: hex output, invalid sizes, and password limits.","body":{"slug":"sha2","name":"SHA2","h1":"SQL SHA2 function","category":"string","lede":"Returns the SHA-2 family hash of a string using the requested digest length.","syntax":"SHA2(string, digest_length)  |  digest lengths: 224, 256, 384, 512 (0 = 256)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"HASHBYTES('SHA2_256' or 'SHA2_512', value); 'SHA2_224' and 'SHA2_384' return NULL, not an error."},{"engine_slug":"postgresql","status":"partial","note":"sha224(), sha256(), sha384() and sha512() are built in from PostgreSQL 11."},{"engine_slug":"mysql","status":"yes","note":"SHA2(str, n) is built in."},{"engine_slug":"sqlite","status":"no","note":"No SHA2 built in."},{"engine_slug":"oracle","status":"partial","note":"STANDARD_HASH(value, 'SHA256'), also SHA384 and SHA512."}],"gotchas":["MySQL's second argument must be 224, 256, 384, 512 or 0 (meaning 256). Any other value returns NULL rather than raising an error.","MySQL returns lowercase hex, twice the digest size in characters: 64 for SHA-256, 128 for SHA-512. PostgreSQL's sha256() returns bytea; wrap it in encode(..., 'hex'). SQL Server's CONVERT(..., 2) returns uppercase hex; wrap it in LOWER(...) to match.","SHA-2 is still fast, so it is not password storage on its own; use a slow salted function (bcrypt, scrypt, Argon2) in application code."],"examples":[{"engine_slug":"mysql","sql":"SELECT SHA2('hello', 256) AS digest;"},{"engine_slug":"postgresql","sql":"SELECT encode(sha256('hello'), 'hex') AS digest;"},{"engine_slug":"sql-server","sql":"SELECT LOWER(CONVERT(varchar(64), HASHBYTES('SHA2_256', 'hello'), 2)) AS digest;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(STANDARD_HASH('hello', 'SHA256')) AS digest\nFROM dual;"}],"faqs":[{"question":"What does the second argument of SHA2 mean?","answer":"The digest length in bits. SHA2(str, 256) is SHA-256; the choice changes both the output length and the collision resistance."},{"question":"Is SHA2 suitable for password hashing?","answer":"Not alone. It is fast and unsalted, so GPU cracking wins. Use bcrypt, scrypt or Argon2 with a salt, computed outside the database."},{"question":"How do I hash a file's contents in SQL?","answer":"Load the bytes as a binary or blob value and hash that: MySQL's SHA2 accepts binary strings, PostgreSQL's sha256 takes bytea, and SQL Server's HASHBYTES takes varbinary(max)."}],"related":["sha1","md5","hashbytes","hex"],"novel_uses":[{"body":"Hashing every row to answer one equality test is wasted work; store SHA2(body, 256) at write time and queries compare digests instead of scanning the blobs.","sql":"SELECT * FROM documents\nWHERE content_hash = SHA2('hello', 256);"},{"body":"Hash the ordered concatenation in the query, then hash the downloaded file the same way: matching digests prove the export arrived complete. Raise group_concat_max_len first or a truncated string hashes quietly.","sql":"SELECT SHA2(GROUP_CONCAT(body ORDER BY id SEPARATOR ''), 256) AS file_digest\nFROM docs;"}]},"source_url":"https://sqlly.app/sql-functions/sha2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sign","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SIGN function","description":"SIGN in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: -1, 0 or 1 from any number, for classifying deltas and replacing small CASE expressions.","body":{"slug":"sign","name":"SIGN","h1":"SQL SIGN function","category":"math","lede":"Returns -1, 0 or 1 depending on the input's sign. Applied to a difference, it says behind, level or ahead.","syntax":"SIGN(number)","return_type":"-1, 0 or 1, in the input's type on SQL Server and PostgreSQL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The value is always -1, 0 or 1, but the type can follow the input: SIGN(-19.5) is -1.0 (decimal) on SQL Server and a numeric on PostgreSQL, and an integer on MySQL and SQLite.","SIGN of NULL is NULL, not 0.","SIGN is a core function in SQLite, available even in builds without the math functions.","SUM(SIGN(actual - target)) is rows ahead minus rows behind. To count rows ahead, use SUM(CASE WHEN actual > target THEN 1 ELSE 0 END)."],"examples":[{"engine_slug":"all","sql":"SELECT SIGN(-19.5) AS direction;  -- -1"},{"engine_slug":"all","sql":"SELECT region, SIGN(actual - target) AS direction, COUNT(*) AS reps\nFROM quotas\nGROUP BY region, SIGN(actual - target);"}],"faqs":[{"question":"What does SIGN(0) return?","answer":"0. SIGN returns -1, 0 or 1, and only returns NULL when the input is NULL."},{"question":"How do SIGN and ABS relate?","answer":"ABS keeps the magnitude and SIGN keeps the direction, and multiplying them gives the original number back: SIGN(x) * ABS(x) = x."}],"related":["abs","case","mod"],"novel_uses":[{"body":"MIN(SIGN(actual - target)) = 1 means every row beat target; MAX = -1 means at least one missed. Reading the two aggregates together tells you whether a group is uniformly ahead, uniformly behind or split, with no CASE chain.","sql":"SELECT MIN(SIGN(actual - target)) AS worst,\n       MAX(SIGN(actual - target)) AS best,\n       COUNT(*) AS rows_checked\nFROM quotas;"},{"body":"Deltas spanning -3 to -50000 flatten into invisibility on a linear chart. SIGN(x) * LN(1 + ABS(x)) keeps the sign while compressing magnitude, the signed-log transform visualization tools apply; computing it in SQL fixes the dashboard at the source. PostgreSQL spells the natural log LN; MySQL and SQL Server use LOG.","sql":"SELECT day, SIGN(delta) * LN(1 + ABS(delta)) AS signed_log\nFROM daily_deltas;"}]},"source_url":"https://sqlly.app/sql-functions/sign","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/signed-unsigned","corpus":"sql-functions","engine":null,"language":"en","title":"SQL CAST to SIGNED","description":"MySQL's CAST(... AS SIGNED) and CAST(... AS UNSIGNED): MySQL's only integer cast targets, prefix parsing with warnings, and unsigned wrap-around below zero.","body":{"slug":"signed-unsigned","name":"SIGNED / UNSIGNED","h1":"SQL CAST to SIGNED","category":"conversion","lede":"CAST('42' AS SIGNED) parses text into a 64-bit integer. These are MySQL's only integer cast targets: CAST(x AS INT) is a syntax error there.","syntax":"CAST(expression AS SIGNED)  |  CAST(expression AS UNSIGNED)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"no SIGNED/UNSIGNED targets; use INT or BIGINT"},{"engine_slug":"postgresql","status":"no","note":"no unsigned integer types; use integer or bigint"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"SIGNED and UNSIGNED parse but only set NUMERIC affinity: CAST('2.7' AS SIGNED) is 2.7; use CAST(... AS INTEGER)"},{"engine_slug":"oracle","status":"no","note":"use NUMBER or INTEGER"}],"gotchas":["CAST('42abc' AS SIGNED) parses the leading numeric prefix and returns 42 with a warning; CAST('abc' AS SIGNED) returns 0. Validate imports before trusting the cast.","Casting a negative number to UNSIGNED wraps instead of failing: CAST(-1 AS UNSIGNED) is 18446744073709551615, in strict mode too. Arithmetic is different: CAST(1 AS UNSIGNED) - 2 raises 'BIGINT UNSIGNED value is out of range'.","Fractions round, not truncate: CAST(2.5 AS SIGNED) is 3 and CAST(-2.5 AS SIGNED) is -3. A DOUBLE rounds half to even, so CAST(2.5e0 AS SIGNED) is 2. Text fractions do truncate: CAST('2.7' AS SIGNED) is 2.","No other engine has these targets: SQL Server and PostgreSQL reject them, and SQLite accepts them only as NUMERIC affinity, so CAST('2.7' AS SIGNED) stays 2.7. Unsigned types are MySQL's too, apart from SQL Server's tinyint (0 to 255). The portable spelling is CAST(x AS INTEGER) or BIGINT, which MySQL in turn does not accept."],"examples":[{"engine_slug":"mysql","sql":"SELECT CAST(order_ref AS SIGNED) AS ref\nFROM uploads;"},{"engine_slug":"mysql","sql":"SELECT CAST('42abc' AS SIGNED) AS prefix_parsed;"}],"faqs":[{"question":"Why does 0 - 1 fail on my unsigned column?","answer":"MySQL treats unsigned subtraction below zero as an out-of-range error. Cast an operand to SIGNED, enable the NO_UNSIGNED_SUBTRACTION SQL mode, or store signed values if the result can go negative."},{"question":"How do I get the integer out of '12kg'?","answer":"CAST('12kg' AS SIGNED) gives 12 because MySQL parses the numeric prefix. That convenience does not exist on the other engines; strip the suffix first."}],"related":["cast","cast-truncation","decimal-cast","implicit-conversion"],"novel_uses":[{"body":"INET_ATON('255.255.255.255') returns 4294967295, past the 2147483647 ceiling of a signed INT column but inside INT UNSIGNED. That is four bytes per address instead of up to 16 for a varchar(15), and INET_NTOA reads it straight back. Do not cast the dotted text itself: CAST('10.0.0.1' AS UNSIGNED) parses only the prefix 10.","sql":"SELECT ip_text, CAST(INET_ATON(ip_text) AS UNSIGNED) AS ip_num,\n       INET_NTOA(INET_ATON(ip_text)) AS round_trip\nFROM access_log;"},{"body":"GROUP BY CAST(sku AS SIGNED) collapses '0007', '07' and '7' into a single group, since all three parse to 7. Filter out non-numeric rows first, because 'A1' would parse as 0 and pollute the fold.","sql":"SELECT CAST(sku AS SIGNED) AS sku_num, COUNT(*) AS variants FROM items GROUP BY sku_num;"}]},"source_url":"https://sqlly.app/sql-functions/signed-unsigned","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/similar-to","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SIMILAR TO operator","description":"PostgreSQL's SIMILAR TO mixes LIKE wildcards with regex alternation and repetition, and must match the whole string. When to use it and what other engines offer.","body":{"slug":"similar-to","name":"SIMILAR TO","h1":"SQL SIMILAR TO operator","category":"conditional","lede":"SIMILAR TO is the SQL standard's regex-flavoured LIKE: % and _ still work, and |, *, +, {n} and [...] are added.","syntax":"string SIMILAR TO pattern [ESCAPE char]","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"no SIMILAR TO; REGEXP_LIKE on 2025, LIKE with [ ] classes before"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"no SIMILAR TO; REGEXP or REGEXP_LIKE"},{"engine_slug":"sqlite","status":"partial","note":"no SIMILAR TO; GLOB, or REGEXP where a regexp function is loaded"},{"engine_slug":"oracle","status":"partial","note":"no SIMILAR TO; REGEXP_LIKE"}],"gotchas":["The pattern must match the whole string, as with LIKE: 'abc' SIMILAR TO 'b' is false and '%b%' is true.","A dot is a literal dot, not 'any character': 'abc' SIMILAR TO 'a.c' is false. Use _ for one character.","PostgreSQL turns SIMILAR TO into a POSIX regular expression internally. Beyond simple alternation, the ~ operator with a real regex is easier to read."],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'abc' SIMILAR TO 'a(b|x)c' AS alt, 'abc' SIMILAR TO 'b' AS partial, 'abc' SIMILAR TO '%b%' AS wildcard;  -- t, f, t"},{"engine_slug":"postgresql","sql":"SELECT code FROM (VALUES ('AB-12'), ('ab-12'), ('AB-1x')) AS t(code)\nWHERE code SIMILAR TO '[A-Z]{2}-[0-9]{2}';  -- AB-12"},{"engine_slug":"mysql","sql":"SELECT 'ab-12' REGEXP '^[A-Z]{2}-[0-9]{2}$' AS ci, REGEXP_LIKE('ab-12', '^[A-Z]{2}-[0-9]{2}$', 'c') AS cs;  -- 1, 0"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN 'AB-12' LIKE '[A-Z][A-Z]-[0-9][0-9]' THEN 1 ELSE 0 END AS m,\n       CASE WHEN 'xab-12' LIKE '[A-Z][A-Z]-[0-9][0-9]' THEN 1 ELSE 0 END AS whole_string;  -- 1, 0"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN REGEXP_LIKE('AB-12', '^[A-Z]{2}-[0-9]{2}$') THEN 'y' END AS m FROM dual;  -- y"}],"faqs":[{"question":"SIMILAR TO or ~?","answer":"Use ~ for anything non-trivial: it is a full POSIX regex and does not need to match the whole string. SIMILAR TO only helps when you want LIKE semantics plus alternation."},{"question":"Why does the MySQL REGEXP match lower-case letters?","answer":"MySQL regex matching follows the collation, and the default utf8mb4 collation ignores case, so [A-Z] matches 'a'. Pass 'c' as the match type, as in the example, for a case-sensitive match."}],"related":["like","regexp-like","ilike","glob"],"novel_uses":[{"body":"There is no case-insensitive SIMILAR TO variant: under PostgreSQL's default collations the match is case-sensitive, so 'ABC' SIMILAR TO 'a%' is false. Fold both sides with lower() when the pattern must ignore case.","sql":"SELECT 'ABC' SIMILAR TO 'a%' AS raw, lower('ABC') SIMILAR TO 'a%' AS folded;  -- f, t"},{"body":"A CHECK constraint built on SIMILAR TO moves a format rule into the database, so no writer can store a malformed code. PostgreSQL accepts it directly; other engines express the same rule with LIKE ladders or REGEXP_LIKE.","sql":"ALTER TABLE orders\n  ADD CONSTRAINT chk_code CHECK (code SIMILAR TO '[A-Z]{2}-[0-9]{4}');"}]},"source_url":"https://sqlly.app/sql-functions/similar-to","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/similarity","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SIMILARITY function","description":"How pg_trgm's similarity scores string resemblance from 0 to 1 in PostgreSQL: how trigrams are taken, the % operator and threshold, and GIN or GiST index support.","body":{"slug":"similarity","name":"SIMILARITY","h1":"SQL SIMILARITY function","category":"string","lede":"Scores how alike two strings are, from 0 (unrelated) to 1 (identical), using shared trigrams.","syntax":"similarity(string1, string2)","return_type":"real","support":[{"engine_slug":"sql-server","status":"no","note":"No trigram similarity built in."},{"engine_slug":"postgresql","status":"yes","note":"Requires CREATE EXTENSION pg_trgm."},{"engine_slug":"mysql","status":"no","note":"No trigram similarity; FULLTEXT is word-based."},{"engine_slug":"sqlite","status":"no","note":"No built-in similarity."},{"engine_slug":"oracle","status":"no","note":"No trigram function; UTL_MATCH scores 0-100 by edit distance or Jaro-Winkler."}],"gotchas":["pg_trgm lowercases the strings, splits them into words, pads each word with spaces and compares the sets of three-character windows. Case does not count, and word order does not matter: 'John Smith' and 'smith john' have identical trigram sets.","There is no universal threshold: 0.3 is the % operator's default, but short strings swing widely: similarity('smith', 'smyth') is only 0.33. Tune per dataset.","The % operator can use a GIN or GiST index built with gin_trgm_ops or gist_trgm_ops, and ORDER BY name <-> 'term' needs a GiST index built with gist_trgm_ops; a bare similarity() call in WHERE cannot."],"examples":[{"engine_slug":"postgresql","sql":"SELECT similarity('smith', 'smyth') AS score;  -- 0.33333334"},{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS pg_trgm;\nSELECT * FROM products\nWHERE name % 'ipone'  -- fuzzy match, can use a trigram index\nORDER BY similarity(name, 'ipone') DESC;"}],"faqs":[{"question":"What is the difference between similarity and Levenshtein?","answer":"Levenshtein counts character edits; similarity compares trigram sets. Similarity can use an index and tolerates word swaps, but it says nothing exact about spelling."},{"question":"What does the % operator do in pg_trgm?","answer":"a % b is true when similarity(a, b) is at least pg_trgm.similarity_threshold, 0.3 by default. Unlike the function, it can use a trigram index."},{"question":"Why do short strings score strangely?","answer":"A short string has few trigrams, so one changed letter removes a large share of them. Use a lower threshold for short names and codes, or switch to levenshtein."}],"related":["word-similarity","levenshtein","soundex","difference"],"novel_uses":[{"body":"The % operator compares two columns directly, so a self join with a.id < b.id lists suspected duplicate titles without calling similarity on every pair. This is also the form that can use a trigram index.","sql":"SELECT a.id, b.id\nFROM movies a JOIN movies b ON a.id < b.id AND a.title % b.title;"},{"body":"show_trgm prints the exact three-character windows pg_trgm compares, which explains a surprising score faster than reasoning about the algorithm.","sql":"SELECT show_trgm('smith');"}]},"source_url":"https://sqlly.app/sql-functions/similarity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sin","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SIN function","description":"SIN(x) returns the sine of an angle given in radians. Domain, precision and NULL propagation, plus the degrees-to-radians step everyone forgets.","body":{"slug":"sin","name":"SIN","h1":"SQL SIN function","category":"math","lede":"Returns the sine of an angle expressed in radians: SIN(0) is 0 and SIN(PI()) is about 1.2e-16, not exactly 0.","syntax":"SIN(angle_radians)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Math functions arrived in 3.35.0 behind the SQLITE_ENABLE_MATH_FUNCTIONS compile flag; without it the call fails with 'no such function'"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The argument is radians. Passing degrees without converting, SIN(30), computes the sine of 30 radians, a completely different angle.","SIN(PI()) is about 1.2e-16, not 0: PI() is approximate, so the result of an exact-angle sine is only approximately exact.","NULL in, NULL out: SIN of a NULL argument returns NULL on every engine."],"examples":[{"engine_slug":"postgresql","sql":"SELECT SIN(0) AS zero, SIN(PI()/6) AS half;  -- 0, 0.49999999999999994"},{"engine_slug":"postgresql","sql":"SELECT SIN(RADIANS(angle_deg)) AS sine\nFROM wave_samples;"},{"engine_slug":"sql-server","sql":"SELECT SIN(30 * PI() / 180) AS sine_30;  -- 0.49999999999999994"},{"engine_slug":"mysql","sql":"SELECT SIN(0) AS zero, SIN(PI()/6) AS half;  -- 0, 0.49999999999999994"},{"engine_slug":"sqlite","sql":"SELECT sin(0) AS zero, sin(pi()/6) AS half;  -- 0.0, 0.5 (the double is 0.49999999999999994; the sqlite3 shell prints 0.5)"},{"engine_slug":"oracle","sql":"SELECT SIN(0) AS zero, SIN(1) AS one_radian FROM dual;  -- 0, .84147098..."}],"faqs":[{"question":"Does SIN take degrees or radians?","answer":"Radians, on all five engines. Convert first: SIN(RADIANS(30.0)) or SIN(30 * PI() / 180) gives the sine of 30 degrees, 0.49999999999999994 in doubles. SQL Server's RADIANS returns an integer for an integer argument, so SIN(RADIANS(30)) there is SIN(0) = 0; use 30.0 or CAST(... AS float). Oracle has neither RADIANS nor PI(), so write SIN(30 * ACOS(-1) / 180)."},{"question":"Why is SIN(PI()) not exactly 0?","answer":"PI() is a double approximation of pi, so PI() is not exactly the angle whose sine is zero. The result is about 1.2e-16: effectively zero, but not literally."},{"question":"What does SIN return for NULL input?","answer":"NULL. Every trig function propagates NULL, so rows with missing angles simply come back NULL rather than erroring."}],"related":["cos","tan","radians","pi"],"novel_uses":[{"body":"On PostgreSQL, SIN(gs * 2 * PI() / 24) over generate_series returns a smooth hourly seasonality curve in one statement, which INSERT ... SELECT can load into a test table. Change 24 to 7 for weekly cycles.","sql":"SELECT SIN(gs * 2 * PI() / 24.0) AS hour_wave FROM generate_series(1, 24) AS gs;"},{"body":"For a pipeline or conveyor of length L at pitch p, the rise is L * SIN(RADIANS(p)). Survey tables store length and pitch, so this computes elevation change without exporting to a calculator.","sql":"SELECT length_m * SIN(RADIANS(CAST(pitch_deg AS float))) AS rise_m FROM tunnel_runs;"}]},"source_url":"https://sqlly.app/sql-functions/sin","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sinh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SINH function","description":"SINH(x) is the hyperbolic sine, (e^x - e^-x)/2. PostgreSQL 12+, SQLite and Oracle have it; SQL Server and MySQL need the EXP identity.","body":{"slug":"sinh","name":"SINH","h1":"SQL SINH function","category":"math","lede":"Returns the hyperbolic sine: SINH(0) is 0 and SINH(1) is about 1.1752, growing exponentially for large inputs.","syntax":"SINH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; compute (EXP(x) - EXP(-x)) / 2.0"},{"engine_slug":"postgresql","status":"yes","note":"Added in PostgreSQL 12; 11 and older raise function sinh does not exist"},{"engine_slug":"mysql","status":"no","note":"MySQL has no SINH, still absent in 8.4; compute (EXP(x) - EXP(-x)) / 2.0"},{"engine_slug":"sqlite","status":"yes","note":"In the 3.35 math set; requires the SQLITE_ENABLE_MATH_FUNCTIONS build flag"},{"engine_slug":"oracle","status":"yes","note":"Oracle ships SINH for NUMBER input"}],"gotchas":["SINH grows exponentially and overflows the double range just past x = 710.48, a little after EXP does near x = 709.78.","The identity SINH(x) = (EXP(x) - EXP(-x)) / 2 is the fallback on SQL Server and MySQL, neither of which has hyperbolic functions. It errors once EXP overflows, past about x = 709.78, though native SINH stays finite up to 710.48.","Hyperbolic functions are not periodic: no [-1, 1] bound and no radians/degrees question; the input is a plain number."],"examples":[{"engine_slug":"postgresql","sql":"SELECT SINH(0) AS zero, SINH(1) AS one;  -- 0, 1.1752011936438014"},{"engine_slug":"sql-server","sql":"SELECT (EXP(1.0) - EXP(-1.0)) / 2.0 AS sinh_one;  -- 1.1752"},{"engine_slug":"postgresql","sql":"SELECT SINH(x) AS hyperbolic_sine FROM curve_points;"},{"engine_slug":"sqlite","sql":"SELECT sinh(0) AS zero, sinh(1) AS one;  -- 0.0, 1.1752011936438"},{"engine_slug":"oracle","sql":"SELECT SINH(0) AS zero, SINH(1) AS one FROM dual;  -- 0, 1.1752011936438014..."}],"faqs":[{"question":"Which engines have SINH?","answer":"PostgreSQL (12+), SQLite (3.35+) and Oracle. SQL Server and MySQL have no hyperbolic functions; use (EXP(x) - EXP(-x)) / 2.0."},{"question":"Is SINH the same as SIN?","answer":"No. Sine is periodic and bounded; hyperbolic sine grows exponentially and is unbounded. The name comes from the unit hyperbola playing the role the unit circle plays for SIN."},{"question":"Does SINH overflow?","answer":"Yes, just past x = 710.48, where the result exceeds the double range. PostgreSQL 18 and SQLite return Infinity rather than raising an error."}],"related":["exp","cosh","tanh"],"novel_uses":[{"body":"Run native SINH beside the EXP identity on PostgreSQL once: when the two agree to 1e-9, the identity is safe to carry into SQL Server or MySQL, which lack SINH, for inputs below about 709.78. An absolute 1e-9 test false-alarms from about x = 16.7 on, where rounding alone exceeds it. One query retires the whole rewrite risk.","sql":"SELECT x, SINH(x) AS native, (EXP(x) - EXP(-x)) / 2.0 AS emulated FROM (SELECT 1.0::float8 AS x) v;"},{"body":"ABS(SINH(asinh_encoded) - original) > 1e-9 flags rows where a symmetric-log encode and decode disagree, which catches a mismatched pair of expressions copied between services. On PostgreSQL or SQLite the round trip is not bit-exact: about three in four values come back off by a few ulps, but the error stays under 6e-14 for inputs up to about 100, far below the 1e-9 threshold.","sql":"SELECT id FROM staging WHERE ABS(SINH(encoded) - original) > 1e-9;"}]},"source_url":"https://sqlly.app/sql-functions/sinh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sleep","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SLEEP, pg_sleep and WAITFOR DELAY","description":"Make a session wait: SLEEP() in MySQL, pg_sleep() in PostgreSQL, WAITFOR DELAY in SQL Server and DBMS_SESSION.SLEEP in Oracle. Useful for testing timeouts and locks.","body":{"slug":"sleep","name":"SLEEP","h1":"SQL SLEEP, pg_sleep and WAITFOR DELAY","category":"system","lede":"A deliberate pause is handy for reproducing lock waits, testing client timeouts and spacing out batch jobs.","syntax":"SLEEP(seconds)  |  pg_sleep(seconds)  |  WAITFOR DELAY 'hh:mm:ss'  |  DBMS_SESSION.SLEEP(seconds)","return_type":"0 (MySQL), void (PostgreSQL)","support":[{"engine_slug":"sql-server","status":"partial","note":"WAITFOR DELAY 'hh:mm:ss[.mmm]', a statement, not a function"},{"engine_slug":"postgresql","status":"partial","note":"pg_sleep(seconds); pg_sleep_for(interval) and pg_sleep_until(timestamp)"},{"engine_slug":"mysql","status":"yes","note":"SLEEP(seconds) returns 0, or 1 when interrupted"},{"engine_slug":"sqlite","status":"no","note":"none in SQL; sqlite3_sleep() is a C API call"},{"engine_slug":"oracle","status":"partial","note":"DBMS_SESSION.SLEEP(seconds) in PL/SQL from 18c; DBMS_LOCK.SLEEP before that"}],"gotchas":["A sleeping session keeps its transaction and locks. Sleep inside a transaction and every writer waiting for those rows waits as well.","MySQL evaluates SLEEP once per row: SELECT SLEEP(1) FROM t with ten rows takes about ten seconds.","WAITFOR DELAY takes a time string, not a number: WAITFOR DELAY '00:00:05' waits five seconds."],"examples":[{"engine_slug":"mysql","sql":"SELECT SLEEP(0.5) AS slept;  -- 0, after half a second"},{"engine_slug":"postgresql","sql":"SELECT pg_sleep_for('500 milliseconds');"},{"engine_slug":"sql-server","sql":"WAITFOR DELAY '00:00:00.500';\nSELECT 'done' AS status;"},{"engine_slug":"oracle","sql":"BEGIN\n  DBMS_SESSION.SLEEP(0.5);\nEND;\n/"}],"faqs":[{"question":"Why would you sleep inside SQL?","answer":"To hold a lock while you test what another session does, to check that an application's query timeout fires, or to throttle a loop that deletes in batches."},{"question":"How do I pause in SQLite?","answer":"Not from SQL. Sleep in the host program between statements, or call sqlite3_sleep() from C."}],"related":["clock-timestamp","connection-id","now"],"novel_uses":[{"body":"WAITFOR TIME '02:00' waits until the wall clock reaches 2am, not for two hours. A batch that starts late still fires its work at the intended moment, which a DELAY computed at start time would miss.","sql":"WAITFOR TIME '02:00';\nSELECT 'past two' AS status;"},{"body":"Oracle's older DBMS_LOCK.SLEEP needs EXECUTE granted on DBMS_LOCK, which many schemas never get, so the call fails with PLS-00201. DBMS_SESSION.SLEEP, from 18c, runs without that grant, which makes it the drop-in for report scripts.","sql":"BEGIN\n  DBMS_SESSION.SLEEP(1);\nEND;\n/"},{"body":"A MySQL procedure can pace its own batch: SLEEP(0.1) between DELETE rounds caps the pressure on replicas without a scheduler or an application loop, at the cost of holding the connection the whole time.","sql":"DELIMITER //\nCREATE PROCEDURE purge_old()\nBEGIN\n  DECLARE done INT DEFAULT 0;\n  REPEAT\n    DELETE FROM events WHERE created < NOW() - INTERVAL 90 DAY LIMIT 1000;\n    SET done = ROW_COUNT() = 0;\n    DO SLEEP(0.1);\n  UNTIL done END REPEAT;\nEND//\nDELIMITER ;"}]},"source_url":"https://sqlly.app/sql-functions/sleep","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/smalldatetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SMALLDATETIME type","description":"SQL Server's smalldatetime: 4-byte storage that silently rounds seconds to the nearest minute. What breaks, and why datetime2 replaced it.","body":{"slug":"smalldatetime","name":"SMALLDATETIME","h1":"SQL SMALLDATETIME type","category":"datetime","lede":"A compact 4-byte type storing minutes only: seconds are dropped on assignment by rounding, not truncation.","syntax":"CAST(value AS SMALLDATETIME)","return_type":"smalldatetime","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Rounding is to the nearest minute: from a string of up to milliseconds or from a datetime, 29.998 seconds or less rounds down and 29.999 or more rounds up, so 10:29:29.998 becomes 10:29 and 10:29:29.999 becomes 10:30. A datetime2 source rounds up only from 30 seconds.","Range is 1900-01-01 through 2079-06-06, fine for business data, a real limit for birthdates of the very old or far-future schedules.","No seconds means joins and comparisons are minute-grained; equality checks that 'worked' on smalldatetime break when columns move to datetime2 with real seconds."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST('2026-08-01 10:29:31' AS SMALLDATETIME);  -- 2026-08-01 10:30"},{"engine_slug":"sql-server","sql":"SELECT CAST(SYSDATETIME() AS SMALLDATETIME);"}],"faqs":[{"question":"Why does anyone still use smalldatetime?","answer":"Legacy schemas and 4-byte storage. New tables should use datetime2(0): 6 bytes, whole seconds, years 0001-9999, and no rounding to the minute."},{"question":"How do I mimic smalldatetime rounding elsewhere?","answer":"PostgreSQL: date_trunc('minute', d + interval '30.001 seconds'), which rounds 29.999 seconds up as SQL Server does. Oracle: ROUND(d, 'MI') rounds to the nearest minute, but its 29.999-second behavior was not verified here."}],"related":["sysdatetime","datetimeoffset","cast","datetrunc"],"novel_uses":[{"body":"Columns that should never hold seconds, like appointment slots, can use smalldatetime as an enforced invariant rather than an application-side rule.","sql":"CREATE TABLE slots (starts_at SMALLDATETIME NOT NULL);"},{"body":"A query against sys.columns and sys.types lists every smalldatetime column, the first step of any migration plan.","sql":"SELECT OBJECT_SCHEMA_NAME(c.object_id), OBJECT_NAME(c.object_id), c.name FROM sys.columns c JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE t.name = 'smalldatetime';"},{"body":"Migrating to datetime2(0) preserves every stored value exactly: every smalldatetime value is a whole minute, which datetime2(0) holds unchanged, and datetime2's range covers all of smalldatetime's.","sql":"ALTER TABLE slots ALTER COLUMN starts_at datetime2(0);"}]},"source_url":"https://sqlly.app/sql-functions/smalldatetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/soundex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SOUNDEX function","description":"SOUNDEX encodes a name by how it sounds in English (Robert and Rupert share a code) on SQL Server, MySQL and Oracle, fuzzystrmatch on PostgreSQL.","body":{"slug":"soundex","name":"SOUNDEX","h1":"SQL SOUNDEX function","category":"string","lede":"Maps a string to a phonetic code so similarly pronounced names compare equal. SQL Server codes are always four characters; MySQL codes can run longer. Built for English surnames in the early 1900s, and still shipped by most engines.","syntax":"SOUNDEX(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"via the fuzzystrmatch extension"},{"engine_slug":"mysql","status":"yes","note":"codes for long names run past four characters"},{"engine_slug":"sqlite","status":"no","note":"only when compiled with SQLITE_SOUNDEX (usually off)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The algorithm is English-centric: it codes consonant sounds after the first letter and collapses repeats. Non-English names produce unreliable codes.","On SQL Server codes pad or truncate to one letter plus three digits, so Smith and Smyth match (S530) but also unrelated short names collide. SQL Server returns 0000 for an empty string, not a letter plus digits, and NULL for NULL input. MySQL does not truncate: SOUNDEX('Quadratically') is Q36324, so compare LEFT(SOUNDEX(x), 4) against codes from other systems.","PostgreSQL needs CREATE EXTENSION fuzzystrmatch; SQLite ships the function only when built with SQLITE_SOUNDEX, which most builds skip.","For serious fuzzy matching, levenshtein distances or trigram indexes (pg_trgm) are usually a better fit than SOUNDEX for serious fuzzy matching."],"examples":[{"engine_slug":"mysql","sql":"SELECT SOUNDEX('Robert') AS r1, SOUNDEX('Rupert') AS r2;\n-- R163, R163"},{"engine_slug":"sql-server","sql":"SELECT SOUNDEX('Smith') AS s1, SOUNDEX('Smyth') AS s2;\n-- S530, S530"},{"engine_slug":"oracle","sql":"SELECT SOUNDEX('Smith') AS s1, SOUNDEX('Smyth') AS s2 FROM dual;  -- S530, S530"},{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;\nSELECT soundex('Smith') AS s1, soundex('Smyth') AS s2;  -- S530, S530"}],"faqs":[{"question":"When do two names share a SOUNDEX code?","answer":"When their consonant sounds map to the same digits after the first letter: Smith/Smyth (S530), Robert/Rupert (R163). Spelling differences that change sounds do change the code."},{"question":"Is SOUNDEX good for name deduplication?","answer":"As a cheap first pass, yes; as the only check, no. Its false positives and English bias are well known. Combine with a Levenshtein threshold or trigram similarity."},{"question":"Why is SOUNDEX missing in my PostgreSQL install?","answer":"It lives in the fuzzystrmatch extension: CREATE EXTENSION fuzzystrmatch; then soundex('Robert') works."}],"related":["difference","case-insensitive-collation","string-sort"],"novel_uses":[{"body":"ORDER BY SOUNDEX(last_name), last_name lands Smith and Smyth next to each other in a review sheet, which turns a dedupe problem into a scan.","sql":"SELECT last_name, phone FROM users ORDER BY SOUNDEX(last_name), last_name;"},{"body":"A persisted computed column on SOUNDEX(last_name) with an index turns phonetic lookups from full scans into seeks, since SOUNDEX is deterministic.","sql":"ALTER TABLE users ADD name_code AS SOUNDEX(last_name) PERSISTED;\nCREATE INDEX ix_users_name_code ON users (name_code);"}]},"source_url":"https://sqlly.app/sql-functions/soundex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/space","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SPACE function","description":"SPACE(n) returns n space characters on SQL Server and MySQL, the readable shortcut inside concatenation, with NULL edge cases on negative counts.","body":{"slug":"space","name":"SPACE","h1":"SQL SPACE function","category":"string","lede":"Builds a run of spaces for padding and alignment inside string expressions, so 'a' + SPACE(3) + 'b' reads better than a magic literal.","syntax":"SPACE(n)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"SPACE is shorthand for REPLICATE(' ', n)"},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":"SPACE(0) and negative counts return an empty string"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["SQL Server returns NULL for a negative count, so a computed width can silently blank out a whole expression; clamp it with CASE (GREATEST exists only on SQL Server 2022 and later).","PostgreSQL has repeat(' ', n); Oracle has RPAD(' ', n); SQLite has neither: printf('%*s', n, '') or literal padding.","Trailing spaces are invisible in result grids, and SQL Server's LEN does not count them: LEN(SPACE(3)) is 0 while DATALENGTH is 3. Padding at the end of a value is easy to lose track of.","For repeated non-space fills, REPLICATE (SQL Server) or REPEAT (MySQL, PostgreSQL) take any string."],"examples":[{"engine_slug":"sql-server","sql":"SELECT 'a' + SPACE(3) + 'b' AS gapped;  -- a   b"},{"engine_slug":"mysql","sql":"SELECT CONCAT('a', SPACE(3), 'b') AS gapped;  -- a   b"}],"faqs":[{"question":"Is SPACE(n) the same as REPLICATE(' ', n)?","answer":"Yes on SQL Server; it returns the same value. The value is readability: the intent survives review better than a magic number of quoted spaces."},{"question":"Why did my SPACE call return NULL?","answer":"A negative n on SQL Server yields NULL, which then poisons the whole + expression. Clamp computed widths to zero or above."},{"question":"Does PostgreSQL have SPACE?","answer":"No. Use repeat(' ', n). Of the engines in this reference, MySQL and SQL Server have a SPACE function."}],"related":["replicate","btrim","zero-pad"],"novel_uses":[{"body":"Padding to a declared width with name + SPACE(20 - LEN(name)) writes banking-style fixed-width records straight from a SELECT; the CASE guard keeps the count from going negative.","sql":"SELECT name + SPACE(CASE WHEN LEN(name) < 20 THEN 20 - LEN(name) ELSE 0 END) AS padded\nFROM items;"},{"body":"SPACE(depth * 2) + name prints an outline that mirrors hierarchy, which makes recursive-structure dumps readable without any client formatting.","sql":"SELECT SPACE(depth * 2) + name AS outline FROM nodes ORDER BY path;"}]},"source_url":"https://sqlly.app/sql-functions/space","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/split-part","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SPLIT_PART function","description":"Get the nth field of a delimited string: SPLIT_PART in PostgreSQL, STRING_SPLIT and SUBSTRING_INDEX elsewhere, and what each engine does instead of a direct equivalent.","body":{"slug":"split-part","name":"SPLIT_PART","h1":"SQL SPLIT_PART function","category":"string","lede":"Returns one field of a delimiter-separated string by position. Only PostgreSQL has it built in; the other engines get there with table-valued splitters, SUBSTRING_INDEX or regexes.","syntax":"SPLIT_PART(string, delimiter, field_number)  -- PostgreSQL","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"STRING_SPLIT (2016+) returns rows; its ordinal column (2022+) picks the nth"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"SUBSTRING_INDEX with nesting: SUBSTRING_INDEX(SUBSTRING_INDEX(s, ',', 2), ',', -1)"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"REGEXP_SUBSTR(s, '[^,]+', 1, n) picks the nth match"}],"gotchas":["SPLIT_PART is 1-based: field 1 is the first piece. An out-of-range field returns an empty string rather than an error, and from PostgreSQL 14 a negative field counts from the end: SPLIT_PART('a-b-c', '-', -1) is 'c'.","MySQL's nested SUBSTRING_INDEX works in two steps: the inner call keeps the first n pieces, the outer call takes the last piece of that.","SQL Server's STRING_SPLIT makes no promise about row order unless you pass the third enable_ordinal argument (SQL Server 2022+), which adds an ordinal column. Before 2022, numbering the rows with ROW_NUMBER is not reliable.","Oracle's REGEXP_SUBSTR(s, '[^,]+', 1, n) skips empty fields: for 'a,,c' field 2 comes back as 'c', not ''."],"examples":[{"engine_slug":"postgresql","sql":"SELECT SPLIT_PART('a-b-c', '-', 2) AS part;  -- b"},{"engine_slug":"mysql","sql":"SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('a-b-c', '-', 2), '-', -1) AS part;  -- b"},{"engine_slug":"sql-server","sql":"-- SQL Server 2022+: the third argument adds the ordinal column\nSELECT value FROM STRING_SPLIT('a-b-c', '-', 1)\nWHERE ordinal = 2;  -- b"},{"engine_slug":"oracle","sql":"-- REGEXP_SUBSTR picks the nth match\nSELECT REGEXP_SUBSTR('a-b-c', '[^-]+', 1, 2) AS part FROM dual;  -- b"}],"faqs":[{"question":"Does SQL Server have SPLIT_PART?","answer":"No. STRING_SPLIT (2016+) breaks the string into rows. On SQL Server 2022+, pass 1 as the third argument and filter on the ordinal column. On older versions, JSON_VALUE on a string rebuilt as a JSON array, or CHARINDEX arithmetic, gives a reliable position."},{"question":"How do I split a string into rows?","answer":"PostgreSQL: unnest(string_to_array(s, ',')). SQL Server: STRING_SPLIT. MySQL: a numbers table with SUBSTRING_INDEX. SQLite: json_each on a JSON-encoded array, or a recursive CTE."}],"related":["instr","substring","regexp-replace"],"novel_uses":[{"body":"The LEFT-and-INSTR pattern produces a -1 offset when the delimiter is missing. SPLIT_PART('ABC', '-', 1) just returns ABC, so prefix extraction needs no guard. From PostgreSQL 14 a negative field counts from the end the same way.","sql":"SELECT SPLIT_PART(reference, '-', 1) AS family\nFROM products;"},{"body":"Splitting 2026-08-01 on - gives year, month and day with no parsing functions at all, handy for quick checks on raw text columns. CAST each piece when arithmetic needs numbers.","sql":"SELECT SPLIT_PART(d, '-', 1) AS yr,\n       SPLIT_PART(d, '-', 2) AS mo,\n       SPLIT_PART(d, '-', 3) AS dy\nFROM raw_dates;"}]},"source_url":"https://sqlly.app/sql-functions/split-part","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sql-server-2022-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server 2022 IGNORE NULLS","description":"SQL Server 2022 added IGNORE NULLS / RESPECT NULLS for LAG, LEAD, FIRST_VALUE and LAST_VALUE, and the named WINDOW clause.","body":{"slug":"sql-server-2022-window","name":"SQL Server 2022 Window Additions","h1":"SQL Server 2022 IGNORE NULLS","category":"window","lede":"LAG, LEAD, FIRST_VALUE and LAST_VALUE gained IGNORE NULLS in SQL Server 2022, which makes forward fill a single window call.","syntax":"FIRST_VALUE(x) IGNORE NULLS OVER (ORDER BY id) | LAST_VALUE(x) IGNORE NULLS OVER (...)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"yes","note":"2022+ and Azure SQL; earlier versions reject the keyword"},{"engine_slug":"postgresql","status":"no","note":"not supported through PostgreSQL 18"},{"engine_slug":"mysql","status":"no","note":"not supported"},{"engine_slug":"sqlite","status":"no","note":"not supported"},{"engine_slug":"oracle","status":"yes","note":"long-standing support; accepts the SQL Server placement and also x IGNORE NULLS inside the parentheses"}],"gotchas":["SQL Server accepts IGNORE NULLS only after the closing parenthesis: FIRST_VALUE(x) IGNORE NULLS OVER (...). FIRST_VALUE(x IGNORE NULLS) is an Oracle spelling and fails here; Oracle accepts both.","On LAG and LEAD it means 'the nearest non-NULL row', not 'one row back': LAG(x) IGNORE NULLS OVER (ORDER BY d) is the previous known value. The same 2022 release added the WINDOW clause for naming windows.","Before 2022 (and on every other engine lacking the clause), the COUNT/MAX emulation or a correlated last-non-NULL subquery replaces it."],"examples":[{"engine_slug":"sql-server","sql":"-- forward-fill the last known price\nSELECT day, price,\n       LAST_VALUE(price) IGNORE NULLS OVER (\n         ORDER BY day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS last_known\nFROM prices;"},{"engine_slug":"oracle","sql":"-- Oracle also takes the parenthesised spelling, rejected on SQL Server\nSELECT day, price,\n       LAST_VALUE(price IGNORE NULLS) OVER (\n         ORDER BY day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS last_known\nFROM prices;"}],"faqs":[{"question":"Which SQL Server version added IGNORE NULLS?","answer":"SQL Server 2022 (and Azure SQL). On 2012-2019 the parser rejects the keyword; use the COUNT/MAX emulation or an OUTER APPLY (SELECT TOP 1 ... WHERE x IS NOT NULL ORDER BY d DESC) lookup."},{"question":"Why does my IGNORE NULLS syntax work on Oracle but not SQL Server?","answer":"You wrote it inside the parentheses, LAST_VALUE(x IGNORE NULLS), which only Oracle accepts. Move it after the closing parenthesis, LAST_VALUE(x) IGNORE NULLS OVER (...); that form runs on both."}],"related":["ignore-nulls","sql-server-frame-support","window-versions"],"novel_uses":[{"body":"Audit tables often store a value only when it changes and NULL everywhere else; LAST_VALUE with IGNORE NULLS over a frame ending at CURRENT ROW reconstructs the effective setting on every row. The dense timeline is one SELECT, not an application-side loop.","sql":"SELECT changed_at, server_id,\n       LAST_VALUE(config_value) IGNORE NULLS OVER (\n         PARTITION BY server_id ORDER BY changed_at\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS config_at_that_time\nFROM config_history;"},{"body":"Forward fill with IGNORE NULLS and a CASE on the raw column at the same time, and every filled row says carried while observed rows say observed; rows before the first real value say missing. Reports can then show the fill rate next to the data, which is the number that decides whether anyone trusts it.","sql":"SELECT day, price, price_filled,\n       CASE WHEN price IS NOT NULL THEN 'observed'\n            WHEN price_filled IS NOT NULL THEN 'carried'\n            ELSE 'missing' END AS source\nFROM (\n  SELECT day, price,\n         LAST_VALUE(price) IGNORE NULLS OVER (\n           ORDER BY day\n           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS price_filled\n  FROM prices\n) f;"}]},"source_url":"https://sqlly.app/sql-functions/sql-server-2022-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sql-server-frame-support","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server window frame limitations","description":"SQL Server's frame clause is the most restricted of the five: full ROWS, RANGE without offsets, no GROUPS, no EXCLUDE and no FILTER, even in 2022.","body":{"slug":"sql-server-frame-support","name":"SQL Server Frame Limits","h1":"SQL Server window frame limitations","category":"window","lede":"What SQL Server accepts in a frame, and the concrete rewrites for the constructs it rejects.","syntax":"SUM(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)","return_type":"type of the expression","support":[{"engine_slug":"sql-server","status":"partial","note":"ROWS full; RANGE only UNBOUNDED / CURRENT ROW bounds; no GROUPS, EXCLUDE or FILTER; WINDOW clause from 2022"},{"engine_slug":"postgresql","status":"yes","note":"ROWS, RANGE with offsets, GROUPS, EXCLUDE, FILTER and WINDOW all run (tested PostgreSQL 18.6)"},{"engine_slug":"mysql","status":"partial","note":"ROWS, RANGE with offsets and WINDOW run; GROUPS, EXCLUDE and FILTER are rejected (tested MySQL 8.4.11)"},{"engine_slug":"sqlite","status":"yes","note":"ROWS, RANGE, GROUPS, EXCLUDE, FILTER and WINDOW all run (tested SQLite 3.51.0)"},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["RANGE in SQL Server accepts only UNBOUNDED PRECEDING, CURRENT ROW and UNBOUNDED FOLLOWING as bounds: no numeric offsets, no intervals. Value-band windows need correlated subqueries or self-joins.","No EXCLUDE clause: 'everything except this row' becomes frame-total minus COALESCE(x, 0) on the current row, because a NULL current value makes the raw difference NULL; the window form returns 0 rather than NULL when the current row is the only row. No FILTER clause: conditional aggregates become CASE aggregates.","The WINDOW clause exists only from SQL Server 2022 (database compatibility level 160); on 2019 and earlier every function repeats its OVER (...) inline."],"examples":[{"engine_slug":"sql-server","sql":"-- value-band emulation for missing RANGE offsets\nSELECT a.product, a.price,\n       (SELECT COUNT(*) FROM products b\n        WHERE b.price BETWEEN a.price - 5 AND a.price + 5) AS nearby\nFROM products a;"}],"faqs":[{"question":"Does SQL Server support GROUPS or EXCLUDE frames?","answer":"No, including SQL Server 2022 ('Incorrect syntax near GROUPS'). ROWS works fully; RANGE works only with UNBOUNDED and CURRENT ROW bounds. Rewrite value-band windows as correlated subqueries and exclusions as total-minus-current."},{"question":"Is there a FILTER clause in SQL Server?","answer":"No. SUM(CASE WHEN condition THEN x END) OVER (...) is the replacement and returns the same values, including NULL when no row matches."}],"related":["rows-frame","filter-over","sql-server-2022-window"],"novel_uses":[{"body":"UNBOUNDED bounds and CURRENT ROW are supported, so full-partition FIRST_VALUE and LAST_VALUE queries run fine; only offsets, GROUPS, EXCLUDE and FILTER are missing. Scope the rewrite to the frames SQL Server actually rejects instead of porting everything.","sql":"SELECT trade_day, price,\n       FIRST_VALUE(price) OVER (PARTITION BY symbol ORDER BY trade_day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS period_open,\n       LAST_VALUE(price) OVER (PARTITION BY symbol ORDER BY trade_day\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS period_close\nFROM ticks;"},{"body":"SQL Server accepts RANGE BETWEEN CURRENT ROW AND CURRENT ROW, so COUNT(*) OVER (ORDER BY d RANGE BETWEEN CURRENT ROW AND CURRENT ROW) returns the peer count directly. A grouped count joined back answers the same question without the frame: how many rows share this value. It is the prerequisite for peer-split totals and tie-aware ranks.","sql":"SELECT t.day, t.amount, g.peers\nFROM trades t\nJOIN (\n  SELECT day, COUNT(*) AS peers\n  FROM trades\n  GROUP BY day\n) g ON g.day = t.day;"}]},"source_url":"https://sqlly.app/sql-functions/sql-server-frame-support","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sql-server-padding","corpus":"sql-functions","engine":null,"language":"en","title":"SQL padding in SQL Server","description":"SQL Server has no LPAD or RPAD in any version: the RIGHT/LEFT + REPLICATE and FORMAT idioms that stand in, and how they truncate.","body":{"slug":"sql-server-padding","name":"Padding in SQL Server","h1":"SQL padding in SQL Server","category":"string","lede":"Every pad idiom on SQL Server is a two-step: build the fill, then slice to width. Learn the two patterns and their silent truncation.","syntax":"RIGHT('00000' + value, 5)  |  LEFT(value + '     ', 10)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["RIGHT('00000' + CAST(n AS varchar(10)), 5) is the LPAD idiom; LEFT(name + REPLICATE(' ', 20), 20) is RPAD. Both slice to exactly the target width.","The slice always truncates longer values: RIGHT('00000' + '123456', 5) is '23456'. Negative numbers break the idiom too: RIGHT('00000' + '-42', 5) is '00-42', so pad ABS and prepend the sign. NULL input gives NULL. There is no built-in that pads-or-keeps. Validate lengths when input is unbounded.","FORMAT(n, '00000') pads numbers cleanly and was not measurably slower than RIGHT on 10000 rows, but FORMAT is the one built-in string function that is not deterministic, so it cannot back a persisted computed column or an index.","The same gap exists in every SQL Server version to date: 2022 added TRIM(LEADING/TRAILING chars FROM s), which needs database compatibility level 160, and 2025 added ||, but neither added LPAD or RPAD."],"examples":[{"engine_slug":"sql-server","sql":"SELECT RIGHT('00000' + CAST(region AS varchar(5)), 5) AS region_code\nFROM stores;"},{"engine_slug":"sql-server","sql":"SELECT LEFT(name + REPLICATE(' ', 12), 12) AS aligned FROM items;"}],"faqs":[{"question":"Did SQL Server 2022 add LPAD?","answer":"No. LPAD and RPAD are still missing. 2022 added TRIM(LEADING/TRAILING chars FROM s) and 2025 added the || operator, so zero-padding still needs FORMAT or RIGHT+REPLICATE."},{"question":"Why does my padded value lose digits?","answer":"The RIGHT/LEFT idiom truncates to the exact width; that is how it works. Pad to a width your data cannot exceed, or check LEN first."},{"question":"Is there a CONCAT-side alternative?","answer":"CONCAT joins but does not pad. The fill-then-slice pattern is unavoidable on SQL Server; keep it in one view or function so the width rule lives in one place."}],"related":["lpad","zero-pad","replicate","space"],"novel_uses":[{"body":"ORDER BY RIGHT('00000' + code, 5) normalizes the sort key in place, so 100 sorts after 42 while the SELECT still returns the raw code.","sql":"SELECT code FROM items ORDER BY RIGHT('00000' + code, 5);"},{"body":"A persisted computed column materializes the padded value and can be indexed, which pays off when joins against externally padded keys run on every load.","sql":"ALTER TABLE items ADD code_padded AS RIGHT('00000' + code, 5) PERSISTED;\nCREATE INDEX ix_items_code_padded ON items (code_padded);"}]},"source_url":"https://sqlly.app/sql-functions/sql-server-padding","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sqlite-affinity","corpus":"sql-functions","engine":null,"language":"en","title":"SQLite type affinity","description":"How SQLite's column affinity decides what a stored value becomes, why 'abc' can live in an INTEGER column, and where CAST fits next to the affinity rules.","body":{"slug":"sqlite-affinity","name":"Type affinity","h1":"SQLite type affinity","category":"conversion","lede":"A SQLite column has a preferred storage class, not an enforced type. INTEGER affinity converts numeric text on insert and stores anything else as it arrived.","syntax":"CREATE TABLE t (col INTEGER);  -- affinity, not a constraint","return_type":"depends on affinity","support":[{"engine_slug":"sql-server","status":"no","note":"columns enforce real types"},{"engine_slug":"postgresql","status":"no","note":"columns enforce real types"},{"engine_slug":"mysql","status":"no","note":"columns enforce real types (mode-dependent)"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"columns enforce real types"}],"gotchas":["Affinity is a preference, not a constraint: an INTEGER-affinity column stores the text 'abc' unchanged because it cannot be converted losslessly; only numeric text becomes a number.","typeof() tells you what actually got stored, which is how you debug affinity surprises; CAST inside a query changes the query's answer, never the stored rows.","A REAL-affinity column turns inserted integers into floats: 3 becomes 3.0. Use NUMERIC affinity when whole numbers should stay integers.","STRICT tables (SQLite 3.37+) do enforce types: inserting 'abc' into an INTEGER column of a STRICT table fails with 'cannot store TEXT value in INTEGER column t.n'."],"examples":[{"engine_slug":"sqlite","sql":"CREATE TABLE t (n INTEGER);\nINSERT INTO t VALUES ('123'), ('abc');\nSELECT n, typeof(n) FROM t;"},{"engine_slug":"sqlite","sql":"SELECT CAST('abc' AS INTEGER) AS n;"}],"faqs":[{"question":"Is affinity a constraint?","answer":"No. In an ordinary table an INTEGER column stores blobs and text without complaint; affinity only decides whether an inserted value gets converted. Declare the table STRICT, or add a CHECK (typeof(col) = 'integer'), to reject wrong types."},{"question":"Why did my integer become 123.0?","answer":"The column has REAL affinity: integers convert to floats on storage, even when you CAST them to INTEGER first. Declare the column INTEGER or NUMERIC to keep whole numbers whole, or CAST(col AS INTEGER) when you read it back."}],"related":["cast","cast-truncation","implicit-conversion"],"novel_uses":[{"body":"Import into INTEGER- and NUMERIC-affinity columns and SQLite converts clean numeric text on insert for free, leaving junk as text. A typeof() census afterwards shows exactly which rows failed the conversion.","sql":"SELECT typeof(qty), COUNT(*) FROM stage GROUP BY typeof(qty);"},{"body":"A TEXT-affinity column never converts, so code '0012' stores as '0012', while the same value in an INTEGER-affinity column comes back 12. Declare identifier and code columns TEXT on purpose; do not let affinity guess.","sql":"SELECT code FROM labels WHERE code = '0012';"}]},"source_url":"https://sqlly.app/sql-functions/sqlite-affinity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sqlite-datetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SQLite date() function","description":"SQLite's date(), time() and datetime() convert or build time values from text plus modifiers; no native DATE type, everything is TEXT, REAL or INTEGER.","body":{"slug":"sqlite-datetime","name":"date() / time() / datetime()","h1":"SQL SQLite date() function","category":"datetime","lede":"Returns a formatted time string built from an input value and optional modifiers; SQLite stores dates as TEXT, REAL or INTEGER, never a DATE type.","syntax":"date('2024-01-15')  |  datetime('now', 'localtime')  |  datetime(1700000000, 'unixepoch')","return_type":"TEXT (ISO-8601)","support":[{"engine_slug":"sql-server","status":"partial","note":"CAST(... AS date/time)"},{"engine_slug":"postgresql","status":"partial","note":"ts::date, ts::time"},{"engine_slug":"mysql","status":"partial","note":"DATE(), TIME(), FROM_UNIXTIME()"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"TRUNC(d) and TO_CHAR"}],"gotchas":["The return is text in ISO-8601; comparisons work because of the format, but arithmetic needs julianday() or strftime().","'now' is UTC: datetime('now') is hours off local time unless you append the 'localtime' modifier.","A bare number is a Julian day, not an epoch: datetime(1700000000) returns NULL until you add 'unixepoch'. SQLite 3.38+ also has unixepoch() for the reverse direction."],"examples":[{"engine_slug":"sqlite","sql":"SELECT date('now', 'start of month', '+1 month', '-1 day') AS month_end;"},{"engine_slug":"sqlite","sql":"SELECT datetime(1700000000, 'unixepoch') AS created;"},{"engine_slug":"sqlite","sql":"SELECT time('15:45') AS t;"},{"engine_slug":"sql-server","sql":"SELECT CAST(created_at AS date) AS day, CAST(created_at AS time) AS clock FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT created_at::date AS day, created_at::time AS clock FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE(created_at) AS day, TIME(created_at) AS clock FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TRUNC(created_at) AS day, TO_CHAR(created_at, 'HH24:MI:SS') AS clock FROM orders;"}],"faqs":[{"question":"What is the SQLite DATE type?","answer":"There is none. Values live as TEXT ('YYYY-MM-DD...'), REAL (Julian day) or INTEGER (Unix seconds), and these functions convert between the forms."},{"question":"How do I add a month in SQLite?","answer":"date(d, '+1 month'). Unlike most engines it does not clamp: date('2024-01-31', '+1 month') is 2024-03-02, because February 31 normalizes forward. Recent versions accept a trailing 'floor' modifier that returns 2024-02-29 instead."}],"related":["sqlite-modifiers","julianday","strftime"],"novel_uses":[{"body":"The 'weekday N' modifier advances to the next day N (0 is Sunday) and stays put when today already matches, so on a Friday it returns today. For the strictly next Friday, add a day first: date('now', '+1 day', 'weekday 5').","sql":"SELECT date('now', 'weekday 5') AS next_friday;"},{"body":"SQLite indexes expressions, so an index on strftime('%s', created_at) lets epoch range queries over ISO-text columns use a real index, as long as the query repeats the same expression and compares it with text bounds. strftime() returns TEXT, so BETWEEN 1700000000 AND 1700086400 with integer literals matches zero rows, and wrapping the expression in CAST(... AS INTEGER) stops the planner from seeking the index.","sql":"CREATE INDEX orders_epoch ON orders (strftime('%s', created_at));"}]},"source_url":"https://sqlly.app/sql-functions/sqlite-datetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sqlite-modifiers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SQLite date modifiers","description":"SQLite chains text modifiers onto date functions ('localtime', 'unixepoch', 'start of month', '+7 days'), doing the work other engines spread over functions.","body":{"slug":"sqlite-modifiers","name":"date modifiers","h1":"SQL SQLite date modifiers","category":"datetime","lede":"Returns a modified time value: each modifier is a text argument applied left to right inside date(), time(), datetime() or strftime().","syntax":"datetime('now', 'localtime')  |  datetime(ts, 'unixepoch')  |  date(d, 'start of month', '+1 month', '-1 day')","return_type":"text","support":[{"engine_slug":"sql-server","status":"no","note":"DATEADD and DATEFROMPARTS apply the shifts"},{"engine_slug":"postgresql","status":"partial","note":"interval arithmetic and date_trunc"},{"engine_slug":"mysql","status":"partial","note":"DATE_ADD with units"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"date arithmetic and TRUNC"}],"gotchas":["Order matters: date('2024-01-31', '+1 month', 'start of month') and the reversed order land on different days; each step applies to the intermediate result.","'unixepoch' must come first, right after the value: datetime(1700000000, 'unixepoch', '+1 day') is valid; a later position returns NULL: datetime(1700000000, '+1 day', 'unixepoch') is NULL.","'localtime' uses the host machine's zone, so results move with the machine; servers running UTC make 'localtime' a no-op."],"examples":[{"engine_slug":"sqlite","sql":"SELECT date('now', 'start of month', '+1 month', '-1 day') AS month_end;"},{"engine_slug":"sqlite","sql":"SELECT datetime(1700000000, 'unixepoch', 'localtime') AS created;"},{"engine_slug":"sqlite","sql":"SELECT date(created_at, '+7 days') AS follow_up FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT created_at + INTERVAL '7 days' AS follow_up FROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD(created_at, INTERVAL 7 DAY) AS follow_up FROM orders;"},{"engine_slug":"oracle","sql":"SELECT created_at + 7 AS follow_up FROM orders;"}],"faqs":[{"question":"How do I get the last day of the month in SQLite?","answer":"date(d, 'start of month', '+1 month', '-1 day'): jump to the first, forward a month, back a day. SQLite has no EOMONTH-style function."},{"question":"Why must 'unixepoch' come first?","answer":"It tells SQLite how to interpret the bare number; later modifiers then shift the decoded value. Putting 'localtime' first makes the whole result NULL."}],"related":["sqlite-datetime","strftime","julianday"],"novel_uses":[{"body":"Chained modifiers build fiscal calendars: 'start of year' then '+9 months' lands on October 1, and the chain reads in order inside one date() call.","sql":"SELECT date('now', 'start of year', '+9 months') AS fiscal_start;"},{"body":"The 'utc' modifier assumes the value is host-local wall time and converts it to UTC, the exact reverse of 'localtime'. Handy for cleaning columns stored through the wrong side.","sql":"SELECT datetime('2024-01-15 14:30', 'utc') AS back_to_utc;"}]},"source_url":"https://sqlly.app/sql-functions/sqlite-modifiers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sqrt","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SQRT function","description":"Square roots with SQL SQRT in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: what each engine does with a negative input, and NULL vs error.","body":{"slug":"sqrt","name":"SQRT","h1":"SQL SQRT function","category":"math","lede":"Returns the square root of a non-negative number. Engines differ on what a negative input does: an error on some, NULL on others.","syntax":"SQRT(number)","return_type":"float (numeric for numeric input on PostgreSQL, NUMBER on Oracle)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"math functions from SQLite 3.35+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Negative input: SQL Server, PostgreSQL and Oracle raise an error; MySQL and SQLite return NULL. Guard with CASE WHEN x >= 0 THEN SQRT(x) END.","The result is not an integer even for perfect squares: SQRT(4) is the float 2 on SQL Server, MySQL and SQLite, and numeric 2.000000000000000 for a numeric input on PostgreSQL.","A NULL input returns NULL everywhere; it does not error."],"examples":[{"engine_slug":"all","sql":"SELECT SQRT(2) AS root2;  -- 1.4142..."},{"engine_slug":"postgresql","sql":"SELECT CASE WHEN x >= 0 THEN SQRT(x) END AS safe_root FROM t;"}],"faqs":[{"question":"What does SQRT(-1) return?","answer":"Depends on the engine: an error on SQL Server, PostgreSQL and Oracle; NULL on MySQL and SQLite. Wrap it in CASE WHEN x >= 0 THEN SQRT(x) END when negatives are possible."},{"question":"Does SQRT return an integer for perfect squares?","answer":"No. It returns a float (or a numeric on PostgreSQL and Oracle) even when the root is whole. CAST it to an integer type if that matters."}],"related":["power","abs","stddev"],"novel_uses":[{"body":"SQRT(POWER(dx, 2) + POWER(dy, 2)) is the Pythagorean distance on plain x/y or nearby lat/long values, enough to order candidates by straight-line distance with no spatial index. Degrees are not meters, so for long ranges switch to a real projection or haversine.","sql":"SELECT name,\n       SQRT(POWER(x - 12.5, 2) + POWER(y - 55.7, 2)) AS dist\nFROM points\nORDER BY dist\nLIMIT 1;"},{"body":"Growth over two equal periods compounds, so SQRT(end / start) - 1 recovers the per-period rate from the total. POWER(end / start, 1.0 / n) - 1 generalizes it to n periods; keep the inputs numeric or the ratio truncates first.","sql":"SELECT SQRT(end_value / start_value) - 1 AS per_period_return\nFROM investments;"}]},"source_url":"https://sqlly.app/sql-functions/sqrt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/square","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SQUARE function","description":"SQUARE(x) multiplies a value by itself and always returns FLOAT. It is a T-SQL convenience; elsewhere write x * x or POWER(x, 2).","body":{"slug":"square","name":"SQUARE","h1":"SQL SQUARE function","category":"math","lede":"Returns the square of a number as a float: SQUARE(5) is 25.0, the same value as x * x or POWER(x, 2).","syntax":"SQUARE(number)","return_type":"float","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"No SQUARE; x * x or power(x, 2)"},{"engine_slug":"mysql","status":"no","note":"No SQUARE; x * x or POWER(x, 2)"},{"engine_slug":"sqlite","status":"no","note":"No SQUARE; x * x"},{"engine_slug":"oracle","status":"no","note":"No SQUARE; x * x or POWER(x, 2)"}],"gotchas":["SQUARE converts its argument to float: SQUARE(5) is 25.0 and SQUARE of a DECIMAL is a float too. For exact money math, write x * x, which keeps the decimal type.","POWER(x, 2) on SQL Server returns the base type of x instead (decimal(10,2) comes back as decimal(38,2)), so POWER(5, 2) is the INT 25 while SQUARE(5) is the FLOAT 25.0.","Because the result is float, SQUARE does not overflow INT the way x * x does: SQUARE(100000) is the float 10000000000, while 100000 * 100000 raises an arithmetic overflow. The price is float precision: integers stay exact only up to 2^53 (about 9.0e15), so SQUARE(123456789) returns 15241578750190520, not 15241578750190521."],"examples":[{"engine_slug":"sql-server","sql":"SELECT SQUARE(5) AS twenty_five;  -- 25.0 (float)"},{"engine_slug":"sql-server","sql":"SELECT SQRT(SQUARE(x1 - x2) + SQUARE(y1 - y2)) AS distance\nFROM points;"}],"faqs":[{"question":"What is the difference between SQUARE and POWER(x, 2)?","answer":"The value is the same, the type is not. SQUARE always returns float; SQL Server's POWER(x, 2) returns the type of x. POWER is also the portable spelling across all five engines."},{"question":"How do I square a number outside SQL Server?","answer":"Multiply it by itself: x * x works on every engine and keeps integer and decimal types exact on SQL Server, PostgreSQL and MySQL; SQLite has no exact decimal type, so 1.1 * 1.1 is a REAL that is not exactly 1.21. POWER(x, 2) also works but returns double on MySQL, SQLite and PostgreSQL for integer input."},{"question":"Does SQUARE overflow on big integers?","answer":"Not at INT range, since the result is float: SQUARE(100000) returns the float 10000000000. x * x on two INTs overflows once the product passes 2147483647, which starts at 46341, so cast to BIGINT there. SQUARE only fails past the float limit near 1.8e308."}],"related":["power","sqrt","arithmetic-operators"],"novel_uses":[{"body":"SQUARE(dx) + SQUARE(dy) < SQUARE(max_dist) answers within-range questions with no square root at all. Squaring the threshold once skips a sqrt per row; on a 2M-row SQL Server scan the saving was small (about 4% elapsed time, one run).","sql":"SELECT id FROM sites WHERE SQUARE(x - @px) + SQUARE(y - @py) < SQUARE(2.5);"},{"body":"AVG(SQUARE(x)) - SQUARE(AVG(x)) is the population variance over any derived set, no VARP required. On huge means the subtraction can cancel in floats; for exact results use x * x on a decimal, since POWER(x, 2) keeps the decimal type but computes through float and drops digits.","sql":"SELECT AVG(SQUARE(latency_ms)) - SQUARE(AVG(latency_ms)) AS variance FROM probes;"}]},"source_url":"https://sqlly.app/sql-functions/square","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/starts-with","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STARTS_WITH function","description":"PostgreSQL's starts_with() and ^@ test a string prefix. Every engine can do the same with LIKE 'abc%', which can use an index when the pattern has no leading wildcard.","body":{"slug":"starts-with","name":"STARTS_WITH","h1":"SQL STARTS_WITH function","category":"conditional","lede":"starts_with('alpha', 'al') is true. Outside PostgreSQL the prefix test is LIKE 'al%', which works everywhere and can use an index.","syntax":"starts_with(string, prefix)  |  string ^@ prefix  |  string LIKE 'prefix%'","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"partial","note":"no function; col LIKE 'abc%' or LEFT(col, 3) = 'abc'"},{"engine_slug":"postgresql","status":"yes","note":"starts_with() and the ^@ operator"},{"engine_slug":"mysql","status":"partial","note":"no function; col LIKE 'abc%' or LEFT(col, 3) = 'abc'"},{"engine_slug":"sqlite","status":"partial","note":"no function; col LIKE 'abc%' or substr(col, 1, 3) = 'abc'"},{"engine_slug":"oracle","status":"partial","note":"no function; col LIKE 'abc%' or SUBSTR(col, 1, 3) = 'abc'"}],"gotchas":["starts_with treats % and _ literally; LIKE treats them as wildcards. When the prefix comes from user input, escape those characters before building a LIKE pattern.","starts_with is case-sensitive. LIKE follows the collation, so on SQL Server and MySQL defaults the prefix test ignores case.","LEFT(col, 3) = 'abc' wraps the column in a function, which stops a plain index from being used. LIKE 'abc%' seeks on SQL Server and MySQL, but on PostgreSQL only under the C collation or a text_pattern_ops index, and on SQLite only with PRAGMA case_sensitive_like = ON or a COLLATE NOCASE column (GLOB 'abc*' seeks a default column)."],"examples":[{"engine_slug":"postgresql","sql":"SELECT starts_with('alpha', 'al') AS a, 'alpha' ^@ 'al' AS b, starts_with('alpha', 'AL') AS c;  -- t, t, f"},{"engine_slug":"postgresql","sql":"SELECT starts_with('50%_off', '50%') AS literal, '5000' LIKE '50%' AS wildcard;  -- t, t"},{"engine_slug":"mysql","sql":"SELECT 'alpha' LIKE 'al%' AS a, LEFT('alpha', 2) = 'al' AS b;  -- 1, 1"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN 'alpha' LIKE 'al%' THEN 1 ELSE 0 END AS like_form,\n       CASE WHEN LEFT('alpha', 2) = 'al' THEN 1 ELSE 0 END AS left_form;  -- 1, 1"},{"engine_slug":"sqlite","sql":"SELECT 'alpha' LIKE 'al%' AS a, substr('alpha', 1, 2) = 'al' AS b, instr('alpha', 'al') = 1 AS c;  -- 1, 1, 1"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN 'alpha' LIKE 'al%' THEN 'y' END AS like_form,\n       CASE WHEN SUBSTR('alpha', 1, 2) = 'al' THEN 'y' END AS substr_form FROM dual;  -- y, y"}],"faqs":[{"question":"Is there an ENDS_WITH?","answer":"Not on these engines. Use LIKE '%abc' or RIGHT(col, 3) = 'abc' (substr(col, -3) = 'abc' on SQLite and Oracle); neither can use a normal index on col."},{"question":"Does a prefix LIKE use an index on PostgreSQL?","answer":"Yes under the C collation. With other collations, create the index with text_pattern_ops (or varchar_pattern_ops)."}],"related":["like","left","position","like-escape"],"novel_uses":[{"body":"A compound index still seeks when the leading column is an equality and the second is the prefix: WHERE tenant_id = 42 AND code LIKE 'ABC%' seeks, while the prefix test alone on the second column cannot seek on SQL Server and at best becomes a skip scan, one probe per tenant_id, on PostgreSQL 18, MySQL 8.0.13+ and Oracle. The index design, not the operator, decides here.","sql":"CREATE INDEX ix ON jobs (tenant_id, code);\nSELECT * FROM jobs WHERE tenant_id = 42 AND code LIKE 'ABC%';"},{"body":"WHERE code >= 'ABC' AND code < 'ABD' is the prefix test written as a range, which every engine plans as a plain seek. It needs the successor prefix, computed by incrementing the last character, and states the upper bound explicitly for tools that cannot reason about LIKE. It equals the LIKE test only under binary-style collations: where punctuation is ignored, as in PostgreSQL's glibc en_US or SQL Server nvarchar, 'AB-Cx' falls inside the range but fails LIKE 'ABC%'.","sql":"SELECT * FROM codes WHERE code >= 'ABC' AND code < 'ABD';"}]},"source_url":"https://sqlly.app/sql-functions/starts-with","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/stddev","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STDDEV function","description":"Standard deviation in SQL: STDEV in SQL Server, STDDEV_SAMP and STDDEV_POP elsewhere, no built-in in SQLite, and why MySQL's STDDEV is the population version.","body":{"slug":"stddev","name":"STDDEV / STDEV","h1":"SQL STDDEV function","category":"aggregate","lede":"Measures how spread out a group's values are around their average. Engines disagree on the name and on whether the plain STDDEV means sample or population, and SQLite has no built-in.","syntax":"STDEV(expr)  -- SQL Server  |  STDDEV_SAMP(expr) / STDDEV_POP(expr)  -- others","return_type":"numeric / double","support":[{"engine_slug":"sql-server","status":"partial","note":"spelled STDEV and STDEVP"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"STDDEV and STD are the population version; STDDEV_SAMP is the sample one"},{"engine_slug":"sqlite","status":"no","note":"not built in; compute it from SUM/COUNT or add an extension"},{"engine_slug":"oracle","status":"yes","note":"STDDEV_SAMP, STDDEV_POP and STDDEV all available"}],"gotchas":["Sample (STDDEV_SAMP / STDEV) divides by n-1, population (STDDEV_POP / STDEVP) by n. Pick sample when your rows are a sample of a larger population.","The plain name is not consistent: STDDEV is the sample version on PostgreSQL and Oracle but the population version on MySQL. Values 1 and 3 give 1.414 on PostgreSQL and 1 on MySQL. Spell out STDDEV_SAMP or STDDEV_POP.","One row: STDDEV_SAMP returns NULL and STDDEV_POP returns 0. Oracle's plain STDDEV returns 0 for one row even though it is otherwise the sample version."],"examples":[{"engine_slug":"sql-server","sql":"SELECT STDEV(response_ms) AS sample_spread\nFROM pings;"},{"engine_slug":"postgresql","sql":"SELECT STDDEV_SAMP(response_ms) AS sample_spread\nFROM pings;"},{"engine_slug":"mysql","sql":"-- plain STDDEV would be the population version here\nSELECT STDDEV_SAMP(response_ms) AS sample_spread\nFROM pings;"},{"engine_slug":"oracle","sql":"-- plain STDDEV is the sample version here\nSELECT STDDEV(response_ms) AS sample_spread\nFROM pings;"}],"faqs":[{"question":"What is the difference between STDDEV_SAMP and STDDEV_POP?","answer":"The divisor: n-1 for the sample version, n for the population version. Use the sample one unless your rows really are the entire population."},{"question":"Does SQLite have STDDEV?","answer":"No, SQLite ships no aggregate for it. The sample version is SQRT((SUM(x*x) - SUM(x)*SUM(x)/COUNT(x)) / (COUNT(x) - 1)), using the SQRT from SQLite's math functions (3.35+), or load an extension."}],"related":["avg","percentile-cont","round"],"novel_uses":[{"body":"Dividing the standard deviation by the mean puts spread on a relative scale, so latency in milliseconds and spend in dollars become comparable. NULLIF guards the divide when a group averages zero. SQLite, which has no STDDEV, needs the manual formula.","sql":"SELECT region,\n       STDDEV_SAMP(latency_ms) / NULLIF(AVG(latency_ms), 0) AS cv\nFROM pings\nGROUP BY region;"},{"body":"Subtract the overall average and divide by the overall standard deviation, both with OVER (), and every row carries its own outlier score in one pass. Scores past 3 in magnitude are the usual flag. Any engine with window functions and STDDEV_SAMP does this; SQL Server spells it STDEV.","sql":"SELECT day, requests,\n       (requests - AVG(requests) OVER ()) /\n       NULLIF(STDDEV_SAMP(requests) OVER (), 0) AS z\nFROM traffic;"}]},"source_url":"https://sqlly.app/sql-functions/stddev","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/stddev-pop","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STDDEV_POP function","description":"STDDEV_POP divides by n and returns 0 for a single value: the STDEVP spelling on SQL Server, support in PostgreSQL, MySQL and Oracle, and when to prefer STDDEV_SAMP.","body":{"slug":"stddev-pop","name":"STDDEV_POP","h1":"SQL STDDEV_POP function","category":"aggregate","lede":"Population standard deviation: divides by n and treats the group as the whole population.","syntax":"STDDEV_POP(x) | STDEVP(x) | STDDEV_POP(x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"STDEVP is the SQL Server spelling"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"not built in; use an extension or compute it manually"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["One non-NULL value returns 0 (unlike STDDEV_SAMP's NULL) because there is no n-1 division.","NULLs are excluded; the denominator is the count of present values.","Use the sample form when your rows are a sample of something bigger; population form when the rows are everything you care about."],"examples":[{"engine_slug":"postgresql","sql":"SELECT stddev_pop(price) FROM products WHERE category_id = 7;"},{"engine_slug":"sql-server","sql":"SELECT STDEVP(price) FROM products WHERE category_id = 7;"},{"engine_slug":"mysql","sql":"SELECT STDDEV_POP(score) FROM results WHERE exam = 'A';"},{"engine_slug":"oracle","sql":"SELECT STDDEV_POP(salary) FROM employees WHERE dept_id = 10;"}],"faqs":[{"question":"STDDEV_POP vs STDDEV_SAMP?","answer":"The divisor: n versus n-1. STDDEV_POP returns 0 for a single row; STDDEV_SAMP returns NULL."},{"question":"What is STDDEV_POP in SQL Server?","answer":"STDEVP."},{"question":"How does it relate to variance?","answer":"It is the square root of VAR_POP."}],"related":["stddev","stddev-samp","var-pop","variance","corr"],"novel_uses":[{"body":"For roughly bell-shaped usage, avg + 3 * stddev_pop sits above about 99.9 percent of observed rows (99.7 percent fall within three standard deviations either side), one way to size a limit from the data itself. The SQL runs as written on PostgreSQL and MySQL; on SQL Server use STDEVP in place of stddev_pop.","sql":"SELECT avg(cpu_pct) + 3 * stddev_pop(cpu_pct) AS suggested_cap FROM metrics WHERE day >= '2026-11-01';"},{"body":"When the rows are the entire population, every exam of the term or every request of the day, the population form gives the textbook z without the n-1 correction. The SQL runs as written on PostgreSQL and MySQL; on SQL Server use STDEVP in place of stddev_pop.","sql":"SELECT student_id, (score - avg(score) OVER ()) / NULLIF(stddev_pop(score) OVER (), 0) AS z FROM exam_results;"}]},"source_url":"https://sqlly.app/sql-functions/stddev-pop","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/stddev-samp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STDDEV_SAMP function","description":"STDDEV_SAMP across the big engines: SQL Server's STDEV spelling, PostgreSQL aliases, MySQL support, why SQLite has none built in, and the NULL-on-one-row rule.","body":{"slug":"stddev-samp","name":"STDDEV_SAMP","h1":"SQL STDDEV_SAMP function","category":"aggregate","lede":"Sample standard deviation: divides by n-1 and returns NULL when there are fewer than two non-NULL values.","syntax":"STDDEV_SAMP(x) | STDEV(x) | STDDEV_SAMP(x) OVER (...)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"STDEV is the SQL Server spelling"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"not built in; use an extension or compute SQRT of the manual sample-variance formula"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Fewer than two non-NULL values returns NULL, not 0: a one-row group has no sample deviation.","NULLs are excluded before counting, so the denominator is the count of present values minus one.","Plain STDDEV is not portable: in PostgreSQL it means STDDEV_SAMP, in MySQL it means STDDEV_POP, and in Oracle it is the sample form except that one row returns 0. SQL Server spells the sample form STDEV."],"examples":[{"engine_slug":"postgresql","sql":"SELECT stddev_samp(price) FROM products WHERE category_id = 7;"},{"engine_slug":"sql-server","sql":"SELECT STDEV(price) FROM products WHERE category_id = 7;"},{"engine_slug":"mysql","sql":"SELECT STDDEV_SAMP(score) OVER (PARTITION BY exam) FROM results;"},{"engine_slug":"oracle","sql":"SELECT STDDEV_SAMP(salary) FROM employees WHERE dept_id = 10;"}],"faqs":[{"question":"Sample or population standard deviation?","answer":"STDDEV_SAMP divides by n-1 (sample). For the population form dividing by n, use STDDEV_POP."},{"question":"Why does one row return NULL?","answer":"With n = 1 the sample formula divides by zero (n-1 = 0), so engines return NULL."},{"question":"What is STDDEV_SAMP in SQL Server?","answer":"STDEV: same computation, shorter name; STDEVP is the population version."}],"related":["stddev","stddev-pop","var-samp","variance","corr"],"novel_uses":[{"body":"Window aggregates put the group's own stats on each row, so the absolute gap from the group average divided by the group stddev flags amounts that are odd for their region, not just for the whole table. The SQL runs as written on PostgreSQL and MySQL; on SQL Server use STDEV in place of stddev_samp.","sql":"SELECT id, abs(amount - avg(amount) OVER (PARTITION BY region)) / NULLIF(stddev_samp(amount) OVER (PARTITION BY region), 0) AS z FROM sales;"},{"body":"stddev_samp(x) / NULLIF(avg(x), 0) compares spread between groups measured in different units, kWh against dollars, without normalizing by hand. The SQL runs as written on PostgreSQL and MySQL; on SQL Server use STDEV in place of stddev_samp.","sql":"SELECT region, stddev_samp(usage_kwh) / NULLIF(avg(usage_kwh), 0) AS cv FROM meter_reads GROUP BY region;"},{"body":"stddev_samp(x) = 0 needs two or more identical values, so a sensor whose readings never move surfaces in one HAVING clause. That is exact for DECIMAL or NUMERIC readings; on a float column identical values can leave a tiny non-zero spread (PostgreSQL float8 gave 8e-18 for 0.1 three times), so compare with HAVING stddev_samp(temp_c) < 1e-9 there. On SQL Server write STDEV in place of stddev_samp.","sql":"SELECT sensor_id FROM readings GROUP BY sensor_id HAVING stddev_samp(temp_c) = 0;"}]},"source_url":"https://sqlly.app/sql-functions/stddev-samp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/stddev-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STDDEV as a window function","description":"STDDEV and STDDEV_POP/STDDEV_SAMP with OVER: per-partition dispersion and rolling volatility on every row, where SQLite sits out.","body":{"slug":"stddev-window","name":"STDDEV with OVER","h1":"SQL STDDEV as a window function","category":"window","lede":"Standard deviation computed over the window frame or partition, keeping every row: group dispersion, rolling volatility and z-scores in one pass.","syntax":"STDDEV_SAMP(x) OVER (PARTITION BY g) | STDDEV_SAMP(x) OVER (ORDER BY d ROWS BETWEEN 29 PRECEDING AND CURRENT ROW)","return_type":"double precision / float","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no STDDEV built-in; register a custom aggregate or compute via AVG of squared differences in a CTE"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Plain STDDEV does not mean the same thing everywhere: PostgreSQL and Oracle treat it as the sample version, MySQL treats STDDEV and STD as population (same as STDDEV_POP). SQL Server spells them STDEV (sample) and STDEVP (population). Write STDDEV_SAMP or STDDEV_POP where they exist.","STDDEV_SAMP (and SQL Server STDEV) over a single row is NULL; STDDEV_POP returns 0. Oracle's plain STDDEV is the exception: it returns 0 for one row where STDDEV_SAMP returns NULL.","Z-scores in one pass: (x - AVG(x) OVER ()) / NULLIF(STDDEV_SAMP(x) OVER (), 0); the NULLIF guards zero spread, where every value in the partition is equal and the divisor would be 0. A single-row partition already gives NULL without an error, because STDDEV_SAMP is NULL there."],"examples":[{"engine_slug":"postgresql","sql":"SELECT symbol, day, close,\n       (close - AVG(close) OVER w) / NULLIF(STDDEV_SAMP(close) OVER w, 0) AS z\nFROM quotes\nWINDOW w AS (PARTITION BY symbol ORDER BY day ROWS BETWEEN 29 PRECEDING AND CURRENT ROW);"},{"engine_slug":"sql-server","sql":"SELECT region, revenue,\n       STDEV(revenue) OVER (PARTITION BY region) AS revenue_stddev\nFROM sales;"},{"engine_slug":"mysql","sql":"SELECT region, revenue,\n       STDDEV_SAMP(revenue) OVER (PARTITION BY region) AS revenue_stddev\nFROM sales;"},{"engine_slug":"oracle","sql":"SELECT symbol, day, close,\n       (close - AVG(close) OVER (PARTITION BY symbol))\n         / NULLIF(STDDEV_SAMP(close) OVER (PARTITION BY symbol), 0) AS z\nFROM quotes;"}],"faqs":[{"question":"Does STDDEV work as a window function in SQLite?","answer":"No built-in stddev exists at all, window or not. Register a custom aggregate via sqlite3_create_window_function, or compute population stddev as SQRT(AVG(x*x) OVER w - AVG(x) OVER w * AVG(x) OVER w). SQRT needs the math functions (built into the sqlite3 shell since 3.35), and the formula loses precision when the mean is large relative to the spread."},{"question":"STDEV or STDDEV: which spelling does my engine take?","answer":"PostgreSQL, Oracle and MySQL accept STDDEV, but MySQL's is the population figure while the other two return the sample one. SQL Server only knows STDEV (sample) and STDEVP (population). STDDEV_SAMP and STDDEV_POP work everywhere except SQL Server and SQLite."}],"related":["variance-window","avg-over","stddev"],"novel_uses":[{"body":"AVG plus and minus two rolling standard deviations over the same frame gives a band that widens in volatile stretches. PostgreSQL and Oracle write STDDEV_SAMP, SQL Server writes STDEV, and MySQL's plain STDDEV is the population form, so pick the spelling deliberately. The SQL below runs as written on PostgreSQL and MySQL 8; SQL Server needs STDEV in place of STDDEV_SAMP, and SQLite has no STDDEV_SAMP at all.","sql":"SELECT day, close,\n       AVG(close) OVER w + 2 * STDDEV_SAMP(close) OVER w AS upper_band,\n       AVG(close) OVER w - 2 * STDDEV_SAMP(close) OVER w AS lower_band\nFROM quotes\nWINDOW w AS (ORDER BY day ROWS BETWEEN 19 PRECEDING AND CURRENT ROW);"},{"body":"Divide the 7-row standard deviation by the 60-row one and values far above 1 mark a regime change rather than noise. Two frames in one query, no self-join.","sql":"SELECT day, close,\n       STDDEV_SAMP(close) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)\n         / NULLIF(STDDEV_SAMP(close) OVER (ORDER BY day ROWS BETWEEN 59 PRECEDING AND CURRENT ROW), 0) AS vol_ratio\nFROM quotes;"},{"body":"Divide the standard deviation by the mean and revenue in dollars and sessions in thousands become comparable: the coefficient of variation ranks volatility by relative size. Guard the mean with NULLIF for a zero mean: PostgreSQL and SQL Server raise division by zero there, while MySQL returns NULL with a warning.","sql":"SELECT region, revenue,\n       STDDEV_SAMP(revenue) OVER (PARTITION BY region)\n         / NULLIF(AVG(revenue) OVER (PARTITION BY region), 0) AS cv\nFROM sales;"}]},"source_url":"https://sqlly.app/sql-functions/stddev-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/str","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Server STR function","description":"SQL Server's STR turns a number into right-aligned text of a set width, rounds, and prints asterisks on overflow. How it compares with FORMAT and TO_CHAR.","body":{"slug":"str","name":"STR","h1":"SQL Server STR function","category":"conversion","lede":"STR(123.456, 8, 2) returns '  123.46': a float rendered at a fixed width with a fixed number of decimals.","syntax":"STR(float_expression [, length [, decimal]])","return_type":"varchar","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"to_char(x, '9990.00') pads to the mask plus one sign position"},{"engine_slug":"mysql","status":"partial","note":"LPAD(FORMAT(x, 2), 8, ' '), though FORMAT adds thousands separators"},{"engine_slug":"sqlite","status":"partial","note":"printf('%8.2f', x)"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(x, '99990.00') or LPAD(TO_CHAR(x), n)"}],"gotchas":["The default length is 10 with no decimals, padded with leading spaces: '[' + STR(42) + ']' is '[        42]'. Wrap it in LTRIM when you only want the digits.","The argument is converted to float first, so STR(1.005, 5, 2) returns ' 1.00': 1.005 is stored as 1.00499... in binary.","A number that does not fit the length comes back as asterisks: STR(1234567, 5) is '*****'.","STR rounds half away from zero: STR(0.5) is 1 and STR(-1.5) is -2, each padded to 10 characters."],"examples":[{"engine_slug":"sql-server","sql":"SELECT STR(123.456, 8, 2) AS padded, LTRIM(STR(123.456, 8, 2)) AS trimmed;  -- '  123.46', '123.46'"},{"engine_slug":"sql-server","sql":"SELECT STR(1234567, 5) AS too_wide, REPLACE(STR(42, 6), ' ', '0') AS zero_padded;  -- '*****', '000042'"},{"engine_slug":"sqlite","sql":"SELECT printf('%8.2f', 123.456) AS padded;  -- '  123.46'"},{"engine_slug":"postgresql","sql":"SELECT to_char(123.456, '9990.00') AS padded;  -- '  123.46'"},{"engine_slug":"mysql","sql":"SELECT LPAD(FORMAT(123.456, 2), 8, ' ') AS padded;  -- '  123.46'"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(123.456, '99990.00') AS padded FROM dual;  -- '  123.46'"}],"faqs":[{"question":"STR or FORMAT?","answer":"STR is fixed-width and does not care about culture. FORMAT uses .NET format strings and the session language, and it is much slower over many rows. For plain text without padding, CAST(x AS varchar) is enough."},{"question":"How do I zero-pad with STR?","answer":"Replace the padding: REPLACE(STR(42, 6), ' ', '0') gives '000042'. It breaks on negative numbers, where the minus sign ends up after the zeros."}],"related":["format-numbers","to-char-numeric","zero-pad","printf-sqlite"],"novel_uses":[{"body":"Fixed-length export formats need every line padded to the same width, which is STR's whole job, and the asterisk result doubles as a loud failure: a row too wide for the layout shows up as '*****' instead of silently shifting every following column.","sql":"SELECT STR(qty, 8, 2) AS line\nFROM (VALUES (12.5), (123456789.1)) AS t(qty);  -- '   12.50', '********'"},{"body":"STR(NULL, 8, 2) is NULL, and + propagates NULL, so one missing qty nulls the whole export line. CONCAT treats NULL as an empty string, which keeps the row but pads it wrong; either way the choice is explicit, not accidental.","sql":"SELECT '[' + STR(NULL, 8, 2) + ']' AS plus_result,\n       CONCAT('[', STR(NULL, 8, 2), ']') AS concat_result;  -- NULL, '[]'"}]},"source_url":"https://sqlly.app/sql-functions/str","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/str-to-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STR_TO_DATE function","description":"MySQL's STR_TO_DATE parses a string with a format mask like '%d/%m/%Y', the reverse of DATE_FORMAT; other engines use TO_DATE, PARSE or casts.","body":{"slug":"str-to-date","name":"STR_TO_DATE","h1":"SQL STR_TO_DATE function","category":"datetime","lede":"Returns a date, datetime or time parsed from a string according to the mask you supply, MySQL's counterpart to Oracle's TO_DATE.","syntax":"STR_TO_DATE('15/01/2024', '%d/%m/%Y')  -- MySQL  |  TO_DATE('15/01/2024', 'DD/MM/YYYY')  -- Oracle","return_type":"date / datetime / time","support":[{"engine_slug":"sql-server","status":"partial","note":"PARSE or CONVERT with a style number"},{"engine_slug":"postgresql","status":"partial","note":"to_date(s, mask) with DD/MM/YYYY-style masks"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no mask parsing; only ISO-8601 text works implicitly"},{"engine_slug":"oracle","status":"partial","note":"TO_DATE"}],"gotchas":["In a SELECT, bad input returns NULL with a warning: a %m/%d/%Y mask against 15/01/2024 yields NULL. Inside an INSERT under strict mode the same call fails with error 1411.","MySQL's masks use %Y-%m-%d; PostgreSQL and Oracle use YYYY-MM-DD-style words. Copying masks between engines does not parse: MySQL gives NULL for a YYYY-MM-DD mask, and PostgreSQL's to_date with a %d/%m/%Y mask returns 2001-01-01 with no error.","Two-digit years follow MySQL's sliding rule: 00-69 becomes 2000-2069, 70-99 becomes 1970-1999."],"examples":[{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('15/01/2024', '%d/%m/%Y') AS parsed;"},{"engine_slug":"oracle","sql":"SELECT TO_DATE('15/01/2024', 'DD/MM/YYYY') AS parsed FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT PARSE('15/01/2024' AS date USING 'en-GB') AS parsed;"},{"engine_slug":"postgresql","sql":"SELECT to_date('15/01/2024', 'DD/MM/YYYY') AS parsed;"}],"faqs":[{"question":"Why does STR_TO_DATE return NULL?","answer":"The mask did not match the string (separators or field order differ), or the result is not a real date, such as 2024-02-30. SHOW WARNINGS names the value it rejected."},{"question":"Is there a SQLite STR_TO_DATE?","answer":"No. SQLite only parses ISO-8601 text; anything else must be reshaped in SQL or the application first."}],"related":["to-date","date-format","makedate"],"novel_uses":[{"body":"The return type follows the mask: a format with only %H and %i yields a TIME, so '09:30' parses to 09:30:00 without any cast.","sql":"SELECT STR_TO_DATE('09:30', '%H:%i') AS t;"},{"body":"Prefix the mask with FX to demand exact punctuation and padding: TO_DATE('15/1/2024', 'FXDD/MM/YYYY') raises where the loose form would shrug and parse it.","sql":"SELECT TO_DATE('15/1/2024', 'FXDD/MM/YYYY') AS strict FROM dual;"},{"body":"to_date defaults missing fields instead of failing: to_date('2024-05', 'YYYY-MM') comes back as May 1, which makes partial keys usable as range starts.","sql":"SELECT to_date('2024-05', 'YYYY-MM') AS month_start;"}]},"source_url":"https://sqlly.app/sql-functions/str-to-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/strcmp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRCMP function","description":"MySQL's STRCMP returns -1, 0 or 1 comparing two strings under the collation's rules, sort-order arithmetic the comparison operators do not give you.","body":{"slug":"strcmp","name":"STRCMP","h1":"SQL STRCMP function","category":"string","lede":"Three-way comparison: negative when the first sorts first, 0 on equality, positive otherwise. Case sensitivity comes from the collation, not the function.","syntax":"STRCMP(string1, string2)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Collation-driven: under a _ci collation STRCMP('apple', 'Apple') is 0; under utf8mb4_bin it is 1, because 'a' (97) sorts after 'A' (65). The function adds no case rules of its own.","NULL if either argument is NULL; it never treats NULL as a sortable value.","Other engines build it with CASE WHEN a < b THEN -1 WHEN a = b THEN 0 ELSE 1 END, or skip it and ORDER BY, which needs no helper.","Useful as a sort key expression and in CASE ranges; for matching, = and < already follow the same collation."],"examples":[{"engine_slug":"mysql","sql":"SELECT STRCMP('apple', 'banana') AS c;  -- -1"},{"engine_slug":"mysql","sql":"SELECT STRCMP('apple', 'Apple') AS c;  -- 0 under a _ci collation"}],"faqs":[{"question":"Is STRCMP case-sensitive?","answer":"Only if the collation is: _ci collations treat 'apple' and 'Apple' as equal (returns 0), _bin collations order them apart. The collation decides, not the function."},{"question":"What is the SQL Server equivalent?","answer":"None by name; the idiom is CASE WHEN a < b THEN -1 WHEN a = b THEN 0 ELSE 1 END, which follows the column collation the same way STRCMP does."},{"question":"Why use STRCMP instead of < and =?","answer":"It yields one sortable integer, handy as an expression in ORDER BY, CASE and application-style three-way logic, where operators would need three branches."}],"related":["string-sort","case-insensitive-collation","difference"],"novel_uses":[{"body":"Wrapping one side in a NO PAD binary collation such as utf8mb4_0900_bin makes STRCMP compare case-sensitively and count trailing spaces for that expression alone, with no change to the column. utf8mb4_bin is PAD SPACE and would also match 'Ab-1 '.","sql":"SELECT * FROM codes WHERE STRCMP(code COLLATE utf8mb4_0900_bin, 'Ab-1') = 0;"},{"body":"Under the MySQL 8 0900 collations STRCMP sees trailing spaces and returns nonzero, while the legacy PAD SPACE collations call them equal, so the same query changes answers on upgrade.","sql":"SELECT STRCMP('abc' COLLATE utf8mb4_0900_ai_ci, 'abc ' COLLATE utf8mb4_0900_ai_ci) AS c;  -- -1 under utf8mb4_0900_* (NO PAD), 0 under legacy PAD SPACE collations such as utf8mb4_general_ci"}]},"source_url":"https://sqlly.app/sql-functions/strcmp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/strftime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRFTIME function","description":"How SQLite's strftime formats date and time values into strings: % placeholders, the accepted input formats, date modifiers, and the TO_CHAR and DATE_FORMAT twins.","body":{"slug":"strftime","name":"STRFTIME","h1":"SQL STRFTIME function","category":"string","lede":"Formats an SQLite date or time value as a string using C-style % placeholders.","syntax":"strftime(format, time_value [, modifier, ...])","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"Use FORMAT(date, format) or CONVERT with a style."},{"engine_slug":"postgresql","status":"partial","note":"Use TO_CHAR(timestamp, format)."},{"engine_slug":"mysql","status":"partial","note":"Use DATE_FORMAT(date, format)."},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"Use TO_CHAR(date, format)."}],"gotchas":["Accepted inputs: 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM[:SS[.SSS]]' with a space or a T, time-only 'HH:MM' forms, an optional timezone suffix, 'now', or a number (a Julian day, or Unix seconds with the 'unixepoch' modifier). Anything else, such as '20/11/2026', returns NULL.","Common placeholders: %Y %m %d %H %M %S, %s (Unix seconds), %j (day of year), %w (weekday, 0 = Sunday), %W (week of year, weeks starting Monday).","Modifiers apply left to right: strftime('%Y-%m-%d', 'now', '-1 day', 'start of month') takes yesterday, then the first of that month."],"examples":[{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d', 'now') AS today;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%s', created_at) AS epoch\nFROM events;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d', created_at, 'start of month') AS month\nFROM orders;"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(created_at, 'yyyy-MM-dd HH:mm:ss') AS formatted\nFROM events;"},{"engine_slug":"postgresql","sql":"SELECT to_char(created_at, 'YYYY-MM-DD HH24:MI:SS') AS formatted\nFROM events;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') AS formatted\nFROM events;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'YYYY-MM-DD HH24:MI:SS') AS formatted\nFROM events;"}],"faqs":[{"question":"How do I get a Unix timestamp in SQLite?","answer":"strftime('%s', value) returns seconds since 1970 as text. unixepoch(value), added in SQLite 3.38, returns it as an integer."},{"question":"What is the MySQL equivalent of strftime?","answer":"DATE_FORMAT(date, '%Y-%m-%d') uses the same % idea, but the letters differ: minutes are %i in MySQL and %M in SQLite, where MySQL's %M is the month name."},{"question":"Why does strftime return NULL on my datetime string?","answer":"The input is not in a format SQLite recognises. ISO forms with a space or T work; '20/11/2026' or 'Nov 20 2026' do not. Store dates as ISO-8601 text, Julian days or Unix seconds."}],"related":["to-char","date-format","date-trunc"],"novel_uses":[{"body":"strftime('%Y-%m', created_at) is the standard SQLite bucketing key: it groups rows per month as text, and the same pattern works for %Y or %Y-%W when the report needs another grain.","sql":"SELECT strftime('%Y-%m', created_at) AS month, COUNT(*) AS n\nFROM orders\nGROUP BY month;"},{"body":"strftime('%J', d) returns the Julian day number, so the difference of two calls is the gap in days and fractions of a day, no separate function needed.","sql":"SELECT strftime('%J', finished) - strftime('%J', started) AS days\nFROM jobs;"},{"body":"The 'unixepoch' modifier must come immediately after the value, and 'localtime' after it, which converts stored seconds into the server's local wall clock in one call.","sql":"SELECT strftime('%Y-%m-%d %H:%M', ts, 'unixepoch', 'localtime') AS local_ts\nFROM events;"}]},"source_url":"https://sqlly.app/sql-functions/strftime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/strftime-bucket","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRFTIME bucketing","description":"Bucketing timestamps in SQLite with strftime masks like '%Y-%m' and '%Y-%W': text buckets, week numbering rules, and the start-of-month alternative.","body":{"slug":"strftime-bucket","name":"STRFTIME bucketing","h1":"SQL STRFTIME bucketing","category":"datetime","lede":"strftime is SQLite's main bucketing tool: drop precision by formatting, then group on the resulting text.","syntax":"strftime('%Y-%m', t)","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"FORMAT(d, 'yyyy-MM') or DATETRUNC"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'YYYY-MM') or date_trunc"},{"engine_slug":"mysql","status":"partial","note":"DATE_FORMAT(d, '%Y-%m')"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'YYYY-MM')"}],"gotchas":["strftime has no month or weekday names: %m and %w are numbers only. Labels like 'Aug' or 'Monday' need a CASE over %m or %w.","Week buckets: %W (Monday-first) runs 00-53, with days before the year's first Monday in week 00. SQLite 3.46 added %U (Sunday-first, same week-00 rule), ISO %V and its year %G; older builds need date arithmetic for Sunday or ISO weeks.","For a date-typed month bucket, date(t, 'start of month') beats strftime: it returns a date string you can compare with other dates directly."],"examples":[{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m', created_at) AS month, COUNT(*) FROM events GROUP BY month;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%W', created_at) AS week FROM events;"},{"engine_slug":"sqlite","sql":"SELECT date(created_at, 'start of month') AS month_start FROM events;"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(created_at, 'yyyy-MM') AS month, COUNT(*) FROM events GROUP BY FORMAT(created_at, 'yyyy-MM');"},{"engine_slug":"postgresql","sql":"SELECT to_char(created_at, 'YYYY-MM') AS month, COUNT(*) FROM events GROUP BY month;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) FROM events GROUP BY month;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'YYYY-MM') AS month, COUNT(*) FROM events GROUP BY TO_CHAR(created_at, 'YYYY-MM');"}],"faqs":[{"question":"How do I bucket by quarter in SQLite?","answer":"Compute it: CAST((strftime('%m', t) - 1) / 3 + 1 AS INTEGER) gives 1-4, or build the quarter start with 'start of month' plus month arithmetic."},{"question":"Why does '%Y-%W' show week 00?","answer":"%W puts days before the year's first Monday in week 00, so 2026-01-01 is week 00. ISO 8601 assigns those days to week 1 or to the previous year's last week; use '%G-%V' (SQLite 3.46+) for ISO keys."}],"related":["strftime","dateformat-bucket","datetime-modifiers","date-trunc"],"novel_uses":[{"body":"SQLite has no date_bin, so divide the epoch second count by the slot width and multiply back: one expression yields 5-minute or hourly grids.","sql":"SELECT CAST(strftime('%s', created_at) AS INTEGER) / 300 * 300 AS slot FROM events;"},{"body":"The %w code strips everything but the weekday number, so one query shows traffic by day of week across the whole table.","sql":"SELECT strftime('%w', created_at) AS dow, COUNT(*) FROM events GROUP BY dow ORDER BY dow;"}]},"source_url":"https://sqlly.app/sql-functions/strftime-bucket","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-agg","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRING_AGG / GROUP_CONCAT function","description":"Turn a column into one comma-separated string: STRING_AGG in SQL Server and PostgreSQL, GROUP_CONCAT in MySQL and SQLite, LISTAGG in Oracle, with ordering and limits.","body":{"slug":"string-agg","name":"STRING_AGG / GROUP_CONCAT","h1":"SQL STRING_AGG / GROUP_CONCAT function","category":"aggregate","lede":"Concatenates the values of a group into one delimited string. All five engines have it, under three names, with different ordering syntax and different length limits.","syntax":"STRING_AGG(expr, sep) WITHIN GROUP (ORDER BY ...)  |  GROUP_CONCAT(expr SEPARATOR sep)  |  LISTAGG(expr, sep) WITHIN GROUP (ORDER BY ...)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"STRING_AGG from SQL Server 2017"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"GROUP_CONCAT, with group_concat_max_len capping the result"},{"engine_slug":"sqlite","status":"yes","note":"GROUP_CONCAT, plus STRING_AGG as an alias and ORDER BY inside the call from 3.44"},{"engine_slug":"oracle","status":"partial","note":"LISTAGG; ON OVERFLOW TRUNCATE from 12.2, DISTINCT from 19c"}],"gotchas":["Ordering syntax differs: WITHIN GROUP (ORDER BY ...) on SQL Server and Oracle, ORDER BY inside the call on PostgreSQL, MySQL and SQLite 3.44+. Older SQLite has no ordering option.","MySQL truncates at group_concat_max_len, 1024 bytes by default, with only a warning. Raise it per session: SET SESSION group_concat_max_len = 1000000.","SQL Server's STRING_AGG raises an error past 8000 bytes for varchar input; CAST the value to varchar(max) to lift the limit. Oracle's LISTAGG raises ORA-01489 when the result outgrows VARCHAR2 (4000 bytes by default) unless you add ON OVERFLOW TRUNCATE.","DISTINCT inside the call works on PostgreSQL, MySQL, SQLite and Oracle 19c+. SQL Server's STRING_AGG has no DISTINCT; dedupe in a subquery first."],"examples":[{"engine_slug":"sql-server","sql":"SELECT customer_id,\n       STRING_AGG(product, ', ') WITHIN GROUP (ORDER BY product) AS basket\nFROM order_items\nGROUP BY customer_id;"},{"engine_slug":"postgresql","sql":"SELECT customer_id,\n       STRING_AGG(product, ', ' ORDER BY product) AS basket\nFROM order_items\nGROUP BY customer_id;"},{"engine_slug":"mysql","sql":"SELECT customer_id,\n       GROUP_CONCAT(product ORDER BY product SEPARATOR ', ') AS basket\nFROM order_items\nGROUP BY customer_id;"},{"engine_slug":"sqlite","sql":"-- ORDER BY inside the call needs SQLite 3.44+\nSELECT customer_id,\n       GROUP_CONCAT(product, ', ' ORDER BY product) AS basket\nFROM order_items\nGROUP BY customer_id;"},{"engine_slug":"oracle","sql":"SELECT customer_id,\n       LISTAGG(product, ', ') WITHIN GROUP (ORDER BY product) AS basket\nFROM order_items\nGROUP BY customer_id;"}],"faqs":[{"question":"Which engines use STRING_AGG and which use GROUP_CONCAT?","answer":"SQL Server (2017+) and PostgreSQL call it STRING_AGG. MySQL calls it GROUP_CONCAT. SQLite has GROUP_CONCAT and, from 3.44, STRING_AGG as well. Oracle calls it LISTAGG."},{"question":"Why is my GROUP_CONCAT result truncated?","answer":"MySQL cuts the string at group_concat_max_len, 1024 bytes by default, and only raises a warning. Raise the variable in your session. SQL Server and Oracle raise an error at their length limits instead of truncating."},{"question":"How do I keep the values in order inside the string?","answer":"SQL Server and Oracle need WITHIN GROUP (ORDER BY ...). PostgreSQL, MySQL and SQLite 3.44+ take ORDER BY inside the call. Before 3.44, SQLite has no ordering option, and sorting in a subquery first is common but not guaranteed to hold."}],"related":["count-distinct","array-agg","concat"],"novel_uses":[{"body":"STRING_AGG has no LIMIT clause, but rank first, keep rn <= 3, and the aggregate becomes a top-three-products column per customer. Ordering the aggregate by the rank keeps the list in priority order.","sql":"WITH ranked AS (\n  SELECT customer_id, product,\n         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn\n  FROM order_items\n)\nSELECT customer_id, STRING_AGG(product, ', ' ORDER BY rn) AS top_three\nFROM ranked\nWHERE rn <= 3\nGROUP BY customer_id;"},{"body":"Aggregating the ids you just found into a quoted list hands you the argument for the next query's IN clause, or a compact audit line of exactly which rows a batch touched. Never feed the result into dynamic SQL with user data in it; keep that parameterized.","sql":"SELECT 'IN (' || STRING_AGG('''' || CAST(id AS text) || '''', ', ') || ')' AS in_list\nFROM flagged_rows;"}]},"source_url":"https://sqlly.app/sql-functions/string-agg","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL cast to text","description":"Converting numbers, dates and blobs to text: the engine-specific target names, implicit default formats, and where formatting belongs instead (TO_CHAR, CONVERT styles).","body":{"slug":"string-cast","name":"CAST AS CHAR / VARCHAR","h1":"SQL cast to text","category":"conversion","lede":"CAST(x AS CHAR) turns a value into text on MySQL, and into a single character on PostgreSQL. The target name, default length and output format all differ per engine.","syntax":"CAST(expression AS CHAR)  -- MySQL  |  CAST(expression AS varchar(n))  -- SQL Server, PostgreSQL  |  CAST(expression AS VARCHAR2(n))  -- Oracle","return_type":"text","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Target names differ: varchar on SQL Server and PostgreSQL, CHAR on MySQL (which rejects CAST AS VARCHAR), TEXT on SQLite, VARCHAR2(n) on Oracle. On PostgreSQL, CHAR means character(1): CAST(123 AS CHAR) is '1'.","Leaving out the length is engine-specific: SQL Server's CAST(x AS varchar) means varchar(30) and cuts, errors or returns '*' beyond that, PostgreSQL's means unlimited, and Oracle's VARCHAR2 without a length is a syntax error.","Dates come out in the engine's default format. On SQL Server, CAST(GETDATE() AS varchar(10)) gives 'Nov 20 202' from datetime's style 0; a date column gives '2026-01-31'. Pin it down with CONVERT style 120/126 or TO_CHAR with a mask."],"examples":[{"engine_slug":"mysql","sql":"SELECT CONCAT(id, ' - ', CAST(total AS CHAR)) AS label\nFROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(price AS TEXT) AS p FROM items;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(19), created_at, 120) AS ts FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT total::text AS label\nFROM orders;"},{"engine_slug":"oracle","sql":"SELECT CAST(total AS VARCHAR2(20)) AS label\nFROM orders;"}],"faqs":[{"question":"How do I get ISO 8601 dates as text?","answer":"SQL Server: CONVERT(varchar(30), d, 126). PostgreSQL: d::date::text or TO_CHAR. MySQL and SQLite store and print ISO by default. Oracle: TO_CHAR(d, 'YYYY-MM-DD')."},{"question":"Why is my number cast losing decimals?","answer":"Float-to-text uses the engine's default conversion: SQL Server's CAST(1.0e0/3 AS varchar) is '0.333333', six significant digits. Exact DECIMAL values keep their scale. For floats, format explicitly with CONVERT style 3, TO_CHAR or printf."}],"related":["cast","to-char-numeric","convert","cast-truncation"],"novel_uses":[{"body":"Concatenating plain varchars cuts the result at 8000 bytes (4000 for nvarchar) with no error. Casting the first operand to varchar(max) promotes the whole expression, so long note concatenations arrive intact.","sql":"SELECT CAST(hdr AS varchar(max)) + body AS full_text FROM templates;"},{"body":"length(CAST(n AS TEXT)) gives the digit count of a number on PostgreSQL and SQLite (MySQL needs LENGTH(CAST(n AS CHAR)), SQL Server LEN(CAST(n AS varchar(20)))), which flags IDs or phone fields that grew past their expected width without any logarithm.","sql":"SELECT n FROM accounts WHERE length(CAST(n AS TEXT)) > 6;"},{"body":"CAST(label AS CHAR CHARACTER SET utf8mb4) gives the value the server's default utf8mb4 collation, which fixes 'Illegal mix of collations' errors in joins between a utf8mb4_unicode_ci column and a utf8mb4_0900_ai_ci one without touching either table's definition.","sql":"SELECT * FROM a JOIN b ON CAST(a.name AS CHAR CHARACTER SET utf8mb4) = b.name;"}]},"source_url":"https://sqlly.app/sql-functions/string-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-hash","corpus":"sql-functions","engine":null,"language":"en","title":"SQL string hashing","description":"Hash strings per engine: MD5 and SHA2 in MySQL, md5 and sha256 in PostgreSQL, HASHBYTES on SQL Server, STANDARD_HASH on Oracle; hex output shapes differ.","body":{"slug":"string-hash","name":"Hashing strings","h1":"SQL string hashing","category":"string","lede":"Compute a cryptographic digest of a value in-query for dedupe, change detection and joins. The function names and output types vary; the caveats do not.","syntax":"MD5(s)  |  HASHBYTES('SHA2_256', s)  |  STANDARD_HASH(s, 'SHA256')","return_type":"string / binary","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no built-in md5 or SHA-2 function; the sqlite3 shell adds sha3() only"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Output types differ: MySQL's MD5 returns lowercase hex text, SQL Server's HASHBYTES returns binary (CONVERT(..., 2) renders uppercase hex without 0x), Oracle's STANDARD_HASH returns RAW.","PostgreSQL: md5() is built in and returns hex text; sha256() (PG 11+) returns bytea: encode(sha256(convert_to(s, 'utf8')), 'hex') for the hex form.","Encoding matters: the hash covers the stored bytes, so latin1 and utf8mb4 columns hash the same visible text differently.","Use hashes for dedupe and comparison only, never for passwords, which need salted, slow KDFs done outside the query."],"examples":[{"engine_slug":"postgresql","sql":"SELECT md5('abc') AS h;  -- 900150983cd24fb0d6963f7d28e17f72"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', 'abc'), 2) AS h;"},{"engine_slug":"mysql","sql":"SELECT SHA2('abc', 256) AS h;"},{"engine_slug":"oracle","sql":"SELECT STANDARD_HASH('abc', 'SHA256') AS h FROM dual;"}],"faqs":[{"question":"Which engines can hash in SQL?","answer":"MySQL (MD5, SHA1, SHA2), PostgreSQL (md5, sha2xx family), SQL Server (HASHBYTES) and Oracle (STANDARD_HASH). SQLite has no built-in md5 or SHA-2; the sqlite3 shell adds sha3() only."},{"question":"Why do my hashes differ between systems?","answer":"Different input encodings (bytes, not characters, are hashed), different algorithms, or hex case. Pin the algorithm, the encoding, and the rendering first."},{"question":"Is MD5 acceptable for deduping rows?","answer":"Yes. Collisions are practically irrelevant there. For integrity or security-sensitive checks, use SHA-256."}],"related":["hex","conv","string-length-limits"],"novel_uses":[{"body":"Hashing JSON_ARRAY(id, status, updated_at) gives one comparable value per row, and JSON_ARRAY keeps each NULL in its own position as JSON null, so rows with NULLs in different columns hash apart. CONCAT_WS skips NULL arguments entirely, so (1, NULL, 'x') and (1, 'x', NULL) both become '1|x', and plain CONCAT returns NULL for the whole row.","sql":"SELECT MD5(JSON_ARRAY(id, status, updated_at)) AS row_hash FROM orders;"},{"body":"md5 of the key hex-encoded starts with 0 for about one row in sixteen, and the same rows qualify every run, which makes reproducible sampling a one-line WHERE on PostgreSQL.","sql":"SELECT * FROM events WHERE md5(user_id::TEXT) LIKE '0%';  -- reproducible ~1/16 sample"}]},"source_url":"https://sqlly.app/sql-functions/string-hash","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-length-limits","corpus":"sql-functions","engine":null,"language":"en","title":"SQL string length limits","description":"Silent truncation and ORA-01489: the string length limits that bite in practice (Oracle literals, SQL Server's 8000-byte math, MySQL packets).","body":{"slug":"string-length-limits","name":"String length limits","h1":"SQL string length limits","category":"string","lede":"Every engine caps strings somewhere, and the caps apply at surprising places: literals, concatenations and aggregate results, not just columns.","syntax":"VARCHAR2(32767)  |  nvarchar(max)  |  TEXT","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server: non-max string math caps at 8000 bytes; REPLICATE('x', 9000) yields 8000 characters silently. Cast REPLICATE's string argument to varchar(max)/nvarchar(max) to lift it; a cast on the count or on an operand added afterwards leaves the 8000 cap in place.","Oracle: VARCHAR2 in SQL caps at 4000 bytes (32767 with MAX_STRING_SIZE=EXTENDED). || past the cap raises ORA-01489, but LPAD and RPAD cut their result to 4000 without a word.","MySQL: row and packet limits apply; max_allowed_packet caps big values, and the 65535-byte row limit is shared across all CHAR/VARCHAR columns (TEXT and BLOB columns count only 9 to 12 bytes each).","PostgreSQL is the outlier: TEXT holds up to about 1 GB per value, and a concatenation result is bound by that same ceiling."],"examples":[{"engine_slug":"sql-server","sql":"SELECT LEN(REPLICATE('x', 9000)) AS cut;  -- 8000"},{"engine_slug":"sql-server","sql":"SELECT LEN(REPLICATE(CAST('x' AS varchar(max)), 9000)) AS full_;  -- 9000"},{"engine_slug":"oracle","sql":"SELECT LENGTH(LPAD('y', 9000, 'y')) FROM dual;  -- 4000, cut silently\nSELECT LPAD('y', 3000, 'y') || LPAD('y', 3000, 'y') FROM dual;  -- ORA-01489"},{"engine_slug":"postgresql","sql":"SELECT length(repeat('x', 1000000)) AS len;  -- 1000000: TEXT stretches to 1 GB"},{"engine_slug":"mysql","sql":"SELECT LENGTH(REPEAT('x', 1000000)) AS len;  -- 1000000: fine, but max_allowed_packet and the 65535-byte row limit cap bigger values"},{"engine_slug":"sqlite","sql":"SELECT length(zeroblob(1000000)) AS len;  -- 1000000: strings and blobs both stop near 1 GB by default, no 8000-byte trap"}],"faqs":[{"question":"Why did my 9000-character string get cut to 8000?","answer":"SQL Server types REPLICATE's result as varchar(8000) because its string argument is not varchar(max). A literal and a varchar(10) variable both cap the same way. A varchar(max) cast on that string argument promotes the result; a cast elsewhere in the expression does not."},{"question":"What is ORA-01489?","answer":"Oracle's error when a concatenated or aggregated string passes 4000 bytes. Set MAX_STRING_SIZE=EXTENDED (32767), or build a CLOB instead: TO_CLOB on one operand, or XMLAGG / JSON_ARRAYAGG ... RETURNING CLOB for aggregates."},{"question":"Does VARCHAR(max) have real limits?","answer":"SQL Server's max types hold 2 GB. The limit is per value, not per expression, but literal-only expressions still default to the 8000-byte trap above."}],"related":["varchar-char-semantics","replicate","string-agg","listagg"],"novel_uses":[{"body":"One expression per engine documents the truncation before you port a string builder: SQL Server lifts its cap with a varchar(max) cast while Oracle's LPAD stops at 4000 without a word.","sql":"SELECT LENGTH(REPLICATE(CAST('x' AS varchar(max)), 100000)) AS cap;  -- 100000; Oracle LPAD would return 4000"},{"body":"PL/SQL VARCHAR2 variables hold 32767 bytes while SQL expressions still cap at 4000 unless MAX_STRING_SIZE=EXTENDED, so a builder that works in a procedure can still fail the moment its result meets a query.","sql":"SELECT LENGTH(LPAD('x', 32000, 'x')) FROM dual;  -- 4000 in SQL; a PL/SQL variable would hold 32000"}]},"source_url":"https://sqlly.app/sql-functions/string-length-limits","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-sort","corpus":"sql-functions","engine":null,"language":"en","title":"SQL string sorting and collation","description":"String order is collation, not ASCII: case-insensitive sorts, NO PAD equality and linguistic orders per engine, and how to pin ORDER BY down.","body":{"slug":"string-sort","name":"Sorting strings","h1":"SQL string sorting and collation","category":"string","lede":"ORDER BY on text follows the column's collation or locale, which decides where capitals, accents and spaces land. Pin it per query when the order matters.","syntax":"ORDER BY name COLLATE collation_name  |  ORDER BY NLSSORT(name, 'NLS_SORT=XGerman')","return_type":"ordering","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Binary order puts 'Zebra' before 'apple' (Z is 90, a is 97). Case-insensitive collations reorder the alphabet; the default differs per engine and per column.","PostgreSQL: the database locale decides, with per-expression COLLATE \"de-x-icu\" overrides on ICU installs.","SQL Server: per-column and per-query collations (Latin1_General_BIN2 for code-point order, _CI variants for case-insensitive listings).","Oracle: NLS_SORT is BINARY by default; ORDER BY NLSSORT(name, 'NLS_SORT=XGERMAN') or NLS_COMP=LINGUISTIC switches to linguistic order."],"examples":[{"engine_slug":"sql-server","sql":"SELECT name FROM users ORDER BY name COLLATE Latin1_General_BIN2;\n-- byte order: 'Zebra' before 'apple'"},{"engine_slug":"postgresql","sql":"SELECT name FROM users ORDER BY name COLLATE \"de-x-icu\";"},{"engine_slug":"oracle","sql":"SELECT name FROM users ORDER BY NLSSORT(name, 'NLS_SORT = XGERMAN');"},{"engine_slug":"mysql","sql":"SELECT name FROM users ORDER BY name COLLATE utf8mb4_bin;  -- byte order: 'Zebra' before 'apple'"},{"engine_slug":"sqlite","sql":"SELECT name FROM users ORDER BY name;  -- BINARY: 'Zebra' before 'apple'; COLLATE NOCASE folds ASCII case only"}],"faqs":[{"question":"Why does the same query sort differently on two servers?","answer":"The columns carry different collations, or the database locales differ. Sorting is a collation property, not an ASCII constant. State the collation for stable cross-server order."},{"question":"How do I sort case-insensitively?","answer":"Use a case-insensitive collation (SQL Server default _CI, MySQL _ci) rather than ORDER BY UPPER(name), which defeats indexes. PostgreSQL's built-in ICU collations such as \"de-x-icu\" are case-sensitive; create a nondeterministic one with locale 'und-u-ks-level2' and deterministic = false when you need case-insensitive equality."},{"question":"Does collation affect WHERE comparisons too?","answer":"Yes. The same collation decides equality, so PAD SPACE and accent rules show up in both ORDER BY and = at once."}],"related":["case-insensitive-collation","char-padding-compare","turkish-i","strcmp"],"novel_uses":[{"body":"Extracting the digit run and casting to int puts item2 before item10 on PostgreSQL, with NULLS LAST keeping the no-number rows at the end.","sql":"SELECT name FROM items\nORDER BY NULLIF(substring(name, '[0-9]+'), '')::INT NULLS LAST, name;"},{"body":"A function-based index on NLSSORT(name, 'NLS_SORT=XGERMAN') lets Oracle satisfy a German-linguistic ORDER BY from the index instead of sorting every time.","sql":"CREATE INDEX customers_name_de ON customers (NLSSORT(name, 'NLS_SORT=XGERMAN'));"}]},"source_url":"https://sqlly.app/sql-functions/string-sort","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-split","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRING_SPLIT function","description":"How STRING_SPLIT turns a delimited string into rows in SQL Server: CROSS APPLY usage, the ordinal argument from SQL Server 2022, and the split functions in other engines.","body":{"slug":"string-split","name":"STRING_SPLIT","h1":"SQL STRING_SPLIT function","category":"string","lede":"A table-valued function that splits a string on a single-character separator and returns one row per element.","syntax":"STRING_SPLIT(string, separator [, enable_ordinal])  |  CROSS APPLY STRING_SPLIT(col, ',')","return_type":"table of value rows","support":[{"engine_slug":"sql-server","status":"yes","note":"Needs database compatibility level 130+; the ordinal argument needs SQL Server 2022 or Azure SQL."},{"engine_slug":"postgresql","status":"partial","note":"string_to_table(str, ',') from PostgreSQL 14, or regexp_split_to_table."},{"engine_slug":"mysql","status":"no","note":"No built-in; JSON_TABLE or a recursive CTE fills the gap."},{"engine_slug":"sqlite","status":"no","note":"No built-in; json_each over a JSON array is the common trick."},{"engine_slug":"oracle","status":"no","note":"No STRING_SPLIT; walk the string with REGEXP_SUBSTR and CONNECT BY."}],"gotchas":["It returns rows, not an array, so you join it: CROSS APPLY STRING_SPLIT(t.csv, ',') produces one row per element of each source row.","Without the third argument row order is not guaranteed. SQL Server 2022 and Azure SQL accept STRING_SPLIT(str, ',', 1), which adds a 1-based ordinal column to sort on. The third argument must be a literal constant; a variable or column raises error 8748.","Empty elements survive: 'a,,b' yields three rows, the middle one empty. Filter value <> '' if blanks should vanish. Spaces after the comma are kept too; TRIM the value."],"examples":[{"engine_slug":"sql-server","sql":"SELECT value FROM STRING_SPLIT('a,b,c', ',');"},{"engine_slug":"sql-server","sql":"SELECT t.id, s.value AS tag\nFROM posts t\nCROSS APPLY STRING_SPLIT(t.tags, ',', 1) s\nORDER BY t.id, s.ordinal;"},{"engine_slug":"postgresql","sql":"SELECT string_to_table('a,b,c', ',') AS value;"}],"faqs":[{"question":"How do I keep the original order of the elements?","answer":"Pass 1 as the third argument (SQL Server 2022+ and Azure SQL): STRING_SPLIT(str, ',', 1) returns an ordinal column; ORDER BY it. Older versions have no reliable order, so use a JSON array and OPENJSON, whose key column is the zero-based position."},{"question":"What is the PostgreSQL equivalent?","answer":"string_to_table(str, ',') from PostgreSQL 14, unnest(string_to_array(str, ',')) in any version, or regexp_split_to_table for regex separators. All return one row per element."},{"question":"Can STRING_SPLIT split on multi-character separators?","answer":"No, the separator must be exactly one character; a multi-character, empty or NULL separator raises error 214. Replace a multi-character delimiter with a character that never occurs in the data first, then split."}],"related":["string-to-array","substring-index","find-in-set","parsename"],"novel_uses":[{"body":"Splitting and re-aggregating in one query trims every element and drops the empties, which normalizes a sloppy CSV column without a script. STRING_AGG needs SQL Server 2017 or later.","sql":"SELECT STRING_AGG(LTRIM(RTRIM(value)), ',') AS cleaned\nFROM (SELECT tags FROM posts WHERE id = 7) t\nCROSS APPLY STRING_SPLIT(t.tags, ',')\nWHERE value <> '';"},{"body":"CROSS APPLY STRING_SPLIT turns each comma-separated cell into rows that join against a dictionary table, which retrofits referential integrity onto a legacy design.","sql":"SELECT p.id, d.label\nFROM posts p\nCROSS APPLY STRING_SPLIT(p.tags, ',') s\nJOIN tag_dict d ON d.name = LTRIM(RTRIM(s.value));"},{"body":"STRING_SPLIT takes one character only. Building a JSON array with REPLACE and reading it with OPENJSON splits on the longer delimiter, as long as no element contains a double quote or a backslash. A double quote makes OPENJSON raise error 13609, and a backslash is read as a JSON escape, so a backslash in a value silently becomes a control character.","sql":"SELECT value FROM OPENJSON('[\"' + REPLACE(cmds, '; ', '\",\"') + '\"]');"}]},"source_url":"https://sqlly.app/sql-functions/string-split","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/string-to-array","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRING_TO_ARRAY function","description":"How string_to_array splits a string into a text array in PostgreSQL: NULL separator semantics, empty-string elements, and unnest or subscripts to consume the result.","body":{"slug":"string-to-array","name":"STRING_TO_ARRAY","h1":"SQL STRING_TO_ARRAY function","category":"string","lede":"Splits a string on a separator and returns the elements as a text array.","syntax":"string_to_array(string, separator [, null_string])","return_type":"text[]","support":[{"engine_slug":"sql-server","status":"no","note":"No arrays; STRING_SPLIT returns rows instead."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"No array type; SUBSTRING_INDEX or JSON functions."},{"engine_slug":"sqlite","status":"no","note":"No array type; JSON arrays via the json functions."},{"engine_slug":"oracle","status":"no","note":"No direct equivalent; collections or REGEXP_SUBSTR walks."}],"gotchas":["A NULL separator splits into single characters: string_to_array('abc', NULL) is {a,b,c}. An empty-string separator does the opposite and returns the whole input as one element.","The optional third argument turns matching elements into NULL: string_to_array('a,,b', ',', '') is {a,NULL,b}.","Consume the result with unnest (to rows), a 1-based subscript (parts[1]), or array_length for the element count. string_to_table, from PostgreSQL 14, skips the array."],"examples":[{"engine_slug":"postgresql","sql":"SELECT string_to_array('a,b,c', ',') AS parts;  -- {a,b,c}"},{"engine_slug":"postgresql","sql":"SELECT unnest(string_to_array(tags, ',')) AS tag\nFROM posts;"}],"faqs":[{"question":"How do I turn the array back into rows?","answer":"Wrap it with unnest: SELECT unnest(string_to_array(str, ',')). On PostgreSQL 14+ string_to_table(str, ',') does both steps."},{"question":"Why do empty elements appear in my array?","answer":"Adjacent separators create empty-string elements by design. Pass '' as the third argument to turn them into NULL, or filter them out after unnest."},{"question":"Are array indexes 1-based?","answer":"Yes in PostgreSQL: parts[1] is the first element, and parts[0] is NULL rather than an error."}],"related":["array-to-string","string-split","regexp-split-to-array","substring-index"],"novel_uses":[{"body":"A NULL separator splits into single characters, so unnest plus GROUP BY turns a word list into a letter frequency table in pure SQL.","sql":"SELECT c AS letter, count(*)\nFROM words, unnest(string_to_array(lower(word), NULL)) AS c\nGROUP BY c\nORDER BY count(*) DESC;"},{"body":"array_position over the split list is the PostgreSQL answer to FIND_IN_SET: true membership, not the substring hit that LIKE would give.","sql":"SELECT * FROM servers\nWHERE array_position(string_to_array(roles, ','), 'replica') IS NOT NULL;"},{"body":"cardinality of the split array is the element count, a cheap sanity check on imported CSV before any unnest.","sql":"SELECT cardinality(string_to_array(row_text, ',')) AS fields\nFROM imports;"}]},"source_url":"https://sqlly.app/sql-functions/string-to-array","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/strip-non-ascii","corpus":"sql-functions","engine":null,"language":"en","title":"SQL strip non-ASCII characters","description":"Clean a string to printable ASCII: REGEXP_REPLACE ranges where regex exists; before SQL Server 2025, TRANSLATE maps only the characters you list, so others survive.","body":{"slug":"strip-non-ascii","name":"Stripping non-ASCII characters","h1":"SQL strip non-ASCII characters","category":"string","lede":"Drop or transliterate characters outside the printable ASCII range, the classic cleanup for feeds, keys and legacy interfaces.","syntax":"REGEXP_REPLACE(s, '[^ -~]', '')","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"REGEXP_REPLACE from SQL Server 2025; TRANSLATE or REPLACE maps before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no REGEXP_REPLACE; nested replace() calls or an extension"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The range ' -~' (space through tilde) is all printable ASCII: REGEXP_REPLACE(s, '[^ -~]', '') strips accents, emoji, NBSPs and control characters in one pass.","PostgreSQL, MySQL 8.0.4+, Oracle and SQL Server 2025 support that regex (PostgreSQL needs the 'g' flag to replace every match). SQL Server 2017 to 2022 has TRANSLATE but no regex, so use explicit TRANSLATE(name, N'éàü', N'eau') maps there; SQL Server 2016 and earlier have no TRANSLATE and need nested REPLACE.","Decide strip versus transliterate: stripping 'café' to 'caf' loses data; unaccent-style transliteration keeps it readable. Usually transliterate first, then strip."],"examples":[{"engine_slug":"postgresql","sql":"SELECT REGEXP_REPLACE(name, '[^ -~]', '', 'g') AS clean FROM names;"},{"engine_slug":"oracle","sql":"SELECT REGEXP_REPLACE(name, '[^ -~]', '') AS clean FROM names;"},{"engine_slug":"sql-server","sql":"SELECT TRANSLATE(N'café №5', N'é№', N'e-') AS clean;  -- cafe -5"},{"engine_slug":"mysql","sql":"SELECT REGEXP_REPLACE(name, '[^ -~]', '') AS clean FROM names;  -- MySQL 8, ICU regex"}],"faqs":[{"question":"What does the pattern '[^ -~]' match?","answer":"Everything outside printable ASCII: the space character starts the range and tilde ends it. Anything accented, emoji, tab or newline falls outside and gets removed."},{"question":"How do I keep accented letters but fold them to ASCII?","answer":"Transliterate before stripping: PostgreSQL's unaccent extension (it turns ß into ss), TRANSLATE maps with your known character set, or Unicode NFKD normalization plus a combining-mark removal. NFKD alone leaves letters such as ß unchanged, so map those by hand."},{"question":"Why does SQL Server make this hard?","answer":"Before SQL Server 2025, T-SQL had no regex. Build an explicit TRANSLATE/REPLACE map of the characters you actually see, and keep the map strings N'': a varchar literal turns № into ? before TRANSLATE ever sees it."}],"related":["translate","unaccent","regexp-replace","remove-nbsp"],"novel_uses":[{"body":"Lowercasing first and replacing every non-alphanumeric run with a dash gives a slug; trimming the edge dashes finishes it on PostgreSQL.","sql":"SELECT btrim(REGEXP_REPLACE(LOWER(name), '[^a-z0-9]+', '-', 'g'), '-') AS slug\nFROM articles;"},{"body":"Matching what is allowed, [^A-Za-z0-9._-], instead of chasing every exotic character keeps the pattern stable when the next unusual code point arrives.","sql":"SELECT REGEXP_REPLACE(name, '[^A-Za-z0-9._-]', '', 'g') AS clean FROM users;"}]},"source_url":"https://sqlly.app/sql-functions/strip-non-ascii","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/strpos","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STRPOS function","description":"How STRPOS(string, substring) works in PostgreSQL: 1-based result, 0 when absent, exact-case matching, and the INSTR and CHARINDEX equivalents in other engines.","body":{"slug":"strpos","name":"STRPOS","h1":"SQL STRPOS function","category":"string","lede":"PostgreSQL's function-call form of POSITION: the string to search comes first, the substring second.","syntax":"STRPOS(string, substring)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"Use CHARINDEX(substr, str); note the reversed order."},{"engine_slug":"postgresql","status":"yes","note":"Same result as POSITION(substr IN str)."},{"engine_slug":"mysql","status":"partial","note":"Use INSTR(str, substr) or LOCATE(substr, str)."},{"engine_slug":"sqlite","status":"partial","note":"Use INSTR(str, substr)."},{"engine_slug":"oracle","status":"partial","note":"Use INSTR(str, substr)."}],"gotchas":["The string comes first, like INSTR and unlike CHARINDEX or POSITION: STRPOS('hello world', 'world') is 7.","Matching is case-sensitive: STRPOS('Hello', 'hello') is 0. Compare lower() of both sides for a case-insensitive position. For a yes or no, ILIKE only works when the needle has no % or _, because those are wildcards there: 'xabc' ILIKE '%a_c%' is true while STRPOS('xabc', 'a_c') is 0.","An empty substring matches at position 1, so STRPOS(s, '') is 1 for any non-NULL s. SQL Server's CHARINDEX returns 0 for the same search."],"examples":[{"engine_slug":"postgresql","sql":"SELECT STRPOS('hello world', 'world') AS pos;  -- 7"},{"engine_slug":"postgresql","sql":"SELECT STRPOS(lower(path), '/admin') AS admin_pos\nFROM page_views;"},{"engine_slug":"sql-server","sql":"SELECT CHARINDEX('world', 'hello world') AS pos;  -- 7"},{"engine_slug":"mysql","sql":"SELECT INSTR('hello world', 'world') AS pos;  -- 7"},{"engine_slug":"sqlite","sql":"SELECT INSTR('hello world', 'world') AS pos;  -- 7"},{"engine_slug":"oracle","sql":"SELECT INSTR('hello world', 'world') AS pos\nFROM dual;"}],"faqs":[{"question":"What is the difference between STRPOS and POSITION in PostgreSQL?","answer":"Only the syntax. STRPOS(str, substr) is a normal function call; POSITION(substr IN str) is the standard keyword form. Both return the same 1-based index."},{"question":"Why does STRPOS return 0 instead of NULL for a missing substring?","answer":"0 is the not-found answer. NULL is reserved for a NULL input, so STRPOS(s, x) > 0 works as a contains test as long as neither s nor x is NULL."}],"related":["position","charindex","instr","substring"],"novel_uses":[{"body":"left(s, strpos(s, d) - 1) and substr(s, strpos(s, d) + 1) return the two halves around the first delimiter when it is present. When it is missing, strpos returns 0 and left(s, -1) drops only the last character, so guard with strpos(s, d) > 0 first. This covers most cases where you would reach for split_part with a computed index.","sql":"SELECT left(path, strpos(path, '/') - 1) AS root,\n       substr(path, strpos(path, '/') + 1) AS rest\nFROM links;"},{"body":"A PostgreSQL 12+ stored generated column accepts strpos because strpos is immutable: a boolean flag computed on write can be indexed. Filter on the flag column (WHERE has_todo) to use that index; WHERE strpos(body, 'TODO') > 0 still scans the table.","sql":"ALTER TABLE notes ADD has_todo boolean\n  GENERATED ALWAYS AS (strpos(body, 'TODO') > 0) STORED;\nCREATE INDEX ON notes (has_todo);"},{"body":"strpos(s, d) + strpos(substr(s, strpos(s, d) + 1), d) lands on the second delimiter when one exists. When it does not, the inner call returns 0 and the sum collapses to the first.","sql":"SELECT strpos(path, '/') + strpos(substr(path, strpos(path, '/') + 1), '/') AS second_slash\nFROM links;"}]},"source_url":"https://sqlly.app/sql-functions/strpos","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/stuff","corpus":"sql-functions","engine":null,"language":"en","title":"SQL STUFF function","description":"STUFF deletes a slice by position and inserts new text there: SQL Server's positional splice, with overlay and INSERT as the PostgreSQL and MySQL twins.","body":{"slug":"stuff","name":"STUFF","h1":"SQL STUFF function","category":"string","lede":"Position-based edit: delete len characters starting at pos, then insert the replacement into the gap. Value-based REPLACE's positional sibling.","syntax":"STUFF(string, pos, len, new_string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"overlay(s placing new FROM pos FOR len)"},{"engine_slug":"mysql","status":"partial","note":"INSERT(s, pos, len, new)"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Positions are 1-based. SQL Server returns NULL when pos is 0, negative, or past the last character (so STUFF cannot append), or when len is negative. len 0 means pure insertion, and a NULL replacement means pure deletion: STUFF('abc', 2, 1, NULL) is 'ac'.","PostgreSQL's overlay(s placing 'XY' FROM 3 FOR 2) and MySQL's INSERT(s, 3, 2, 'XY') do the same job, but edge cases differ: MySQL's INSERT returns the original string when pos is out of range instead of NULL. A negative len is also not NULL in MySQL: INSERT('abc', 2, -1, 'X') is 'aX', and a NULL replacement makes INSERT return NULL where STUFF deletes.","It is not REPLACE: STUFF edits by coordinates, REPLACE by value, and TRANSLATE character by character.","Formatting idioms: STUFF(phone, 4, 0, '-') inserts dashes without deleting anything."],"examples":[{"engine_slug":"sql-server","sql":"SELECT STUFF('abcdef', 3, 2, 'XY') AS spliced;  -- abXYef"},{"engine_slug":"postgresql","sql":"SELECT overlay('abcdef' placing 'XY' from 3 for 2) AS spliced;  -- abXYef"},{"engine_slug":"mysql","sql":"SELECT INSERT('abcdef', 3, 2, 'XY') AS spliced;  -- abXYef"}],"faqs":[{"question":"What does len = 0 do in STUFF?","answer":"Nothing is deleted: the replacement is inserted at the position. STUFF('abc', 2, 0, 'X') gives 'aXbc', the standard insert-at-position idiom."},{"question":"Why does MySQL's INSERT return the whole string?","answer":"MySQL's INSERT(str, pos, len, new) returns the original unchanged when pos is outside the string, while SQL Server's STUFF returns NULL. Different edge semantics for the same shape."},{"question":"Is STUFF available outside SQL Server?","answer":"Not in MySQL, PostgreSQL or SQLite. PostgreSQL's overlay() and MySQL's INSERT() are the equivalents; SQLite hand-rolls with SUBSTR concatenation."}],"related":["replace","substring","translate"],"novel_uses":[{"body":"Two zero-length STUFF calls insert dashes at fixed positions, turning a stored 1234567890 into 123-456-7890 for display while the column stays clean.","sql":"SELECT STUFF(STUFF(phone_raw, 4, 0, '-'), 8, 0, '-') AS phone FROM contacts;"},{"body":"STUFF(line, 12, 8, '') removes columns 12 through 19 of a fixed-width record, the kind of positional edit REPLACE cannot express because it matches by value.","sql":"SELECT STUFF(line, 12, 8, '') AS cleaned FROM feed;"}]},"source_url":"https://sqlly.app/sql-functions/stuff","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/substr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUBSTR function","description":"How SUBSTR(str, start, length) extracts a substring in SQLite, Oracle, MySQL and PostgreSQL: 1-based starts, what start 0 and negative values do, and SUBSTRING.","body":{"slug":"substr","name":"SUBSTR","h1":"SQL SUBSTR function","category":"string","lede":"Extracts part of a string starting at a 1-based position, optionally limited to a length.","syntax":"SUBSTR(str, start)  |  SUBSTR(str, start, length)","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"No SUBSTR; spelled SUBSTRING(str, start, length)."},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Start 0 is not the same as 1 everywhere: Oracle treats 0 as 1 (SUBSTR('abc', 0, 2) is 'ab'), SQLite and PostgreSQL count position 0 against the length ('a'), and MySQL returns an empty string.","Negative starts count from the end in Oracle, MySQL and SQLite: SUBSTR('abcdef', -3) is 'def'. PostgreSQL does not; the same call returns 'abcdef'.","A zero length returns '' in MySQL, PostgreSQL and SQLite but NULL in Oracle. A negative length is an error in PostgreSQL, NULL in Oracle, '' in MySQL, and in SQLite it returns the characters before the start: SUBSTR('abcdef', 4, -2) is 'bc'."],"examples":[{"engine_slug":"sqlite","sql":"SELECT SUBSTR('2026-11-20', 1, 7) AS year_month;  -- 2026-11"},{"engine_slug":"oracle","sql":"SELECT SUBSTR(phone, -4) AS last_four\nFROM contacts;"},{"engine_slug":"postgresql","sql":"SELECT SUBSTR(code, 4, 2) AS region\nFROM postcodes;"},{"engine_slug":"mysql","sql":"SELECT SUBSTR('abcdef', -3) AS tail;  -- def"},{"engine_slug":"sql-server","sql":"SELECT SUBSTRING('abcdef', 2, 3) AS middle;  -- bcd"}],"faqs":[{"question":"Is SUBSTR different from SUBSTRING?","answer":"Same function. SUBSTRING is the standard name and the only one SQL Server accepts; SQLite, Oracle, MySQL and PostgreSQL accept SUBSTR, and all of them except Oracle also accept SUBSTRING."},{"question":"What does a negative start position mean?","answer":"In Oracle, MySQL and SQLite it counts from the end: SUBSTR('abcdef', -3) is 'def'. PostgreSQL treats it as a position before the string, so use RIGHT(s, 3) there."},{"question":"What happens when the length runs past the end of the string?","answer":"You get the characters that exist, with no error: SUBSTR('abc', 2, 99) is 'bc'."}],"related":["substring","left","right","charindex"],"novel_uses":[{"body":"Legacy exports put each field at a fixed offset, and one SUBSTR per field with 1-based offsets reads them without a parser. Keep the offsets next to the query; they are the documentation.","sql":"SELECT SUBSTR(line, 1, 10) AS account,\n       SUBSTR(line, 11, 8) AS date_iso,\n       SUBSTR(line, 19) AS amount\nFROM uploads;"},{"body":"SQLite substr counts bytes on a BLOB, so the 16 stored bytes slice into the standard groups and hex renders each one for display.","sql":"SELECT lower(hex(substr(raw_uuid, 1, 4))) || '-'\n    || lower(hex(substr(raw_uuid, 5, 2))) || '-'\n    || lower(hex(substr(raw_uuid, 7, 2))) AS uuid_head\nFROM devices;"},{"body":"substring over bytea reads bytes in PostgreSQL, so comparing the first four bytes against the PNG signature routes files by content instead of by extension.","sql":"SELECT * FROM uploads\nWHERE substring(bytes from 1 for 4) = decode('89504e47', 'hex');"}]},"source_url":"https://sqlly.app/sql-functions/substr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/substrb","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUBSTRB function","description":"How SUBSTRB extracts by byte position instead of character position in Oracle: multi-byte UTF-8 pitfalls, blanks at mid-character cuts, and character-based SUBSTR.","body":{"slug":"substrb","name":"SUBSTRB","h1":"SQL SUBSTRB function","category":"string","lede":"Oracle's byte-oriented SUBSTR: positions and lengths count bytes, not characters.","syntax":"SUBSTRB(str, start_byte)  |  SUBSTRB(str, start_byte, length_bytes)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No SUBSTRB; SUBSTRING on a varbinary cast counts bytes."},{"engine_slug":"postgresql","status":"no","note":"No SUBSTRB; substring() on convert_to(s, 'UTF8') counts bytes."},{"engine_slug":"mysql","status":"no","note":"No SUBSTRB; SUBSTRING on a BINARY cast counts bytes."},{"engine_slug":"sqlite","status":"no","note":"No SUBSTRB; SUBSTR on a BLOB counts bytes."},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["In UTF-8 one character takes one to four bytes. When the byte range starts or ends inside a character, Oracle replaces the partial character with a space: SUBSTRB('aéb', 1, 2) cannot return 'aé' in an AL32UTF8 database, because 'é' is two bytes and 'aé' is three; SUBSTRB('aéb', 1, 3) returns 'aé'.","Use SUBSTRB when the limit really is in bytes: fixed single-byte data, hex strings, or fields a downstream system caps by byte length. Use SUBSTR for user-visible text.","LENGTHB is the byte-counting companion of LENGTH; comparing the two shows which rows hold multi-byte characters."],"examples":[{"engine_slug":"oracle","sql":"SELECT SUBSTRB(hex_hash, 1, 16) AS first_16_bytes\nFROM digests;"},{"engine_slug":"oracle","sql":"SELECT LENGTHB(note) AS bytes, LENGTH(note) AS chars\nFROM messages;"}],"faqs":[{"question":"When should I use SUBSTRB instead of SUBSTR?","answer":"When the value is defined in bytes: fixed-width single-byte encodings, or interfaces that cap a field at N bytes rather than N characters."},{"question":"Why does SUBSTRB return trailing blanks?","answer":"The cut landed inside a multi-byte character, and Oracle pads the partial character with spaces. Use SUBSTR, or cut by LENGTHB-aware logic, for text."}],"related":["substr","substring","length","octet-length"],"novel_uses":[{"body":"SUBSTRB(note, 1, 4000) caps a value at an interface's byte limit even when the text is multi-byte, at the cost of a padded space when the cut lands inside a character. Use it for byte-capped exports, not for user-visible text.","sql":"SELECT SUBSTRB(note, 1, 4000) AS capped FROM messages;"},{"body":"LENGTHB counts what the downstream system counts. Comparing it against the cap finds the rows a byte-limited interface would reject before the export runs.","sql":"SELECT id FROM messages\nWHERE LENGTHB(note) > 4000;"}]},"source_url":"https://sqlly.app/sql-functions/substrb","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/substring","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUBSTRING function","description":"Extract part of a string with SUBSTRING and SUBSTR in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: 1-based indexes, optional lengths and negative starts explained.","body":{"slug":"substring","name":"SUBSTRING / SUBSTR","h1":"SQL SUBSTRING function","category":"string","lede":"Returns a slice of a string by position. Every engine counts from 1, but the name (SUBSTRING or SUBSTR), the optional length and the meaning of a negative start all vary.","syntax":"SUBSTRING(string, start [, length])  |  SUBSTRING(string FROM start FOR length)  |  SUBSTR(string, start [, length])","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"length is required before SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"SUBSTR, and SUBSTRING from 3.34"},{"engine_slug":"oracle","status":"partial","note":"SUBSTR only; there is no SUBSTRING"}],"gotchas":["Positions are 1-based. Start 0 is not an error but differs: SUBSTRING('abc', 0, 2) is 'a' on SQL Server, PostgreSQL and SQLite (position 0 eats one of the two characters), '' on MySQL, and 'ab' on Oracle, which treats 0 as 1.","SQL Server required all three arguments until SQL Server 2025 made length optional. PostgreSQL, MySQL, SQLite and Oracle let you omit length to take the rest of the string.","A negative start counts from the end on MySQL, SQLite and Oracle: SUBSTR('abcdef', -3) is 'def'. On SQL Server and PostgreSQL it is a position before the string, so SUBSTRING('abcdef', -2, 4) is just 'a'."],"examples":[{"engine_slug":"sql-server","sql":"-- also PostgreSQL, MySQL and SQLite; Oracle spells it SUBSTR\nSELECT SUBSTRING('2026-08-01', 1, 4) AS year;  -- 2026"},{"engine_slug":"postgresql","sql":"SELECT SUBSTRING('abcdef' FROM 2 FOR 3) AS mid;  -- bcd"},{"engine_slug":"mysql","sql":"SELECT SUBSTRING('sqlly.dev', 7) AS tld;  -- dev"},{"engine_slug":"sqlite","sql":"-- substr() is the native spelling; substring() arrived in 3.34\nSELECT substr('sqlly.dev', 7) AS tld;  -- dev"},{"engine_slug":"oracle","sql":"SELECT SUBSTR('abcdef', -3) AS tail FROM dual;  -- def"}],"faqs":[{"question":"Is SUBSTRING 0-based or 1-based?","answer":"1-based in every major engine. Position 0 does not raise an error, but the result differs by engine: one character short on SQL Server, PostgreSQL and SQLite, empty on MySQL, unchanged on Oracle."},{"question":"Why does my SUBSTRING need three arguments on SQL Server?","answer":"Before SQL Server 2025, SUBSTRING required both start and length; pass LEN(s) as the length to take the rest. SQL Server 2025, PostgreSQL, MySQL, SQLite and Oracle all accept the two-argument form."}],"related":["left","right","instr"],"novel_uses":[{"body":"Feed a position from POSITION or INSTR into SUBSTRING and the slice starts at a marker instead of a fixed offset: everything after the @ in an email. No fixed-width assumptions, and it adapts as the local part changes length.","sql":"SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain\nFROM users;"},{"body":"REVERSE the string, find the first delimiter in the reversed text, and SUBSTRING with that offset cuts at the last dot or slash wherever REVERSE exists: PostgreSQL, MySQL and SQL Server (SQL Server spells SUBSTRING with commas). Oracle's INSTR has a backwards search built in, and SQLite has no REVERSE.","sql":"SELECT SUBSTRING(path FROM 1 FOR LENGTH(path) - POSITION('/' IN REVERSE(path))) AS directory\nFROM files;"}]},"source_url":"https://sqlly.app/sql-functions/substring","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/substring-index","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUBSTRING_INDEX function","description":"How SUBSTRING_INDEX(str, delim, count) slices a delimited string in MySQL: positive versus negative counts, missing delimiters, case-sensitive matching and portability.","body":{"slug":"substring-index","name":"SUBSTRING_INDEX","h1":"SQL SUBSTRING_INDEX function","category":"string","lede":"Returns everything before (positive count) or after (negative count) the nth occurrence of a delimiter.","syntax":"SUBSTRING_INDEX(str, delim, count)  |  SUBSTRING_INDEX(str, delim, -count)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No equivalent; LEFT/RIGHT with CHARINDEX, or STRING_SPLIT with ordinal (SQL Server 2022 and later)."},{"engine_slug":"postgresql","status":"no","note":"No equivalent; SPLIT_PART returns a single element."},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"No equivalent; INSTR arithmetic with SUBSTR."},{"engine_slug":"oracle","status":"no","note":"No equivalent; REGEXP_SUBSTR with occurrence counts."}],"gotchas":["A positive count keeps the part before the nth delimiter, a negative count the part after the nth delimiter from the right: SUBSTRING_INDEX('a.b.c', '.', 2) is 'a.b', SUBSTRING_INDEX('a.b.c', '.', -2) is 'b.c'.","When the delimiter occurs fewer than count times, the whole string comes back; there is no NULL or error to signal the shortfall.","The delimiter match is case-sensitive even under a case-insensitive collation: SUBSTRING_INDEX('aXbxc', 'x', 1) is 'aXb'."],"examples":[{"engine_slug":"mysql","sql":"SELECT SUBSTRING_INDEX('www.example.com', '.', 2) AS part;  -- www.example"},{"engine_slug":"mysql","sql":"SELECT SUBSTRING_INDEX(email, '@', -1) AS domain\nFROM users;"}],"faqs":[{"question":"How do I get the third element of a delimited string?","answer":"Nest two calls: SUBSTRING_INDEX(SUBSTRING_INDEX(str, ',', 3), ',', -1). If the string has fewer than three elements this returns the last element, not an empty string."},{"question":"What is the PostgreSQL equivalent?","answer":"SPLIT_PART(str, ',', 3) returns the third element directly, or an empty string when it does not exist. From PostgreSQL 14 a negative position counts from the end."},{"question":"What happens when the delimiter is missing?","answer":"SUBSTRING_INDEX returns the entire string for positive and negative counts alike. Check LOCATE(delim, str) > 0 first when a missing delimiter matters."}],"related":["string-split","find-in-set","position","substr"],"novel_uses":[{"body":"Count 1 keeps everything before the comma and count -1 everything after, which swaps the two halves in one SELECT without nested REPLACE calls. The TRIM removes the space that follows the comma in \"Last, First\" input.","sql":"SELECT CONCAT(TRIM(SUBSTRING_INDEX(full_name, ',', -1)), ' ',\n       SUBSTRING_INDEX(full_name, ',', 1)) AS natural_name\nFROM people;"},{"body":"The host sits between the second and third slash, so SUBSTRING_INDEX(url, '/', 3) keeps the scheme plus host and a second call with -1 drops the scheme. It also copes with the empty second segment of 'https://'.","sql":"SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(url, '/', 3), '/', -1) AS host\nFROM links;"}]},"source_url":"https://sqlly.app/sql-functions/substring-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/subtime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUBTIME function","description":"SUBTIME in MySQL: subtract a time span from a datetime or time, with the negative-interval spelling each other engine uses.","body":{"slug":"subtime","name":"SUBTIME","h1":"SQL SUBTIME function","category":"datetime","lede":"Subtracts a time span from a datetime or another time, the mirror of ADDTIME.","syntax":"SUBTIME(dt, time_value)","return_type":"datetime / time","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD with negative parts"},{"engine_slug":"postgresql","status":"partial","note":"dt - INTERVAL '2 hours 30 minutes'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"datetime(d, '-2 hours')"},{"engine_slug":"oracle","status":"partial","note":"dt - INTERVAL '2:30' HOUR TO MINUTE"}],"gotchas":["Like ADDTIME, the span is a TIME value ('02:30:00', or '1 02:30:00' with a day part); months and years need DATE_SUB with an INTERVAL.","SUBTIME('2026-08-01 01:00:00', '02:30:00') correctly rolls back to 2026-07-31 22:30:00 when the first argument is a datetime.","There is no bare-day form here; use DATE_SUB(d, INTERVAL n DAY) for day granularity, or SUBDATE(d, n)."],"examples":[{"engine_slug":"mysql","sql":"SELECT SUBTIME('2026-08-01 01:00:00', '02:30:00');  -- 2026-07-31 22:30:00"},{"engine_slug":"postgresql","sql":"SELECT '2026-08-01 01:00:00'::timestamp - INTERVAL '2:30';"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MINUTE, -150, '2026-08-01 01:00:00');  -- 2026-07-31 22:30:00"},{"engine_slug":"sqlite","sql":"SELECT datetime('2026-08-01 01:00:00', '-2 hours', '-30 minutes');  -- 2026-07-31 22:30:00"},{"engine_slug":"oracle","sql":"SELECT TIMESTAMP '2026-08-01 01:00:00' - INTERVAL '2:30' HOUR TO MINUTE FROM dual;  -- 2026-07-31 22:30:00"}],"faqs":[{"question":"SUBTIME vs DATE_SUB?","answer":"SUBTIME takes a TIME span like '02:30:00'; DATE_SUB takes INTERVAL unit terms only (DATE_SUB(d, 1) is a syntax error). SUBDATE(d, 1) is the bare day-count form. Use SUBTIME for sub-day precision on the clock."},{"question":"What is the Oracle equivalent?","answer":"d - INTERVAL '0 02:30:00' DAY TO SECOND, or plain subtraction with a fraction of a day: d - 2.5/24."}],"related":["date-sub","addtime","timediff"],"novel_uses":[{"body":"Nodes that log with drifting clocks get one correction column: diff each node against a reference once, then SUBTIME the drift on read. Negative drift values subtract backwards correctly.","sql":"SELECT SUBTIME(logged_at, drift) FROM node_logs;"},{"body":"When history kept only the finish time and the duration, SUBTIME recovers the start, which unblocks gap checks on tables that never stored it. The duration must be a TIME column: an integer such as 230 is read as 00:02:30, not 230 seconds.","sql":"SELECT SUBTIME(finished, run_time) AS reconstructed_start FROM jobs;"}]},"source_url":"https://sqlly.app/sql-functions/subtime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sum","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUM function","description":"How SUM works in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: NULL handling, why an empty group sums to NULL not zero, and how to sum with a condition.","body":{"slug":"sum","name":"SUM","h1":"SQL SUM function","category":"aggregate","lede":"Adds up the non-null values of an expression across a group. The result type and the empty-group result both differ from what most people expect.","syntax":"SUM(expression)  |  SUM(DISTINCT expression)","return_type":"numeric; int input gives int on SQL Server, bigint on PostgreSQL, DECIMAL on MySQL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SUM skips NULLs: 10, NULL and 5 sum to 15. It only returns NULL when every value in the group is NULL or the group is empty.","Summing zero rows returns NULL, not 0. Wrap it: COALESCE(SUM(amount), 0).","On SQL Server, SUM of an int column returns int and fails with an arithmetic overflow past 2,147,483,647. CAST the column to BIGINT first. PostgreSQL widens int sums to bigint, and bigint sums to numeric, so it does not overflow there."],"examples":[{"engine_slug":"all","sql":"SELECT COALESCE(SUM(amount), 0) AS total\nFROM payments;"},{"engine_slug":"sql-server","sql":"SELECT SUM(CAST(quantity AS BIGINT)) AS total_items\nFROM order_items;"}],"faqs":[{"question":"Why does SUM return NULL instead of 0?","answer":"An aggregate over zero rows has nothing to add, and SQL's answer to nothing is NULL. Use COALESCE(SUM(x), 0) when the caller expects a number."},{"question":"How do I sum only rows that match a condition?","answer":"SUM(CASE WHEN status = 'paid' THEN amount END) works everywhere. PostgreSQL and SQLite 3.30+ also have the FILTER clause: SUM(amount) FILTER (WHERE status = 'paid')."}],"related":["count","avg","coalesce"],"novel_uses":[{"body":"SUM(amount) OVER (ORDER BY day) carries the total forward row by row with no self join and no correlated subquery. The default RANGE frame lumps ties together; switch to ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for strict row-by-row totals. Window aggregates with ORDER BY arrived in SQL Server 2012 and MySQL 8.0; SQLite has them from 3.25.","sql":"SELECT day,\n       SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total\nFROM payments;"},{"body":"MySQL and SQLite store booleans as integers, so SUM(flag) counts the true rows directly. PostgreSQL has a real boolean type and rejects SUM(boolean); write SUM(flag::int). SQL Server's bit type refuses too: SUM(CAST(flag AS int)).","sql":"SELECT SUM(CAST(is_active AS int)) AS active_users\nFROM users;"},{"body":"Give each status a power of two and SUM(DISTINCT) collapses the group into one number whose bits say which statuses appeared. A repeated status adds nothing, so 7 means new, paid and shipped all showed up; 5 means new and shipped only. Decode it with bitwise AND.","sql":"SELECT order_id,\n       SUM(DISTINCT CASE status WHEN 'new' THEN 1\n                                WHEN 'paid' THEN 2\n                                WHEN 'shipped' THEN 4 END) AS status_mask\nFROM order_events\nGROUP BY order_id;"}]},"source_url":"https://sqlly.app/sql-functions/sum","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sum-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SUM with OVER","description":"SUM() OVER for partition totals, grand totals and conditional sums on every row, the base pattern behind shares, ratios and rebasing.","body":{"slug":"sum-over","name":"SUM OVER","h1":"SQL SUM with OVER","category":"window","lede":"Sums the window frame or partition and keeps every row: group totals without GROUP BY, and the denominator for percent-of-total queries.","syntax":"SUM(x) OVER (PARTITION BY g) | SUM(x) OVER () | SUM(CASE WHEN c THEN x END) OVER (PARTITION BY g)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SUM returns NULL when the frame has no non-NULL rows; wrap in COALESCE if downstream arithmetic needs 0.","SUM(CASE WHEN ...) OVER (...) is the portable FILTER: per-partition conditional totals on SQL Server, MySQL and Oracle before 23.26.1, which lack the FILTER clause.","Inside a GROUP BY query, SUM(SUM(x)) OVER () sums the aggregated values: the inner SUM aggregates rows, the outer one windows over the groups."],"examples":[{"engine_slug":"all","sql":"SELECT region, amount,\n       SUM(amount) OVER (PARTITION BY region) AS region_total,\n       SUM(amount) OVER () AS grand_total\nFROM sales;"},{"engine_slug":"all","sql":"-- only closed deals count toward the pipeline total\nSELECT deal_id, amount, status,\n       SUM(CASE WHEN status = 'closed' THEN amount END) OVER (PARTITION BY rep) AS closed_total\nFROM deals;"}],"faqs":[{"question":"How do I mix SUM OVER with GROUP BY?","answer":"Window functions evaluate after grouping, so SUM(SUM(x)) OVER (PARTITION BY dim) works: inner SUM per group, outer SUM across groups. The window's PARTITION BY must name grouped columns. SQL Server, PostgreSQL and MySQL reject anything else; SQLite accepts a non-grouped column without an error, so check the key yourself."},{"question":"Does WHERE change what SUM OVER adds up?","answer":"Yes. WHERE removes rows before windows run, so SUM(x) OVER () totals only the surviving rows. To keep a row in the output but out of the total, leave it in and put the condition inside the aggregate with FILTER or CASE."}],"related":["aggregate-over","percent-of-total","running-total"],"novel_uses":[{"body":"Fold the sign into a CASE inside the sum and a running balance falls out of the event log: debits subtract, credits add, one pass in day order. Without the tiebreaker, same-day entries share the day's end balance; the id gives each entry its own running balance.","sql":"SELECT day, entry_type, amount,\n       SUM(CASE WHEN entry_type = 'debit' THEN -amount ELSE amount END)\n         OVER (ORDER BY day, entry_id) AS balance\nFROM ledger;"},{"body":"Divide a conditional running sum by a running count and each row shows the failure rate so far, which is how flaky pipelines surface before alerts do. Multiply by 1.0 first or SQL Server, PostgreSQL and SQLite truncate the rate to 0; MySQL divides as decimal either way.","sql":"SELECT ts, status,\n       1.0 * SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) OVER (ORDER BY ts)\n         / COUNT(*) OVER (ORDER BY ts) AS failure_rate_so_far\nFROM job_runs;"}]},"source_url":"https://sqlly.app/sql-functions/sum-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/switchoffset","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TODATETIMEOFFSET function","description":"TODATETIMEOFFSET tags a datetime with an offset; SWITCHOFFSET re-expresses the same instant in another offset. The two offset-editing verbs of SQL Server.","body":{"slug":"switchoffset","name":"TODATETIMEOFFSET / SWITCHOFFSET","h1":"SQL TODATETIMEOFFSET function","category":"datetime","lede":"Attaches a new offset to a naive datetime (TODATETIMEOFFSET) or shifts an aware value's offset without moving the instant (SWITCHOFFSET).","syntax":"TODATETIMEOFFSET(dt, '+02:00')  |  SWITCHOFFSET(dto, '-05:00')","return_type":"datetimeoffset","support":[{"engine_slug":"sql-server","status":"yes","note":"both: the native pair"},{"engine_slug":"postgresql","status":"partial","note":"AT TIME ZONE does both jobs by direction"},{"engine_slug":"mysql","status":"partial","note":"CONVERT_TZ for the shift; no tagging"},{"engine_slug":"sqlite","status":"no","note":"none"},{"engine_slug":"oracle","status":"partial","note":"FROM_TZ to tag; AT TIME ZONE to render"}],"gotchas":["TODATETIMEOFFSET does not convert; it asserts: TODATETIMEOFFSET('2026-08-01 14:30', '-05:00') claims that wall time was in -05:00. Wrong claim, wrong instant, no error.","SWITCHOFFSET never changes the instant: 14:30+02:00 becomes 07:30-05:00. For 'same wall time, different zone' you need TODATETIMEOFFSET on the naive part.","Neither takes a zone name: SWITCHOFFSET(d, 'Pacific Standard Time') fails with error 9812. For DST-aware conversion use AT TIME ZONE 'Pacific Standard Time' (SQL Server 2016+)."],"examples":[{"engine_slug":"sql-server","sql":"SELECT SWITCHOFFSET('2026-08-01 14:30:00 +02:00', '-05:00');  -- 07:30 -05:00"},{"engine_slug":"sql-server","sql":"SELECT TODATETIMEOFFSET(order_date, '-07:00') FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT TIMESTAMP '2026-08-01 14:30' AT TIME ZONE 'America/Los_Angeles';  -- tag"},{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ('2026-08-01 14:30:00', '+02:00', '-05:00');  -- 2026-08-01 07:30:00"},{"engine_slug":"oracle","sql":"SELECT FROM_TZ(TIMESTAMP '2026-08-01 14:30:00', '+02:00') AT TIME ZONE '-05:00' FROM dual;  -- 2026-08-01 07:30:00 -05:00"}],"faqs":[{"question":"TODATETIMEOFFSET or AT TIME ZONE?","answer":"They overlap: AT TIME ZONE on a naive datetime tags it with a named zone and picks the DST-correct offset. TODATETIMEOFFSET (SQL Server 2008) takes only a fixed offset string or a number of minutes."},{"question":"Why did SWITCHOFFSET 'change' my time?","answer":"It changed the display, not the instant; the wall clock differs because the offset differs. Check the UTC read if values look wrong."}],"related":["datetimeoffset","at-time-zone","from-tz","convert-tz"],"novel_uses":[{"body":"Files that arrived without zone info get awareness attached at load: TODATETIMEOFFSET claims the known offset once, upstream of every reader.","sql":"SELECT TODATETIMEOFFSET(wall_time, '+09:00') FROM imported_rows;"},{"body":"A persisted computed column running SWITCHOFFSET to +00:00 gives indexes and merges a canonical UTC copy while the original offset stays untouched.","sql":"ALTER TABLE logs ADD at_utc AS (SWITCHOFFSET(at, '+00:00')) PERSISTED;"}]},"source_url":"https://sqlly.app/sql-functions/switchoffset","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sys-guid","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYS_GUID function","description":"Oracle's SYS_GUID returns a 16-byte RAW global identifier (not a string), with RAWTOHEX for text and comparisons to the other engines' UUID functions.","body":{"slug":"sys-guid","name":"SYS_GUID","h1":"SQL SYS_GUID function","category":"conversion","lede":"SELECT SYS_GUID() FROM dual returns a unique 16-byte RAW value. It is not a standard UUID, and consecutive calls often differ in only a few bytes.","syntax":"SYS_GUID()","return_type":"raw(16)","support":[{"engine_slug":"sql-server","status":"partial","note":"NEWID() returns a 16-byte uniqueidentifier, shown dashed"},{"engine_slug":"postgresql","status":"partial","note":"gen_random_uuid() returns a 16-byte uuid, shown dashed"},{"engine_slug":"mysql","status":"partial","note":"UUID() is the string-form twin"},{"engine_slug":"sqlite","status":"no","note":"no built-in; hex(randomblob(16))"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The value is RAW(16) bytes, not a 36-character string: RAWTOHEX gives 32 hex characters, or convert in the application when an interchange format is needed.","On many platforms SYS_GUID values are close to sequential: three calls in a row can come back as ...1F4C054F..., ...1F4D054F..., ...1F4E054F.... They are unique but guessable, so never use them as tokens or secrets.","Oracle 23ai release update 23.9 adds UUID(), which returns a random version 4 UUID as RAW(16), and RAW_TO_UUID to print it with dashes. Prefer it over SYS_GUID when you need a real UUID."],"examples":[{"engine_slug":"oracle","sql":"SELECT SYS_GUID() FROM dual;"},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(SYS_GUID()) AS guid_text FROM dual;"},{"engine_slug":"oracle","sql":"CREATE TABLE sessions (\n  id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,\n  label VARCHAR2(100)\n);"},{"engine_slug":"sql-server","sql":"SELECT NEWID() AS guid;"},{"engine_slug":"postgresql","sql":"SELECT gen_random_uuid() AS guid;"},{"engine_slug":"mysql","sql":"SELECT UUID() AS guid;"}],"faqs":[{"question":"How do I get a standard UUID string?","answer":"Format the hex: REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\\1-\\2-\\3-\\4-\\5'). The result has UUID shape but no version bits. On 23.9 and later, RAW_TO_UUID(UUID()) returns a real v4 UUID string directly."},{"question":"Are SYS_GUID values random?","answer":"No. Oracle documents them as unique, built from a host identifier and a counter on most platforms, which is why neighbouring values share most of their bytes. Use DBMS_CRYPTO.RANDOMBYTES, or UUID() on 23.9 and later, for randomness."}],"related":["gen-random-uuid","newid","uuid-function","hex"],"novel_uses":[{"body":"A non-correlated scalar subquery evaluates once per statement, so SET load_id = (SELECT SYS_GUID() FROM dual) marks every row of that UPDATE with the same batch id. Finding one run's rows becomes an equality lookup.","sql":"UPDATE staged_rows SET load_id = (SELECT SYS_GUID() FROM dual);"},{"body":"Because neighbouring calls differ in only a few bytes, SYS_GUID inserts land near each other in the index, the behavior NEWSEQUENTIALID imitates on SQL Server. Good for hot insert tables; never for anything secret.","sql":"CREATE TABLE jobs (id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, payload BLOB);"}]},"source_url":"https://sqlly.app/sql-functions/sys-guid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sysdate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYSDATE function","description":"Oracle's current date and time: SYSDATE reads the server clock at DATE precision, SYSTIMESTAMP adds fractional seconds and a time zone.","body":{"slug":"sysdate","name":"SYSDATE","h1":"SQL SYSDATE function","category":"datetime","lede":"Returns the current date and time on the database server. SYSDATE truncates to the second and returns the plain DATE type that still carries a time.","syntax":"SYSDATE  |  SYSTIMESTAMP  |  CURRENT_DATE / CURRENT_TIMESTAMP  -- session time zone","return_type":"DATE (with time) / TIMESTAMP WITH TIME ZONE","support":[{"engine_slug":"sql-server","status":"partial","note":"GETDATE() (datetime, about 3 ms) or SYSDATETIME() (datetime2, 100 ns); no SYSDATE"},{"engine_slug":"postgresql","status":"partial","note":"clock_timestamp() (per call); NOW() is fixed at transaction start"},{"engine_slug":"mysql","status":"yes","note":"SYSDATE() exists, but it is the per-call clock; NOW() is fixed per statement"},{"engine_slug":"sqlite","status":"partial","note":"datetime('now'), in UTC"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SYSDATE follows the database server's operating-system clock, not the session time zone; CURRENT_DATE and CURRENT_TIMESTAMP follow the session.","Oracle DATE is not date-only: it stores hours, minutes and seconds. TRUNC(SYSDATE) gives today at midnight.","SYSDATE is evaluated once per statement, so every row in one UPDATE sees the same value."],"examples":[{"engine_slug":"oracle","sql":"SELECT SYSDATE AS loaded_at FROM dual;"},{"engine_slug":"oracle","sql":"SELECT TRUNC(SYSDATE) AS today FROM dual;"},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AS precise_ts FROM dual;"},{"engine_slug":"mysql","sql":"SELECT NOW() AS statement_clock, SLEEP(2), SYSDATE() AS call_clock;  -- SYSDATE moved, NOW did not"},{"engine_slug":"sql-server","sql":"SELECT GETDATE() AS loaded_at;"},{"engine_slug":"postgresql","sql":"SELECT now() AS txn_start_clock, clock_timestamp() AS call_clock;"},{"engine_slug":"sqlite","sql":"SELECT datetime('now') AS utc_now;"}],"faqs":[{"question":"Is SYSDATE date-only?","answer":"No. Oracle's DATE type always carries a time, so WHERE order_date = SYSDATE almost never matches. Compare against TRUNC(SYSDATE) or use a range from TRUNC(SYSDATE) to TRUNC(SYSDATE) + 1."},{"question":"Why does SYSDATE differ from CURRENT_TIMESTAMP?","answer":"SYSDATE is a zone-less DATE taken from the database server's operating-system clock. CURRENT_TIMESTAMP is a TIMESTAMP WITH TIME ZONE shown in the session time zone set by ALTER SESSION. Both can name the same instant; only the displayed wall time changes with the zone."}],"related":["now","systimestamp","session-timezone"],"novel_uses":[{"body":"TRUNC takes a format mask as its second argument, so TRUNC(SYSDATE, 'MM') is the first of the month and TRUNC(SYSDATE, 'IW') is the Monday of the ISO week. No string building needed.","sql":"SELECT TRUNC(SYSDATE, 'MM') AS month_start, TRUNC(SYSDATE, 'IW') AS week_monday FROM dual;"},{"body":"Oracle DATE arithmetic counts in days, so SYSDATE + 3/24 adds three hours and SYSDATE + 90/86400 adds ninety seconds. The fraction form works anywhere a DATE expression does.","sql":"SELECT SYSDATE + 3/24 AS in_three_hours FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/sysdate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sysdatetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYSDATETIME function","description":"GETDATE, SYSDATETIME, SYSDATETIMEOFFSET and their Oracle and MySQL cousins: what precision each clock returns and which one to use in new code.","body":{"slug":"sysdatetime","name":"SYSDATETIME / GETDATE","h1":"SQL SYSDATETIME function","category":"datetime","lede":"Server clocks come in two precisions on SQL Server and two styles on Oracle; picking the wrong one quietly rounds your timestamps.","syntax":"SYSDATETIME()  |  GETDATE()  |  SYSDATETIMEOFFSET()","return_type":"datetime2 / datetime / datetimeoffset","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"clock_timestamp() for real time; now() is transaction-start"},{"engine_slug":"mysql","status":"partial","note":"NOW(6) for microseconds; NOW() truncates to seconds"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%f','now') carries milliseconds"},{"engine_slug":"oracle","status":"yes","note":"SYSTIMESTAMP: server zone; CURRENT_TIMESTAMP: session zone"}],"gotchas":["GETDATE returns datetime (~3.33 ms precision, always rounded); SYSDATETIME returns datetime2 with 100 ns precision. Written into a datetime column, the value is still rounded to .000, .003 or .007 seconds.","Oracle splits by zone, not precision: SYSTIMESTAMP is the server's zone, CURRENT_TIMESTAMP the session's (the classic why-is-this-two-hours-off bug).","PostgreSQL's now() is fixed at transaction start so all statements in one transaction agree; clock_timestamp() advances within the transaction."],"examples":[{"engine_slug":"sql-server","sql":"SELECT SYSDATETIME(), GETDATE(), SYSDATETIMEOFFSET();"},{"engine_slug":"mysql","sql":"SELECT NOW(6);  -- microseconds"},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP FROM dual;"},{"engine_slug":"postgresql","sql":"SELECT clock_timestamp();  -- ticks per call, now() is fixed per transaction"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d %H:%M:%f', 'now');  -- milliseconds"}],"faqs":[{"question":"Which clock should new SQL Server code use?","answer":"SYSDATETIME() for local wall time, SYSDATETIMEOFFSET() when the offset matters. GETDATE survives for compatibility with datetime columns."},{"question":"Why do all rows in my transaction share the same timestamp?","answer":"PostgreSQL's now() and CURRENT_TIMESTAMP are fixed at transaction start; call clock_timestamp() if you need time that advances."}],"related":["now","current-date","sysutcdatetime","localtimestamp"],"novel_uses":[{"body":"GETDATE and SYSDATETIME evaluate once per statement, so every row an INSERT SELECT touches shares one instant and batch stamps cannot disagree row to row.","sql":"SELECT SYSDATETIME() AS a, SYSDATETIME() AS b;  -- identical values"},{"body":"Across statements the clock moves, so capture it once into a variable when several steps must agree on the same cutoff.","sql":"DECLARE @now datetime2 = SYSDATETIME();  SELECT * FROM orders WHERE ordered_at < @now;"},{"body":"PostgreSQL slots statement_timestamp between now's transaction start and clock_timestamp's real time: per-statement timing inside one transaction without losing statement-level agreement.","sql":"SELECT statement_timestamp(), now();  -- the statement clock is later or equal"}]},"source_url":"https://sqlly.app/sql-functions/sysdatetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sysdatetimeoffset","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYSDATETIMEOFFSET function","description":"SQL Server's zone-aware clock: SYSDATETIMEOFFSET returns the current time as datetimeoffset, and TODATETIMEOFFSET or SWITCHOFFSET adjust the zone.","body":{"slug":"sysdatetimeoffset","name":"SYSDATETIMEOFFSET","h1":"SQL SYSDATETIMEOFFSET function","category":"datetime","lede":"Returns the current date and time as a datetimeoffset carrying the server's UTC offset, with 100-nanosecond precision.","syntax":"SYSDATETIMEOFFSET()  |  SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00')  |  TODATETIMEOFFSET(d, '+02:00')","return_type":"datetimeoffset","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"NOW() is timestamptz, the zone-aware equivalent"},{"engine_slug":"mysql","status":"no","note":"TIMESTAMP converts per session time_zone; NOW() is the session clock"},{"engine_slug":"sqlite","status":"no","note":"no zone-aware type"},{"engine_slug":"oracle","status":"partial","note":"SYSTIMESTAMP"}],"gotchas":["The offset comes from the server operating system's time zone; SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' converts to a named zone instead of trusting it.","TODATETIMEOFFSET tags a zone-less value with an offset you supply; SWITCHOFFSET keeps the instant and changes the offset. Mixing them up shifts the time.","Only SQL Server's datetimeoffset and Oracle's TIMESTAMP WITH TIME ZONE keep the offset. PostgreSQL's timestamptz normalizes to UTC and forgets the input offset; MySQL's TIMESTAMP stores UTC and converts on read per session time_zone, while MySQL's DATETIME and SQLite have no zone type."],"examples":[{"engine_slug":"sql-server","sql":"SELECT SYSDATETIMEOFFSET() AS now_local;"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIMEOFFSET() AT TIME ZONE 'UTC' AS now_utc;"},{"engine_slug":"postgresql","sql":"SELECT now() AS zoned_now;"},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AS zoned_now FROM dual;"}],"faqs":[{"question":"How do I convert SYSDATETIMEOFFSET to UTC?","answer":"SYSDATETIMEOFFSET() AT TIME ZONE 'UTC', or SYSUTCDATETIME() directly. SWITCHOFFSET(..., '+00:00') gives the same instant."},{"question":"What is the difference between TODATETIMEOFFSET and SWITCHOFFSET?","answer":"TODATETIMEOFFSET attaches an offset to a zone-less value, changing the instant if the value was local. SWITCHOFFSET keeps the instant and rewrites the offset."}],"related":["getdate","utc-timestamp","todatetimeoffset"],"novel_uses":[{"body":"datetimeoffset comparisons and sorts use the UTC instant, not the stored wall time, so a column holding mixed offsets still ranges and groups correctly.","sql":"SELECT * FROM events WHERE at = '2024-01-15T09:30:00-05:00';"},{"body":"DATEPART(tz, col) returns the offset in signed minutes and DATENAME(tz, col) returns the '+05:30' string, the cheap way to audit which zone each row claims.","sql":"SELECT DATEPART(tz, SYSDATETIMEOFFSET()) AS offset_minutes;"},{"body":"Rows can carry different offsets for the same instant when clients insert their own datetimeoffset values; SYSDATETIMEOFFSET() writes only the server's offset. GROUP BY already merges equal instants, so render every value through AT TIME ZONE 'UTC' before GROUP BY to get one stable label per instant.","sql":"SELECT CAST(at AT TIME ZONE 'UTC' AS datetime2(0)) AS utc_bucket, COUNT(*) AS n\nFROM events\nGROUP BY CAST(at AT TIME ZONE 'UTC' AS datetime2(0));"}]},"source_url":"https://sqlly.app/sql-functions/sysdatetimeoffset","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/systimestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYSTIMESTAMP function","description":"Oracle's current timestamp with fractional seconds and time zone: SYSTIMESTAMP on the server clock, CURRENT_TIMESTAMP on the session clock.","body":{"slug":"systimestamp","name":"SYSTIMESTAMP","h1":"SQL SYSTIMESTAMP function","category":"datetime","lede":"Returns the current TIMESTAMP WITH TIME ZONE, read from the database server's operating-system clock, with fractional seconds (six digits on most platforms).","syntax":"SYSTIMESTAMP  |  SYSTIMESTAMP AT TIME ZONE 'UTC'","return_type":"TIMESTAMP WITH TIME ZONE","support":[{"engine_slug":"sql-server","status":"partial","note":"SYSDATETIMEOFFSET()"},{"engine_slug":"postgresql","status":"partial","note":"NOW() returns timestamptz"},{"engine_slug":"mysql","status":"partial","note":"NOW(6) has fractions but no zone"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y-%m-%d %H:%M:%f', 'now') is UTC text, no zone"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SYSTIMESTAMP uses the DB server clock; CURRENT_TIMESTAMP uses the session time zone. They can differ by hours in one query.","The value is time-zone aware, but assigning it into a plain TIMESTAMP column drops the zone and keeps the wall time.","MySQL and SQLite have no zone-aware current timestamp; store UTC and convert in the application there."],"examples":[{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AS loaded_at FROM dual;"},{"engine_slug":"oracle","sql":"SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP) AS utc_ts FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT SYSDATETIMEOFFSET() AS zoned_now;"},{"engine_slug":"postgresql","sql":"SELECT now() AS zoned_now, pg_typeof(now()) AS its_type;  -- timestamp with time zone"},{"engine_slug":"mysql","sql":"SELECT NOW(6) AS precise_now;  -- fractions, no zone"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d %H:%M:%f', 'now') AS utc_text;  -- UTC text, no zone"}],"faqs":[{"question":"How do I get UTC from SYSTIMESTAMP?","answer":"SYS_EXTRACT_UTC(SYSTIMESTAMP) or SYSTIMESTAMP AT TIME ZONE 'UTC' both return the instant in UTC."},{"question":"Is SYSTIMESTAMP the same as SYSDATE?","answer":"SYSDATE returns plain DATE with second precision and no zone; SYSTIMESTAMP returns TIMESTAMP WITH TIME ZONE with fractional seconds."}],"related":["sysdate","now","session-timezone"],"novel_uses":[{"body":"Subtracting two TIMESTAMP values returns an INTERVAL DAY TO SECOND directly, so runtime math needs no datediff function: end minus start reads like a sentence.","sql":"SELECT end_ts - start_ts AS runtime FROM jobs;"},{"body":"CAST(SYSTIMESTAMP AS DATE) drops the fractional seconds and the zone in one step, which is enough for second-granularity checks where the zone was already handled upstream.","sql":"SELECT CAST(SYSTIMESTAMP AS DATE) AS coarse FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/systimestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/sysutcdatetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL SYSUTCDATETIME function","description":"The UTC clocks: SYSUTCDATETIME and GETUTCDATE in SQL Server, UTC_TIMESTAMP in MySQL, datetime('now') in SQLite. UTC now without zone math.","body":{"slug":"sysutcdatetime","name":"SYSUTCDATETIME","h1":"SQL SYSUTCDATETIME function","category":"datetime","lede":"Returns the current instant in UTC directly, skipping the local-clock-minus-offset arithmetic where bugs breed.","syntax":"SYSUTCDATETIME()  |  GETUTCDATE()  |  UTC_TIMESTAMP","return_type":"datetime2 / datetime / timestamp","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"now() AT TIME ZONE 'UTC' or CURRENT_TIMESTAMP rendered in UTC"},{"engine_slug":"mysql","status":"partial","note":"UTC_TIMESTAMP()"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y-%m-%d %H:%M:%S', 'now'); 'now' is UTC"},{"engine_slug":"oracle","status":"partial","note":"SYS_EXTRACT_UTC(SYSTIMESTAMP)"}],"gotchas":["UTC now is the timestamp to store: event ordering survives servers moved across zones, and DST never rewrites history. Local clocks belong at the edges of the system.","GETUTCDATE returns datetime (1/300-second ticks) and SYSUTCDATETIME returns datetime2(7). Neither carries an offset; SYSDATETIMEOFFSET() is the call that does.","SQLite's 'now' is already UTC; datetime('now', 'localtime') is the explicit local step, never the reverse."],"examples":[{"engine_slug":"sql-server","sql":"SELECT SYSUTCDATETIME(), GETUTCDATE();"},{"engine_slug":"mysql","sql":"SELECT UTC_TIMESTAMP(6);"},{"engine_slug":"oracle","sql":"SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP) FROM dual;"},{"engine_slug":"postgresql","sql":"SELECT CURRENT_TIMESTAMP AT TIME ZONE 'UTC';"},{"engine_slug":"sqlite","sql":"SELECT datetime('now');  -- 'now' is already UTC"}],"faqs":[{"question":"Why prefer UTC columns over local time?","answer":"Local times repeat during DST fall-back and skip during spring-forward, so in Central European time '2026-03-29 02:30' does not exist and '2026-10-25 02:30' happens twice. UTC has no gaps or repeats."},{"question":"What is the Oracle equivalent of SYSUTCDATETIME?","answer":"SYS_EXTRACT_UTC(SYSTIMESTAMP) for the instant; SYSTIMESTAMP AT TIME ZONE 'UTC' gives the same with zone-aware rendering."}],"related":["utc-timestamp","sysdatetime","localtimestamp","session-time-zone"],"novel_uses":[{"body":"Diff the client's UTC claim against the server's at receipt; the gap in milliseconds is your skew budget for ordering and conflict rules.","sql":"SELECT DATEDIFF_BIG(MILLISECOND, @client_utc, SYSUTCDATETIME()) AS skew_ms;"},{"body":"Casting SYSUTCDATETIME to date draws day boundaries in UTC, so partition keys and daily rollups agree with the stored instants wherever the server sits.","sql":"SELECT CONVERT(date, SYSUTCDATETIME()) AS utc_today;"}]},"source_url":"https://sqlly.app/sql-functions/sysutcdatetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/tan","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TAN function","description":"TAN(x) returns the tangent of a radian angle (unbounded, so near right angles the result explodes). Radians in, floats out, NULL propagated.","body":{"slug":"tan","name":"TAN","h1":"SQL TAN function","category":"math","lede":"Returns the tangent of an angle expressed in radians: TAN(0) is 0 and the result grows without bound near PI()/2.","syntax":"TAN(angle_radians)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"Needs SQLite 3.35.0 or newer with the math functions compiled in; run SELECT tan(1) once to check a library that came from a package"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["There is no vertical asymptote error: TAN(PI()/2) returns about 1.6e16, a huge finite value, because PI()/2 in floats is not exactly a right angle.","The argument is radians; TAN(45) is the tangent of 45 radians, not 45 degrees.","Results can be anything (there is no [-1, 1] bound like SIN and COS), so plausibility checks tuned for those will not transfer."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TAN(0) AS zero, TAN(PI()/4) AS one;  -- 0, 0.9999999999999999"},{"engine_slug":"postgresql","sql":"SELECT TAN(RADIANS(slope_deg)) AS rise_over_run\nFROM grades;"},{"engine_slug":"sql-server","sql":"SELECT TAN(PI()/2) AS huge;  -- about 1.63e16, not infinity"},{"engine_slug":"mysql","sql":"SELECT TAN(0) AS zero, TAN(PI()/4) AS one;  -- 0, 0.9999999999999999"},{"engine_slug":"sqlite","sql":"SELECT tan(0) AS zero, tan(pi()/4) AS one;  -- 0.0, 1.0 (stored as 0.9999999999999999; the CLI prints 15 digits)"},{"engine_slug":"oracle","sql":"SELECT TAN(0) AS zero, TAN(1) AS one_radian FROM dual;  -- 0, 1.55740772..."}],"faqs":[{"question":"What does TAN(PI()/2) return?","answer":"A huge finite number, about 1.6e16, not an error and not infinity: PI()/2 as a double is not exactly a right angle, so the tangent is defined but enormous."},{"question":"Why does TAN give a wild value for my angle?","answer":"Either the angle is in degrees and you passed radians, or it sits near PI()/2 where tangent is mathematically unbounded. Convert with RADIANS() and check proximity to right angles."},{"question":"Does TAN ever error?","answer":"Only for some non-numeric or infinite inputs, and engines differ. PostgreSQL and SQL Server raise an error for text such as 'abc'; MySQL returns 0 with a warning and SQLite returns NULL. PostgreSQL also raises 'input is out of range' for Infinity. Finite angles, including ones next to PI()/2, never error; they return large finite numbers."}],"related":["sin","cos","atan","radians"],"novel_uses":[{"body":"2 * distance * TAN(RADIANS(fov_deg) / 2) is the swath a sensor covers at a given altitude or range. Drone and scanner coverage tables compute it per shot to plan flight lines.","sql":"SELECT 2 * altitude_m * TAN(RADIANS(fov_deg) / 2) AS swath_m FROM survey_shots;"},{"body":"TAN(RADIANS(max_grade_deg)) turns a compliance angle into the multiplier inspectors compare against, so stored rise and run columns check with a plain less-than. One conversion in a view keeps the spec in degrees and the data in ratios.","sql":"SELECT TAN(RADIANS(10.0)) AS grade_multiplier;  -- 0.176, a rise of 0.176 per unit run"}]},"source_url":"https://sqlly.app/sql-functions/tan","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/tanh","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TANH function","description":"TANH(x) is the hyperbolic tangent, bounded between -1 and 1: the classic squashing curve. Missing on SQL Server and MySQL, where the EXP identity fills in.","body":{"slug":"tanh","name":"TANH","h1":"SQL TANH function","category":"math","lede":"Returns the hyperbolic tangent: TANH(0) is 0, values approach 1 for large positive x and -1 for large negative x.","syntax":"TANH(number)","return_type":"float / double","support":[{"engine_slug":"sql-server","status":"no","note":"No hyperbolic functions; compute (EXP(x) - EXP(-x)) / (EXP(x) + EXP(-x))"},{"engine_slug":"postgresql","status":"yes","note":"Ships from PostgreSQL 12 on; earlier releases report the function as missing"},{"engine_slug":"mysql","status":"no","note":"MySQL has no TANH; (EXP(x) - EXP(-x)) / (EXP(x) + EXP(-x)) stands in"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.35 added it with the math functions; without the compile flag the name is unknown"},{"engine_slug":"oracle","status":"yes","note":"Present in Oracle for NUMBER input"}],"gotchas":["Mathematically the result is in (-1, 1), but for |x| beyond about 19.06 the double rounds to exactly 1.0 or -1.0.","TANH never overflows for large inputs even though SINH and COSH do (the ratio converges), but the SQL Server EXP-based fallback fails once EXP(|x|) passes about 709.78, because that term appears in both the numerator and the denominator.","It is SINH(x) / COSH(x); the identity is also the portable definition."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TANH(0) AS zero, TANH(100) AS capped;  -- 0, 1"},{"engine_slug":"sql-server","sql":"SELECT (EXP(1.0) - EXP(-1.0)) / (EXP(1.0) + EXP(-1.0)) AS tanh_one;  -- 0.7615"},{"engine_slug":"postgresql","sql":"SELECT TANH(score / 10.0) AS normalized FROM rankings;"},{"engine_slug":"sqlite","sql":"SELECT tanh(0) AS zero, tanh(1) AS at_one;  -- 0.0, 0.7615941559557649"},{"engine_slug":"oracle","sql":"SELECT TANH(0) AS zero, TANH(1) AS at_one FROM dual;  -- 0, 0.7615941559557649..."}],"faqs":[{"question":"What range does TANH return?","answer":"Strictly between -1 and 1 in theory. Large inputs saturate: from about |x| = 19.06 the double result is exactly 1.0 or -1.0."},{"question":"How do I compute TANH on SQL Server or MySQL?","answer":"(EXP(x) - EXP(-x)) / (EXP(x) + EXP(-x)). Neither has native hyperbolic functions. Guard against EXP overflow for |x| above about 709, where TANH is 1 or -1 anyway."},{"question":"Why use TANH for normalization?","answer":"It squashes any real number smoothly into (-1, 1) with a stable midpoint at 0, handy for scoring columns without a known maximum."}],"related":["sinh","cosh","exp"],"novel_uses":[{"body":"TANH(LN(a / b) / 2) equals (a - b) / (a + b) for positive a and b: a symmetric percent difference that stays in (-1, 1) and never divides by zero unless both are zero. It compares readings of wildly different sizes on one scale.","sql":"SELECT TANH(LN(cur * 1.0 / prev) / 2) AS rel_diff FROM counters WHERE prev > 0 AND cur > 0;"},{"body":"TANH((amount - threshold) / width) grades smoothly around a cutoff where CASE gives a hard jump, so a value one unit below the line scores almost as well as one above. Width sets how soft the edge is.","sql":"SELECT TANH((amount - 1000.0) / 250.0) AS soft_score FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/tanh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/three-valued-logic","corpus":"sql-functions","engine":null,"language":"en","title":"SQL three-valued logic","description":"SQL conditions can be TRUE, FALSE or UNKNOWN when NULL is involved: AND, OR and NOT truth tables, WHERE keeping only TRUE, CHECK accepting UNKNOWN and boolean aggregates.","body":{"slug":"three-valued-logic","name":"NULL","h1":"SQL three-valued logic","category":"conditional","lede":"The logic system behind every NULL comparison: three truth values instead of two.","syntax":"a AND b | a OR b | NOT a","return_type":"TRUE / FALSE / UNKNOWN","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Truth tables: TRUE AND UNKNOWN = UNKNOWN; TRUE OR UNKNOWN = TRUE; FALSE OR UNKNOWN = UNKNOWN; FALSE AND UNKNOWN = FALSE; NOT UNKNOWN = UNKNOWN.","WHERE, HAVING and ON keep only TRUE rows: UNKNOWN and FALSE are dropped the same way.","CHECK constraints pass UNKNOWN: a row violates the constraint only when the condition is FALSE, which is why NULL columns sneak past checks.","Aggregates like BOOL_AND skip NULL inputs rather than using UNKNOWN internally."],"examples":[{"engine_slug":"postgresql","sql":"SELECT CASE WHEN NULL = NULL THEN 'equal' ELSE 'unknown' END AS result;"},{"engine_slug":"mysql","sql":"SELECT CASE WHEN (NULL = 1) OR TRUE THEN 'kept' ELSE 'dropped' END AS result;"},{"engine_slug":"sql-server","sql":"SELECT CASE WHEN (NULL = 1) AND 1 = 1 THEN 'kept' ELSE 'dropped' END AS result;"},{"engine_slug":"sqlite","sql":"SELECT CASE WHEN (NULL = 1) OR 1 THEN 'kept' ELSE 'dropped' END AS result;"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN NULL = NULL THEN 'equal' ELSE 'unknown' END AS result FROM dual;"}],"faqs":[{"question":"Is NULL = NULL true?","answer":"No, it is UNKNOWN; use IS NULL, or IS NOT DISTINCT FROM (<=> on MySQL), when you need NULLs to compare equal."},{"question":"Why did my WHERE drop NULL rows?","answer":"Comparisons against NULL yield UNKNOWN and WHERE keeps only TRUE, so = never matches NULL (SQL Server's deprecated SET ANSI_NULLS OFF aside); test it with IS NULL."},{"question":"Does TRUE OR NULL save a row?","answer":"Yes: TRUE OR UNKNOWN = TRUE, so the row survives."}],"related":["null","is-null","distinct-from","not-in","bool-and"],"novel_uses":[{"body":"A branch fires only on TRUE, so ELSE catches FALSE and UNKNOWN alike and a NULL x reads as 'no' in CASE WHEN x = 1; give NULL its own WHEN when that matters.","sql":"SELECT x, CASE WHEN x = 1 THEN 'yes' WHEN x IS NULL THEN 'unknown' ELSE 'no' END AS verdict FROM t;"},{"body":"CHECK (price > 0) lets NULL prices through by definition, so a rule that must be absolute pairs the predicate with NOT NULL on the column.","sql":"CREATE TABLE items (price NUMERIC NOT NULL CHECK (price > 0));"}]},"source_url":"https://sqlly.app/sql-functions/three-valued-logic","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/time-format","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIME_FORMAT function","description":"TIME_FORMAT and DATE_FORMAT in MySQL, to_char HH24:MI elsewhere: format the time-of-day part, with the 12-hour and elapsed-hours gotchas.","body":{"slug":"time-format","name":"TIME_FORMAT","h1":"SQL TIME_FORMAT function","category":"datetime","lede":"Formats the time portion of a value: MySQL's TIME_FORMAT works on TIMEs (and returns only the time part of a DATETIME), DATE_FORMAT covers datetimes, and TO_CHAR masks do it everywhere else.","syntax":"TIME_FORMAT(time, '%H:%i:%s')","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"CONVERT(varchar(8), t, 108) for a time; FORMAT(d, 'HH:mm:ss') works on datetime/datetime2 but returns NULL on time"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'HH24:MI:SS')"},{"engine_slug":"mysql","status":"yes","note":"TIME_FORMAT(t, '%H:%i:%s') / DATE_FORMAT"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%H:%M:%S', d)"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'HH24:MI:SS')"}],"gotchas":["MySQL's TIME_FORMAT accepts only hour/minute/second-style codes: %Y and %d on a TIME return zero-filled text (0000, 00) with no warning, and %W or %j return NULL; use DATE_FORMAT for datetimes.","PostgreSQL's to_char on an interval reads the hour field: to_char(INTERVAL '30 hours', 'HH24') is 30, but to_char(INTERVAL '1 day 6 hours', 'HH24') is 06 because the day sits in its own field. EXTRACT(EPOCH FROM iv) / 3600 gives total hours.","MySQL TIME values can be negative or above 24 hours (up to 838:59:59) and print as stored. PostgreSQL and SQL Server time types stop at one day, and Oracle has no TIME type."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIME_FORMAT('14:30:00', '%h:%i %p');  -- 02:30 PM"},{"engine_slug":"postgresql","sql":"SELECT to_char(TIMESTAMP '2026-08-01 14:30:00', 'HH12:MI:SS AM');  -- 02:30:00 PM"},{"engine_slug":"sqlite","sql":"SELECT strftime('%H:%M', created_at) FROM events;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(varchar(8), CAST('2026-08-01 14:30:00' AS datetime), 108);  -- 14:30:00"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(TIMESTAMP '2026-08-01 14:30:00', 'HH24:MI:SS') FROM dual;  -- 14:30:00"}],"faqs":[{"question":"Why does %H give 14 but %h gives 02?","answer":"%H is 00-23 (24-hour), %h (and MySQL's %I) is 01-12 and needs %p for the AM/PM marker. Mixing them gives wrong-but-plausible output."},{"question":"How do I format an interval over 24 hours?","answer":"In MySQL, TIME_FORMAT prints hours up to 838 as stored, so SEC_TO_TIME(TIMESTAMPDIFF(SECOND, ...)) gives a display value like 31:00:00. In PostgreSQL, a time mask stops at the day field: use EXTRACT(EPOCH FROM iv)/3600 for total hours."}],"related":["hour-12-24","strftime","date-format","sec-to-time"],"novel_uses":[{"body":"MySQL's %f prints the fractional part a TIME value carries, down to six digits, for stopwatch-style readouts.","sql":"SELECT TIME_FORMAT('10:00:00.123456', '%H:%i:%s.%f');  -- 10:00:00.123456"},{"body":"%l gives the hour 1 through 12 without a leading zero, the compact shape for schedule boards, still paired with %p.","sql":"SELECT TIME_FORMAT('14:30:00', '%l:%i %p');  -- 2:30 PM"}]},"source_url":"https://sqlly.app/sql-functions/time-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/time-from-datetime","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIME() function","description":"Get the time of day from a timestamp: TIME() on MySQL and SQLite, CAST AS time on SQL Server, ::time on PostgreSQL, TO_CHAR or subtraction on Oracle.","body":{"slug":"time-from-datetime","name":"TIME()","h1":"SQL TIME() function","category":"datetime","lede":"Returns just the clock portion, the standard trick for hour-of-day histograms and time-window comparisons across days.","syntax":"TIME(ts)  -- MySQL, SQLite  |  CAST(ts AS time)  -- SQL Server  |  ts::time  -- PostgreSQL","return_type":"time (SQLite returns text)","support":[{"engine_slug":"sql-server","status":"partial","note":"CAST(ts AS time)"},{"engine_slug":"postgresql","status":"partial","note":"ts::time; time(ts) is a syntax error"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"no TIME type: TO_CHAR(d, 'HH24:MI:SS'), or d - TRUNC(d) as a fraction of a day"}],"gotchas":["Oracle has no TIME type. d - TRUNC(d) on a DATE is a NUMBER, the fraction of the day (0.5 is noon); TO_CHAR(d, 'HH24:MI:SS') renders the clock as text.","PostgreSQL's ::time renders the timestamptz in the session zone first; pin the zone with AT TIME ZONE before casting for stable results. AT TIME ZONE only pins a timestamptz: on a zone-less timestamp, ::time already returns the stored clock, and AT TIME ZONE would shift it by the session zone.","Comparing TIME across DST days has a hidden trap: wall clocks repeat an hour in autumn, so two real events share one time value."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIME(created_at) AS clock FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT (created_at AT TIME ZONE 'UTC')::time AS clock FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT time(created_at) AS clock FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT CAST(created_at AS time) AS clock FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'HH24:MI:SS') AS clock FROM orders;"}],"faqs":[{"question":"How do I filter for events after 17:00?","answer":"MySQL: TIME(ts) > '17:00:00'. PostgreSQL: ts::time > '17:00' or EXTRACT(hour FROM ts) >= 17. Neither can use a plain index on ts; an expression index on the time part can. On a timestamptz column, index the pinned form, (ts AT TIME ZONE 'UTC')::time: a bare ts::time is not IMMUTABLE and CREATE INDEX rejects it."},{"question":"What does Oracle return for the time part?","answer":"Not a TIME type. d - TRUNC(d) on a DATE is a number of days (0.75 is 18:00); TO_CHAR(d, 'HH24:MI:SS') is the text route."}],"related":["date-from-datetime","current-time","extract"],"novel_uses":[{"body":"MySQL's TIME() keeps fractional seconds: TIME('2024-01-15 09:30:00.500') is 09:30:00.500, so millisecond-level clock comparisons survive the extraction.","sql":"SELECT TIME('2024-01-15 09:30:00.500') AS clock;"},{"body":"PostgreSQL's cast takes a precision: now()::time(0) keeps the whole seconds and rounds the fraction in the type itself (09:30:00.5 becomes 09:30:01, 09:30:00.4 stays 09:30:00), giving whole-second clock keys with no string trimming.","sql":"SELECT now()::time(0) AS to_the_second;"}]},"source_url":"https://sqlly.app/sql-functions/time-from-datetime","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/time-to-sec","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIME_TO_SEC function","description":"MySQL's TIME_TO_SEC turns a time into a count of seconds and SEC_TO_TIME reverses it: the pair for summing durations and averaging clock times.","body":{"slug":"time-to-sec","name":"TIME_TO_SEC / SEC_TO_TIME","h1":"SQL TIME_TO_SEC function","category":"datetime","lede":"Returns the time as a count of seconds (past midnight for a clock time, the full length for a duration), or turns a second count back into a time: arithmetic-friendly seconds instead of HH:MM:SS strings.","syntax":"TIME_TO_SEC('09:30:00')  |  SEC_TO_TIME(34200)  |  AVG(TIME_TO_SEC(shift))  -- duration math","return_type":"integer / time","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(second, '00:00:00', t); DATEADD(second, n, CAST('00:00' AS time)) reverses"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(epoch FROM t::interval) and make_interval(secs => n)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"arithmetic on strftime('%s')"},{"engine_slug":"oracle","status":"partial","note":"numeric interval arithmetic"}],"gotchas":["Values past 24 hours keep counting: TIME_TO_SEC('25:00:00') is 90000, because MySQL's TIME is also a duration type.","Negative durations come back negative: SEC_TO_TIME(-3600) is -01:00:00, which breaks parsers expecting clock times.","Averaging clock times directly is wrong on MySQL (AVG on a TIME adds the hhmmss numbers) and errors on SQL Server; convert to seconds, average, and convert back with SEC_TO_TIME."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIME_TO_SEC('09:30:00') AS s;  -- 34200"},{"engine_slug":"mysql","sql":"SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(shift_len))) AS avg_shift FROM shifts;"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(epoch FROM interval '9 hours 30 minutes') AS s;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(SECOND, '00:00:00', CAST(created_at AS time)) AS s FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%s', '2024-01-15 09:30:00') - strftime('%s', '2024-01-15 00:00:00') AS s;  -- 34200"},{"engine_slug":"oracle","sql":"SELECT TO_NUMBER(TO_CHAR(SYSDATE, 'SSSSS')) AS s FROM dual;  -- seconds past midnight"}],"faqs":[{"question":"How do I average a time column?","answer":"Not directly: MySQL's AVG on a TIME treats 09:30:00 as the number 93000. TIME_TO_SEC each row, average the integers, then SEC_TO_TIME the result."},{"question":"What does TIME_TO_SEC of a duration return?","answer":"Seconds, sign included and past-24h counts kept: 25:00:00 gives 90000. Use % 86400 if you need clock-time semantics: TIME_TO_SEC('25:00:00') % 86400 is 3600. Do not CAST the count to TIME, since CAST(90000 AS TIME) gives 09:00:00."}],"related":["maketime","to-seconds","date-from-datetime"],"novel_uses":[{"body":"TIME_TO_SEC(NOW()) over 86400 gives the day's progress as a number, the cheap gauge for shift coverage or day-part charts.","sql":"SELECT ROUND(100 * TIME_TO_SEC(NOW()) / 86400, 1) AS pct_of_day;"},{"body":"Divide by the slot length: TIME_TO_SEC(clock_in) DIV 900 numbers every 15-minute slot of the day 0 through 95, ready for GROUP BY or a heat map.","sql":"SELECT TIME_TO_SEC(clock_in) DIV 900 AS slot FROM punches;"}]},"source_url":"https://sqlly.app/sql-functions/time-to-sec","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timediff","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMEDIFF function","description":"TIMEDIFF in MySQL: subtract two times or two datetimes and get a TIME span, plus the interval subtraction other engines return instead.","body":{"slug":"timediff","name":"TIMEDIFF","h1":"SQL TIMEDIFF function","category":"datetime","lede":"Returns dt1 minus dt2 as a TIME value, capped at the range TIME allows.","syntax":"TIMEDIFF(dt1, dt2)","return_type":"time","support":[{"engine_slug":"sql-server","status":"partial","note":"no TIMEDIFF; DATEDIFF(SECOND, ...) or cast arithmetic"},{"engine_slug":"postgresql","status":"partial","note":"dt1 - dt2 returns an interval"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"dt1 - dt2 returns INTERVAL DAY TO SECOND"}],"gotchas":["The result is a TIME, so a span over 838:59:59 (about 35 days) is clipped to that value with only a warning in a SELECT; inserting it into a TIME column in strict mode fails with ERROR 1292 instead. Use TIMESTAMPDIFF(SECOND, ...) for long spans.","Both arguments must be the same kind: two times, or two datetimes. MySQL's TIMEDIFF returns NULL, not an error, on a mix: TIMEDIFF('12:00:00', '2026-08-01 10:30:00') is NULL, so give the time side a date with the two-argument TIMESTAMP(date, time), such as TIMESTAMP('2026-08-01', '12:00:00'); the one-argument TIMESTAMP('12:00:00') is NULL.","Negative spans are fine: TIMEDIFF('10:00:00', '12:30:00') gives -02:30:00."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIMEDIFF('2026-08-01 12:00:00', '2026-08-01 10:30:00');  -- 01:30:00"},{"engine_slug":"postgresql","sql":"SELECT TIME '12:00:00' - TIME '10:30:00';  -- 01:30:00"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(SECOND, '2026-08-01 10:30:00', '2026-08-01 12:00:00');  -- 5400"},{"engine_slug":"oracle","sql":"SELECT TIMESTAMP '2026-08-01 12:00:00' - TIMESTAMP '2026-08-01 10:30:00' FROM dual;  -- +000000000 01:30:00.000000000"}],"faqs":[{"question":"How do I time a long job in MySQL?","answer":"TIMESTAMPDIFF(SECOND, started, ended); TIMEDIFF's TIME result maxes out at 838:59:59 (about 35 days) and clips beyond that with a warning."},{"question":"What does PostgreSQL return for time subtraction?","answer":"time - time gives an interval such as 01:30:00; timestamp - timestamp gives an interval that can span days, such as 33 days 03:00:00."}],"related":["timestampdiff","timestamp-difference","sec-to-time"],"novel_uses":[{"body":"Diff each row's timestamp against LAG's previous timestamp to expose inter-event gaps in the result, the quick way to find idle stretches or session breaks in an event stream.","sql":"SELECT at, TIMEDIFF(at, LAG(at) OVER (ORDER BY at)) AS gap FROM events;"},{"body":"One column reports both directions: negative output means the ticket closed ahead of its due time, positive means it breached, with no CASE ladder.","sql":"SELECT TIMEDIFF(resolved_at, due_at) FROM tickets;"}]},"source_url":"https://sqlly.app/sql-functions/timediff","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timefromparts","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMEFROMPARTS function","description":"Assemble a time of day from hours, minutes, seconds and fractions: TIMEFROMPARTS on SQL Server, make_time on PostgreSQL, MAKETIME on MySQL.","body":{"slug":"timefromparts","name":"TIMEFROMPARTS","h1":"SQL TIMEFROMPARTS function","category":"datetime","lede":"Returns a time from integers. SQL Server's TIMEFROMPARTS takes five arguments with fractional precision; MySQL's MAKETIME takes three.","syntax":"TIMEFROMPARTS(hh, mm, ss, fff, precision)  -- SQL Server  |  MAKE_TIME(hh, mm, ss)  -- PostgreSQL  |  MAKETIME(hh, mm, ss)  -- MySQL","return_type":"time","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"make_time(hh, mm, ss)"},{"engine_slug":"mysql","status":"partial","note":"MAKETIME(hh, mm, ss)"},{"engine_slug":"sqlite","status":"partial","note":"printf into a 'HH:MM:SS' string"},{"engine_slug":"oracle","status":"no","note":"no direct function; TO_DSINTERVAL builds an interval, not a time"}],"gotchas":["SQL Server's last two arguments work together: the fraction must fit the declared precision (500 with precision 3 is .500), and precision 0 requires a fraction of 0. The precision must be a constant from 0 to 7; a NULL or variable precision is a compile error.","MySQL's MAKETIME accepts hours up to 838 because TIME doubles as a duration type, so MAKETIME(30, 0, 0) is legal there and an error on SQL Server and PostgreSQL.","SQLite and Oracle have no constructor; SQLite builds the string by hand and Oracle, which has no TIME type, composes a DATE or an INTERVAL instead."],"examples":[{"engine_slug":"sql-server","sql":"SELECT TIMEFROMPARTS(9, 30, 0, 0, 0) AS start_time;"},{"engine_slug":"mysql","sql":"SELECT MAKETIME(9, 30, 0) AS start_time;"},{"engine_slug":"postgresql","sql":"SELECT make_time(9, 30, 0) AS start_time;"},{"engine_slug":"sqlite","sql":"SELECT printf('%02d:%02d:%02d', 9, 30, 0) AS start_time;  -- 09:30:00"}],"faqs":[{"question":"Why does TIMEFROMPARTS have five arguments?","answer":"Arguments four and five are the fractional-seconds value and its precision: TIMEFROMPARTS(9,30,0,500,3) means 09:30:00.500."},{"question":"What is the hour limit for a time?","answer":"On SQL Server, clock times stop at 23; hour 24 is an error. PostgreSQL's make_time(24, 0, 0) returns 24:00:00. MySQL's TIME type allows up to 838 hours because it doubles as a duration type: MAKETIME(100,0,0) is legal there."}],"related":["maketime","datefromparts","current-time"],"novel_uses":[{"body":"Rebuilding just the clock with make_time(EXTRACT(hour FROM ts)::int, EXTRACT(minute FROM ts)::int, 0) collapses every day onto one 24-hour axis, the shape time-of-day histograms want.","sql":"SELECT make_time(EXTRACT(hour FROM ts)::int, EXTRACT(minute FROM ts)::int, 0) AS clock_of_day\nFROM events;"},{"body":"Floored parts plus TIMEFROMPARTS give an appointment-grid key: hours stay, minutes drop to their 15-minute slot, seconds and fractions go to zero.","sql":"DECLARE @t time = '09:37:00';\nSELECT TIMEFROMPARTS(DATEPART(hour, @t), DATEPART(minute, @t) / 15 * 15, 0, 0, 0) AS grid_slot;"}]},"source_url":"https://sqlly.app/sql-functions/timefromparts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timestamp-difference","corpus":"sql-functions","engine":null,"language":"en","title":"SQL timestamp minus timestamp","description":"Subtracting two timestamps in PostgreSQL and Oracle returns an interval, not a count: how that differs from DATEDIFF-style boundary math in the other engines.","body":{"slug":"timestamp-difference","name":"TIMESTAMP - TIMESTAMP","h1":"SQL timestamp minus timestamp","category":"datetime","lede":"Direct subtraction of two timestamps yields a duration on PostgreSQL and Oracle. MySQL and SQL Server datetime accept the minus sign but return something that is not a duration; SQL Server datetime2 and date reject it with error 8117.","syntax":"ts1 - ts2","return_type":"interval (PG, Oracle) / number (Oracle DATE)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(unit, a, b) or DATEDIFF_BIG; no interval type"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"TIMESTAMPDIFF(unit, a, b)"},{"engine_slug":"sqlite","status":"partial","note":"JULIANDAY(a) - JULIANDAY(b)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL returns days and time, never months: TIMESTAMP '2026-09-03 03:00' - TIMESTAMP '2026-08-01' is 33 days 03:00:00. Use AGE for a years-months-days answer and EXTRACT(EPOCH FROM ...) for seconds.","Oracle DATE subtraction gives a number of days with a fraction (1.125 = 27 hours); TIMESTAMP subtraction gives INTERVAL DAY TO SECOND instead. Same operator, two behaviours.","On PostgreSQL, timestamptz - timestamptz measures real elapsed time: midnight to midnight across the 2026-03-08 spring-forward in America/New_York is 23:00:00, while timestamp - timestamp on the same wall times reports 1 day.","SQL Server's datetime - datetime returns a datetime counted from 1900-01-01 (14:30 minus 12:00 is 1900-01-01 02:30:00), and MySQL's DATETIME - DATETIME subtracts the values as YYYYMMDDhhmmss numbers (14:30 minus 12:00 is 23000). Use DATEDIFF or TIMESTAMPDIFF instead."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TIMESTAMPTZ '2026-08-01 12:00+00' - TIMESTAMPTZ '2026-08-01 09:00+00';  -- 03:00:00"},{"engine_slug":"oracle","sql":"SELECT TIMESTAMP '2026-08-01 12:00:00' - TIMESTAMP '2026-08-01 09:00:00' FROM dual;  -- +000000000 03:00:00.000000000"},{"engine_slug":"sqlite","sql":"SELECT JULIANDAY(ended) - JULIANDAY(started) AS days FROM jobs;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(SECOND, '2026-08-01 09:00:00', '2026-08-01 12:00:00');  -- 10800"},{"engine_slug":"mysql","sql":"SELECT TIMESTAMPDIFF(HOUR, '2026-08-01 09:00:00', '2026-08-01 12:00:00');  -- 3"}],"faqs":[{"question":"How do I turn a PostgreSQL interval into hours?","answer":"EXTRACT(EPOCH FROM iv) / 3600. EXTRACT(HOUR FROM iv) only reads the interval's hour field and ignores days and months."},{"question":"What does SQL Server give instead?","answer":"An interval type does not exist; pick the unit up front with DATEDIFF or compute seconds and divide."}],"related":["datediff","timestampdiff","interval-arithmetic","justify-interval"],"novel_uses":[{"body":"Intervals are orderable, so percentile_cont takes a timestamp difference directly and returns an interval median without converting to seconds first.","sql":"SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY ended - started) FROM jobs;"},{"body":"AVG accepts intervals but stddev does not, so reduce the difference through EXTRACT(EPOCH) before computing variance or outlier thresholds.","sql":"SELECT stddev(EXTRACT(EPOCH FROM ended - started)) FROM jobs;"}]},"source_url":"https://sqlly.app/sql-functions/timestamp-difference","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timestamp-with-local-tz","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMESTAMP WITH LOCAL TIME ZONE","description":"Oracle's TIMESTAMP WITH LOCAL TIME ZONE: stored normalized to the database zone, rendered in the session zone. The transparent two-column trick in one type.","body":{"slug":"timestamp-with-local-tz","name":"TIMESTAMP WITH LOCAL TIME ZONE","h1":"SQL TIMESTAMP WITH LOCAL TIME ZONE","category":"datetime","lede":"A type that stores the instant normalized to UTC/database zone but always displays it converted to the querying session's zone.","syntax":"TIMESTAMP WITH LOCAL TIME ZONE","return_type":"timestamp with local time zone","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"timestamptz renders per session via the session zone; closest behaviour"},{"engine_slug":"mysql","status":"partial","note":"TIMESTAMP already converts to UTC on store and to the session time_zone on read; no aware type, range ends 2038-01-19 03:14:07"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"this type: automatic session-zone rendering"}],"gotchas":["There is no visible zone on the value: display conversion is automatic and depends entirely on ALTER SESSION SET TIME_ZONE, which makes 'what did I insert?' answers session-dependent.","It cannot be a named-zone-aware value: no way to ask for the original offset back. If you must keep the user's zone, use TIMESTAMP WITH TIME ZONE or a separate zone column.","PostgreSQL's timestamptz behaves the same way in practice: it stores UTC and renders in the zone set by SET TIME ZONE."],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE logins (at TIMESTAMP WITH LOCAL TIME ZONE);"},{"engine_slug":"oracle","sql":"ALTER SESSION SET TIME_ZONE = 'UTC'; SELECT at FROM logins;  -- shown in UTC"},{"engine_slug":"postgresql","sql":"SET TIME ZONE 'America/New_York';  SELECT now();  -- rendered in the session zone"}],"faqs":[{"question":"LOCAL TIME ZONE vs WITH TIME ZONE?","answer":"WITH keeps the offset you supplied and can return it; WITH LOCAL stores in the database's zone and always renders in the session's. LOCAL is the display-friendly, zone-invisible variant."},{"question":"Why do my times differ between two sessions?","answer":"That is the type working: each session sees its own wall time. Pin the session zone for stable exports."}],"related":["timestamp-with-time-zone","session-time-zone","localtimestamp","from-tz"],"novel_uses":[{"body":"Casting the column to TIMESTAMP WITH TIME ZONE reveals the database-zone offset the type normally hides, the quickest answer to what actually got stored.","sql":"SELECT CAST(at AS TIMESTAMP WITH TIME ZONE) FROM logins;"},{"body":"The type normalizes to the database's own zone, so read DBTIMEZONE before importing: two databases with different settings show the same row differently.","sql":"SELECT DBTIMEZONE FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/timestamp-with-local-tz","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timestamp-with-time-zone","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMESTAMP WITH TIME ZONE type","description":"The timestamptz type in PostgreSQL and Oracle: stored as UTC, rendered per zone, and why timestamp without time zone is usually the wrong choice.","body":{"slug":"timestamp-with-time-zone","name":"TIMESTAMP WITH TIME ZONE","h1":"SQL TIMESTAMP WITH TIME ZONE type","category":"datetime","lede":"A timestamp paired with a zone or offset, stored as one instant in time and displayed in whatever zone the session or query asks for.","syntax":"TIMESTAMPTZ '2026-08-01 14:30+02'","return_type":"timestamp with time zone","support":[{"engine_slug":"sql-server","status":"partial","note":"datetimeoffset is the offset-carrying type"},{"engine_slug":"postgresql","status":"yes","note":"timestamptz, the type to default to"},{"engine_slug":"mysql","status":"partial","note":"TIMESTAMP stores UTC and renders per session time_zone, but its range ends in 2038; DATETIME is naive"},{"engine_slug":"sqlite","status":"no","note":"none; text storage conventions only"},{"engine_slug":"oracle","status":"yes","note":"TIMESTAMP WITH TIME ZONE, the original"}],"gotchas":["Neither engine stores the literal string you typed: PostgreSQL normalizes to UTC (the display offset moves with the session), Oracle keeps the stored offset in the column but converts for comparisons.","It is a point in time, not a schedule: '09:00 in the shop's zone' belongs in a naive timestamp plus a zone column, because timestamptz pins the instant and DST will shift future occurrences.","Comparisons and indexes work in UTC space, so rows inserted from Tokyo and London sort correctly: the whole reason to prefer timestamptz over naive timestamps for events."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TIMESTAMPTZ '2026-08-01 14:30+02' AT TIME ZONE 'UTC';  -- 12:30"},{"engine_slug":"oracle","sql":"SELECT CAST(TIMESTAMP '2026-08-01 14:30:00' AS TIMESTAMP WITH TIME ZONE) FROM dual;"},{"engine_slug":"postgresql","sql":"CREATE TABLE events (starts_at timestamptz NOT NULL);"},{"engine_slug":"sql-server","sql":"SELECT CAST('2026-08-01 14:30:00 +02:00' AS datetimeoffset) AT TIME ZONE 'UTC';  -- 2026-08-01 12:30:00.0000000 +00:00"}],"faqs":[{"question":"Should I always use timestamptz in PostgreSQL?","answer":"For instants, yes. Use timestamp without zone only for zone-independent wall times (schedules, opening hours), and pair those with a zone column when users span zones."},{"question":"What does SQL Server offer instead?","answer":"datetimeoffset(n) carries the offset with the value; AT TIME ZONE builds and renders it. It is the closest cousin to Oracle's type."}],"related":["at-time-zone","localtimestamp","datetimeoffset","timestamp-with-local-tz"],"novel_uses":[{"body":"PostgreSQL accepts a named zone inside the literal itself, so a fixture pins the instant DST-correctly with no AT TIME ZONE call.","sql":"SELECT TIMESTAMPTZ '2026-08-01 12:00 Europe/Paris';"},{"body":"Adding months or days to a timestamptz happens in the session's zone and converts back, so schedules keep their wall time while elapsed spans across DST change length. Pick the type by which of those you meant.","sql":"SELECT now() + INTERVAL '1 month';"},{"body":"AT LOCAL renders a TIMESTAMP WITH TIME ZONE in the session zone without naming it, the one-word version of AT TIME ZONE for session-following displays.","sql":"SELECT starts_at AT LOCAL FROM showings;"}]},"source_url":"https://sqlly.app/sql-functions/timestamp-with-time-zone","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timestampadd","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMESTAMPADD function","description":"TIMESTAMPADD in MySQL: add a unit count to a datetime with the ODBC unit names, and the DATEADD and interval equivalents in the other engines.","body":{"slug":"timestampadd","name":"TIMESTAMPADD","h1":"SQL TIMESTAMPADD function","category":"datetime","lede":"Adds an integer count of a named unit (SECOND, DAY, MONTH...) to a datetime, MySQL's ODBC-style spelling of DATEADD.","syntax":"TIMESTAMPADD(unit, n, datetime)","return_type":"datetime","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEADD(unit, n, d); closest match"},{"engine_slug":"postgresql","status":"partial","note":"d + make_interval(...) or d + INTERVAL 'n unit'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"datetime(d, '+' || n || ' days')"},{"engine_slug":"oracle","status":"partial","note":"d + n * INTERVAL '1' DAY or ADD_MONTHS"}],"gotchas":["Units are bare keywords (MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR). The SQL_TSI_ prefix works for every unit except MICROSECOND (SQL_TSI_MICROSECOND is a syntax error). The old FRAC_SECOND unit was removed in MySQL 5.5 and is now a syntax error.","MONTH, QUARTER and YEAR clamp at month ends like DATE_ADD: TIMESTAMPADD(MONTH, 1, '2026-01-31') is 2026-02-28.","The count may be fractional: coarse units such as DAY and MONTH round it to a whole number (TIMESTAMPADD(DAY, 1.5, d) adds 2 days), while SECOND keeps the fraction. For sub-second steps use the MICROSECOND unit: TIMESTAMPADD(MICROSECOND, 1500, d) adds 1.5 ms."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIMESTAMPADD(MONTH, 3, '2026-08-01');  -- 2026-11-01"},{"engine_slug":"sql-server","sql":"SELECT DATEADD(MONTH, 3, '2026-08-01');"},{"engine_slug":"postgresql","sql":"SELECT TIMESTAMP '2026-08-01' + INTERVAL '3 months';  -- 2026-11-01 00:00:00"},{"engine_slug":"sqlite","sql":"SELECT datetime('2026-08-01', '+3 months');  -- 2026-11-01 00:00:00"},{"engine_slug":"oracle","sql":"SELECT DATE '2026-08-01' + INTERVAL '3' DAY FROM dual;  -- 2026-08-04"}],"faqs":[{"question":"TIMESTAMPADD vs DATE_ADD in MySQL?","answer":"Same result. TIMESTAMPADD uses the ODBC unit vocabulary (SQL_TSI_ names also work, except SQL_TSI_MICROSECOND) and was kept for ODBC compatibility; DATE_ADD with INTERVAL is the idiomatic spelling."},{"question":"What is the SQL Server equivalent?","answer":"DATEADD(MONTH, 3, d); the argument order moves the unit first, exactly like TIMESTAMPADD."}],"related":["dateadd","adddate","timestampdiff","add-months"],"novel_uses":[{"body":"MySQL accepts TIMESTAMPADD in a generated column because it is deterministic, so the expiry value can be indexed. Without a storage keyword the column is VIRTUAL and computed on read; add STORED to keep the value on disk.","sql":"CREATE TABLE tokens (created_at DATETIME, expires_at DATETIME AS (TIMESTAMPADD(HOUR, 24, created_at)));"},{"body":"The MICROSECOND unit reaches sub-second precision directly; INTERVAL 500000 MICROSECOND gives the same result. Pair it with NOW(6) for half-second session timeouts.","sql":"SELECT TIMESTAMPADD(MICROSECOND, 500000, NOW(6));"},{"body":"Feed TIMESTAMPADD to a recursive CTE to walk a calendar in pure SQL, MySQL's stand-in for other engines' generate_series.","sql":"WITH RECURSIVE week AS (SELECT DATE '2026-08-01' AS d UNION ALL SELECT TIMESTAMPADD(DAY, 1, d) FROM week WHERE d < '2026-08-07') SELECT d FROM week;"}]},"source_url":"https://sqlly.app/sql-functions/timestampadd","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/timestampdiff","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TIMESTAMPDIFF function","description":"TIMESTAMPDIFF in MySQL: whole units between two datetimes in the order you'd expect, and why DATEDIFF means something different on every engine.","body":{"slug":"timestampdiff","name":"TIMESTAMPDIFF","h1":"SQL TIMESTAMPDIFF function","category":"datetime","lede":"Returns the whole number of named units between two datetimes, truncating any remainder.","syntax":"TIMESTAMPDIFF(unit, datetime1, datetime2)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(unit, a, b); same order, but boundary-crossing semantics"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(EPOCH FROM b - a) / 86400 or AGE-based month math"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"CAST((JULIANDAY(b) - JULIANDAY(a)) AS INTEGER) for days"},{"engine_slug":"oracle","status":"partial","note":"b - a for days; MONTHS_BETWEEN for months"}],"gotchas":["Argument order matters: TIMESTAMPDIFF(MONTH, earlier, later) is positive; swapping them gives a negative.","The result is truncated, never rounded: TIMESTAMPDIFF(HOUR, '2026-01-01 10:00', '2026-01-01 10:59') returns 0.","SQL Server's DATEDIFF counts unit boundaries crossed, so DATEDIFF(YEAR, '2025-12-31', '2026-01-01') is 1; TIMESTAMPDIFF(YEAR, ...) returns 0. MySQL's DATEDIFF, meanwhile, only does days."],"examples":[{"engine_slug":"mysql","sql":"SELECT TIMESTAMPDIFF(MONTH, '2026-01-15', '2026-08-01');  -- 6"},{"engine_slug":"mysql","sql":"SELECT TIMESTAMPDIFF(MINUTE, started_at, ended_at) FROM jobs;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(MONTH, '2026-01-15', '2026-08-01');  -- 7 (boundary count)"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(EPOCH FROM TIMESTAMP '2026-08-02' - TIMESTAMP '2026-08-01') / 3600;  -- 24"},{"engine_slug":"sqlite","sql":"SELECT CAST(julianday('2026-08-02') - julianday('2026-08-01') AS INTEGER);  -- 1"},{"engine_slug":"oracle","sql":"SELECT MONTHS_BETWEEN(DATE '2026-08-01', DATE '2026-02-01') FROM dual;  -- 6"}],"faqs":[{"question":"Why does SQL Server's DATEDIFF give 7 months when TIMESTAMPDIFF gives 6?","answer":"SQL Server's DATEDIFF counts how many month boundaries you crossed; TIMESTAMPDIFF computes complete months elapsed. For tenure-style answers, TIMESTAMPDIFF's semantics are usually what you want."},{"question":"How do I get fractional months?","answer":"Oracle's MONTHS_BETWEEN(b, a) returns decimal months. MySQL has no fractional form; TIMESTAMPDIFF(DAY, a, b) / 30.4375 is an average-month approximation, not a calendar answer."}],"related":["datediff","timestampadd","months-between","age"],"novel_uses":[{"body":"Capture NOW(6) into a variable, run the work, then diff the two captures in microseconds. It times procedure bodies without a client round trip.","sql":"SET @t0 = NOW(6);  SELECT SLEEP(0.1);  SELECT TIMESTAMPDIFF(MICROSECOND, @t0, NOW(6));"},{"body":"Pair each hit with the hits that land up to sixty seconds after it by diffing timestamps in a join condition. The join returns pairs, not visits; tune the window per domain instead of building a sessions table first.","sql":"SELECT a.hit_id, b.hit_id FROM hits a JOIN hits b ON TIMESTAMPDIFF(SECOND, a.at, b.at) BETWEEN 0 AND 60;"}]},"source_url":"https://sqlly.app/sql-functions/timestampdiff","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/title-case","corpus":"sql-functions","engine":null,"language":"en","title":"SQL title-case pattern","description":"PostgreSQL, Oracle and Snowflake have INITCAP, and SQL Server, MySQL and SQLite do not: here are the hand-rolled title-case patterns for those three, and their limits.","body":{"slug":"title-case","name":"Title-casing a string","h1":"SQL title-case pattern","category":"string","lede":"Capitalise the first letter of a string or of every word, per engine, and where the naive patterns fall apart (apostrophes, mid-word capitals).","syntax":"UPPER(LEFT(s, 1)) + LOWER(SUBSTRING(s, 2, ...))  |  INITCAP(s)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The one-liner UPPER(LEFT(s,1)) + LOWER(SUBSTRING(s,2,...)) capitalises the whole string's first letter only; word-by-word needs INITCAP, a UDF, or the app layer.","INITCAP (PostgreSQL, Oracle) lowercases the rest of every word: 'iPhone' becomes 'Iphone' and 'McDonald' becomes 'Mcdonald'.","Word boundaries are any non-alphanumeric character, so 'o'brien' and 'state-of-the-art' capitalise after apostrophes and hyphens too.","If the casing matters, normalize on write and keep it stored; per-read title-casing costs CPU and can never be name-aware."],"examples":[{"engine_slug":"sql-server","sql":"SELECT UPPER(LEFT(name, 1)) + LOWER(SUBSTRING(name, 2, LEN(name))) AS capped\nFROM brands;"},{"engine_slug":"postgresql","sql":"SELECT INITCAP(name) AS capped FROM brands;  -- 'mcdonald' becomes 'Mcdonald'"},{"engine_slug":"sqlite","sql":"SELECT UPPER(substr(name, 1, 1)) || lower(substr(name, 2)) AS capped FROM brands;"},{"engine_slug":"mysql","sql":"SELECT CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2))) AS capped FROM brands;  -- no INITCAP in MySQL"},{"engine_slug":"oracle","sql":"SELECT INITCAP('state-of-the-art') AS capped FROM dual;  -- State-Of-The-Art"}],"faqs":[{"question":"How do I title-case every word in SQL Server?","answer":"There is no built-in. Either accept first-letter-of-string, write a T-SQL UDF that walks the separators, or do it in the application where you have real casing rules."},{"question":"Why does INITCAP produce Mcdonald?","answer":"INITCAP lowercases everything after each word's first character and treats any non-alphanumeric as a boundary; it has no dictionary of name exceptions."},{"question":"Is title-casing safe for identifiers like SKU codes?","answer":"No. Codes like 'AB1C' lose their shape. Apply casing only to free-text display fields, never to codes, emails or keys."}],"related":["initcap","upper","lower","ucase"],"novel_uses":[{"body":"STRING_SPLIT plus STRING_AGG capitalizes each word without a scalar UDF on SQL Server 2017+, which is the piece the simple LEFT-and-UPPER one-liner cannot do.","sql":"SELECT name,\n  (SELECT STRING_AGG(UPPER(LEFT(w, 1)) + LOWER(SUBSTRING(w, 2, 400)), ' ')\n   FROM STRING_SPLIT(name, ' ')) AS titled\nFROM brands;"},{"body":"A CASE around the same per-word expression leaves of, and and the lowercase except where the title starts, which is what book and article titles expect.","sql":"CASE WHEN w IN ('of', 'and', 'the', 'a') THEN LOWER(w)\n     ELSE UPPER(LEFT(w, 1)) + LOWER(SUBSTRING(w, 2, 400)) END"}]},"source_url":"https://sqlly.app/sql-functions/title-case","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-ascii","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_ASCII function","description":"How PostgreSQL's to_ascii strips accents, why it fails in UTF8 databases, and the unaccent extension, ASCIISTR and TRANSLATE alternatives.","body":{"slug":"to-ascii","name":"TO_ASCII","h1":"SQL TO_ASCII function","category":"string","lede":"Strips accents from text in a single-byte Latin encoding, turning é into e. It does not work on UTF-8 text.","syntax":"to_ascii(string [, encoding])","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":"No to_ascii; COLLATE ... _AI comparisons, or the application."},{"engine_slug":"postgresql","status":"yes","note":"Supports only LATIN1, LATIN2, LATIN9 and WIN1250."},{"engine_slug":"mysql","status":"no","note":"No to_ascii; accent-insensitive collations handle comparisons."},{"engine_slug":"sqlite","status":"no","note":"No to_ascii; transliterate in the application."},{"engine_slug":"oracle","status":"no","note":"No to_ascii; ASCIISTR escapes instead of transliterating."}],"gotchas":["to_ascii only reads LATIN1, LATIN2, LATIN9 and WIN1250 text. In a UTF8 database, the usual case, to_ascii(text) fails with 'encoding conversion from UTF8 to ASCII not supported'.","The encoding argument does not convert anything; it tells to_ascii how to read the bytes. Passing 'LATIN1' for UTF-8 text returns garbage: to_ascii('über', 'LATIN1') comes back as 'A ber'.","In a UTF8 database use the unaccent extension: unaccent('José Müller') is 'Jose Muller', and its rules file can be extended."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_ascii('Karel');  -- works only in a LATIN1, LATIN2, LATIN9 or WIN1250 database"},{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS unaccent;\nSELECT unaccent('José Müller') AS plain;  -- Jose Muller"}],"faqs":[{"question":"Why does to_ascii fail on my UTF-8 database?","answer":"It has no UTF-8 support at all, and naming a Latin encoding only makes it misread the bytes. Use unaccent() from the unaccent extension instead."},{"question":"What should I use for accent-insensitive search?","answer":"unaccent() on both sides in PostgreSQL (an expression index needs an IMMUTABLE wrapper function), an accent-insensitive collation in MySQL or SQL Server, or a pre-computed folded column."},{"question":"Is to_ascii the same as ASCIISTR?","answer":"No. Oracle's ASCIISTR replaces non-ASCII characters with backslash escapes and keeps all the information; to_ascii drops the accents to produce readable plain text."}],"related":["asciistr","translate","normalize","unistr"],"novel_uses":[{"body":"In a single-byte Latin database to_ascii(lower(name)) builds the folded key in one call, but only where lower() can fold the letters: under the C locale it changes ASCII letters alone, so 'École' keys as 'Ecole' and 'José' as 'jose'. A stored generated column keeps the key computed at write time.","sql":"ALTER TABLE people ADD search_key text\n  GENERATED ALWAYS AS (to_ascii(lower(name))) STORED;"},{"body":"TRANSLATE with aligned from and to strings strips a chosen set of accents in any engine that has translate, including PostgreSQL databases where to_ascii cannot read the encoding.","sql":"SELECT TRANSLATE(title, 'áàâäéèêëíìîïóòôöúùûüçñ',\n                 'aaaaeeeeiiiioooouuuucn') AS folded\nFROM articles;"}]},"source_url":"https://sqlly.app/sql-functions/to-ascii","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-base64","corpus":"sql-functions","engine":null,"language":"en","title":"SQL base64 encoding","description":"Encode text as base64: TO_BASE64 on MySQL (with MIME line breaks), encode(..., 'base64') on PostgreSQL, and what SQL Server and Oracle cost you.","body":{"slug":"to-base64","name":"TO_BASE64 / encode","h1":"SQL base64 encoding","category":"string","lede":"Turns bytes into base64 text for embedding and transport. The bytes come from an encoding, and MySQL wraps lines; both facts surprise people.","syntax":"TO_BASE64(string)  |  encode(data, 'base64')","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"encode(convert_to(s, 'utf8'), 'base64')"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["MySQL's TO_BASE64 inserts a newline every 76 characters, MIME-style. Strip it with REPLACE for single-line output.","PostgreSQL encodes bytea: encode(convert_to('héllo', 'utf8'), 'base64'). Encoding text directly needs that conversion step.","The base64 payload reflects the source encoding: UTF-8 versus latin1 input gives different output for accented text.","SQL Server and Oracle have no native function: SQL Server reaches for XML/FOR XML tricks, Oracle for UTL_ENCODE or APEX helpers."],"examples":[{"engine_slug":"mysql","sql":"SELECT TO_BASE64('ab') AS b64;  -- YWI="},{"engine_slug":"postgresql","sql":"SELECT encode(convert_to('ab', 'utf8'), 'base64') AS b64;  -- YWI="}],"faqs":[{"question":"Why does my base64 output contain newlines?","answer":"MySQL's TO_BASE64 and PostgreSQL's encode(..., 'base64') both wrap at 76 characters like MIME. On MySQL, REPLACE(TO_BASE64(x), '\\n', '') produces the single-line form most consumers expect; on PostgreSQL use REPLACE(encode(x, 'base64'), E'\\n', ''), because '\\n' there is a backslash and an n, not a line break."},{"question":"Does base64 encoding change my data?","answer":"Not the underlying bytes: the output is a reversible text form. It does grow size by about a third, and it is not encryption."},{"question":"How do I base64 in SQL Server?","answer":"No built-in. The common tricks encode via FOR XML PATH and XQUERY, or you encode in the application layer before the value reaches SQL."}],"related":["from-base64","hex","string-hash"],"novel_uses":[{"body":"Prefixing the encoded bytes with data:image/png;base64, produces a value an <img> tag displays directly, one query instead of a file pipeline for small badges.","sql":"SELECT CONCAT('data:image/png;base64,', REPLACE(TO_BASE64(icon), '\\n', '')) AS src\nFROM icons WHERE id = 3;"},{"body":"PostgreSQL's encode(thumb, 'base64') turns a bytea column into base64 text inside the query, wrapped every 76 characters; decode accepts those line breaks, so the client gets a decodable string and never opens a blob stream.","sql":"SELECT encode(thumb, 'base64') AS thumb_b64 FROM photos;"}]},"source_url":"https://sqlly.app/sql-functions/to-base64","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-char","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_CHAR / date formatting function","description":"Format timestamps as text: TO_CHAR in PostgreSQL and Oracle, DATE_FORMAT in MySQL, strftime in SQLite, FORMAT and CONVERT on SQL Server, with format code tables.","body":{"slug":"to-char","name":"TO_CHAR / DATE_FORMAT","h1":"SQL TO_CHAR / date formatting function","category":"datetime","lede":"Renders a timestamp as text in a template: 'YYYY-MM-DD', month names, 12-hour clocks. Every engine can do it, but the function names and format codes differ.","syntax":"TO_CHAR(ts, 'YYYY-MM-DD')  |  DATE_FORMAT(ts, '%Y-%m-%d')  |  strftime('%Y-%m-%d', ts)  |  FORMAT(ts, 'yyyy-MM-dd')","return_type":"string","support":[{"engine_slug":"sql-server","status":"partial","note":"no TO_CHAR; FORMAT(d, 'yyyy-MM-dd') or CONVERT with style codes"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"DATE_FORMAT(ts, '%Y-%m-%d')"},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y-%m-%d', ts): format first, then the value"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The codes are per-engine: PostgreSQL/Oracle 'YYYY-MM-DD HH24:MI', MySQL '%Y-%m-%d %H:%i', SQLite '%Y-%m-%d %H:%M', SQL Server FORMAT 'yyyy-MM-dd HH:mm'. A format string has to be rewritten for each engine.","TO_CHAR pads month and day names to a fixed width: 'Month' gives 'May      '. The FM prefix ('FMMonth') removes the padding on PostgreSQL and Oracle.","SQL Server's FORMAT is convenient but CLR-backed and slow on large sets; CONVERT with style numbers is the fast path.","Formatting is for display. Storing formatted dates in columns destroys sorting, arithmetic and indexes. Keep the native type."],"examples":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(created_at, 'dddd, dd MMMM yyyy') AS pretty\nFROM orders;"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(created_at, 'FMDay, DD Month YYYY') AS pretty\nFROM orders;"},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(created_at, '%W, %d %M %Y') AS pretty FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'FMDay, DD Month YYYY') AS pretty FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d %H:%M', created_at) AS stamp FROM orders;"}],"faqs":[{"question":"What are the format codes for a date with time?","answer":"PostgreSQL/Oracle: 'YYYY-MM-DD HH24:MI:SS'. MySQL: '%Y-%m-%d %H:%i:%s'. SQLite: '%Y-%m-%d %H:%M:%S'. SQL Server: CONVERT(varchar, d, 120) with style 120."},{"question":"Why is FORMAT so slow in SQL Server?","answer":"SQL Server has no TO_CHAR, and its FORMAT function calls into the .NET CLR once per row. CONVERT(varchar(30), d, style) is native and much faster on large result sets."}],"related":["to-date","date-trunc","extract"],"novel_uses":[{"body":"Double quotes embed fixed text in the mask, so TO_CHAR(ts, '\"Q\"Q YYYY') renders Q3 2026 in one call instead of three pieces concatenated. PostgreSQL and Oracle both read the quoted literals the same way.","sql":"SELECT TO_CHAR(created_at, '\"Q\"Q YYYY') AS quarter_label\nFROM orders;"},{"body":"TO_CHAR formats numbers too: TO_CHAR(total, 'FM999,999,990.00') prints thousands separators and pins two decimals, and L in the mask adds the locale currency symbol on Oracle. The FM prefix is what stops leading spaces on PostgreSQL.","sql":"SELECT TO_CHAR(total, 'FM999,999,990.00') AS pretty_total\nFROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/to-char","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-char-numeric","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_CHAR number formatting","description":"TO_CHAR number formatting in PostgreSQL and Oracle: masks for thousands separators, currency, leading zeros and signs, with the per-engine stand-ins used elsewhere.","body":{"slug":"to-char-numeric","name":"TO_CHAR (numbers)","h1":"SQL TO_CHAR number formatting","category":"conversion","lede":"TO_CHAR(1234567.891, 'FM999,999,999.00') renders a number as '1,234,567.89'. The mask controls every digit position, which CONVERT styles and MySQL's FORMAT do not.","syntax":"TO_CHAR(number, format_mask)","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"no TO_CHAR; FORMAT(value, 'N2') or CONVERT with styles"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"FORMAT(value, 2) rounds and separates but has no masks"},{"engine_slug":"sqlite","status":"partial","note":"printf('%.2f', v), also spelled format() from 3.38"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["FM strips the padding TO_CHAR adds for unused digit positions and the sign. Without it, TO_CHAR(42, '999') returns '  42' with two leading blanks, one for the empty digit slot and one reserved for the sign, the classic why-is-there-a-space mystery.","9 is a digit shown if significant, 0 forces a digit (leading zeros), D and G are the locale's decimal point and group separator, L is the local currency symbol. ',' and '.' are always comma and period.","Digits past the mask's scale are rounded, never truncated: TO_CHAR(0.567, '0.99') is ' 0.57'. With '9.99' the leading zero disappears and you get '  .57'.","A number too wide for the mask prints as # characters instead of erroring: TO_CHAR(12345, '999') is '####' on Oracle and ' ###' on PostgreSQL. Check masks against the largest value you expect."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(1234567.891, 'FM999,999,999.00') AS total;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(salary, 'L99G999D00') AS pay FROM employees;"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(42, 'FM000099') AS zero_padded;"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(1234567.891, 'N2') AS total;"},{"engine_slug":"mysql","sql":"SELECT FORMAT(1234567.891, 2) AS total;"},{"engine_slug":"sqlite","sql":"SELECT printf('%.2f', 1234567.891) AS total;"}],"faqs":[{"question":"Why a leading space in my number?","answer":"TO_CHAR reserves a character for the sign of negative numbers. Prefix the mask with FM to drop the padding: TO_CHAR(42, 'FM999')."},{"question":"How do I add a currency symbol?","answer":"Use $ for a literal dollar or L for the session's local currency symbol: TO_CHAR(total, 'FML99G999D00')."}],"related":["to-char","cast","convert","date-format"],"novel_uses":[{"body":"The RN mask prints the value as a Roman numeral, padded with spaces; prefix FM to trim them. Chapter numbers, edition labels and legal citations come out without a lookup table.","sql":"SELECT TO_CHAR(14, 'FMRN') AS part;"},{"body":"MI moves the minus sign after the digits, so TO_CHAR(-42, 'FM999MI') prints '42-' the way mainframe and bank formats expect. PR is the alternative: it wraps negatives in angle brackets.","sql":"SELECT TO_CHAR(balance, 'FM9999990.00MI') AS feed_line FROM accounts;"},{"body":"The Oracle-only JSP date format spells a whole number out in uppercase English once the number is turned into a Julian date: TO_CHAR(TO_DATE(1675, 'J'), 'JSP') gives ONE THOUSAND SIX HUNDRED SEVENTY-FIVE. Because it goes through the Julian-day mask, it covers integers from 1 to 5373484 only.","sql":"SELECT TO_CHAR(TO_DATE(1675, 'J'), 'JSP') AS words FROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/to-char-numeric","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_DATE function","description":"Parse text into a date: TO_DATE in PostgreSQL and Oracle, STR_TO_DATE in MySQL, CAST and CONVERT on SQL Server, date() on SQLite, with format-mask and locale traps.","body":{"slug":"to-date","name":"TO_DATE / STR_TO_DATE","h1":"SQL TO_DATE function","category":"datetime","lede":"Converts a text value into a real date using a format mask. The inverse of TO_CHAR, with the same per-engine format codes plus locale and ambiguity traps.","syntax":"TO_DATE('2026-08-01', 'YYYY-MM-DD')  |  STR_TO_DATE('2026-08-01', '%Y-%m-%d')","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"CAST('2026-08-01' AS date) or TRY_CONVERT with style"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"STR_TO_DATE(text, '%Y-%m-%d')"},{"engine_slug":"sqlite","status":"no","note":"date(text) understands ISO 8601 only"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Oracle's TO_DATE without a mask falls back to NLS_DATE_FORMAT, so code that works in one session breaks in another. Always pass the mask. Oracle DATEs also keep the time: TO_DATE('2026-08-01 14:30', 'YYYY-MM-DD HH24:MI') stores 14:30.","Two-digit years and day/month order are locale traps: '03/04/2026' is March 4 or April 3 depending on settings. ISO 8601 (YYYY-MM-DD) avoids the guesswork, with one SQL Server exception: the old datetime type can read '2026-08-01' as year-day-month under some session languages, while date and datetime2 never do.","SQLite's date() accepts ISO 8601 strings only; anything else needs text surgery first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TO_DATE('01/08/2026', 'DD/MM/YYYY') AS d;  -- 2026-08-01"},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('01/08/2026', '%d/%m/%Y') AS d;"},{"engine_slug":"sql-server","sql":"SELECT TRY_CONVERT(date, '01/08/2026', 103) AS d;  -- British style"},{"engine_slug":"oracle","sql":"SELECT TO_DATE('01/08/2026', 'DD/MM/YYYY') AS d FROM dual;"}],"faqs":[{"question":"What happens if the text is not a valid date?","answer":"PostgreSQL and Oracle raise an error, which fails the whole query. SQL Server's TRY_CONVERT and TRY_CAST return NULL instead. MySQL's STR_TO_DATE returns NULL with a warning. Oracle 12.2+ accepts TO_DATE(s DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD'), and PostgreSQL 16+ can test first with pg_input_is_valid(s, 'date')."},{"question":"Which date format should I always use?","answer":"ISO 8601, YYYY-MM-DD. All five engines parse it the same way, apart from SQL Server's legacy datetime type described above; for that type, '20260801' without dashes is always safe."}],"related":["to-char","cast","try-cast"],"novel_uses":[{"body":"PostgreSQL's TO_DATE fills in what the mask omits: parsing 2026-03 with YYYY-MM gives March 1, exactly the key monthly rollups want. How much other engines fill in varies, so test before relying on it outside PostgreSQL.","sql":"SELECT TO_DATE('2026-03', 'YYYY-MM') AS month_start;"},{"body":"Parse with the mask, render back with the same mask, and compare: rows that print differently were never clean dates, missing zero padding or holding day-month swaps that only look parseable. Values that fail the parse raise errors, so pre-filter with a regex when the column is wild.","sql":"SELECT raw_date\nFROM imports\nWHERE TO_CHAR(TO_DATE(raw_date, 'DD/MM/YYYY'), 'DD/MM/YYYY') <> raw_date;"}]},"source_url":"https://sqlly.app/sql-functions/to-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-days","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_DAYS function","description":"MySQL's TO_DAYS counts days since year 0 and FROM_DAYS reverses it: a day-number pair for date math that other engines do with DATEDIFF or subtraction.","body":{"slug":"to-days","name":"TO_DAYS / FROM_DAYS","h1":"SQL TO_DAYS function","category":"datetime","lede":"Returns the calendar day number of a date, or a date back from that number: the classic MySQL idiom for day-count arithmetic.","syntax":"TO_DAYS('2024-01-15')  -- 739265  |  FROM_DAYS(739265)  |  DATEDIFF(day, 0, d)  -- SQL Server, days since 1900","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF(day, 0, d) counts from 1900-01-01; DATEADD(day, n, 0) reverses"},{"engine_slug":"postgresql","status":"partial","note":"d - DATE '0001-01-01' + 366 matches TO_DAYS"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"julianday(d), a different origin"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'J'), a different origin"}],"gotchas":["TO_DAYS counts from year 0 of MySQL's calendar, not 1970: TO_DAYS('2024-01-15') is 739265. Every engine's day number uses its own origin, so never compare them across engines.","It ignores the time part: 2024-01-15 00:01 and 23:59 give the same number. Good for daily keys; wrong for measuring spans shorter than a day.","FROM_DAYS is not meant for dates before 1582: MySQL counts days on the proleptic Gregorian calendar and ignores the switch from the Julian calendar."],"examples":[{"engine_slug":"mysql","sql":"SELECT TO_DAYS('2024-01-15') AS day_no;"},{"engine_slug":"mysql","sql":"SELECT FROM_DAYS(TO_DAYS('2024-01-15') + 30) AS in_30_days;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(DAY, 0, created_at) AS day_no FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT created_at::date - DATE '0001-01-01' + 366 AS day_no FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT julianday(created_at) AS day_no FROM orders;"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'J') AS day_no FROM orders;"}],"faqs":[{"question":"What is TO_DAYS used for?","answer":"Daily bucketing keys and date arithmetic in one integer: FROM_DAYS(TO_DAYS(d) + 30) is thirty days later, and equal TO_DAYS means the same calendar day."},{"question":"Is the day number an epoch?","answer":"No. It counts from year 0 in MySQL's proleptic Gregorian calendar, not from 1970. SQLite's julianday uses a different origin again."}],"related":["julianday","datediff","unix-timestamp"],"novel_uses":[{"body":"FROM_DAYS(TO_DAYS('2024-01-01') + n) walks the calendar from any anchor: the gap-filling spine for charts, built from one integer expression.","sql":"SELECT FROM_DAYS(TO_DAYS('2024-01-01') + n) AS d\nFROM (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) s;"},{"body":"TO_DAYS(d) DIV 7 numbers blocks of exactly seven days from MySQL's year 0. Not ISO weeks, but when you want equal spans and no week-mode arguments, this is the key.","sql":"SELECT TO_DAYS(d) DIV 7 AS week_block, COUNT(*) AS n\nFROM events GROUP BY week_block;"}]},"source_url":"https://sqlly.app/sql-functions/to-days","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-dsinterval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_DSINTERVAL function","description":"Oracle's TO_DSINTERVAL and TO_YMINTERVAL parse interval strings like '0 02:30:00': days-to-seconds and years-to-months spans as real interval values.","body":{"slug":"to-dsinterval","name":"TO_DSINTERVAL","h1":"SQL TO_DSINTERVAL function","category":"datetime","lede":"Returns an INTERVAL value parsed from text: TO_DSINTERVAL for day-hour-minute-second spans, TO_YMINTERVAL for year-month spans.","syntax":"TO_DSINTERVAL('0 02:30:00')  |  TO_YMINTERVAL('01-06')  |  NUMTODSINTERVAL(150, 'minute')","return_type":"INTERVAL DAY TO SECOND / YEAR TO MONTH","support":[{"engine_slug":"sql-server","status":"no","note":"no interval type; DATEADD applies units directly"},{"engine_slug":"postgresql","status":"partial","note":"'02:30:00'::interval or INTERVAL '02:30:00' literals"},{"engine_slug":"mysql","status":"partial","note":"INTERVAL 150 MINUTE literals"},{"engine_slug":"sqlite","status":"no","note":"no interval type; date modifiers"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The SQL format needs the days field: '1 02:30:00' is one day plus 2h30m, and TO_DSINTERVAL('02:30:00') raises ORA-01867. The ISO form 'PT2H30M' is also accepted.","Adding a year-month interval does not clamp the way ADD_MONTHS does: DATE '2024-02-29' + TO_YMINTERVAL('01-00') raises ORA-01839 instead of returning February 28.","NUMTODSINTERVAL(n, unit) builds the same span from a number, which is the right form when the amount arrives from a column."],"examples":[{"engine_slug":"oracle","sql":"SELECT d + TO_DSINTERVAL('0 02:30:00') AS later FROM events;"},{"engine_slug":"oracle","sql":"SELECT d + TO_YMINTERVAL('01-06') AS in_18_months FROM events;"},{"engine_slug":"oracle","sql":"SELECT d + NUMTODSINTERVAL(mins, 'minute') AS later FROM jobs;"},{"engine_slug":"postgresql","sql":"SELECT created_at + INTERVAL '02:30:00' AS later FROM events;"},{"engine_slug":"mysql","sql":"SELECT created_at + INTERVAL 150 MINUTE AS later FROM events;"}],"faqs":[{"question":"TO_DSINTERVAL or NUMTODSINTERVAL?","answer":"TO_DSINTERVAL parses a text literal; NUMTODSINTERVAL builds from a numeric amount and unit. Use the numeric form when the value comes from a column."},{"question":"Why does TO_DSINTERVAL raise ORA-01867?","answer":"The string is missing the days field: write '0 02:30:00', not '02:30:00', or use the ISO form 'PT2H30M'."}],"related":["make-interval","interval-literal","dateadd"],"novel_uses":[{"body":"When the span is whole days or a simple fraction, d + 0.25 beats any interval string: Oracle DATE plus number counts days, so a quarter day is six hours.","sql":"SELECT d + 0.25 AS plus_six_hours FROM events;"},{"body":"Comparing an INTERVAL column against TO_DSINTERVAL('0 00:00:00') works in CHECK constraints, so negative or absurd estimates fail at write time.","sql":"ALTER TABLE jobs ADD CONSTRAINT ck_jobs_est\nCHECK (est >= TO_DSINTERVAL('0 00:00:00'));"}]},"source_url":"https://sqlly.app/sql-functions/to-dsinterval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-json","corpus":"sql-functions","engine":null,"language":"en","title":"SQL to_json function","description":"PostgreSQL's to_json and to_jsonb, SQLite's json() and MySQL's CAST(... AS JSON): turning rows and scalars into JSON documents, with engine-specific typing.","body":{"slug":"to-json","name":"to_json / JSON()","h1":"SQL to_json function","category":"string","lede":"to_jsonb(u) turns a whole row into a JSON object keyed by column name; to_jsonb(42) turns a scalar into JSON. SQLite's json() and MySQL's CAST AS JSON parse text instead.","syntax":"to_json(expr)  |  to_jsonb(expr)  -- PostgreSQL  |  json(x)  -- SQLite","return_type":"JSON or jsonb","support":[{"engine_slug":"sql-server","status":"partial","note":"no to_json; FOR JSON builds documents"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"CAST(x AS JSON) validates; JSON_ARRAY/JSON_OBJECT build"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"partial","note":"JSON_OBJECT and constructors; no single to_json"}],"gotchas":["to_json returns json (text, keeps duplicate keys and key order) and to_jsonb returns jsonb (parsed binary, duplicate keys collapsed with the last winning, keys reordered shortest first, supports @>, ? and GIN indexes). Prefer jsonb for anything you will query.","SQLite's json() parses its argument and returns minified canonical JSON. It errors on invalid input, and it converts JSON5 such as {a:1} to {\"a\":1}.","to_jsonb of a text value makes a JSON string: to_jsonb('{\"a\":1}'::text) is the string \"{\\\"a\\\":1}\", not an object. To parse text, cast it: '{\"a\":1}'::jsonb.","SQL Server builds documents with FOR JSON rather than a function; row-to-JSON there is SELECT ... FOR JSON PATH, WITHOUT_ARRAY_WRAPPER."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_jsonb(u) AS doc\nFROM users u;"},{"engine_slug":"sqlite","sql":"SELECT json(value) AS normalised FROM imports;"},{"engine_slug":"mysql","sql":"SELECT CAST(info AS JSON) AS checked FROM staging;"},{"engine_slug":"sql-server","sql":"SELECT (SELECT id, name FROM users FOR JSON PATH) AS doc;"},{"engine_slug":"oracle","sql":"SELECT JSON_OBJECT('id' VALUE id, 'name' VALUE name) AS doc\nFROM users;"}],"faqs":[{"question":"Row to JSON in one call?","answer":"PostgreSQL: to_jsonb(table_alias). SQL Server: FOR JSON PATH, WITHOUT_ARRAY_WRAPPER. Oracle: JSON_OBJECT(*). MySQL and SQLite: JSON_OBJECT listing the columns."},{"question":"json or jsonb on PostgreSQL?","answer":"jsonb for anything stored and queried: indexes, containment, operators. json only when the exact original text must survive, duplicates and key order included."}],"related":["json-object","json-array","json-valid","jsonb-contains"],"novel_uses":[{"body":"Casting to jsonb parses the document into one canonical form, so '{\"a\":1}' and '{ \"a\" : 1 }' become equal. DISTINCT or GROUP BY over payload::jsonb collapses documents that differ only in whitespace or key order. to_jsonb(payload) does the same only when payload is already json; on a text column it makes JSON strings that stay distinct.","sql":"SELECT DISTINCT payload::jsonb AS canonical FROM staging.docs;"},{"body":"to_jsonb(NEW) serializes every column by name, so an audit trigger logs the full row image and keeps working when columns are added. No column list to maintain.","sql":"INSERT INTO audit_log (data) VALUES (to_jsonb(NEW));"}]},"source_url":"https://sqlly.app/sql-functions/to-json","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-number","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_NUMBER function","description":"TO_NUMBER in PostgreSQL and Oracle: parse text to a number with a format mask, what SQL Server, MySQL and SQLite use instead, and silent-truncation traps.","body":{"slug":"to-number","name":"TO_NUMBER","h1":"SQL TO_NUMBER function","category":"conversion","lede":"Parses text into a number using a format mask that describes currency symbols, thousand separators and the decimal point. PostgreSQL and Oracle have it; the other engines use CAST, which accepts only plain digits.","syntax":"TO_NUMBER(text [, format])","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"no TO_NUMBER; CAST/TRY_CAST, or PARSE with culture"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no TO_NUMBER; CAST(x AS DECIMAL) or x + 0"},{"engine_slug":"sqlite","status":"no","note":"no TO_NUMBER; CAST or numeric affinity"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL's TO_NUMBER quietly ignores characters it does not recognize: TO_NUMBER('12abc', '999') is 12. Pre-validate when the input is untrusted.","The mask uses 9s and 0s: TO_NUMBER('1,234.5', '9G999D9'). G is the group separator, D the decimal, resolved per locale settings on Oracle.","MySQL's x + 0 coerces by reading the leading number: '42abc' + 0 is 42, with a warning. CAST('42abc' AS DECIMAL(10,2)) does the same and returns 42.00.","PostgreSQL requires the mask: TO_NUMBER(text) with one argument does not exist. Oracle's mask is optional."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TO_NUMBER('1,234.50', '9G999D99') AS amount;  -- 1234.50"},{"engine_slug":"oracle","sql":"SELECT TO_NUMBER('$1,234.50', 'L9G999D99', 'NLS_NUMERIC_CHARACTERS=''.,''') AS amount\nFROM dual;"},{"engine_slug":"mysql","sql":"SELECT CAST('1234.50' AS DECIMAL(10,2)) AS amount;"}],"faqs":[{"question":"Does TO_NUMBER error on invalid text?","answer":"Oracle does (ORA-01722); PostgreSQL does not: it stops parsing and returns the leading digits, so TO_NUMBER('12abc', '999') is 12. A plain CAST of the same text errors on both engines."},{"question":"What is the equivalent of TO_NUMBER in SQL Server?","answer":"CAST or TRY_CAST to a numeric type for plain digits. For separators and currency in a given locale, PARSE or TRY_PARSE: TRY_PARSE('1.234,50' AS decimal(10,2) USING 'de-DE') is 1234.50. There is no format-mask parsing."}],"related":["cast","try-cast","to-date"],"novel_uses":[{"body":"Accounting systems print negatives as <123>. Oracle's PR mask element parses them straight back: TO_NUMBER('<123>', '999PR') gives -123, which plain CAST refuses.","sql":"SELECT TO_NUMBER(amount_text, '999PR') AS amount\nFROM ledger_texts;"},{"body":"A varchar code column sorts 10 before 9. TO_NUMBER in the ORDER BY restores numeric order; pre-filter with a regex first, because PostgreSQL stops at the first non-digit rather than erroring.","sql":"SELECT code\nFROM parts\nWHERE code ~ '^[0-9]+$'\nORDER BY TO_NUMBER(code, '999999');"}]},"source_url":"https://sqlly.app/sql-functions/to-number","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-seconds","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_SECONDS function","description":"MySQL's TO_SECONDS counts seconds since year 0, a finer-grained day number used for range pruning; epoch seconds start from 1970 instead.","body":{"slug":"to-seconds","name":"TO_SECONDS","h1":"SQL TO_SECONDS function","category":"datetime","lede":"Returns the number of seconds from year 0 to a date or datetime: TO_DAYS scaled by 86,400, plus the time when given a datetime.","syntax":"TO_SECONDS('2024-01-15')  |  TO_SECONDS('2024-01-15 09:30:00')","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF_BIG(second, '0001-01-01', d) + 31622400; plain DATEDIFF overflows int"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(epoch FROM ts) + 62167219200"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"unixepoch(ts) + 62167219200"},{"engine_slug":"oracle","status":"partial","note":"(d - DATE '1970-01-01') * 86400 + 62167219200"}],"gotchas":["It is not epoch time: TO_SECONDS('1970-01-01') is 62,167,219,200, so add or subtract that constant to move between the two scales.","With a date-only argument the time counts as midnight; with a datetime the seconds include the clock. Mixed inputs shift results by the time of day.","PostgreSQL and SQL Server reject TO_SECONDS; use the equivalents in the examples. It takes the value as written with no time-zone conversion, whereas UNIX_TIMESTAMP first converts from the session time_zone to UTC."],"examples":[{"engine_slug":"mysql","sql":"SELECT TO_SECONDS('2024-01-15 09:30:00') AS s;"},{"engine_slug":"mysql","sql":"SELECT UNIX_TIMESTAMP('2024-01-15') AS epoch, TO_SECONDS('2024-01-15') AS since_year0;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF_BIG(SECOND, '0001-01-01', '2024-01-15') + 31622400 AS s;"},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(epoch FROM created_at) + 62167219200 AS s FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT unixepoch(created_at) + 62167219200 AS s FROM orders;"},{"engine_slug":"oracle","sql":"SELECT (created_at - DATE '1970-01-01') * 86400 + 62167219200 AS s FROM orders;"}],"faqs":[{"question":"Is TO_SECONDS the same as UNIX_TIMESTAMP?","answer":"No: TO_SECONDS counts from year 0, UNIX_TIMESTAMP from 1970 UTC. For a UTC session the difference is exactly 62,167,219,200 seconds."},{"question":"Where is TO_SECONDS actually used?","answer":"Mostly partition pruning: MySQL's RANGE partitioning on TO_SECONDS(expr) prunes plain datetime range predicates (ts >= ... AND ts < ...) the way it does for TO_DAYS; a predicate written as TO_SECONDS(ts) >= ... does not prune on either."}],"related":["to-days","unix-timestamp","time-to-sec"],"novel_uses":[{"body":"The difference of two TO_SECONDS values is the span in seconds, midnight based for date-only inputs, which replaces DATEDIFF times 86400 in one expression.","sql":"SELECT TO_SECONDS('2024-03-01') - TO_SECONDS('2024-01-01') AS seconds_apart;"},{"body":"TO_SECONDS(ts) DIV 900 numbers 15-minute blocks, and because 86400 divides by 900 exactly, every block starts on a real clock quarter hour.","sql":"SELECT TO_SECONDS(ts) DIV 900 AS quarter_hour, COUNT(*) AS n\nFROM events GROUP BY quarter_hour;"}]},"source_url":"https://sqlly.app/sql-functions/to-seconds","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-timestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_TIMESTAMP function","description":"TO_TIMESTAMP in PostgreSQL and Oracle: text to timestamp with a format mask, the SQL Server, MySQL and SQLite alternatives, and time-zone behaviour.","body":{"slug":"to-timestamp","name":"TO_TIMESTAMP","h1":"SQL TO_TIMESTAMP function","category":"conversion","lede":"Parses text into a timestamp using a format mask, keeping hours, minutes, seconds and fractions. On PostgreSQL the one-argument form converts Unix epoch seconds instead.","syntax":"TO_TIMESTAMP(text, format)  |  TO_TIMESTAMP(epoch_seconds)  -- PostgreSQL","return_type":"timestamptz on PostgreSQL, TIMESTAMP on Oracle","support":[{"engine_slug":"sql-server","status":"partial","note":"CONVERT(datetime2, text, style) or CAST"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"STR_TO_DATE(text, '%Y-%m-%d %H:%i:%s')"},{"engine_slug":"sqlite","status":"no","note":"datetime(text) parses ISO 8601 only"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["PostgreSQL's TO_TIMESTAMP always returns timestamptz. The text is read in the session time zone unless the mask includes an offset (TZH:TZM), so the same call stores different instants in sessions with different TimeZone settings.","PostgreSQL's one-argument TO_TIMESTAMP takes a number of seconds since 1970: TO_TIMESTAMP(1785000000) is 2026-07-25 17:20:00+00. Oracle's TO_TIMESTAMP returns a TIMESTAMP without a zone; TO_TIMESTAMP_TZ keeps one.","The mask codes mirror TO_CHAR: PostgreSQL/Oracle 'YYYY-MM-DD HH24:MI:SS', MySQL '%Y-%m-%d %H:%i:%s'.","SQLite's datetime() accepts ISO 8601 text only; anything else needs REPLACE surgery to ISO first."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TO_TIMESTAMP('2026-08-01 14:30:00', 'YYYY-MM-DD HH24:MI:SS');"},{"engine_slug":"oracle","sql":"SELECT TO_TIMESTAMP('2026-08-01 14:30:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual;"},{"engine_slug":"sql-server","sql":"SELECT CONVERT(DATETIME2, '2026-08-01 14:30:00', 120);"},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('2026-08-01 14:30:00', '%Y-%m-%d %H:%i:%s');"}],"faqs":[{"question":"What is the difference between TO_TIMESTAMP and TO_DATE?","answer":"On PostgreSQL, TO_DATE returns a date and drops the time; TO_TIMESTAMP keeps the time and returns timestamptz. On Oracle both keep the time of day, because Oracle's DATE has seconds; TO_TIMESTAMP adds fractional seconds."},{"question":"What is the equivalent of TO_TIMESTAMP in MySQL?","answer":"STR_TO_DATE(text, '%Y-%m-%d %H:%i:%s') with MySQL's percent-format codes."}],"related":["to-date","to-char","now"],"novel_uses":[{"body":"TO_TIMESTAMP reads the text in the session's time zone, so the same string becomes different instants for different sessions. Cast to a naive timestamp first and re-tag with AT TIME ZONE 'UTC' to pin the meaning regardless of who runs the query.","sql":"SELECT ts_text::timestamp AT TIME ZONE 'UTC' AS instant\nFROM imports;"},{"body":"The TZH:TZM mask elements read a numeric offset like +02:00 out of the text on Oracle, so the zone travels with the value instead of being dropped the way plain TO_TIMESTAMP would drop it.","sql":"SELECT TO_TIMESTAMP_TZ('2026-08-01 12:00 +02:00',\n         'YYYY-MM-DD HH24:MI TZH:TZM') AS with_offset\nFROM dual;"}]},"source_url":"https://sqlly.app/sql-functions/to-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/to-yminterval","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TO_YMINTERVAL function","description":"TO_YMINTERVAL in Oracle: parse '1-6' into a YEAR TO MONTH interval, and why adding it to January 31 raises an error where ADD_MONTHS would not.","body":{"slug":"to-yminterval","name":"TO_YMINTERVAL","h1":"SQL TO_YMINTERVAL function","category":"datetime","lede":"Converts a years-months string into an INTERVAL YEAR TO MONTH value.","syntax":"TO_YMINTERVAL('1-6')","return_type":"interval year to month","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"INTERVAL '1 year 6 months' literal"},{"engine_slug":"mysql","status":"partial","note":"INTERVAL '1-6' YEAR_MONTH compound unit; clamps at month ends"},{"engine_slug":"sqlite","status":"partial","note":"no months type; '+18 months' modifiers"},{"engine_slug":"oracle","status":"yes","note":"this, or INTERVAL '1-6' YEAR TO MONTH literal"}],"gotchas":["The format is years-months: TO_YMINTERVAL('1-6') is one year six months, and ISO 'P1Y6M' also works. A plain '18' raises ORA-01867.","Oracle does not clamp interval month arithmetic: DATE '2026-01-31' + TO_YMINTERVAL('0-1') raises ORA-01839 (date not valid for month specified). Use ADD_MONTHS when the start date can be a 29th, 30th or 31st.","Day-second strings error here; TO_DSINTERVAL is the mirror. A DATE plus either interval type works directly and returns a DATE."],"examples":[{"engine_slug":"oracle","sql":"SELECT DATE '2026-08-01' + TO_YMINTERVAL('1-6') FROM dual;  -- 2028-02-01"},{"engine_slug":"oracle","sql":"SELECT DATE '2026-01-31' + TO_YMINTERVAL('0-1') FROM dual;  -- ORA-01839"},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-08-01', INTERVAL '1-6' YEAR_MONTH);  -- 2028-02-01"},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-08-01' + INTERVAL '1 year 6 months';  -- 2028-02-01 00:00:00"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-01', '+18 months');  -- 2028-02-01"}],"faqs":[{"question":"Why does DATE '2026-08-01' + TO_YMINTERVAL('1-6') give 2028-02-01?","answer":"18 calendar months: August 2026 + 18 months is February 2028, same day. Calendar months, not 30-day blocks; that is the YEAR TO MONTH contract."},{"question":"What is the PostgreSQL spelling?","answer":"PostgreSQL accepts the SQL-standard '1-6' text too: INTERVAL '1-6' is 1 year 6 mons, the same as INTERVAL '18 months'. PostgreSQL clamps at month ends rather than erroring."}],"related":["to-dsinterval","numtoyminterval","add-months","interval-keyword"],"novel_uses":[{"body":"Storing contract lengths as INTERVAL YEAR TO MONTH makes term comparisons read like the business question and sort correctly past twelve months.","sql":"SELECT * FROM contracts WHERE term > TO_YMINTERVAL('1-0');"},{"body":"Extract the years and months from the stored interval and hand them to ADD_MONTHS, which clamps month ends instead of raising ORA-01839.","sql":"SELECT ADD_MONTHS(started, EXTRACT(YEAR FROM term) * 12 + EXTRACT(MONTH FROM term)) FROM contracts;"}]},"source_url":"https://sqlly.app/sql-functions/to-yminterval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/todatetimeoffset","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TODATETIMEOFFSET function","description":"TODATETIMEOFFSET stamps a zone-less datetime with a UTC offset; SWITCHOFFSET keeps the instant and re-expresses it in another offset.","body":{"slug":"todatetimeoffset","name":"TODATETIMEOFFSET","h1":"SQL TODATETIMEOFFSET function","category":"datetime","lede":"Returns a datetimeoffset. TODATETIMEOFFSET attaches an offset you supply; SWITCHOFFSET moves the same instant to a different offset.","syntax":"TODATETIMEOFFSET(GETDATE(), '-05:00')  |  SWITCHOFFSET(SYSDATETIMEOFFSET(), '+00:00')","return_type":"datetimeoffset","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"ts AT TIME ZONE 'zone' tags a timestamp; timestamptz has no stored offset"},{"engine_slug":"mysql","status":"no","note":"no offset type; CONVERT_TZ converts"},{"engine_slug":"sqlite","status":"no","note":"no offset type"},{"engine_slug":"oracle","status":"partial","note":"SYSTIMESTAMP AT TIME ZONE or FROM_TZ"}],"gotchas":["TODATETIMEOFFSET does not convert: it declares a zone-less value WAS in that offset, so tagging a UTC value with '-05:00' changes the instant.","Fixed offsets freeze daylight saving: an offset captured in summer stays wrong in winter. AT TIME ZONE with a named zone handles DST.","Both accept the offset as a '+hh:mm' string or as signed minutes: TODATETIMEOFFSET(d, -300) is the same as TODATETIMEOFFSET(d, '-05:00')."],"examples":[{"engine_slug":"sql-server","sql":"SELECT TODATETIMEOFFSET('2024-01-15 09:30', '-05:00') AS tagged;"},{"engine_slug":"sql-server","sql":"SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '+00:00') AS utc_instant;"},{"engine_slug":"postgresql","sql":"SELECT '2024-01-15 09:30:00'::timestamp AT TIME ZONE 'America/New_York' AS tagged;"},{"engine_slug":"oracle","sql":"SELECT FROM_TZ(TIMESTAMP '2024-01-15 09:30:00', '-05:00') AS tagged FROM dual;"}],"faqs":[{"question":"TODATETIMEOFFSET or SWITCHOFFSET: which converts?","answer":"Neither converts zones the way AT TIME ZONE does. SWITCHOFFSET re-expresses one instant; TODATETIMEOFFSET just labels a zone-less value."},{"question":"Why did my time shift by five hours?","answer":"You tagged a UTC value with -05:00 using TODATETIMEOFFSET. The function trusts the offset you gave; it never converts for you."}],"related":["sysdatetimeoffset","utc-timestamp","getdate"],"novel_uses":[{"body":"Zone-less datetime columns migrate in two steps: ALTER COLUMN to datetimeoffset first, then one UPDATE through TODATETIMEOFFSET to declare which zone the stored wall time was really in.","sql":"ALTER TABLE calls ALTER COLUMN at datetimeoffset(0);\nUPDATE calls SET at = TODATETIMEOFFSET(CAST(at AS datetime2(0)), '-05:00');"},{"body":"AT TIME ZONE arrived in SQL Server 2016. On older servers, a CASE that switches to '-04:00' at 02:00 on the DST start date and back to '-05:00' at 02:00 on the DST end date is one DST-aware way to choose the offset TODATETIMEOFFSET takes.","sql":"SELECT TODATETIMEOFFSET(at,\n    CASE WHEN at >= '2024-03-10 02:00' AND at < '2024-11-03 02:00' THEN '-04:00' ELSE '-05:00' END) AS tagged\nFROM calls;"}]},"source_url":"https://sqlly.app/sql-functions/todatetimeoffset","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/top-n-per-group","corpus":"sql-functions","engine":null,"language":"en","title":"SQL top N rows per group","description":"The ROW_NUMBER pattern for top-N-per-group: rank inside each partition, keep rn <= N outside, and add the tiebreaker that makes it deterministic.","body":{"slug":"top-n-per-group","name":"Top N Per Group","h1":"SQL top N rows per group","category":"window","lede":"Rank rows within each partition with ROW_NUMBER, then filter rn <= N in an outer query, the standard replacement for the unsupported 'LIMIT per group'.","syntax":"WITH r AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) AS rn FROM t)\nSELECT * FROM r WHERE rn <= N","return_type":"up to N rows per group","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The filter must live outside the window: WHERE rn <= N in the same SELECT is invalid because windows evaluate after WHERE. A CTE or derived table is the portable wrapper.","Ties beyond N are silently dropped and, without a unique tiebreaker, which rows make the cut can change run to run. Append a unique column as the last ORDER BY key.","For 'N including ties' use RANK or DENSE_RANK instead: RANK() <= 3 can return four rows when two tie for third."],"examples":[{"engine_slug":"all","sql":"-- three biggest orders per customer\nWITH r AS (\n  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders o\n)\nSELECT * FROM r WHERE rn <= 3;"}],"faqs":[{"question":"Why is there no LIMIT per group in SQL?","answer":"LIMIT applies to the whole result set, not per partition. The portable fix is exactly this pattern: number rows per partition, then filter. PostgreSQL also offers DISTINCT ON for N = 1."},{"question":"ROW_NUMBER, RANK or DENSE_RANK for top N?","answer":"ROW_NUMBER for at most N rows per group (exactly N when the group has that many), RANK for N including ties (can exceed N), DENSE_RANK when ties should share a level and the count of levels is what matters."}],"related":["row-number","dedupe-rows","rank"],"novel_uses":[{"body":"The outer filter is ordinary SQL, so the cut can vary: rn <= CASE WHEN region = 'EMEA' THEN 5 ELSE 2 END keeps five from one region and two elsewhere. A single LIMIT cannot vary by group, and MySQL rejects an expression in LIMIT; PostgreSQL (LATERAL) and SQL Server (CROSS APPLY with TOP) can vary it per group, but the window filter works on every engine.","sql":"WITH r AS (\n  SELECT region, product_id, revenue,\n         ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS rn\n  FROM product_revenue\n)\nSELECT * FROM r\nWHERE rn <= CASE WHEN region = 'EMEA' THEN 5 ELSE 2 END;"},{"body":"Compute the partition count in the same CTE and the result can say top 3 of 47, which is what dashboards need to rank small and large groups fairly. The count costs one more window over the same partition.","sql":"WITH r AS (\n  SELECT customer_id, order_id, amount,\n         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn,\n         COUNT(*) OVER (PARTITION BY customer_id) AS order_count\n  FROM orders\n)\nSELECT customer_id, order_id, amount, order_count\nFROM r\nWHERE rn <= 3;"}]},"source_url":"https://sqlly.app/sql-functions/top-n-per-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/total","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TOTAL function","description":"SQLite's TOTAL(x) aggregates as REAL and returns 0.0 when there are no rows or only NULLs, where SUM returns NULL and raises integer-overflow errors.","body":{"slug":"total","name":"TOTAL","h1":"SQL TOTAL function","category":"aggregate","lede":"SQLite's SUM variant that never returns NULL and never fails on integer overflow.","syntax":"total(x) | total(x) FILTER (WHERE ...)","return_type":"real","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["SUM over an empty or all-NULL group returns NULL; TOTAL returns 0.0, no COALESCE needed.","TOTAL always returns a REAL, so large integers lose precision past 2^53; SUM throws an integer-overflow error where TOTAL silently floats.","Elsewhere the portable pattern is COALESCE(SUM(x), 0)."],"examples":[{"engine_slug":"sqlite","sql":"SELECT total(amount) FROM ledger WHERE account_id = 3;"},{"engine_slug":"sqlite","sql":"SELECT SUM(amount), TOTAL(amount) FROM ledger WHERE 0 = 1;"}],"faqs":[{"question":"TOTAL vs SUM in SQLite?","answer":"TOTAL returns 0.0 instead of NULL for empty input and floats instead of erroring on overflow; SUM keeps integers exact."},{"question":"How do I get TOTAL's behaviour elsewhere?","answer":"COALESCE(SUM(x), 0), the standard trick on the other four engines."},{"question":"Is TOTAL exact for big integers?","answer":"No, it is a 64-bit float; beyond 2^53 the low bits are lost."}],"related":["sum","aggregate-nulls","coalesce","avg"],"novel_uses":[{"body":"Bake total() into a view and report consumers get 0.0 for empty accounts instead of NULL they must handle in every client.","sql":"CREATE VIEW v_balances AS SELECT account_id, total(amount) AS balance FROM ledger GROUP BY account_id;"},{"body":"FILTER keeps the refund subtotal beside the gross in the same SELECT, and neither column can come back NULL.","sql":"SELECT total(amount) AS gross, total(amount) FILTER (WHERE kind = 'refund') AS refunds FROM payments;"}]},"source_url":"https://sqlly.app/sql-functions/total","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/transaction-timestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL transaction_timestamp function","description":"PostgreSQL's transaction_timestamp() and statement_timestamp() return transaction-start and statement-start times; other engines freeze per statement.","body":{"slug":"transaction-timestamp","name":"transaction_timestamp","h1":"SQL transaction_timestamp function","category":"datetime","lede":"Returns the time the current transaction began (identical to NOW()), with statement_timestamp() as the per-statement sibling.","syntax":"transaction_timestamp()  |  statement_timestamp()","return_type":"timestamptz","support":[{"engine_slug":"sql-server","status":"partial","note":"no function; sys.dm_tran_active_transactions.transaction_begin_time"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"partial","note":"no function; information_schema.innodb_trx.trx_started"},{"engine_slug":"sqlite","status":"no","note":"no transaction clock"},{"engine_slug":"oracle","status":"partial","note":"no function; V$TRANSACTION.START_DATE, which needs privileges"}],"gotchas":["Every statement in a long transaction sees the same transaction_timestamp(), so rows inserted minutes apart in one transaction get identical created_at values.","statement_timestamp() resets on each statement, so it differs from transaction_timestamp() on every statement after the first. Even the first statement after an explicit BEGIN runs a few microseconds later; the two match only when a single statement runs in autocommit.","Elsewhere the clock functions freeze per statement at most. SQL Server exposes the start time only through sys.dm_tran_active_transactions, filtered on CURRENT_TRANSACTION_ID()."],"examples":[{"engine_slug":"postgresql","sql":"BEGIN;\nSELECT transaction_timestamp() AS txn_start;\nSELECT pg_sleep(2), transaction_timestamp() AS same_txn_start;\nCOMMIT;"},{"engine_slug":"postgresql","sql":"SELECT statement_timestamp() AS stmt_start FROM orders LIMIT 1;"},{"engine_slug":"sql-server","sql":"SELECT transaction_begin_time FROM sys.dm_tran_active_transactions WHERE transaction_id = CURRENT_TRANSACTION_ID();"},{"engine_slug":"mysql","sql":"SELECT trx_started FROM information_schema.innodb_trx;"},{"engine_slug":"oracle","sql":"SELECT start_date FROM v$transaction;"}],"faqs":[{"question":"Is transaction_timestamp different from NOW()?","answer":"No. They are aliases. Both freeze at transaction start; statement_timestamp() is the one that resets per statement."},{"question":"Why would I want a frozen timestamp?","answer":"Consistency: every row a transaction writes gets one value, so a batch can be found again by its timestamp and nothing in it looks older than the rest."}],"related":["now","clock-timestamp","localtimestamp"],"novel_uses":[{"body":"transaction_timestamp() alone cannot order two overlapping transactions that started in the same instant. Add txid_current() and the pair sorts events by time and then by transaction.","sql":"SELECT transaction_timestamp() AS at, txid_current() AS txn;"},{"body":"pg_stat_activity exposes each session's xact_start, so now() minus xact_start ranks open transactions by age. The oldest is only a suspect: a session with no snapshot (backend_xmin IS NULL) cannot hold back VACUUM, so check backend_xmin before blaming the oldest row.","sql":"SELECT pid, now() - xact_start AS age\nFROM pg_stat_activity\nWHERE xact_start IS NOT NULL\nORDER BY age DESC;"}]},"source_url":"https://sqlly.app/sql-functions/transaction-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/translate","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRANSLATE function","description":"TRANSLATE swaps characters one-for-one by position on SQL Server 2017+, PostgreSQL and Oracle. It is not a multi-REPLACE shortcut.","body":{"slug":"translate","name":"TRANSLATE","h1":"SQL TRANSLATE function","category":"string","lede":"Maps each character of a from-set to the character at the same position in a to-set. One call replaces a chain of single-character REPLACEs.","syntax":"TRANSLATE(string, from_chars, to_chars)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"from SQL Server 2017"},{"engine_slug":"postgresql","status":"yes","note":"translate(), in every supported version"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Positional, not sequential: TRANSLATE('2[3]4', '[]', '()') gives 2(3)4. It cannot map one character to two, and it is not a substring replace; that is REPLACE.","Length mismatch splits the engines: PostgreSQL and Oracle delete from-chars that have no partner in to_chars, while SQL Server refuses with error 9828 unless both lists are the same length. Oracle needs at least one mapped character, because an empty to-list is NULL there: TRANSLATE(s, '-', '') returns NULL, TRANSLATE(s, 'x-', 'x') deletes the dashes.","Unavailable on MySQL and SQLite: nested REPLACE (which runs in order and can re-map already-replaced text) is the workaround; TRANSLATE avoids that cascade.","For full substring swaps, or patterns, use REPLACE or REGEXP_REPLACE; TRANSLATE is strictly character-for-character.","Case: PostgreSQL and Oracle match exactly, but SQL Server follows the collation, so under a case-insensitive one TRANSLATE('ABC', 'abc', 'xyz') returns 'xyz'."],"examples":[{"engine_slug":"sql-server","sql":"SELECT TRANSLATE('2[3]4', '[]', '()') AS t;  -- 2(3)4"},{"engine_slug":"postgresql","sql":"SELECT TRANSLATE('12345', '143', 'ax') AS t;  -- a2x5"},{"engine_slug":"oracle","sql":"SELECT TRANSLATE('23423', '12345', 'abcd') AS t FROM dual;  -- bcdbc: 2->b, 3->c, 4->d"}],"faqs":[{"question":"What is the difference between TRANSLATE and REPLACE?","answer":"REPLACE swaps whole substrings left to right; TRANSLATE maps single characters positionally and can never turn one character into two. On PostgreSQL and Oracle, TRANSLATE('ab', 'a', 'xy') gives 'xb', not 'xyb'; SQL Server rejects the unequal lists with error 9828."},{"question":"Why is TRANSLATE not available in MySQL?","answer":"It never shipped there, nor in SQLite. Chain REPLACE calls for a known set, but remember sequential REPLACE can re-process earlier replacements; TRANSLATE has no cascade."},{"question":"Can TRANSLATE delete characters?","answer":"On PostgreSQL and Oracle, yes. Leave them unmatched: TRANSLATE(s, 'abc', 'ab') deletes every 'c'. SQL Server rejects unequal lists, so delete with REPLACE(s, 'c', '') there."}],"related":["replace","regexp-replace","strip-non-ascii"],"novel_uses":[{"body":"Japanese and Korean imports carry full-width digits that defeat numeric casts and pattern matches; one TRANSLATE maps all ten at once on SQL Server 2017+, PostgreSQL and Oracle.","sql":"SELECT TRANSLATE(sku, '０１２３４５６７８９', '0123456789') AS sku FROM imports;"},{"body":"Mapping the characters people confuse, O to 0, I and L to 1, S to 5, B to 8, makes transcribed ids collide on purpose so near-duplicates surface in a GROUP BY.","sql":"SELECT TRANSLATE(UPPER(code), 'OILSB', '01158') AS folded FROM skus;\n-- 'BO1S' and '8015' now match"}]},"source_url":"https://sqlly.app/sql-functions/translate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/trim","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRIM function","description":"Trim spaces or characters with TRIM, LTRIM and RTRIM in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: leading, trailing, both, and which characters.","body":{"slug":"trim","name":"TRIM / LTRIM / RTRIM","h1":"SQL TRIM function","category":"string","lede":"Removes leading or trailing characters, spaces by default. The usual cleaner for pasted CSV values and form input; engines differ on which characters you can strip and from which side.","syntax":"TRIM(string)  |  TRIM([LEADING | TRAILING | BOTH] 'chars' FROM string)  |  LTRIM(string, chars)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"TRIM from SQL Server 2017; LEADING/TRAILING and LTRIM/RTRIM character arguments from 2022"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"LTRIM and RTRIM strip spaces only; use TRIM(LEADING 'x' FROM s) for other characters"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Plain TRIM removes spaces only, not tabs or newlines, on every engine. Strip those with REGEXP_REPLACE, or by naming them: TRIM(BOTH E'\\t\\n ' FROM s) on PostgreSQL.","SQL Server 2017 added TRIM('chars' FROM s) for both ends; LEADING and TRAILING, and the second argument to LTRIM and RTRIM, arrived in SQL Server 2022.","Oracle treats '' as NULL, so RTRIM('   ') returns NULL, not an empty string.","LTRIM(s, chars) and RTRIM(s, chars) work on PostgreSQL, SQLite, Oracle and SQL Server 2022+. MySQL's LTRIM and RTRIM take one argument and strip spaces only."],"examples":[{"engine_slug":"all","sql":"SELECT TRIM('  padded  ') AS tight;  -- 'padded'"},{"engine_slug":"postgresql","sql":"SELECT TRIM(BOTH ',' FROM ',a,b,,') AS stripped;  -- 'a,b'"},{"engine_slug":"oracle","sql":"SELECT LTRIM('000123', '0') AS n FROM dual;  -- '123'"}],"faqs":[{"question":"Does TRIM remove tabs and newlines?","answer":"No. Plain TRIM removes only spaces. On PostgreSQL, REGEXP_REPLACE(s, '^\\s+|\\s+$', '', 'g') strips all leading and trailing whitespace. On SQL Server, TRIM(CHAR(9) + CHAR(10) + CHAR(13) + ' ' FROM s) names the characters to strip."},{"question":"What is the difference between TRIM, LTRIM and RTRIM?","answer":"TRIM strips both ends, LTRIM the left, RTRIM the right. TRIM also takes LEADING or TRAILING to do one side, and on most engines a set of characters to strip instead of spaces."}],"related":["length","replace","regexp-replace"],"novel_uses":[{"body":"TRIM(BOTH '$' FROM price_text) removes decoration from both ends so CAST sees bare digits. MySQL, PostgreSQL and Oracle spell it this way; SQLite 3.44+ and SQL Server 2022+ have the shorter TRIM(x, '$') form, and older engines need nested REPLACE.","sql":"SELECT CAST(TRIM(BOTH '$' FROM price_text) AS numeric) AS price\nFROM imports;"},{"body":"Grouping on TRIM(code) and counting the untrimmed values inside each group finds records whose only difference is whitespace: COUNT(DISTINCT code) > 1 in a trimmed group means both ACME and ACME-padded exist. One UPDATE setting code = TRIM(code) ends the split-brain keys.","sql":"SELECT TRIM(code) AS code_norm, COUNT(*) AS n,\n       COUNT(DISTINCT code) AS variants\nFROM imports\nGROUP BY 1\nHAVING COUNT(DISTINCT code) > 1;"}]},"source_url":"https://sqlly.app/sql-functions/trim","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/trim-leading-zeros","corpus":"sql-functions","engine":null,"language":"en","title":"SQL trim leading zeros","description":"Strip leading zeros: LTRIM(s, '0') on PostgreSQL, Oracle, SQLite and SQL Server 2022+ (compatibility level 160), TRIM(LEADING) on MySQL, PATINDEX on older SQL Server.","body":{"slug":"trim-leading-zeros","name":"Trimming leading zeros","h1":"SQL trim leading zeros","category":"string","lede":"Turn 000420 into 420. The one-liner is a character-set left trim; only SQL Server before 2022 needs a longer recipe.","syntax":"LTRIM(s, '0')  |  TRIM(LEADING '0' FROM s)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"LTRIM(s, '0') from SQL Server 2022; PATINDEX + SUBSTRING before that"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"TRIM(LEADING '0' FROM s); MySQL's LTRIM takes no character set"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["It removes every leading zero, not exactly five: 00000120 becomes 120. That is usually the goal, but it is not a fixed-width substring.","An all-zeros string trims to empty, and on Oracle '' is NULL, so LTRIM('000', '0') IS NULL. Guard with NULLIF/COALESCE as needed.","Casting to a number also drops the zeros but reformats everything else (decimal separators, scientific notation); trim when the value is a code, cast when it is a quantity.","Do not reach for SQLite's trim(s, '0'): it strips both ends, so '000420' becomes '42'. ltrim(s, '0') is the leading-only form."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LTRIM('000420', '0') AS n;  -- 420"},{"engine_slug":"mysql","sql":"SELECT TRIM(LEADING '0' FROM '000420') AS n;  -- 420"},{"engine_slug":"sqlite","sql":"SELECT ltrim('000420', '0') AS n;  -- 420"},{"engine_slug":"sql-server","sql":"-- before SQL Server 2022, which has LTRIM(code, '0')\nSELECT SUBSTRING(code, PATINDEX('%[^0]%', code + '1'), LEN(code)) AS n\nFROM items;"},{"engine_slug":"oracle","sql":"SELECT LTRIM('000420', '0') AS n FROM dual;  -- 420"}],"faqs":[{"question":"Why is my trimmed all-zero value NULL on Oracle?","answer":"Oracle treats the empty result as NULL: LTRIM('000', '0') IS NULL is true there. Oracle documents this as current behaviour and advises not to rely on it. Wrap with COALESCE(..., '0') when a zero value must survive."},{"question":"Does SQL Server LTRIM support a character set?","answer":"From SQL Server 2022, yes, provided the database compatibility level is set to 160: LTRIM('000420', '0') is '420'. On 2019 and older LTRIM strips spaces only, so SUBSTRING with PATINDEX('%[^0]%', s + '1') finds the first non-zero instead."},{"question":"Should I trim zeros or cast to a number?","answer":"Codes that can regain or lose meaning (prefixes, checksums) should be trimmed as text; pure quantities can be cast, but the cast reformats, not just unpads."}],"related":["trim","zero-pad","cast"],"novel_uses":[{"body":"A lookahead keeps one zero alive: REGEXP_REPLACE(code, '^0+(?=[0-9])', '') turns 007 into 7 but leaves 000 as 0, working on PostgreSQL and MySQL 8 where the regex engine supports lookaheads.","sql":"SELECT REGEXP_REPLACE(code, '^0+(?=[0-9])', '') AS trimmed FROM items;"},{"body":"Wrapping both join keys in a leading-zero trim matches 00420 to 420 in place, which suits one-off integrations where neither schema can change.","sql":"SELECT a.id FROM a JOIN b ON LTRIM(a.code, '0') = LTRIM(b.code, '0');"}]},"source_url":"https://sqlly.app/sql-functions/trim-leading-zeros","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/trim-scale","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRIM_SCALE function","description":"PostgreSQL trim_scale(numeric) drops trailing zeros from a value's stored scale (1.2300 becomes 1.23), display cleanup without string functions.","body":{"slug":"trim-scale","name":"TRIM_SCALE","h1":"SQL TRIM_SCALE function","category":"math","lede":"Reduces a numeric's scale by removing trailing zeros: trim_scale(1.2300) is 1.23 and trim_scale(42.00) is 42.","syntax":"TRIM_SCALE(numeric)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"no","note":"No equivalent; FORMAT or string trimming for display"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 13+ (it arrived in the same release as min_scale)"},{"engine_slug":"mysql","status":"no","note":"No equivalent; DECIMAL always prints its declared scale, and adding 0 does not drop the zeros. Cast to DOUBLE or trim the string for display"},{"engine_slug":"sqlite","status":"no","note":"No equivalent; REAL already has no decimal-scale concept"},{"engine_slug":"oracle","status":"no","note":"NUMBER already drops trailing zeros; there is nothing to trim"}],"gotchas":["The result is a numeric with the same value but the smallest scale: trim_scale(1.2300) is 1.23, not 1.2300.","It changes storage scale, not the value; comparisons and sums are unaffected.","Only worth having on types that keep trailing zeros. Oracle NUMBER already prints 1.23 for 1.2300; MySQL and SQL Server DECIMAL print the declared scale, 1.2300, and have no trim function."],"examples":[{"engine_slug":"postgresql","sql":"SELECT TRIM_SCALE(1.2300::numeric) AS t;  -- 1.23"},{"engine_slug":"postgresql","sql":"SELECT TRIM_SCALE(AVG(discount)::numeric) AS clean_avg\nFROM orders;"}],"faqs":[{"question":"What does trim_scale(42.00) return?","answer":"42. All trailing fractional zeros are removed, so the stored scale drops to 0 while the value is unchanged."},{"question":"How is trim_scale different from round?","answer":"round() may change the value to hit a digit count; trim_scale never changes the value, only how many decimal digits are stored."},{"question":"Why does my DECIMAL still print 1.2300?","answer":"MySQL and SQL Server DECIMAL output honours the declared scale regardless of stored zeros. trim_scale is a PostgreSQL numeric feature for stored scale."}],"related":["scale","min-scale","numeric-precision-scale"],"novel_uses":[{"body":"1.2300 and 1.23 compare equal in SQL but cast to different text, which splits any GROUP BY, cache key or CSV dedup that runs on the text form. Grouping the numeric column itself already merges them. TRIM_SCALE(x)::text gives every equal value the same string form.","sql":"SELECT DISTINCT TRIM_SCALE(rate)::text AS rate_key FROM fx_rates;"},{"body":"Unconstrained numeric columns keep whatever scale the producer wrote, so exports carry 1.2300-style padding. Wrapping the column in TRIM_SCALE cuts the export down to the digits that matter.","sql":"SELECT TRIM_SCALE(amount) AS amount FROM unmetered_usage;"}]},"source_url":"https://sqlly.app/sql-functions/trim-scale","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/trunc-date","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRUNC date function","description":"TRUNC on dates in Oracle: floor to day, week, month, quarter or year with a format mask, the truncation half of ROUND(date).","body":{"slug":"trunc-date","name":"TRUNC (date)","h1":"SQL TRUNC date function","category":"datetime","lede":"Returns the date floored to the boundary named by an optional format mask; with no mask it strips the time of day.","syntax":"TRUNC(date)  |  TRUNC(date, fmt)","return_type":"date","support":[{"engine_slug":"sql-server","status":"partial","note":"DATETRUNC on 2022+, DATEADD idiom before"},{"engine_slug":"postgresql","status":"partial","note":"date_trunc('day', d)"},{"engine_slug":"mysql","status":"partial","note":"DATE(d) for the day form; DATE_FORMAT tricks for the rest"},{"engine_slug":"sqlite","status":"partial","note":"date(d) strips time; modifiers truncate further"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["TRUNC(d) alone zeroes the time, the every-day idiom for joining on dates or stripping times from SYSDATE.","The mask names the unit: 'IW' gives the ISO Monday, 'MM' the month's first day, 'Q' the quarter start, 'YYYY' the year start, and 'DAY' the first day of the week under the session's NLS_TERRITORY.","TRUNC always returns a DATE: on a TIMESTAMP input it drops fractional seconds and any zone. CAST the result back to TIMESTAMP if the column type matters."],"examples":[{"engine_slug":"oracle","sql":"SELECT TRUNC(SYSDATE) FROM dual;  -- today at midnight"},{"engine_slug":"oracle","sql":"SELECT TRUNC(DATE '2026-08-15', 'IW') FROM dual;  -- 2026-08-10 (Monday)"},{"engine_slug":"oracle","sql":"SELECT TRUNC(order_date, 'MM') AS month_start, COUNT(*) FROM orders GROUP BY TRUNC(order_date, 'MM');"},{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(MONTH, '2026-08-15 14:30');  -- 2026-08-01 00:00:00.0000000"},{"engine_slug":"postgresql","sql":"SELECT date_trunc('month', TIMESTAMP '2026-08-15 14:30');  -- 2026-08-01 00:00:00"},{"engine_slug":"mysql","sql":"SELECT DATE('2026-08-15 14:30');  -- 2026-08-15"},{"engine_slug":"sqlite","sql":"SELECT date('2026-08-15 14:30');  -- 2026-08-15"}],"faqs":[{"question":"What is the PostgreSQL equivalent of TRUNC(d, 'IW')?","answer":"date_trunc('week', d); both give the ISO Monday. For Sunday-start weeks, Oracle's TRUNC(d, 'DAY') follows NLS_TERRITORY; PostgreSQL has no such setting, so shift by hand: date_trunc('week', d + INTERVAL '1 day') - INTERVAL '1 day'."},{"question":"Does TRUNC round or floor?","answer":"Floor, always: anything after the boundary is discarded. ROUND(date) is the nearest-boundary cousin."}],"related":["round-date","datetrunc","date-trunc","last-day"],"novel_uses":[{"body":"Beyond month and year masks, TRUNC accepts 'HH', 'HH24' and 'MI', flooring timestamps to the hour or minute for rollup jobs on engines that only have mask-based truncation.","sql":"SELECT TRUNC(SYSDATE, 'HH') FROM dual;  -- this hour, zeroed minutes"},{"body":"TRUNC to the ISO week and add six days to land on Sunday. That value is Sunday at midnight, so BETWEEN stops early and drops that day's later rows. Use a half-open range instead: >= TRUNC(d, 'IW') AND < TRUNC(d, 'IW') + 7.","sql":"SELECT TRUNC(DATE '2026-08-15', 'IW') + 6 FROM dual;  -- 2026-08-16"}]},"source_url":"https://sqlly.app/sql-functions/trunc-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/truncate-ellipsis","corpus":"sql-functions","engine":null,"language":"en","title":"SQL truncate with ellipsis","description":"Shorten long text to a fixed width with an ellipsis in SQL: LEFT plus length checks, and the multibyte traps that make 'width' ambiguous.","body":{"slug":"truncate-ellipsis","name":"Truncating with an ellipsis","h1":"SQL truncate with ellipsis","category":"string","lede":"The display-truncation pattern: cut to N characters and append ... when the value was longer. Simple until emoji and combining marks join.","syntax":"CASE WHEN LEN(s) > 40 THEN LEFT(s, 37) + '...' ELSE s END","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Count the ellipsis inside the budget: cutting to 37 and appending '...' yields 40 characters total. Decide which number your spec means.","Multibyte width: under a non-SC collation SQL Server's LEN and LEFT count UTF-16 code units, so an emoji is 2 units and a cut can split it in half. PostgreSQL and SQLite count code points.","Cutting mid-word looks broken; cutting on the last space before the limit reads better but costs a second CHARINDEX/position call.","The single ellipsis character … (U+2026) is one character but three bytes in UTF-8, so a byte-limited varchar under a UTF-8 collation (SQL Server _UTF8) counts it as 3. Under SQL Server's default Latin1 collation it is 1 byte."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CASE WHEN LEN(title + 'x') > 41 THEN LEFT(title, 37) + '...' ELSE title END AS short\nFROM posts;"},{"engine_slug":"postgresql","sql":"SELECT CASE WHEN length(title) > 40 THEN left(title, 37) || '...' ELSE title END AS short\nFROM posts;"},{"engine_slug":"mysql","sql":"SELECT CASE WHEN CHAR_LENGTH(body) > 40 THEN CONCAT(LEFT(body, 37), '...') ELSE body END AS short\nFROM posts;  -- CHAR_LENGTH, not LENGTH: the cut counts characters"},{"engine_slug":"sqlite","sql":"SELECT CASE WHEN length(body) > 40 THEN substr(body, 1, 37) || '...' ELSE body END AS short\nFROM posts;"},{"engine_slug":"oracle","sql":"SELECT CASE WHEN LENGTH(body) > 40 THEN SUBSTR(body, 1, 37) || '...' ELSE body END AS short\nFROM posts;  -- LENGTH counts characters; LENGTHB counts bytes (verify on a live Oracle before publishing)"}],"faqs":[{"question":"Why is my truncated string 40 characters but too wide?","answer":"Characters are not display width: emoji, CJK and combining marks render wider or narrower than they count. Character-based truncation approximates visual width only."},{"question":"Can truncation split an emoji in half?","answer":"Yes on SQL Server under a non-SC collation: SUBSTRING and LEFT count code units, so a boundary can fall between surrogate halves. A supplementary-character collation (_SC, _140) makes them count whole characters."},{"question":"Should I truncate in SQL or the app?","answer":"SQL is fine for fixed-width feeds and previews; the app has better tools for word-aware truncation and locale text. Keep the rule in one place either way."}],"related":["substring","left","emoji-length","varchar-char-semantics"],"novel_uses":[{"body":"REVERSE plus INSTR finds the last space inside the budget, so the cut backs up to a whole word on MySQL; no space means the INSTR result is 0 and the full width stays.","sql":"SELECT CASE WHEN CHAR_LENGTH(title) > 40\n             THEN LEFT(title, 40 - INSTR(REVERSE(LEFT(title, 40)), ' '))\n             ELSE title END AS cut\nFROM posts;"},{"body":"For keys and hashes the tail carries the check digits, so LEFT(token, 6) + '...' + RIGHT(token, 4) preserves both anchor ends where a plain prefix cut loses them.","sql":"SELECT CASE WHEN LEN(token) > 10 THEN LEFT(token, 6) + '...' + RIGHT(token, 4) ELSE token END AS display FROM api_keys;  -- SQL Server; PostgreSQL uses ||, MySQL uses CONCAT"}]},"source_url":"https://sqlly.app/sql-functions/truncate-ellipsis","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/try-cast","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRY_CAST function","description":"TRY_CAST and TRY_CONVERT in SQL Server, and what PostgreSQL, MySQL, SQLite and Oracle do instead when a conversion fails: NULL versus error versus silent zero.","body":{"slug":"try-cast","name":"TRY_CAST / TRY_CONVERT","h1":"SQL TRY_CAST function","category":"conversion","lede":"Attempts a conversion and returns NULL instead of raising an error when the value cannot convert: the safe path for user-entered and imported data.","syntax":"TRY_CAST(expression AS type)  -- SQL Server 2012+","return_type":"the target type, or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"no TRY_CAST; pg_input_is_valid (16+) tests first"},{"engine_slug":"mysql","status":"no","note":"no TRY_CAST; CAST turns bad input into 0 with a warning"},{"engine_slug":"sqlite","status":"partial","note":"CAST never errors; invalid text becomes 0 or 0.0"},{"engine_slug":"oracle","status":"partial","note":"CAST(x AS NUMBER DEFAULT NULL ON CONVERSION ERROR) and VALIDATE_CONVERSION, both 12.2+"}],"gotchas":["TRY_CAST and TRY_CONVERT arrived in SQL Server 2012 and return NULL on failure instead of an error. Oracle 12.2 has the same effect with CAST(x AS NUMBER DEFAULT NULL ON CONVERSION ERROR).","SQLite's CAST never fails: CAST('abc' AS INTEGER) is 0. MySQL does the same in a SELECT, with a warning. A bad value turns into a plausible number instead of a NULL you can find.","Silent NULLs hide bad data: pair TRY_CAST with a WHERE check (WHERE TRY_CAST(x AS INT) IS NULL AND x IS NOT NULL) to find the rows that did not make it."],"examples":[{"engine_slug":"sql-server","sql":"SELECT TRY_CAST(text_value AS INT) AS n\nFROM imports;"},{"engine_slug":"sql-server","sql":"-- find the rows that failed to convert\nSELECT * FROM imports\nWHERE TRY_CAST(text_value AS INT) IS NULL AND text_value IS NOT NULL;"},{"engine_slug":"oracle","sql":"-- Oracle 12.2+\nSELECT CAST(text_value AS NUMBER DEFAULT NULL ON CONVERSION ERROR) AS n\nFROM imports;"},{"engine_slug":"postgresql","sql":"-- PostgreSQL 16+\nSELECT CASE WHEN pg_input_is_valid(text_value, 'integer')\n            THEN text_value::integer END AS n\nFROM imports;"},{"engine_slug":"sqlite","sql":"-- CAST never errors; invalid text becomes 0 or 0.0\nSELECT CAST(text_value AS INTEGER) AS n FROM imports;"}],"faqs":[{"question":"Does TRY_CAST exist in PostgreSQL or MySQL?","answer":"No. PostgreSQL's CAST raises an error; PostgreSQL 16+ can test first with pg_input_is_valid(text, 'integer'). MySQL's CAST returns 0 with a warning in a SELECT and errors in a strict-mode INSERT. Oracle 12.2+ has CAST ... DEFAULT NULL ON CONVERSION ERROR and VALIDATE_CONVERSION."},{"question":"What does SQLite's CAST do with invalid text?","answer":"It converts the longest numeric prefix and ignores the rest: CAST('12abc' AS INTEGER) is 12 and CAST('abc' AS INTEGER) is 0, with no error. Check with typeof() or a GLOB pattern when importing dirty data."}],"related":["cast","convert","to-number"],"novel_uses":[{"body":"A CASE on which TRY_CAST succeeds classifies each imported value: integer, decimal or text, with the NULL branch as the garbage queue. The rows then go down the typed paths they actually fit instead of one column pretending to be three types.","sql":"SELECT CASE WHEN TRY_CAST(v AS INT) IS NOT NULL THEN 'int'\n            WHEN TRY_CAST(v AS DECIMAL(10, 2)) IS NOT NULL THEN 'decimal'\n            ELSE 'text' END AS shape\nFROM imports;"},{"body":"The varchar code column and the int id column hold the same numbers; TRY_CAST bridges them in the join condition. Run the LEFT JOIN ... IS NULL check first to see the codes that will never match, leading zeros included.","sql":"SELECT a.code\nFROM legacy a\nLEFT JOIN items b ON TRY_CAST(a.code AS INT) = b.id\nWHERE b.id IS NULL;"}]},"source_url":"https://sqlly.app/sql-functions/try-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/try-convert","corpus":"sql-functions","engine":null,"language":"en","title":"SQL TRY_CONVERT function","description":"SQL Server's TRY_CONVERT takes CONVERT's style codes but returns NULL instead of raising an error on bad input. Useful for imported and user-entered data.","body":{"slug":"try-convert","name":"TRY_CONVERT","h1":"SQL TRY_CONVERT function","category":"conversion","lede":"TRY_CONVERT(type, value, style) returns NULL when the value cannot convert, so one bad row does not abort a whole INSERT ... SELECT.","syntax":"TRY_CONVERT(type, expression [, style])","return_type":"the target type, or NULL","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"no","note":"no TRY_CONVERT; test first with pg_input_is_valid (16+) or a regex in CASE"},{"engine_slug":"mysql","status":"no","note":"no TRY_CONVERT; in a SELECT a bad CAST returns 0 or NULL with a warning, and it raises an error only inside a strict-mode INSERT or UPDATE"},{"engine_slug":"sqlite","status":"no","note":"no TRY_CONVERT; CAST('x' AS INTEGER) yields 0, a different failure mode"},{"engine_slug":"oracle","status":"no","note":"CAST(x AS type DEFAULT NULL ON CONVERSION ERROR) and VALIDATE_CONVERSION, both 12.2+"}],"gotchas":["NULL on failure hides problems: thousands of NULLs after a load usually mean a format mismatch, not missing data. Compare TRY_CONVERT output against the raw column to size the damage.","The style decides day/month order: TRY_CONVERT(DATE, '13/07/2026', 101) is NULL under US style 101 and 2026-07-13 under British style 103. Worse, '05/07/2026' parses under both styles, as two different dates.","NULL is only for values that fail to parse. A conversion SQL Server never allows, such as TRY_CONVERT(xml, 4) from int, still raises an error."],"examples":[{"engine_slug":"sql-server","sql":"SELECT TRY_CONVERT(DATE, value, 103) AS d\nFROM staging.imports;"},{"engine_slug":"sql-server","sql":"SELECT TRY_CONVERT(BIGINT, phone) AS phone_num\nFROM customers;"}],"faqs":[{"question":"TRY_CONVERT vs TRY_CAST?","answer":"TRY_CAST has no style argument; TRY_CONVERT is CONVERT plus NULL-on-failure. Use TRY_CONVERT when you need a style code, TRY_CAST when you do not."},{"question":"Why is everything NULL after my import?","answer":"Usually a style mismatch or an unexpected format. List the failures with SELECT raw FROM staging WHERE raw IS NOT NULL AND TRY_CONVERT(DATE, raw, 103) IS NULL to see which pattern does not parse."}],"related":["try-cast","convert","parse","cast-truncation"],"novel_uses":[{"body":"Mixed-format feeds rarely agree on one style, so chain the candidates in priority order: COALESCE(TRY_CONVERT(DATE, raw, 103), TRY_CONVERT(DATE, raw, 101), TRY_CONVERT(DATE, raw, 112)) takes the first style that parses. Rows the earlier styles miss pay one extra failed parse each.","sql":"SELECT COALESCE(TRY_CONVERT(DATE, raw, 103), TRY_CONVERT(DATE, raw, 101)) AS d FROM staging.imports;"},{"body":"Filter on the same TRY_CONVERT you load with: one INSERT ... SELECT with WHERE TRY_CONVERT(DATE, raw, 103) IS NOT NULL fills the target, and the complement WHERE clause fills a quarantine table. Every row gets exactly one destination and no TRY/CATCH batch aborts.","sql":"INSERT INTO dbo.quarantine_dates (raw) SELECT raw FROM staging.imports WHERE TRY_CONVERT(DATE, raw, 103) IS NULL;"},{"body":"TRY_CONVERT(MONEY, '$5,999.00') accepts dollar signs and thousands commas, so it strips display formatting that a DECIMAL target would reject. Recast the result to DECIMAL to drop MONEY's fixed four decimal places.","sql":"SELECT CAST(TRY_CONVERT(MONEY, list_price_text) AS DECIMAL(10,2)) AS price FROM staging.products;"}]},"source_url":"https://sqlly.app/sql-functions/try-convert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/turkish-i","corpus":"sql-functions","engine":null,"language":"en","title":"SQL casing and the Turkish I","description":"UPPER('i') is 'I' or 'İ' depending on collation (SQL Server) or locale (PostgreSQL ICU): the Turkish I problem, how each engine picks casing rules, how to sidestep it.","body":{"slug":"turkish-i","name":"The Turkish I problem","h1":"SQL casing and the Turkish I","category":"string","lede":"One lowercase letter, two uppercase answers: casing rules are locale-dependent, and the Turkish dotted/dotless I pair is where it bites.","syntax":"UPPER('i' COLLATE Turkish_CI_AS)  -- engine-specific","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["In Turkish, uppercase('i') is 'İ' (dotted) and uppercase('ı') is 'I'. Engines only do this when the locale says so.","SQL Server: a Turkish collation drives it. UPPER('i' COLLATE Turkish_CI_AS) is 'İ'; a default Latin collation gives 'I'.","PostgreSQL: casing follows the database locale or a per-expression COLLATE; upper('i' COLLATE \"tr-TR-x-icu\") is 'İ' on an ICU install.","MySQL's UPPER/LOWER use Unicode mappings without a locale switch and return 'I'; SQLite maps ASCII only. Neither can be 'wrong' per locale, which is itself the gotcha."],"examples":[{"engine_slug":"sql-server","sql":"SELECT UPPER('i' COLLATE Turkish_CI_AS) AS tr,\n       UPPER('i' COLLATE Latin1_General_CI_AS) AS plain;\n-- İ, I"},{"engine_slug":"postgresql","sql":"SELECT upper('i' COLLATE \"tr-TR-x-icu\") AS tr;  -- İ"},{"engine_slug":"mysql","sql":"SELECT UPPER('i') AS plain;  -- I: MySQL's UPPER has no Turkish locale switch"},{"engine_slug":"sqlite","sql":"SELECT UPPER('ı') AS folded;  -- ı: upper() maps ASCII only, so the dotless ı passes through unchanged"},{"engine_slug":"oracle","sql":"SELECT NLS_UPPER('i', 'NLS_SORT = XTURKISH') AS tr FROM dual;  -- İ"}],"faqs":[{"question":"Why does my data break when the server moves regions?","answer":"Casing and sorting followed the collation the database or column was created with, not the machine's region. Values cased under one locale compare differently under another. Pin collations explicitly on columns and expressions."},{"question":"How do I avoid the problem entirely?","answer":"Compare and match through case-insensitive collations or CI indexes instead of UPPER/LOWER round-trips, and never use UPPER as a normalization step for identifiers in multilingual data."},{"question":"Does this affect ORDER BY too?","answer":"Yes. Sorting is locale-driven too: a Turkish collation treats dotless ı and dotted i as separate letters, with ı sorting first, so the same names can come back in a different order. The same COLLATE/NLS_SORT controls apply."}],"related":["upper","lower","case-insensitive-collation","string-sort"],"novel_uses":[{"body":"Searching for the dotted capital I flags text that was cased through a Turkish locale: on a case-sensitive column SQL Server uses WHERE name COLLATE Turkish_CS_AS LIKE N'%İ%' (on a Turkish _CI_ column, i and İ match each other), and PostgreSQL matches U&'\\0130'.","sql":"SELECT * FROM names WHERE name COLLATE Turkish_CS_AS LIKE N'%İ%';"},{"body":"Grouping under a Turkish case-insensitive collation folds ı and I together, so the query below lists values that would collide on a unique index after the change.","sql":"SELECT name COLLATE Turkish_CI_AS AS folded, COUNT(*) AS n\nFROM users\nGROUP BY name COLLATE Turkish_CI_AS\nHAVING COUNT(*) > 1;"}]},"source_url":"https://sqlly.app/sql-functions/turkish-i","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/typeof","corpus":"sql-functions","engine":null,"language":"en","title":"SQL typeof() and pg_typeof()","description":"See what type an expression has: typeof() in SQLite, pg_typeof() in PostgreSQL, SQL_VARIANT_PROPERTY in SQL Server and DUMP in Oracle. Useful for chasing implicit casts.","body":{"slug":"typeof","name":"TYPEOF / pg_typeof","h1":"SQL typeof() and pg_typeof()","category":"system","lede":"When a comparison or a sum behaves strangely, the first question is what type the value really has. Four of the five engines can tell you from a query.","syntax":"typeof(x)  |  pg_typeof(x)  |  SQL_VARIANT_PROPERTY(x, 'BaseType')  |  DUMP(x)","return_type":"text (regtype for pg_typeof, sql_variant for SQL_VARIANT_PROPERTY)","support":[{"engine_slug":"sql-server","status":"partial","note":"SQL_VARIANT_PROPERTY(x, 'BaseType')"},{"engine_slug":"postgresql","status":"partial","note":"pg_typeof(x)"},{"engine_slug":"mysql","status":"no","note":"no function; CREATE TABLE t AS SELECT x, then DESCRIBE t"},{"engine_slug":"sqlite","status":"yes","note":"typeof(x) returns the storage class"},{"engine_slug":"oracle","status":"partial","note":"DUMP(x) shows a type code: Typ=2 is NUMBER, Typ=1 VARCHAR2"}],"gotchas":["SQLite's typeof() reports the storage class of the value, not the column's declared type. Inserting 5 into a TEXT column stores the text '5', and inserting 'abc' into an INTEGER column stores text.","pg_typeof('a') is unknown: a quoted literal has no type until the context gives it one.","SQL_VARIANT_PROPERTY converts its argument to sql_variant, so types that sql_variant cannot hold, such as varchar(max) and xml, raise an operand type clash."],"examples":[{"engine_slug":"sqlite","sql":"SELECT typeof(1) AS a, typeof(1.5) AS b, typeof('1') AS c, typeof(NULL) AS d;  -- integer, real, text, null"},{"engine_slug":"postgresql","sql":"SELECT pg_typeof(1) AS a, pg_typeof(1.5) AS b, pg_typeof(1::bigint + 1) AS c;  -- integer, numeric, bigint"},{"engine_slug":"sql-server","sql":"SELECT SQL_VARIANT_PROPERTY(1.5, 'BaseType') AS base_type, SQL_VARIANT_PROPERTY(1.5, 'Precision') AS prec;  -- numeric, 2"},{"engine_slug":"oracle","sql":"SELECT DUMP(1.5) AS d FROM dual;  -- Typ=2 Len=3: 193,2,51"}],"faqs":[{"question":"What does typeof() return for a date in SQLite?","answer":"text, real or integer, depending on how the value was stored. SQLite has no date type; the date functions read ISO-8601 text, Julian day numbers or Unix seconds."},{"question":"How do I see a column's declared type instead?","answer":"Query information_schema.columns (SQL Server, PostgreSQL, MySQL), PRAGMA table_info('t') on SQLite, or user_tab_columns on Oracle."}],"related":["sqlite-affinity","dump","implicit-conversion","cast"],"novel_uses":[{"body":"pg_typeof settles which cast a report needs: sum() of a smallint or integer column comes back as bigint, so pg_typeof(sum(x)) prints bigint and the CSV writer should expect 64-bit output, not the column type.","sql":"SELECT pg_typeof(sum(x)) AS sum_type\nFROM (VALUES (1::smallint), (2::smallint)) AS t(x);  -- bigint"},{"body":"json_extract returns whatever the document stored, so typeof(json_extract(doc, '$.qty')) distinguishes integer from text in one call. That is the check for documents where \"5\" and 5 both appear and only one binds to an int parameter.","sql":"SELECT typeof(json_extract('{\"qty\":5}', '$.qty')) AS a,\n       typeof(json_extract('{\"qty\":\"5\"}', '$.qty')) AS b;  -- integer, text"},{"body":"DUMP(x, 1010) prints each byte code plus the character set name, which shows whether that odd glyph is a two-byte UTF-8 sequence or a mangled single byte. Encoding bugs stop being guesswork once the codes are on screen.","sql":"SELECT DUMP(UNISTR('caf\\00E9'), 1010) AS codes FROM dual;  -- Typ=1 Len=5 CharacterSet=AL32UTF8: 99,97,102,195,169"}]},"source_url":"https://sqlly.app/sql-functions/typeof","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/ucase","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UCASE function","description":"UCASE uppercases a string in MySQL, a plain synonym of UPPER, with collation-driven behaviour worth knowing before you port it elsewhere.","body":{"slug":"ucase","name":"UCASE","h1":"SQL UCASE function","category":"string","lede":"Returns the string with every character uppercased. It is UPPER under another name, and MySQL and MariaDB both accept it.","syntax":"UCASE(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["UCASE is an exact synonym of UPPER in MySQL: same collation-driven behaviour, no performance or Unicode difference.","Only MySQL and MariaDB have it: SQL Server, PostgreSQL, SQLite and Oracle all use UPPER alone, so UCASE in shared code breaks the moment it runs elsewhere.","Casing follows the argument's collation; MySQL's standard collations case per Unicode, not per locale like Turkish.","SQLite's upper() maps ASCII only: 'é' stays lowercase there, which surprises people moving from MySQL."],"examples":[{"engine_slug":"mysql","sql":"SELECT UCASE('ship') AS loud;  -- SHIP"},{"engine_slug":"mysql","sql":"SELECT UCASE(name) FROM products WHERE UCASE(code) = 'AB-1';"}],"faqs":[{"question":"Is UCASE faster than UPPER in MySQL?","answer":"No. They are the same function under two names. Pick UPPER for portability."},{"question":"Why does my UCASE query not use the index?","answer":"Wrapping the column in any function disables a plain index on it. Use a case-insensitive collation for matching, or index the expression UCASE(col)."},{"question":"Does SQLite have UCASE?","answer":"No. SQLite has upper() and lower() only, and lower() converts ASCII characters only unless the ICU extension is loaded, and upper() converts ASCII characters only."}],"related":["upper","lcase","lower"],"novel_uses":[{"body":"GROUP BY UCASE(tag) collapses 'X' and 'x' into one bucket per query while the column keeps its case-sensitive collation for every other use.","sql":"SELECT UCASE(tag) AS folded, COUNT(*) FROM tags GROUP BY UCASE(tag);"},{"body":"UCASE and LCASE run on MySQL and MariaDB only, so their presence in generated SQL or migration scripts marks code that was never tested on another engine; grep for them before a multi-engine release.","sql":null}]},"source_url":"https://sqlly.app/sql-functions/ucase","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unaccent","corpus":"sql-functions","engine":null,"language":"en","title":"SQL unaccent function","description":"PostgreSQL's unaccent extension folds accented Latin letters to their unaccented forms (Héllo becomes Hello) for accent-insensitive search and unique keys.","body":{"slug":"unaccent","name":"unaccent","h1":"SQL unaccent function","category":"string","lede":"Transliterates accented characters using a configurable rule file. An extension function, not core SQL, with an immutability catch for indexes.","syntax":"unaccent(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"requires CREATE EXTENSION unaccent"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["It is an extension: CREATE EXTENSION unaccent; first. Rule sets live in unaccent.rules under the server's tsearch_data share directory and can be customized per dictionary.","unaccent() is STABLE, not IMMUTABLE, so expression indexes over it need an IMMUTABLE wrapper function (the single most-asked follow-up).","Typical uses: accents-insensitive unique indexes, search normalization, and cleaning feeds before comparison.","SQL Server reaches for TRANSLATE maps or accent-insensitive collations; MySQL for _ai collations; Oracle for TRANSLATE or LINGUISTIC sorts."],"examples":[{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS unaccent;\nSELECT unaccent('Héllo Wörld') AS plain;  -- Hello World"}],"faqs":[{"question":"Why can I not index unaccent(col) directly?","answer":"The function is STABLE because rules may change, and index expressions demand IMMUTABLE. Create an IMMUTABLE wrapper that calls unaccent and index that."},{"question":"Does unaccent exist outside PostgreSQL?","answer":"Not as a function. SQL Server and MySQL fold accents through collations (_AI/_ai), Oracle through TRANSLATE or linguistic indexes."},{"question":"Is unaccent safe for keys?","answer":"It makes 'café' and 'cafe' collide, which is the point for dedupe, and a hazard if the original spelling is meaningful. Normalize on a derived column, keep the original."}],"related":["strip-non-ascii","translate","case-insensitive-collation"],"novel_uses":[{"body":"unaccent accepts a dictionary argument, so a second rules file with project-specific folds runs beside the default instead of editing the shared one. The file must already exist as unaccent_tech.rules in the server's tsearch_data directory, or CREATE TEXT SEARCH DICTIONARY fails with \"could not open unaccent file\".","sql":"CREATE TEXT SEARCH DICTIONARY tech_rules (TEMPLATE = unaccent, RULES = 'unaccent_tech');\nSELECT unaccent('tech_rules'::regdictionary, 'café');"},{"body":"Building the GIN index on to_tsvector('simple', immut_unaccent(body)) and querying through the same IMMUTABLE wrapper makes cafe match café in text search, not just in equality.","sql":"CREATE FUNCTION immut_unaccent(text) RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT AS $$ SELECT public.unaccent('public.unaccent'::regdictionary, $1) $$;\nCREATE INDEX articles_fts ON articles USING GIN (to_tsvector('simple', immut_unaccent(body)));"}]},"source_url":"https://sqlly.app/sql-functions/unaccent","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unhex","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNHEX function","description":"UNHEX turns hex text back into bytes on MySQL and SQLite (the inverse of HEX), with PostgreSQL's decode and Oracle's HEXTORAW as the engine twins.","body":{"slug":"unhex","name":"UNHEX","h1":"SQL UNHEX function","category":"string","lede":"Decodes a hexadecimal string into binary data. Getting text back out needs one more cast, because the result is bytes, not characters.","syntax":"UNHEX(hex_string)","return_type":"binary","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"partial","note":"decode(h, 'hex') returns bytea"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":"unhex() from SQLite 3.41; returns a blob"},{"engine_slug":"oracle","status":"partial","note":"HEXTORAW returns RAW"}],"gotchas":["The result is binary: UNHEX('6162') is 'ab' only because the bytes are valid ASCII. Comparing it to typed text needs an explicit cast on SQLite and PostgreSQL (bytea = text is an error); MySQL compares the bytes and matches without one.","Bad input is handled differently: MySQL and SQLite return NULL for non-hex characters, including spaces; PostgreSQL's decode() raises an error for non-hex characters but skips whitespace; Oracle's HEXTORAW raises ORA-01465.","PostgreSQL's bytea result needs convert_from(decode(...), 'utf8') to become text.","SQL Server has no UNHEX: CONVERT(varbinary(max), '6162', 2) parses hex text without the 0x prefix (style 1 expects it)."],"examples":[{"engine_slug":"mysql","sql":"SELECT UNHEX('6162') AS s;  -- ab"},{"engine_slug":"postgresql","sql":"SELECT convert_from(decode('6162', 'hex'), 'utf8') AS s;  -- ab"},{"engine_slug":"sqlite","sql":"SELECT CAST(unhex('6162') AS TEXT) AS s;  -- ab: unhex() returns a BLOB (SQLite 3.41+)"},{"engine_slug":"oracle","sql":"SELECT UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW('6162')) AS s FROM dual;  -- ab"}],"faqs":[{"question":"Why does UNHEX return gibberish or NULL?","answer":"UNHEX never checks text validity: it returns the bytes. A NULL means the input had a non-hex character, and MySQL returns that NULL silently. Gibberish or NULL after a text conversion means the bytes are not valid in the target charset: CONVERT(x USING utf8mb4) returns NULL with warning 1300 for invalid UTF-8."},{"question":"What is the PostgreSQL equivalent of UNHEX?","answer":"decode(hex, 'hex'), which returns bytea. Wrap it in convert_from(..., 'utf8') when the target is text."},{"question":"Does UNHEX work on odd-length input?","answer":"MySQL pads a leading zero, so UNHEX('616') is the two bytes 0x06 0x16, probably not what you meant. Fix the length in the source rather than relying on it."}],"related":["hex","from-base64","conv"],"novel_uses":[{"body":"INSERTing UNHEX('F09F918D') writes exact bytes no matter what encoding the migration file, editor or terminal uses, which pasted emoji cannot promise. The column must be utf8mb4: a utf8mb3 column rejects the 4-byte sequence with ERROR 1366 in strict mode.","sql":"INSERT INTO reactions (emoji) VALUES (UNHEX('F09F918D'));  -- exact bytes, no editor encoding involved"},{"body":"UNHEX of a 32-character hex id into BINARY(16) halves the storage of a CHAR(32) key, and HEX(id) renders it back for display.","sql":"CREATE TABLE tokens (id BINARY(16) PRIMARY KEY);\nINSERT INTO tokens VALUES (UNHEX('9f86d081884c7d659a2feaa0c55ad015'));"}]},"source_url":"https://sqlly.app/sql-functions/unhex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unicode","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNICODE function","description":"How UNICODE returns the first character's code point in SQL Server and SQLite: surrogate pairs and _SC collations, the ASCII and ORD siblings, and the NCHAR inverse.","body":{"slug":"unicode","name":"UNICODE","h1":"SQL UNICODE function","category":"string","lede":"Returns the Unicode code point of the first character of a string, except on SQL Server without an _SC or UTF-8 collation, where characters above U+FFFF return the high surrogate.","syntax":"UNICODE(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"ascii() returns the code point in a UTF8 database."},{"engine_slug":"mysql","status":"no","note":"No UNICODE; ORD(CONVERT(c USING utf32)) gives the code point."},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":"No code-point function; ASCII returns the encoded bytes as a number."}],"gotchas":["SQL Server returns the full code point for characters above U+FFFF only under a supplementary-character (_SC) or UTF-8 collation. Otherwise UNICODE(N'\uD83D\uDE00') returns 55357, the first UTF-16 surrogate, instead of 128512.","SQLite's unicode() returns the code point of the first character, and NULL for an empty string.","NCHAR(n) (SQL Server) and char(n) (SQLite) are the inverses: unicode(char(233)) is 233."],"examples":[{"engine_slug":"sql-server","sql":"SELECT UNICODE(N'A') AS code;  -- 65"},{"engine_slug":"sqlite","sql":"SELECT unicode(word) AS first_code\nFROM words;"},{"engine_slug":"postgresql","sql":"SELECT ascii('é') AS code;  -- 233"}],"faqs":[{"question":"What is the difference between UNICODE and ASCII?","answer":"ASCII is meant for 0 to 127, and beyond that it varies: SQL Server returns the code-page byte (233 for é under Latin1 collations), MySQL the first UTF-8 byte (195), Oracle the whole encoded value (50089). UNICODE returns the code point."},{"question":"Why does UNICODE return 55357 for my emoji?","answer":"The column or literal uses a collation without supplementary-character support, so SQL Server sees two UTF-16 surrogates and reports the first. Apply a _SC collation: UNICODE(col COLLATE Latin1_General_100_CI_AS_SC)."},{"question":"How do I convert a code point back to a character?","answer":"NCHAR(233) in SQL Server, char(233) in SQLite, chr(233) in PostgreSQL, NCHR(233) in Oracle, and CHAR(233 USING utf32) in MySQL."}],"related":["ascii","chr","substr","char-length"],"novel_uses":[{"body":"The first code point's range identifies the script: 1024 to 1279 is Cyrillic and 19968 to 40959 is the main CJK block, which routes rows to the right tokenizer or sort order.","sql":"SELECT CASE WHEN UNICODE(name) BETWEEN 1024 AND 1279 THEN 'cyrillic'\n            WHEN UNICODE(name) BETWEEN 19968 AND 40959 THEN 'cjk'\n            ELSE 'latin' END AS script\nFROM contacts;"},{"body":"Copied-in text often hides a BOM (65279) or zero-width space (8203) at the start, which breaks exact matches. UNICODE reports the leading code point without you knowing which invisible character to search for; LIKE needs the exact one.","sql":"SELECT id FROM notes\nWHERE UNICODE(body) IN (65279, 8203);"}]},"source_url":"https://sqlly.app/sql-functions/unicode","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unicode-function","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNICODE function","description":"UNICODE returns the code of a string's first character: a UTF-16 unit or code point on SQL Server depending on collation, a code point on SQLite.","body":{"slug":"unicode-function","name":"UNICODE / unicode()","h1":"SQL UNICODE function","category":"string","lede":"The Unicode-aware sibling of ASCII. Same first-character-only rule, but for emoji the answer depends on whether the engine counts code points or UTF-16 units.","syntax":"UNICODE(string)  |  unicode(string)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":"UTF-16 code units unless the collation is _SC"},{"engine_slug":"postgresql","status":"partial","note":"ascii() returns the code point in a UTF8 database"},{"engine_slug":"mysql","status":"no","note":"no UNICODE(); ORD() returns encoded bytes"},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["SQL Server's UNICODE(N'\uD83D\uDE00') is 55357 (the high surrogate half) under a default collation. Under a supplementary-character (_SC) collation it returns 128512, the code point SQLite's unicode() gives.","The reverse call follows the same rule: NCHAR(128512) returns the emoji under an _SC collation and NULL otherwise.","First character only: UNICODE('abc') is 97 on SQL Server and SQLite, the two engines with a UNICODE() function.","PostgreSQL has no UNICODE(), but in a UTF8 database ascii('\uD83D\uDE00') already returns 128512. MySQL has no UNICODE(); ORD() returns the UTF-8 bytes as one number, and ORD(CONVERT(c USING utf32)) gives the code point."],"examples":[{"engine_slug":"sql-server","sql":"SELECT UNICODE(N'a') AS cp;  -- 97"},{"engine_slug":"sql-server","sql":"SELECT UNICODE(N'\uD83D\uDE00') AS unit;  -- 55357 (surrogate half)"},{"engine_slug":"sqlite","sql":"SELECT unicode('\uD83D\uDE00') AS cp;  -- 128512"},{"engine_slug":"postgresql","sql":"SELECT ascii('a') AS cp, ascii('\uD83D\uDE00') AS emoji;  -- 97, 128512"}],"faqs":[{"question":"Why is UNICODE of an emoji 55357?","answer":"Under a non-SC collation SQL Server returns UTF-16 code units, and an emoji is a surrogate pair starting at 55357 (0xD83D). An _SC collation, SQLite's unicode() and PostgreSQL's ascii() report the code point 128512."},{"question":"What is the difference between UNICODE and ASCII?","answer":"Scope: ASCII reads the first byte/code of a string and tops out in the single-byte range; UNICODE reads the first Unicode character. On nvarchar data, UNICODE is the correct call."},{"question":"How do I convert a code point back to a character?","answer":"NCHAR(n) on SQL Server (above 65535 only under an _SC collation), char(n) on SQLite, chr(n) on PostgreSQL and Oracle. MySQL's CHAR(n) takes bytes, not code points."}],"related":["ascii","chr","emoji-length"],"novel_uses":[{"body":"UNICODE above 127 on the first character flags rows that start with an accented letter, symbol or emoji; the function reads position one only, which keeps the scan cheap and the claim precise.","sql":"SELECT id FROM notes WHERE UNICODE(note) > 127;  -- first character only"},{"body":"A first code point in the surrogate range 55296 to 57343 means the string starts on a lone half of a supplementary character, usually left behind by a substring that cut mid-emoji.","sql":"SELECT id FROM t WHERE UNICODE(col COLLATE Latin1_General_100_CI_AS_SC) BETWEEN 55296 AND 57343;  -- lone surrogate halves only"}]},"source_url":"https://sqlly.app/sql-functions/unicode-function","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unicode-literals","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Unicode string literals","description":"The N'...' prefix, MySQL introducers and PostgreSQL's database encoding: how each engine marks a literal as Unicode, and what happens without it.","body":{"slug":"unicode-literals","name":"Unicode literals (N'...')","h1":"SQL Unicode string literals","category":"string","lede":"Mark a literal as Unicode text or risk the classic result: characters outside the database code page silently become ? in plain varchar literals.","syntax":"N'café'  |  _utf8mb4'café'  |  'café'","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["SQL Server: N'café' is nvarchar; the plain 'café' literal is varchar and non-representable characters become ? under a non-Unicode collation.","MySQL: literals take the connection charset; introducers like _utf8mb4'...' pin it per literal. The connection charset is usually the real lever.","PostgreSQL: literals use the database encoding, UTF-8 on nearly every install, so no prefix is needed. U&'d\\0061ta' writes characters by code point.","Oracle: N'...' is for NCHAR types; in an AL32UTF8 database a plain literal already carries Unicode; the prefix matters for national-charset columns."],"examples":[{"engine_slug":"sql-server","sql":"SELECT N'中文' AS good, '中文' AS risky;"},{"engine_slug":"mysql","sql":"SELECT _utf8mb4'é' AS ch;"},{"engine_slug":"postgresql","sql":"SELECT 'café' AS plain;  -- no prefix in a UTF8 database"},{"engine_slug":"sqlite","sql":"SELECT 'é' AS plain, x'4142' AS blob_literal;  -- no prefix: text is UTF-8; x'..' makes a BLOB"},{"engine_slug":"oracle","sql":"SELECT N'café' AS nchar_literal, UNISTR('\\00E9') AS by_code_point FROM dual;"}],"faqs":[{"question":"Why did my accented text become question marks?","answer":"The literal or the column was non-Unicode: a plain varchar literal keeps only what its database code page can represent, so CJK text stores as ??. Under a Latin collation é survives, but under a Cyrillic one it becomes e. Use N'' literals and nvarchar columns on SQL Server."},{"question":"Do I need N'' in PostgreSQL or MySQL?","answer":"PostgreSQL: no. Text uses the database encoding. MySQL: usually no. The connection charset decides; introducers are for pinning a specific charset per literal."},{"question":"What is U&'...' in PostgreSQL?","answer":"Unicode escape syntax: U&'d\\0061ta' inserts characters by hex code, with \\ as the default escape, useful when source files must stay ASCII. It is rejected while standard_conforming_strings is off."}],"related":["unistr","utf8mb4","backslash-escapes","varchar-char-semantics"],"novel_uses":[{"body":"Selecting a literal e-acute shows the whole pipe at once: the character means driver and server agree, a question mark or a two-character result means an encoding layer is wrong.","sql":"SELECT 'é' AS shown, CHAR_LENGTH('é') AS chars;  -- MySQL or PostgreSQL; 1 means the connection is clean"},{"body":"PostgreSQL's UESCAPE clause swaps the backslash for any character, which keeps U&'...' literals readable in files where backslashes already mean something else.","sql":"SELECT U&'d!0061ta' UESCAPE '!' AS dta;  -- data"}]},"source_url":"https://sqlly.app/sql-functions/unicode-literals","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unicode-normalize","corpus":"sql-functions","engine":null,"language":"en","title":"SQL Unicode normalization (NFC/NFD)","description":"Two ways to write café (one code point or e plus combining accent) and why they can fail equality until normalized: PostgreSQL's normalize(), Oracle's COMPOSE.","body":{"slug":"unicode-normalize","name":"Unicode normalization","h1":"SQL Unicode normalization (NFC/NFD)","category":"string","lede":"The same visible text can have different underlying code points. Lengths and hashes differ until you normalize both sides, and equality differs under PostgreSQL and binary collations; SQL Server's non-binary collations and MySQL's utf8mb4_0900_ai_ci can report them equal.","syntax":"normalize(s, NFC)  |  s IS NFC NORMALIZED","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"yes","note":"normalize() and the IS NFC/NFD/NFKC/NFKD predicates from PG 13"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"partial","note":"COMPOSE gives NFC and DECOMPOSE gives NFD; no NFKC/NFKD"}],"gotchas":["NFC composes é as one code point; NFD decomposes it into e plus a combining accent (U+0301). The two forms look identical, compare unequal, and have lengths 5 versus 4 in 'café'.","PostgreSQL: normalize(s) defaults to NFC; predicates like s IS NFC NORMALIZED test without converting. PG 13+.","Oracle has COMPOSE(s) for NFC and DECOMPOSE(s) for NFD. MySQL, SQL Server and SQLite have no normalize function. Whether NFD equals NFC then depends on the collation: SQLite and binary collations (_bin, BIN2) keep them apart, while SQL Server's non-binary collations and MySQL's utf8mb4_0900_ai_ci treat them as equal, so the mismatch shows in lengths, hashes and binary comparisons. NFD text is common in macOS file names.","Practical fix on those three: normalize in the application on write, or REPLACE the decomposed pairs you know about, incomplete but usually enough."],"examples":[{"engine_slug":"postgresql","sql":"SELECT length(U&'cafe\\0301') AS nfd_len, length('café') AS nfc_len;\n-- 5, 4"},{"engine_slug":"postgresql","sql":"SELECT normalize(U&'cafe\\0301', NFC) = 'café' AS same;  -- true"},{"engine_slug":"oracle","sql":"SELECT COMPOSE('e' || UNISTR('\\0301')) AS nfc FROM dual;  -- é: COMPOSE gives NFC, DECOMPOSE gives NFD, no NFKC/NFKD"}],"faqs":[{"question":"Why do two identical-looking strings fail equality?","answer":"Different normalization forms: one stores the composed character, the other the base letter plus combining accent. Equal-looking, different code points."},{"question":"Which form should I store?","answer":"NFC for almost everything: it is the web's default and the shorter form. Normalize once on write rather than on every comparison."},{"question":"Does MySQL normalize automatically?","answer":"No function does it, but the 0900 collations compare canonically equivalent forms as equal, so 'café' (NFC) = the NFD form under utf8mb4_0900_ai_ci. Lengths, hashes and _bin comparisons still differ, so normalize on write."}],"related":["unicode-literals","case-insensitive-collation","emoji-length","translate"],"novel_uses":[{"body":"Comparing normalize(a, NFC) = normalize(b, NFC) lets macOS-sourced NFD keys meet web-typed NFC input in one query, no stored-data rewrite needed.","sql":"SELECT w.id FROM web_users w JOIN mac_import m\n  ON normalize(w.name, NFC) = normalize(m.name, NFC);"},{"body":"PostgreSQL 13's IS NOT NFC NORMALIZED predicate counts the rows that need converting before you decide on a migration, and Oracle answers the same question with s <> COMPOSE(s).","sql":"SELECT COUNT(*) FROM t WHERE name IS NOT NFC NORMALIZED;  -- PostgreSQL 13+"}]},"source_url":"https://sqlly.app/sql-functions/unicode-normalize","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unistr","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNISTR function","description":"UNISTR turns \\XXXX hex escapes into characters on Oracle, PostgreSQL 14+, SQLite 3.50+ and SQL Server 2025: Unicode in ASCII-safe literals, alongside NCHAR and U&''.","body":{"slug":"unistr","name":"UNISTR","h1":"SQL UNISTR function","category":"string","lede":"Builds a string from Unicode escapes: UNISTR('caf\\00E9') is café. The ASCII-safe way to ship Unicode through channels that mangle non-ASCII.","syntax":"UNISTR('caf\\00E9')  |  unistr('\\+01F600')  -- 6-hex form: PostgreSQL and SQL Server","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2025 and Azure SQL; varchar input needs a UTF-8 collation, so pass N'...'"},{"engine_slug":"postgresql","status":"yes","note":"unistr() from PG 14; accepts \\XXXX, \\+XXXXXX, \\uXXXX and \\UXXXXXXXX"},{"engine_slug":"mysql","status":"no","note":null},{"engine_slug":"sqlite","status":"yes","note":"unistr() is a core SQLite function from 3.50.0"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Oracle accepts only 4 hex digits (\\00E9); characters above U+FFFF are written as a UTF-16 surrogate pair, \\D83D\\DE00. PostgreSQL and SQL Server 2025 also take \\+01F600 for the code point directly. A literal backslash needs doubling.","SQL Server gained UNISTR in SQL Server 2025 (and Azure SQL); a varchar argument needs a UTF-8 collation (the docs require one), so pass N'...'. Older versions build characters with NCHAR(233).","MySQL has no Unicode escape syntax in literals; build characters from bytes with an introducer, _utf8mb4 X'C3A9', or with CHAR(0xC3A9 USING utf8mb4).","The output is ordinary text: UNISTR is for writing literals, not for transcoding stored data; the result compares and sorts per its column's collation."],"examples":[{"engine_slug":"oracle","sql":"SELECT UNISTR('caf\\00E9') AS word FROM dual;  -- café"},{"engine_slug":"postgresql","sql":"SELECT unistr('caf\\00E9') AS word;  -- café"},{"engine_slug":"sql-server","sql":"-- SQL Server 2025\nSELECT UNISTR(N'caf\\00E9') AS word;  -- café"}],"faqs":[{"question":"What is the difference between UNISTR and NCHAR?","answer":"UNISTR takes a whole string with embedded escapes; NCHAR takes one integer code point. UNISTR('caf\\00E9') is one call; the NCHAR version is a three-part concatenation."},{"question":"How do I write a literal backslash in UNISTR?","answer":"Double it: UNISTR('a\\\\b') on Oracle, PostgreSQL and SQL Server 2025, the same doubling rule as backslash escapes elsewhere."},{"question":"Why use escapes instead of the real characters?","answer":"ASCII-only channels (legacy loaders, source control, some protocols) corrupt non-ASCII. Escapes survive them, then UNISTR restores the text inside the database."}],"related":["chr","unicode-literals","backslash-escapes","ascii"],"novel_uses":[{"body":"When a payload arrives with the escape sequence as visible text, unistr turns it back into the real character in one call on PostgreSQL 14+ (the \\u form is PostgreSQL-only; SQL Server 2025 documents \\XXXX and \\+XXXXXX).","sql":"SELECT unistr('caf\\u00e9') AS fixed;  -- repairs text that arrived with a literal backslash-u"},{"body":"UNISTR passes plain text through unchanged, so an UPDATE over rows containing backslash sequences restores them in place; only run it where the column stores escapes and not real paths.","sql":"-- Oracle\nUPDATE legacy_notes SET body = UNISTR(body) WHERE INSTR(body, '\\') > 0;\n-- PostgreSQL: UPDATE legacy_notes SET body = unistr(body) WHERE strpos(body, '\\') > 0;"}]},"source_url":"https://sqlly.app/sql-functions/unistr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unix-timestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNIX_TIMESTAMP function","description":"Timestamp to Unix epoch seconds: UNIX_TIMESTAMP on MySQL, EXTRACT(epoch) on PostgreSQL, strftime('%s') on SQLite, DATEDIFF_BIG on SQL Server and arithmetic on Oracle.","body":{"slug":"unix-timestamp","name":"UNIX_TIMESTAMP","h1":"SQL UNIX_TIMESTAMP function","category":"datetime","lede":"Returns seconds since 1970-01-01 00:00:00 UTC, the interchange format for APIs, key ranges and compact time storage.","syntax":"UNIX_TIMESTAMP(d)  -- MySQL  |  EXTRACT(epoch FROM ts)  -- PostgreSQL  |  strftime('%s', ts)  -- SQLite","return_type":"integer for whole-second input (DECIMAL on MySQL when the argument has fractional seconds; numeric on PostgreSQL)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEDIFF_BIG(second, '1970-01-01', d)"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(epoch FROM ts)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"unixepoch(ts) (3.38+) or strftime('%s', ts)"},{"engine_slug":"oracle","status":"partial","note":"(CAST(d AS DATE) - DATE '1970-01-01') * 86400"}],"gotchas":["The epoch is UTC: MySQL's UNIX_TIMESTAMP() applies the session time_zone to zone-less datetimes first, so a naive column shifts with the session.","SQL Server's DATEDIFF returns int, so DATEDIFF(second, '1970-01-01', d) overflows for dates after 2038-01-19. DATEDIFF_BIG returns bigint and has no such limit.","PostgreSQL's EXTRACT(epoch) keeps the fraction (numeric since version 14). Cast to bigint rounds rather than truncates, so 09:30:00.500 becomes 1705311001; wrap in FLOOR(...) first for truncated whole seconds, or multiply by 1000 first for the millisecond epochs JavaScript uses."],"examples":[{"engine_slug":"mysql","sql":"SELECT UNIX_TIMESTAMP(created_at) AS epoch FROM orders;"},{"engine_slug":"postgresql","sql":"SELECT FLOOR(EXTRACT(epoch FROM created_at))::bigint AS epoch FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT unixepoch(created_at) AS epoch FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT DATEDIFF_BIG(SECOND, '1970-01-01', created_at) AS epoch FROM orders;"},{"engine_slug":"oracle","sql":"SELECT (CAST(created_at AS DATE) - DATE '1970-01-01') * 86400 AS epoch FROM orders;"}],"faqs":[{"question":"Why is my epoch off by hours?","answer":"The input was interpreted in the wrong zone. MySQL applies the session time_zone to zone-less datetimes; store UTC or pass a timestamp with zone."},{"question":"How do I get milliseconds?","answer":"Multiply by 1000. On MySQL, UNIX_TIMESTAMP returns whole seconds for a date argument; pass a datetime with fraction (NOW(3)) to keep sub-second digits."}],"related":["from-unixtime","extract-epoch","strftime"],"novel_uses":[{"body":"Wrapping the epoch column in UNIX_TIMESTAMP kills its index. Push the constant through the function instead and the stored seconds compare raw.","sql":"SELECT * FROM orders WHERE epoch_created >= UNIX_TIMESTAMP('2024-01-01 00:00:00');"},{"body":"Epoch days start at UTC midnight, so UNIX_TIMESTAMP(created_at) DIV 86400 is a day key that sorts as an integer and needs no date cast.","sql":"SELECT UNIX_TIMESTAMP(created_at) DIV 86400 AS utc_day_no FROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/unix-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/unnest","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UNNEST function","description":"UNNEST spreads an array into one row per element on PostgreSQL, pairs with WITH ORDINALITY for positions, and Oracle's TABLE() does the same for collections.","body":{"slug":"unnest","name":"UNNEST","h1":"SQL UNNEST function","category":"conversion","lede":"SELECT unnest(tags) turns one array value into one row per element, so array columns can be joined, filtered and grouped like ordinary rows.","syntax":"UNNEST(array)  |  unnest(array) WITH ORDINALITY","return_type":"setof element type","support":[{"engine_slug":"sql-server","status":"no","note":"no array type; OPENJSON for JSON arrays"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no array type; JSON_TABLE for JSON arrays"},{"engine_slug":"sqlite","status":"partial","note":"json_each for JSON arrays"},{"engine_slug":"oracle","status":"partial","note":"TABLE(collection) unwraps nested tables"}],"gotchas":["unnest(a, b) in FROM zips arrays by position and pads the shorter one with NULL: unnest(ARRAY[1,2,3], ARRAY['x','y']) gives (1,x), (2,y), (3,NULL). Two unnest calls in the SELECT list behave the same way on PostgreSQL 10+.","unnest returns elements in array order, but a later join or GROUP BY can reorder rows. WITH ORDINALITY adds the position so you can ORDER BY it.","SQLite's json_each and MySQL's JSON_TABLE fill this role for JSON arrays; SQL Server uses OPENJSON. The concept ports, the syntax does not."],"examples":[{"engine_slug":"postgresql","sql":"SELECT unnest(tags) AS tag FROM articles;"},{"engine_slug":"postgresql","sql":"SELECT t.tag, t.pos\nFROM articles a,\nunnest(a.tags) WITH ORDINALITY AS t(tag, pos);"},{"engine_slug":"postgresql","sql":"SELECT count(*) FROM unnest(ARRAY['a', 'b', 'c']);"},{"engine_slug":"sqlite","sql":"SELECT je.value AS tag\nFROM articles a, json_each(a.tags) je;"},{"engine_slug":"oracle","sql":"SELECT column_value AS tag\nFROM TABLE(SYS.ODCIVARCHAR2LIST('sql', 'db'));"}],"faqs":[{"question":"How do I keep the element index?","answer":"WITH ORDINALITY: unnest(a.tags) WITH ORDINALITY AS t(tag, pos) adds a bigint position column, 1-based, matching the array order."},{"question":"Why did rows with empty arrays vanish?","answer":"Each outer row is repeated once per element, so an empty or NULL array contributes no rows and the outer row drops out. Keep it with LEFT JOIN LATERAL unnest(a.tags) AS t(tag) ON true."}],"related":["generate-series","array-length","json-each","array-to-string"],"novel_uses":[{"body":"Send one array bind parameter and join it: FROM unnest(?::bigint[]) AS ids(id) JOIN orders o ON o.id = ids.id. The driver sends a single value, the planner joins it like any small row source (an index nested loop on a keyed column, a hash join otherwise), and empty arrays simply match nothing.","sql":"SELECT o.* FROM orders o JOIN unnest(?::bigint[]) AS ids(id) ON o.id = ids.id;"},{"body":"INSERT ... SELECT over unnest turns every array column into normalized rows in one statement, the standard escape hatch when an array column outgrows its welcome.","sql":"INSERT INTO article_tags (article_id, tag) SELECT a.id, t.tag FROM articles a, unnest(a.tags) AS t(tag);"}]},"source_url":"https://sqlly.app/sql-functions/unnest","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/upper","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UPPER function","description":"Uppercase text with UPPER in SQL Server, PostgreSQL, MySQL, SQLite and Oracle: collation effects, locale surprises and when UPPER stops using your index.","body":{"slug":"upper","name":"UPPER","h1":"SQL UPPER function","category":"string","lede":"Returns the string with every character uppercased. Non-ASCII letters follow the collation's case rules, and uppercasing a column in a WHERE clause stops a plain index on it from being used.","syntax":"UPPER(string)","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["UPPER maps one character to one character on all five engines by default, so UPPER('straße') stays 'STRAßE'. PostgreSQL 18's pg_unicode_fast collation applies full Unicode case mapping and returns 'STRASSE'.","SQLite's built-in UPPER only changes ASCII letters: UPPER('é') stays 'é' unless the ICU extension is loaded.","WHERE UPPER(email) = ... cannot use a plain index on email. Use a case-insensitive collation or an expression index. PostgreSQL's ILIKE does not help here: it cannot use a plain b-tree index either."],"examples":[{"engine_slug":"all","sql":"SELECT UPPER('mixed Case') AS shouted;  -- MIXED CASE"},{"engine_slug":"postgresql","sql":"CREATE INDEX users_email_upper_idx ON users (UPPER(email));"}],"faqs":[{"question":"Why does UPPER make my query slow?","answer":"Wrapping a column in a function stops the plain index on that column from being used. Add an expression index on UPPER(column), or compare case-insensitively via collation instead."},{"question":"Do I need UPPER for case-insensitive matching?","answer":"On SQL Server and MySQL, usually not: their default collations are case-insensitive, so 'a' = 'A' is already true. PostgreSQL, Oracle and SQLite compare case-sensitively with =, so LOWER/UPPER on both sides, ILIKE (PostgreSQL) or a case-insensitive collation is needed. SQLite's LIKE is case-insensitive for ASCII only."}],"related":["lower","length","trim"],"novel_uses":[{"body":"GROUP BY UPPER(email) collapses the casing variants into one bucket, and MIN(email) in the same query picks a canonical spelling. SQLite's built-in UPPER only folds ASCII, which is fine for addresses that should be ASCII anyway.","sql":"SELECT MIN(email) AS canonical, COUNT(*) AS variants\nFROM users\nGROUP BY UPPER(email)\nHAVING COUNT(*) > 1;"},{"body":"With a case-sensitive collation every uppercase letter sorts before every lowercase one, so Zebra precedes apple. ORDER BY UPPER(name) gives dictionary order; on SQL Server and MySQL the default collations already compare case-insensitively, so it changes nothing there.","sql":"SELECT name FROM products ORDER BY UPPER(name);"}]},"source_url":"https://sqlly.app/sql-functions/upper","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/utc-timestamp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UTC_TIMESTAMP function","description":"Get the current UTC time: UTC_TIMESTAMP on MySQL, GETUTCDATE on SQL Server, and why SQLite's clock is UTC already while PostgreSQL uses AT TIME ZONE.","body":{"slug":"utc-timestamp","name":"UTC_TIMESTAMP / GETUTCDATE","h1":"SQL UTC_TIMESTAMP function","category":"datetime","lede":"Returns the current instant in UTC regardless of the server's local zone, the safest value to store for event timestamps.","syntax":"UTC_TIMESTAMP  -- MySQL  |  GETUTCDATE()  -- SQL Server  |  SYSUTCDATETIME()  |  now() AT TIME ZONE 'UTC'","return_type":"datetime (MySQL, SQL Server) / timestamp (PostgreSQL)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"NOW() AT TIME ZONE 'UTC'"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"no function needed: datetime('now') is already UTC"},{"engine_slug":"oracle","status":"partial","note":"SYS_EXTRACT_UTC(SYSTIMESTAMP)"}],"gotchas":["SQLite needs no function: CURRENT_TIMESTAMP and datetime('now') are already UTC; append 'localtime' to get the wall clock instead.","MySQL's UTC_TIMESTAMP and NOW() differ by the session time_zone setting; mixed sessions can write mixed clocks into one table. A TIMESTAMP column reads the inserted value through the session time_zone, so UTC_TIMESTAMP() stores correctly there only from a session at +00:00; a DATETIME column keeps the value as written.","PostgreSQL's NOW() is timestamptz and already an absolute instant; NOW() AT TIME ZONE 'UTC' turns it into a zone-less timestamp holding the UTC wall time."],"examples":[{"engine_slug":"mysql","sql":"SELECT UTC_TIMESTAMP() AS utc_now;"},{"engine_slug":"sql-server","sql":"SELECT SYSUTCDATETIME() AS utc_now;"},{"engine_slug":"postgresql","sql":"SELECT now() AT TIME ZONE 'UTC' AS utc_now;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%Y-%m-%d %H:%M:%S','now') AS utc_now;"},{"engine_slug":"oracle","sql":"SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP) AS utc_now FROM dual;"}],"faqs":[{"question":"Why store UTC instead of local time?","answer":"Local zones shift with DST and politics. Store UTC, convert at the edges, and sorting plus comparisons stay correct forever."},{"question":"Does SQLite really need no function for UTC?","answer":"Right. Its clock is UTC by default, which is why local lookups there use the 'localtime' modifier instead."}],"related":["now","sysdatetimeoffset","getdate"],"novel_uses":[{"body":"DATETIME columns never convert zones, so a parenthesized expression default (MySQL 8.0.13+) stamps the UTC clock no matter which zone each session runs in.","sql":"CREATE TABLE orders (created_utc DATETIME DEFAULT (UTC_TIMESTAMP()));"},{"body":"Derive midnight from GETUTCDATE() rather than GETDATE() when your day keys are UTC, or the boundary moves whenever the server's local offset changes, such as at each DST switch.","sql":"SELECT DATEADD(day, DATEDIFF(day, 0, GETUTCDATE()), 0) AS utc_midnight;"}]},"source_url":"https://sqlly.app/sql-functions/utc-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/utf8mb4","corpus":"sql-functions","engine":null,"language":"en","title":"SQL utf8mb4 charset","description":"MySQL's utf8 charset is really utf8mb3 (three bytes, no emoji) while utf8mb4 is true UTF-8: the storage, index and connection details that change.","body":{"slug":"utf8mb4","name":"utf8mb4","h1":"SQL utf8mb4 charset","category":"string","lede":"Why 'Incorrect string value' appears on emoji inserts, why indexes grow, and the four places (column, table, connection, driver) utf8mb4 must be set.","syntax":"ALTER TABLE t CONVERT TO CHARACTER SET utf8mb4;","return_type":"charset","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["MySQL's utf8 alias means utf8mb3 (max 3 bytes), so emoji and some rare CJK fail to insert. utf8mb4 (4 bytes) is the real UTF-8; use it everywhere new.","Index key lengths grow: a VARCHAR(255) utf8mb4 unique key needs 1020 bytes, which fits the 3072-byte InnoDB limit of the default DYNAMIC row format but not ROW_FORMAT=COMPACT, whose limit is 767 bytes.","The connection must agree too: SET NAMES utf8mb4 (or the driver's charset option), or 4-byte characters turn into '?' between app and server even with utf8mb4 columns. The substitution is silent: the insert succeeds even in strict mode with only warning 1300, so check HEX or SHOW WARNINGS rather than waiting for an error.","Converting: ALTER TABLE t CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci. Test index lengths and collation changes on real data first."],"examples":[{"engine_slug":"mysql","sql":"INSERT INTO reactions (emoji) VALUES ('\uD83D\uDC4D');\n-- fails on utf8mb3: Incorrect string value"},{"engine_slug":"mysql","sql":"SELECT CONVERT('\uD83D\uDC4D' USING utf8mb4) AS ok;"}],"faqs":[{"question":"Why can MySQL not store emoji?","answer":"The legacy utf8 charset is utf8mb3, capped at 3-byte characters; emoji need 4. Convert the column and connection to utf8mb4."},{"question":"Is there a downside to utf8mb4?","answer":"Slightly larger index keys and memory estimates for multi-byte data. Since 8.0 the defaults are utf8mb4; the cost is mostly in old schemas."},{"question":"What is the difference between utf8mb4_general_ci and utf8mb4_0900_ai_ci?","answer":"Both collations are case- and accent-insensitive. The real difference is padding: utf8mb4_general_ci is PAD SPACE, so 'abc' = 'abc ' is true, while utf8mb4_0900_ai_ci is NO PAD and returns false. The 0900 collation also orders by the newer Unicode rules. Prefer it on MySQL 8+."}],"related":["emoji-length","varchar-char-semantics","octet-length"],"novel_uses":[{"body":"MODIFY with a CHARACTER SET clause rewrites a single column and leaves the rest of the table's charsets and indexes alone, which CONVERT TO cannot promise.","sql":"ALTER TABLE messages MODIFY body VARCHAR(2000) CHARACTER SET utf8mb4;"},{"body":"HEX of a known emoji should print its four UTF-8 bytes; seeing 3F means a layer between client and column is substituting question marks,","sql":"SELECT HEX('\uD83D\uDC4D');  -- F09F918D means the connection is clean; 3F means a layer is substituting"}]},"source_url":"https://sqlly.app/sql-functions/utf8mb4","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/uuid-function","corpus":"sql-functions","engine":null,"language":"en","title":"SQL UUID function","description":"MySQL's UUID() returns a version 1 UUID string built from a timestamp and node id. Store it as BINARY(16) with UUID_TO_BIN to keep indexes small.","body":{"slug":"uuid-function","name":"UUID","h1":"SQL UUID function","category":"conversion","lede":"SELECT UUID() returns a 36-character version 1 UUID. It is unique, but not random: the timestamp and node part can be read back out of the value.","syntax":"UUID()","return_type":"text (UUID string)","support":[{"engine_slug":"sql-server","status":"partial","note":"NEWID() is the equivalent (v4)"},{"engine_slug":"postgresql","status":"partial","note":"gen_random_uuid() / uuidv4(); uuidv7() on 18+"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"uuid() only in the sqlite3 shell; randomblob(16) in the library"},{"engine_slug":"oracle","status":"partial","note":"UUID() from 23ai release update 23.9 returns a v4 RAW(16); SYS_GUID() before"}],"gotchas":["UUID() is version 1: a timestamp plus a node id (a MAC address or random bytes). Because the low time bits come first in the string, the text form does not sort by creation time.","Store UUIDs as BINARY(16) with UUID_TO_BIN, not CHAR(36): 36 characters per indexed row adds up, and UUID_TO_BIN(u, 1) can swap the time halves for index locality.","Statement-based replication does not reproduce UUID() values; MySQL switches to row-based logging for statements that call it under MIXED, and flags it unsafe under STATEMENT."],"examples":[{"engine_slug":"mysql","sql":"SELECT UUID() AS id;"},{"engine_slug":"mysql","sql":"SELECT BIN_TO_UUID(UUID_TO_BIN(UUID())) AS round_trip;"},{"engine_slug":"sql-server","sql":"SELECT NEWID() AS id;"},{"engine_slug":"postgresql","sql":"SELECT gen_random_uuid() AS id;"},{"engine_slug":"sqlite","sql":"SELECT lower(hex(randomblob(16))) AS id;"},{"engine_slug":"oracle","sql":"SELECT UUID() AS id FROM dual;  -- 23.9+"}],"faqs":[{"question":"UUID or auto-increment for keys?","answer":"UUIDs generate anywhere (no central counter) and merge cleanly; auto-increment is smaller, sequential and index-friendly. For hot insert tables, prefer BIGINT or time-ordered UUIDs."},{"question":"Why is my UUID index slow?","answer":"CHAR(36) keys are large, and the v1 text form puts the fastest-changing time bits first, so inserts land all over the B-tree. UUID_TO_BIN(UUID(), 1) moves the time-high bits first and stores 16 bytes."}],"related":["gen-random-uuid","newid","sys-guid","randomblob"],"novel_uses":[{"body":"MySQL 8.0.13+ accepts expression defaults, so a column can generate its own id: no application code and no trigger. With binary logging on (the 8.0+ default), ADD COLUMN with a UUID() default fails with error 1674, so add the column first and then set the default; existing rows stay NULL. Pair it with UUID_TO_BIN storage to keep the index small.","sql":"ALTER TABLE sessions ADD COLUMN request_id CHAR(36);\nALTER TABLE sessions ALTER COLUMN request_id SET DEFAULT (UUID());"},{"body":"IS_UUID returns 1 only for a well-formed UUID string, so a load pass can list the malformed references before any conversion touches them.","sql":"SELECT ref FROM staging.imports WHERE ref IS NOT NULL AND NOT IS_UUID(ref);"}]},"source_url":"https://sqlly.app/sql-functions/uuid-function","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/var-pop","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VAR_POP function","description":"VAR_POP divides by n and returns 0 for a single value: the VARP spelling on SQL Server, support in PostgreSQL, MySQL and Oracle, and how it differs from VAR_SAMP.","body":{"slug":"var-pop","name":"VAR_POP","h1":"SQL VAR_POP function","category":"aggregate","lede":"Population variance: divides by n and treats the group as the whole population.","syntax":"VAR_POP(x) | VARP(x)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"VARP is the SQL Server spelling"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"not built in; use an extension or SUM((x-avg)*(x-avg))/COUNT(x)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["One non-NULL value returns 0, unlike VAR_SAMP's NULL, because the divisor is n.","NULLs are excluded before the count.","MySQL's plain VARIANCE() is this function, not the sample one: a classic porting surprise."],"examples":[{"engine_slug":"postgresql","sql":"SELECT var_pop(price) FROM products WHERE category_id = 7;"},{"engine_slug":"sql-server","sql":"SELECT VARP(price) FROM products WHERE category_id = 7;"},{"engine_slug":"mysql","sql":"SELECT VAR_POP(score) FROM results WHERE exam = 'A';"},{"engine_slug":"oracle","sql":"SELECT VAR_POP(salary) FROM employees WHERE dept_id = 10;"}],"faqs":[{"question":"VAR_POP vs VAR_SAMP?","answer":"Divisor n versus n-1, and a single row yields 0 versus NULL."},{"question":"What is VAR_POP in SQL Server?","answer":"VARP."},{"question":"Why does MySQL's VARIANCE differ?","answer":"MySQL aliases VARIANCE to VAR_POP; PostgreSQL aliases it to VAR_SAMP. Always spell the variant you mean."}],"related":["variance","var-samp","stddev-pop","stddev"],"novel_uses":[{"body":"Compare var_pop of the group means with the average var_pop inside groups: when the means barely spread past the within-group noise, the GROUP BY dimension explains little.","sql":"SELECT var_pop(gmean) AS between_var, (SELECT avg(gvar) FROM (SELECT region, var_pop(amount) AS gvar FROM sales GROUP BY region) t) AS within_var FROM (SELECT region, avg(amount) AS gmean FROM sales GROUP BY region) s;"},{"body":"When the rows are everything under study, every order of 2026, the population form is the honest number and var_samp would overstate it by n/(n-1), 11 percent at n = 10.","sql":"SELECT var_pop(total) FROM orders WHERE yr = 2026;"}]},"source_url":"https://sqlly.app/sql-functions/var-pop","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/var-samp","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VAR_SAMP function","description":"VAR_SAMP divides by n-1 and returns NULL for a single value: support in PostgreSQL, MySQL and Oracle, SQL Server's VAR spelling, and the SQLite workaround.","body":{"slug":"var-samp","name":"VAR_SAMP","h1":"SQL VAR_SAMP function","category":"aggregate","lede":"Sample variance: divides by n-1 and needs at least two non-NULL values.","syntax":"VAR_SAMP(x) | VAR(x)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"VAR is the SQL Server spelling"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"not built in; use an extension or SUM((x-avg)*(x-avg))/(COUNT(x)-1)"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["One non-NULL value returns NULL; two or more divide by count-1.","NULLs are skipped, so the denominator counts only present values.","In SQLite the whole family is missing; an extension or a manual SUM((x-avg)*(x-avg))/(COUNT(x)-1) formula fills the gap."],"examples":[{"engine_slug":"postgresql","sql":"SELECT var_samp(price) FROM products WHERE category_id = 7;"},{"engine_slug":"sql-server","sql":"SELECT VAR(price) FROM products WHERE category_id = 7;"},{"engine_slug":"mysql","sql":"SELECT VAR_SAMP(score) FROM results WHERE exam = 'A';"},{"engine_slug":"oracle","sql":"SELECT VAR_SAMP(salary) FROM employees WHERE dept_id = 10;"}],"faqs":[{"question":"VAR_SAMP vs VAR_POP?","answer":"The divisor: n-1 versus n, and the one-row result: NULL versus 0."},{"question":"What is VAR_SAMP in SQL Server?","answer":"VAR."},{"question":"How do I get standard deviation from it?","answer":"Take the square root, or call STDDEV_SAMP directly (STDEV on SQL Server)."}],"related":["variance","var-pop","stddev-samp","stddev"],"novel_uses":[{"body":"var_samp(x) is NULL exactly when a group holds fewer than two non-NULL values, so a HAVING on that NULL lists every one-observation group. On SQL Server write VAR(order_total).","sql":"SELECT customer_id FROM orders GROUP BY customer_id HAVING var_samp(order_total) IS NULL;"},{"body":"The n-1 correction shrinks as n grows but starts big: with 5 rows the sample variance is 25 percent larger than the population one, which is why small dashboards disagree with textbooks. The query is PostgreSQL; MySQL needs VALUES ROW(2), ROW(4), ... and SQL Server spells the pair VAR and VARP.","sql":"SELECT var_samp(x) AS sample_var, var_pop(x) * 5.0 / 4 AS check_value FROM (VALUES (2), (4), (4), (4), (10)) v(x);"}]},"source_url":"https://sqlly.app/sql-functions/var-samp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/varchar-char-semantics","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VARCHAR length semantics","description":"VARCHAR(n) counts characters on MySQL and PostgreSQL, bytes on SQL Server varchar, and either on Oracle VARCHAR2: the cross-engine length trap.","body":{"slug":"varchar-char-semantics","name":"VARCHAR(n): chars or bytes?","h1":"SQL VARCHAR length semantics","category":"string","lede":"The same declaration enforces different limits per engine, which is why a 50-char field migrates fine and then truncates on real names.","syntax":"VARCHAR2(50 CHAR)  -- Oracle: characters, not bytes","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["MySQL VARCHAR(n) and PostgreSQL VARCHAR(n) count characters; SQL Server VARCHAR(n) counts bytes (NVARCHAR(n) counts UTF-16 code units).","Oracle VARCHAR2(n) is bytes by default; VARCHAR2(n CHAR) opts into characters, and NLS_LENGTH_SEMANTICS sets the database default.","SQLite declares lengths but does not enforce them: any string fits any column.","Overflow behaviour differs too: MySQL strict mode and SQL Server and PostgreSQL all error on insert; permissive MySQL truncates with a warning."],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE names (name VARCHAR2(50 CHAR));  -- 50 characters, not bytes"},{"engine_slug":"sql-server","sql":"SELECT LEN('héllo') AS chars, DATALENGTH('héllo') AS bytes;\n-- 5, 5 under a Latin1 collation. A COLLATE clause on a literal relabels its bytes instead of converting them; for 5, 6 under a UTF-8 (_UTF8) collation, store the value in a column of that collation and run LEN and DATALENGTH on the column."},{"engine_slug":"postgresql","sql":"SELECT length('héllo') AS chars, octet_length('héllo') AS bytes;\n-- 5, 6"},{"engine_slug":"mysql","sql":"CREATE TABLE names (name VARCHAR(5));  -- 5 characters, not bytes: five é fit in 10 stored bytes"},{"engine_slug":"sqlite","sql":"CREATE TABLE names (name VARCHAR(5));\nINSERT INTO names VALUES ('1234567890');  -- fits anyway: SQLite declares lengths but never enforces them"}],"faqs":[{"question":"Why did my VARCHAR(50) reject a 50-character name?","answer":"SQL Server varchar counts bytes, and the count depends on the collation. Under a Latin1 collation, é costs one byte, but characters outside that code page are stored as '?'. Under a UTF-8 collation, é costs two bytes, so a 50-character name can exceed 50 bytes. Oracle VARCHAR2 defaults to bytes. Switch to nvarchar, or VARCHAR2(50 CHAR)."},{"question":"Does NVARCHAR(n) count characters?","answer":"It counts UTF-16 code units: one for most characters, two for emoji and other supplementary characters. Close enough to characters until emoji appear."},{"question":"Is VARCHAR(n) enforced in SQLite?","answer":"No. SQLite accepts any length regardless of the declared n. Constraints there are app-level or via CHECK(length(col) <= n)."}],"related":["length","octet-length","datalength","utf8mb4"],"novel_uses":[{"body":"ALTER SESSION SET NLS_LENGTH_SEMANTICS = CHAR makes every VARCHAR2(n) in a vendor DDL script mean characters, with no edits to the script itself.","sql":"ALTER SESSION SET NLS_LENGTH_SEMANTICS = CHAR;"},{"body":"NVARCHAR(n) holds n UTF-16 code units (n characters outside the supplementary planes), so varchar(50) becomes NVARCHAR(50) and not NVARCHAR(25); halving the number is the classic mistake that ships a column half the intended size.","sql":"ALTER TABLE users ALTER COLUMN name NVARCHAR(50);"}]},"source_url":"https://sqlly.app/sql-functions/varchar-char-semantics","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/variance","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VARIANCE function","description":"VARIANCE looks portable but is not: PostgreSQL treats it as VAR_SAMP, MySQL as VAR_POP, Oracle returns 0 for a single row, and SQL Server spells it VAR.","body":{"slug":"variance","name":"VARIANCE","h1":"SQL VARIANCE function","category":"aggregate","lede":"The variance aggregate whose definition silently changes between engines.","syntax":"VARIANCE(x) | VAR_SAMP(x) | VAR_POP(x)","return_type":"numeric","support":[{"engine_slug":"sql-server","status":"partial","note":"SQL Server spells it VAR (sample) and VARP (population); no VARIANCE"},{"engine_slug":"postgresql","status":"yes","note":"VARIANCE is a historical alias of var_samp"},{"engine_slug":"mysql","status":"yes","note":"MySQL's VARIANCE is population variance, an alias of VAR_POP"},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"yes","note":"Oracle's VARIANCE returns 0 instead of NULL for a single row"}],"gotchas":["The same query returns different numbers per engine: sample variance in PostgreSQL, population variance in MySQL.","Oracle's single-row behaviour is the odd one out: its otherwise-sample VARIANCE gives 0 where VAR_SAMP gives NULL. MySQL also returns 0 there, but only because its VARIANCE is the population form.","NULLs are skipped everywhere; an empty group returns NULL.","Prefer the explicit VAR_SAMP / VAR_POP spellings so the intent survives a port."],"examples":[{"engine_slug":"postgresql","sql":"SELECT variance(price) FROM products WHERE category_id = 7;"},{"engine_slug":"mysql","sql":"SELECT VARIANCE(score) FROM results WHERE exam = 'A';"},{"engine_slug":"oracle","sql":"SELECT VARIANCE(salary) FROM employees;"},{"engine_slug":"sql-server","sql":"SELECT VARP(price) FROM products WHERE category_id = 7;"}],"faqs":[{"question":"Is VARIANCE sample or population?","answer":"Depends on the engine: PostgreSQL sample, MySQL population, Oracle sample except it returns 0 for one row. Use VAR_SAMP or VAR_POP to be explicit."},{"question":"How does variance relate to standard deviation?","answer":"Standard deviation is the square root of variance; MySQL's STDDEV uses its population VARIANCE."},{"question":"What is VARIANCE in SQL Server?","answer":"VAR (sample) or VARP (population); there is no VARIANCE spelling."}],"related":["var-samp","var-pop","stddev","stddev-samp","stddev-pop"],"novel_uses":[{"body":"var_pop divided by the mean reads near 1 for even, Poisson-like traffic and well above 1 when arrivals cluster into bursts, a queuing check in one line.","sql":"SELECT var_pop(per_minute) / NULLIF(avg(per_minute), 0) AS burst_factor FROM request_counts;"},{"body":"Rows that carry weights need the weighted formula, three SUMs and no VARIANCE call at all, so it runs on every engine. Keep the * 1.0: with integer columns PostgreSQL, SQL Server and SQLite would otherwise truncate the division.","sql":"SELECT (SUM(w * x * x) - SUM(w * x) * SUM(w * x) * 1.0 / SUM(w)) / SUM(w) AS weighted_var FROM samples;"}]},"source_url":"https://sqlly.app/sql-functions/variance","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/variance-window","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VARIANCE as a window function","description":"VARIANCE, VAR_POP and VAR_SAMP with OVER: the square of STDDEV, partition-wide or rolling, with the same single-row and SQLite caveats.","body":{"slug":"variance-window","name":"VARIANCE with OVER","h1":"SQL VARIANCE as a window function","category":"window","lede":"Variance over the window frame or partition; it is STDDEV squared and shares its sampling semantics, frame behaviour and NULL handling.","syntax":"VAR_SAMP(x) OVER (PARTITION BY g) | VAR_POP(x) OVER (ORDER BY d ROWS BETWEEN n PRECEDING AND CURRENT ROW)","return_type":"double precision / float (numeric on PostgreSQL for integer and numeric input)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":"no VARIANCE built-in; same workaround as STDDEV"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Spelling splits again: VAR_SAMP/VAR_POP on Oracle, PostgreSQL and MySQL; SQL Server says VAR (sample) and VARP (population). Plain VARIANCE is sample variance on PostgreSQL and Oracle but population variance on MySQL.","VAR_SAMP of one row is NULL and VAR_POP of one row is 0. Oracle's plain VARIANCE also returns 0 for one row, unlike its VAR_SAMP.","Windowed aggregates evaluate after WHERE and GROUP BY but before ORDER BY, so you can ORDER BY the variance in the same SELECT."],"examples":[{"engine_slug":"postgresql","sql":"SELECT region, revenue,\n       VAR_POP(revenue) OVER (PARTITION BY region) AS var_all,\n       VAR_SAMP(revenue) OVER (PARTITION BY region) AS var_sample\nFROM sales;"},{"engine_slug":"sql-server","sql":"SELECT region, revenue,\n       VAR(revenue) OVER (PARTITION BY region) AS var_sample,\n       VARP(revenue) OVER (PARTITION BY region) AS var_all\nFROM sales;"},{"engine_slug":"mysql","sql":"SELECT region, revenue,\n       VAR_SAMP(revenue) OVER (PARTITION BY region) AS var_sample\nFROM sales;"},{"engine_slug":"oracle","sql":"SELECT region, revenue,\n       VAR_POP(revenue) OVER (PARTITION BY region) AS var_all,\n       VAR_SAMP(revenue) OVER (PARTITION BY region) AS var_sample\nFROM sales;"}],"faqs":[{"question":"VARIANCE or STDDEV: which belongs in a report?","answer":"Variance is in squared units (dollars squared), so it feeds further math such as ANOVA or portfolio risk. For a spread people can read, report STDDEV, which is in the same units as the data."},{"question":"Why is my variance NULL then 0 across rows?","answer":"VAR_SAMP returns NULL for a frame with one row, because a sample needs two values, so the NULL is the first rows of a rolling frame. The 0 comes from a frame whose values are all equal, which VAR_SAMP also reports as 0. VAR_POP returns 0 for a one-row frame instead of NULL, so pick it if a lone row should read as no spread. To skip the short first frames, drop those output rows in an outer query."}],"related":["stddev-window","avg-over","stddev"],"novel_uses":[{"body":"Give the frame an end of 1 PRECEDING so the variance never includes the row being judged, then flag values whose squared distance from the running mean exceeds a few multiples of that variance. The row cannot influence its own verdict, which keeps the test honest on streaming data. The SQL uses VAR_SAMP, which PostgreSQL and MySQL accept; SQL Server spells it VAR.","sql":"SELECT day, temp,\n       AVG(temp) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS avg_before,\n       VAR_SAMP(temp) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS var_before\nFROM readings;"},{"body":"A trending series inflates the variance of its levels; take the variance of the deltas instead and the trend drops out, leaving wiggliness. It is the difference between a growth chart and a risk measure. The SQL uses VAR_SAMP, which PostgreSQL and MySQL accept; SQL Server spells it VAR.","sql":"WITH d AS (\n  SELECT day, price, price - LAG(price) OVER (ORDER BY day) AS move\n  FROM prices\n)\nSELECT day, price,\n       VAR_SAMP(move) OVER (ORDER BY day ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS move_var\nFROM d;"}]},"source_url":"https://sqlly.app/sql-functions/variance-window","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/vector-distance","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VECTOR_DISTANCE function","description":"SQL Server 2025 and Oracle 23ai compute vector distances in SQL for embedding search. Metrics, argument order and dimension rules, plus pgvector for PostgreSQL.","body":{"slug":"vector-distance","name":"VECTOR_DISTANCE","h1":"SQL VECTOR_DISTANCE function","category":"math","lede":"Embedding search ranks rows by how close their vectors are to a query vector. SQL Server 2025 and Oracle 23ai do this with a built-in VECTOR_DISTANCE.","syntax":"VECTOR_DISTANCE('metric', v1, v2)  -- SQL Server  |  VECTOR_DISTANCE(v1, v2, METRIC)  -- Oracle","return_type":"float","support":[{"engine_slug":"sql-server","status":"yes","note":"VECTOR_DISTANCE('cosine' | 'euclidean' | 'dot', v1, v2) on 2025"},{"engine_slug":"postgresql","status":"no","note":"not built in; the pgvector extension adds <=> (cosine), <-> (Euclidean) and <#> (negative inner product)"},{"engine_slug":"mysql","status":"no","note":"no vector functions in 8.4"},{"engine_slug":"sqlite","status":"no","note":"not built in; extensions such as sqlite-vec"},{"engine_slug":"oracle","status":"yes","note":"VECTOR_DISTANCE(v1, v2, COSINE), plus COSINE_DISTANCE and L2_DISTANCE, 23ai+"}],"gotchas":["The argument order differs: SQL Server puts the metric first as a string, VECTOR_DISTANCE('cosine', a, b); Oracle puts it last as a keyword, VECTOR_DISTANCE(a, b, COSINE).","Cosine distance is 1 minus cosine similarity: 0 means the same direction and 1 means orthogonal. Sort ascending to get the nearest rows.","SQL Server's 'dot' metric returns the negative dot product, so smaller still means closer: [1,2] and [3,4] give -11.","Both vectors must have the same number of dimensions; SQL Server raises error 42204 otherwise."],"examples":[{"engine_slug":"sql-server","sql":"SELECT VECTOR_DISTANCE('cosine', CAST('[1,0]' AS VECTOR(2)), CAST('[0,1]' AS VECTOR(2))) AS cos_d,\n       VECTOR_DISTANCE('euclidean', CAST('[0,0]' AS VECTOR(2)), CAST('[3,4]' AS VECTOR(2))) AS l2;  -- 1.0, 5.0"},{"engine_slug":"oracle","sql":"SELECT VECTOR_DISTANCE(TO_VECTOR('[1,0]'), TO_VECTOR('[0,1]'), COSINE) AS cos_d,\n       VECTOR_DISTANCE(TO_VECTOR('[0,0]'), TO_VECTOR('[3,4]'), EUCLIDEAN) AS l2\nFROM dual;  -- 1, 5"},{"engine_slug":"sql-server","sql":"SELECT VECTOR_DISTANCE('dot', CAST('[1,2]' AS VECTOR(2)), CAST('[3,4]' AS VECTOR(2))) AS neg_dot;  -- -11.0"}],"faqs":[{"question":"Does ORDER BY VECTOR_DISTANCE use an index?","answer":"No, it computes the distance for every row. Oracle 23ai adds vector indexes used through FETCH APPROX FIRST n ROWS ONLY, and SQL Server 2025 has a separate VECTOR_SEARCH function (in preview) for approximate search over a vector index."},{"question":"Which metric should I use?","answer":"The one the embedding model was trained for, which is usually cosine. For vectors normalized to length 1, cosine and dot product give the same ranking."}],"related":["sqrt","power","corr"],"novel_uses":[{"body":"Embedding columns hold thousands of floats per row, so a ranking query that also SELECTs the vector ships megabytes to the client and slows the sort. Select the id, then fetch the payloads for the top k afterwards.","sql":"SELECT id\nFROM docs\nORDER BY VECTOR_DISTANCE('cosine', embedding, CAST('[1,0]' AS VECTOR(2)))\nOFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;"},{"body":"The sqlite-vec extension answers nearest-neighbor queries from a vec0 virtual table with a MATCH and a k in the WHERE clause. Without the virtual table, vec_distance_L2(vec, :q) in a plain query is an honest brute-force scan.","sql":"CREATE VIRTUAL TABLE docs USING vec0(embedding float[2]);\nSELECT rowid, distance\nFROM docs WHERE embedding MATCH '[1,0]' AND k = 10;"}]},"source_url":"https://sqlly.app/sql-functions/vector-distance","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/version","corpus":"sql-functions","engine":null,"language":"en","title":"SQL VERSION() and @@VERSION","description":"Query the server version from SQL: @@VERSION and SERVERPROPERTY on SQL Server, version() on PostgreSQL and MySQL, sqlite_version(), and v$version on Oracle.","body":{"slug":"version","name":"VERSION()","h1":"SQL VERSION() and @@VERSION","category":"system","lede":"Feature checks, bug reports and upgrade scripts all start with the server version. Every engine reports it from a query, in a different shape.","syntax":"@@VERSION  |  version()  |  VERSION()  |  sqlite_version()  |  SELECT banner_full FROM v$version","return_type":"text","support":[{"engine_slug":"sql-server","status":"partial","note":"@@VERSION; SERVERPROPERTY('ProductVersion') for the number alone"},{"engine_slug":"postgresql","status":"yes","note":"version(); current_setting('server_version_num')::int for a comparable integer"},{"engine_slug":"mysql","status":"yes","note":"VERSION() or @@version"},{"engine_slug":"sqlite","status":"partial","note":"sqlite_version()"},{"engine_slug":"oracle","status":"partial","note":"SELECT banner_full FROM v$version (needs access to the view)"}],"gotchas":["Compare numbers, not banners. SERVERPROPERTY('ProductMajorVersion') returns 17 on SQL Server 2025, and server_version_num returns 180006 on PostgreSQL 18.6; comparing the strings '9.6' and '18.1' sorts them the wrong way.","SQLite's version is the library linked into the program, so two applications on one machine can report different versions for the same database file.","Recent Oracle Free images print 'Oracle AI Database 26ai Free Release 23.26.3.0.0': the marketing name changed, the release number still starts with 23."],"examples":[{"engine_slug":"sql-server","sql":"SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)) AS version,\n       CAST(SERVERPROPERTY('ProductMajorVersion') AS VARCHAR(5)) AS major;  -- 17.0.4035.5, 17"},{"engine_slug":"postgresql","sql":"SELECT version(), current_setting('server_version_num') AS num;  -- num is 180006 on 18.6"},{"engine_slug":"mysql","sql":"SELECT VERSION();  -- 8.4.11"},{"engine_slug":"sqlite","sql":"SELECT sqlite_version();  -- 3.51.0"},{"engine_slug":"oracle","sql":"SELECT banner_full FROM v$version;  -- one row per component; the Oracle AI Database line holds the release"}],"faqs":[{"question":"Which major version numbers go with which SQL Server releases?","answer":"17 is SQL Server 2025, 16 is 2022, 15 is 2019, 14 is 2017 and 13 is 2016."},{"question":"How should code test for a minimum version?","answer":"Cast to an integer and compare that: current_setting('server_version_num')::int >= 170000 on PostgreSQL, CAST(SERVERPROPERTY('ProductMajorVersion') AS INT) >= 16 on SQL Server. Both values come back as text, so the uncast comparison is an error on PostgreSQL and quietly false on SQL Server. On MySQL and SQLite split the dotted string into numbers first."}],"related":["current-database","current-user","window-versions"],"novel_uses":[{"body":"Feature branches on SQL Server should read SERVERPROPERTY('EngineEdition') rather than parse @@VERSION: it returns 5 for Azure SQL Database and 8 for Azure SQL Managed Instance, numbers that stay stable across builds and clouds.","sql":"SELECT CAST(SERVERPROPERTY('EngineEdition') AS INT) AS engine_edition;  -- 5 on Azure SQL Database, 8 on Managed Instance"},{"body":"The same VERSION() call answers '8.4.11' on MySQL and '10.6.12-MariaDB' on MariaDB. Code that splits the string into numbers must drop the suffix first, and checking for that suffix is the cheapest way to tell the fork before running fork-specific SQL.","sql":"SELECT VERSION();  -- 10.6.12-MariaDB on MariaDB, 8.4.11 on MySQL"},{"body":"Two devices reporting the same sqlite_version() can run different code when a distribution backports fixes. sqlite_source_id() returns the checkin hash and timestamp behind the build, which pins a bug report to the exact source.","sql":"SELECT sqlite_version(), sqlite_source_id();"}]},"source_url":"https://sqlly.app/sql-functions/version","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/week","corpus":"sql-functions","engine":null,"language":"en","title":"SQL WEEK function","description":"Week of year per engine: SQL Server's DATEPART(week) vs ISO_WEEK, MySQL's non-ISO default WEEK mode, and PostgreSQL's ISO EXTRACT(week).","body":{"slug":"week","name":"WEEK / ISO_WEEK","h1":"SQL WEEK function","category":"datetime","lede":"Returns the week number. PostgreSQL's EXTRACT(week) follows ISO-8601; the default week functions on SQL Server, MySQL, SQLite and Oracle do not.","syntax":"EXTRACT(week FROM d)  -- PostgreSQL, ISO  |  DATEPART(iso_week, d)  -- SQL Server  |  WEEK(d, 3)  -- MySQL, ISO mode","return_type":"integer (PostgreSQL: numeric; SQLite: text)","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(week) follows DATEFIRST; ISO_WEEK is the ISO one"},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(week FROM d) is ISO"},{"engine_slug":"mysql","status":"yes","note":"WEEK(d) defaults to mode 0; WEEK(d, 3) or WEEKOFYEAR(d) for ISO"},{"engine_slug":"sqlite","status":"partial","note":"%W is Monday-based and %U is Sunday-based; the ISO %G and %V formats arrived in SQLite 3.46"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'WW') is not ISO; TO_CHAR(d, 'IW') is"}],"gotchas":["ISO weeks start Monday and week 1 holds the year's first Thursday, so December 29 can be week 1 of next year and January 1 can be week 52 or 53 of the last.","SQL Server's DATEPART(week) counts January 1 as week 1 and shifts with DATEFIRST; DATEPART(iso_week) is the ISO-8601 answer.","MySQL's WEEK(d) uses default_week_format, which is 0 (Sunday start, weeks 0-53): WEEK('2024-12-30') is 52 while WEEK('2024-12-30', 3) and WEEKOFYEAR are 1.","Oracle's 'WW' just divides the year into 7-day blocks from January 1; 'IW' is the ISO spelling."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(isoyear FROM d) AS iso_yr,\n       EXTRACT(week FROM d) AS iso_wk FROM events;"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(ISO_WEEK, d) AS iso_wk FROM events;"},{"engine_slug":"mysql","sql":"SELECT WEEKOFYEAR(d) AS iso_wk FROM events;"},{"engine_slug":"sqlite","sql":"SELECT strftime('%G-%V', d) AS iso_wk FROM events;  -- SQLite 3.46+"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'WW') AS plain_wk, TO_CHAR(created_at, 'IW') AS iso_wk FROM orders;"}],"faqs":[{"question":"Why is my week number off by one?","answer":"Two systems coexist: ISO-8601 (Monday weeks, first-Thursday rule) and the US convention (Sunday weeks, January 1 starts week 1). Pick the ISO spelling your engine provides."},{"question":"How do I group by ISO week-year?","answer":"Pair the ISO year with the ISO week: to_char(d, 'IYYY-IW') on PostgreSQL and Oracle, YEARWEEK(d, 3) on MySQL. SQL Server has no iso_year datepart; YEAR(DATEADD(day, 26 - DATEPART(iso_week, d), d)) computes it."}],"related":["extract","yearweek","day-of-week"],"novel_uses":[{"body":"EXTRACT(isodow FROM d) numbers Monday 1 through Sunday 7, so d minus (isodow - 1) days lands on the week's Monday with no mode arguments to get wrong.","sql":"SELECT CAST(d AS date) - (EXTRACT(isodow FROM d)::int - 1) AS monday FROM events;"},{"body":"DATEPART(weekday) numbers shift with SET DATEFIRST, which wrecks naive Monday math. The @@DATEFIRST term in this formula cancels the shift, so the anchor stays correct under any session setting.","sql":"SELECT DATEADD(day, -((DATEPART(weekday, d) + @@DATEFIRST + 5) % 7), CAST(d AS date)) AS monday FROM events;"}]},"source_url":"https://sqlly.app/sql-functions/week","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/week-numbers","corpus":"sql-functions","engine":null,"language":"en","title":"SQL week numbers per engine","description":"ISO weeks vs Sunday weeks vs 'week 1 = Jan 1': WEEK modes in MySQL, IW masks in Oracle and PostgreSQL, %U/%W in SQLite and SQL Server's DATEFIRST trap.","body":{"slug":"week-numbers","name":"Week numbers","h1":"SQL week numbers per engine","category":"datetime","lede":"Week numbering has four competing conventions (ISO 8601, Sunday-first, Monday-first and calendar-anchored), and each engine exports a different subset.","syntax":"to_char(d, 'IW')  |  WEEK(d, mode)  |  DATEPART(ISO_WEEK, d)","return_type":"integer; text from to_char, strftime and DATE_FORMAT","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(ISO_WEEK, d); plain WEEK follows DATEFIRST"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'IW') ISO; EXTRACT(WEEK) is also ISO"},{"engine_slug":"mysql","status":"yes","note":"WEEK(d, mode) / YEARWEEK with modes 0-7"},{"engine_slug":"sqlite","status":"partial","note":"strftime %W (Monday weeks); %U (Sunday weeks) and ISO %V since 3.46"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'IW') ISO; 'WW' is Jan-1-anchored"}],"gotchas":["ISO 8601 ('IW', WEEK mode 3, ISO_WEEK): weeks start Monday, week 1 contains the first Thursday, and year boundaries roll weeks into the adjacent ISO year; Dec 29 2025 is ISO week 1 of 2026.","MySQL's WEEK has 8 modes (0-7) mixing Sunday/Monday start and week-1 definitions; YEARWEEK(d, 3) pairs with %x-%v in DATE_FORMAT for ISO year-week keys.","SQL Server's plain WEEK depends on SET DATEFIRST and counts weeks from Jan 1. Never use it for interchange; ISO_WEEK exists for that."],"examples":[{"engine_slug":"postgresql","sql":"SELECT to_char(DATE '2026-01-01', 'IW');  -- 01 (ISO: belongs to 2026-W01)"},{"engine_slug":"mysql","sql":"SELECT WEEK('2026-01-01', 3), YEARWEEK('2026-01-01', 3);  -- 1, 202601"},{"engine_slug":"sql-server","sql":"SELECT DATEPART(ISO_WEEK, '2026-01-01');  -- 1"},{"engine_slug":"sqlite","sql":"SELECT strftime('%W', '2026-01-01'), strftime('%V', '2026-01-01');  -- 00, 01"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(DATE '2026-01-05', 'IW'), TO_CHAR(DATE '2026-01-05', 'WW') FROM dual;  -- 02, 01"}],"faqs":[{"question":"Why do two engines give different week numbers for the same date?","answer":"Different conventions: ISO weeks vs Jan-1-anchored weeks vs DATEFIRST-dependent counts. Agree on ISO 8601 and use IW / ISO_WEEK / WEEK(d,3) everywhere it exists."},{"question":"How do I group by year-week in MySQL?","answer":"DATE_FORMAT(d, '%x-%v') with ISO week numbers, or YEARWEEK(d, 3) as a sortable integer; %U and %u follow the non-ISO Sunday- and Monday-first modes, and %W is the weekday name (Thursday), not a week number."}],"related":["day-of-week","datefirst","datetrunc","date-format"],"novel_uses":[{"body":"EXTRACT(WEEK) follows ISO, so its year edges need the ISO year too: to_char's IYYY keeps 2025-12-29 in 2026-W01 instead of pairing it with the wrong year.","sql":"SELECT to_char(DATE '2025-12-29', 'IYYY-IW');  -- 2026-01"},{"body":"The 'WW' mask numbers seven-day blocks from January 1, so use it when buckets must stay fixed-width within a year and ISO roll-back rules do not apply.","sql":"SELECT TO_CHAR(DATE '2026-01-01', 'WW') FROM dual;  -- 01, anchored to Jan 1"}]},"source_url":"https://sqlly.app/sql-functions/week-numbers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/width-bucket","corpus":"sql-functions","engine":null,"language":"en","title":"SQL WIDTH_BUCKET function","description":"WIDTH_BUCKET(x, min, max, n) tells you which of n equal buckets a value falls into: histogram binning in one call, built into PostgreSQL and Oracle.","body":{"slug":"width-bucket","name":"WIDTH_BUCKET","h1":"SQL WIDTH_BUCKET function","category":"math","lede":"Returns the 1-based bucket number of a value within an equal-width histogram: WIDTH_BUCKET(15, 0, 100, 4) is 1 for the 0-25 bucket.","syntax":"WIDTH_BUCKET(value, min, max, buckets)","return_type":"integer","support":[{"engine_slug":"sql-server","status":"no","note":"No WIDTH_BUCKET; emulate with CASE WHEN x < min THEN 0 WHEN x >= max THEN n + 1 ELSE 1 + FLOOR((x - min) * 1.0 * n / NULLIF(max - min, 0)) END"},{"engine_slug":"postgresql","status":"yes","note":"Built in; also WIDTH_BUCKET(x, thresholds[]) for uneven buckets"},{"engine_slug":"mysql","status":"no","note":"No built-in; emulate with the CASE form in the guarded emulation tip below"},{"engine_slug":"sqlite","status":"no","note":"No built-in; emulate with the CASE form in the guarded emulation tip below"},{"engine_slug":"oracle","status":"yes","note":"Built in, same argument order"}],"gotchas":["Values below min go to bucket 0 and values at or above max go to buckets + 1: out-of-range values do not error, they clip to the edges, so GROUP BY will show those buckets too.","The min bound is inclusive, the max bound exclusive: WIDTH_BUCKET(100, 0, 100, 4) is 5, not 4.","Buckets are equal-width, not equal-count: for equal-count bins use NTILE; PERCENTILE_CONT gives the cut points, not the bins."],"examples":[{"engine_slug":"postgresql","sql":"SELECT WIDTH_BUCKET(15, 0, 100, 4) AS bucket;  -- 1"},{"engine_slug":"oracle","sql":"SELECT WIDTH_BUCKET(60, 0, 100, 4) AS bucket FROM dual;  -- 3"},{"engine_slug":"postgresql","sql":"SELECT WIDTH_BUCKET(age, 0, 100, 10) AS decade, COUNT(*)\nFROM users GROUP BY 1 ORDER BY 1;  -- bucket 1 is ages 0-9; bucket 11 is ages 100 and over"}],"faqs":[{"question":"What does WIDTH_BUCKET return for out-of-range values?","answer":"0 for values below min, buckets + 1 for values at or above max. Nothing errors. That makes GROUP BY bucket self-documenting, with the edge buckets showing stragglers."},{"question":"Is the max bound included in the last bucket?","answer":"No. The interval is [min, max): WIDTH_BUCKET(100, 0, 100, 4) returns 5, one past the last bucket. Only values strictly below max land in bucket 4."},{"question":"How is WIDTH_BUCKET different from NTILE?","answer":"WIDTH_BUCKET bins by value ranges; NTILE bins by row count. Equal-count buckets (quartiles of rows) are NTILE; equal-width ranges of the value are WIDTH_BUCKET."}],"related":["percentile-cont","ntile","floor","ceiling"],"novel_uses":[{"body":"PostgreSQL's array form WIDTH_BUCKET(ms, ARRAY[100, 250, 500, 1000]) bins each request into business-defined tiers in one call, no CASE ladder. Changing the SLA means editing the array, not the query.","sql":"SELECT WIDTH_BUCKET(response_ms, ARRAY[100, 250, 500, 1000]) AS tier, COUNT(*) FROM requests GROUP BY 1;"},{"body":"CASE WHEN x < lo THEN 0 WHEN x >= hi THEN n + 1 ELSE 1 + FLOOR((x - lo) * 1.0 * n / NULLIF(hi - lo, 0)) END emulates WIDTH_BUCKET on MySQL, SQL Server and SQLite. The CASE clamps out-of-range values (the bare floor formula gives -1 or 21 where WIDTH_BUCKET gives 0 or 5), the 1.0 keeps the division decimal (SQL Server truncates integer division toward zero, so x = -10 gives 1 instead of 0), and NULLIF turns a zero-width range into NULL instead of a divide-by-zero error on SQL Server. Cheap insurance in generated SQL.","sql":"SELECT CASE WHEN x < 0 THEN 0 WHEN x >= 100 THEN 5 ELSE 1 + FLOOR((x - 0) * 1.0 * 4 / NULLIF(100 - 0, 0)) END AS bucket FROM samples;"}]},"source_url":"https://sqlly.app/sql-functions/width-bucket","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-clause","corpus":"sql-functions","engine":null,"language":"en","title":"SQL named WINDOW clause","description":"The WINDOW clause names a window once and reuses it. All five engines have it now (SQL Server from 2022, Oracle from 21c); here are the override rules.","body":{"slug":"window-clause","name":"WINDOW Clause","h1":"SQL named WINDOW clause","category":"window","lede":"WINDOW w AS (...) declares a window once; functions reference it with OVER w, and definitions can extend other definitions.","syntax":"SELECT ... OVER w FROM t WINDOW w AS (PARTITION BY g), w2 AS (w ORDER BY d)","return_type":"named window definition","support":[{"engine_slug":"sql-server","status":"yes","note":"SQL Server 2022+ and Azure SQL; earlier versions need every OVER written out"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+; one window built on another since 3.28"},{"engine_slug":"oracle","status":"yes","note":"Oracle 21c+"}],"gotchas":["A reference may add only what the base window leaves out: with w AS (PARTITION BY g), both OVER (w ORDER BY x) and w2 AS (w ORDER BY x) are legal. If w already has an ORDER BY, adding another fails on every engine (PostgreSQL: 'cannot override ORDER BY clause of window \"w\"'; SQL Server reports 'Window element in OVER clause can not also be specified in WINDOW clause').","A window built on another can never re-specify PARTITION BY, and a window that has a frame clause cannot be extended with ORDER BY or a frame. PostgreSQL, MySQL and SQLite also refuse a bare copy (PostgreSQL: 'cannot copy window \"w\" because it has a frame clause'); SQL Server 2022 accepts a bare copy in a definition. Only a bare OVER w can use it.","Put the shared PARTITION BY in the named window and the ORDER BY at each use; that is the shape that keeps one definition useful for ranks, running totals and plain partition aggregates."],"examples":[{"engine_slug":"all","sql":"SELECT department, employee_id, salary,\n       RANK() OVER (w ORDER BY salary DESC) AS salary_rank,\n       SUM(salary) OVER (w ORDER BY hire_date) AS running_payroll,\n       AVG(salary) OVER w AS dept_avg\nFROM employees\nWINDOW w AS (PARTITION BY department);"}],"faqs":[{"question":"Why does my engine reject OVER (w ORDER BY ...)?","answer":"Because w already has an ORDER BY or a frame clause, and a reference cannot override either. Move the ORDER BY out of w and add it at each use, as in the example."},{"question":"Which SQL Server versions have the WINDOW clause?","answer":"SQL Server 2022 and later, plus Azure SQL Database. On 2019 and earlier there is none, and every window function repeats its full OVER (...) inline."}],"related":["over-clause","over-vs-order-by","sql-server-frame-support"],"novel_uses":[{"body":"Declare the PARTITION BY once and add the ordering and frame at each reference, OVER (w ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW): one named partition feeds ranks and moving averages without repeating itself. The base window must stay bare for the extension to be legal.","sql":"SELECT department, employee_id, salary,\n       RANK() OVER (w ORDER BY salary DESC) AS salary_rank,\n       AVG(salary) OVER (w ORDER BY hire_date\n         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7_pay\nFROM employees\nWINDOW w AS (PARTITION BY department);"},{"body":"COUNT(*) FILTER (WHERE status = 'won') OVER (w) combines the conditional aggregate with the shared partition, which keeps a wins and games pair readable. PostgreSQL 9.4+, SQLite 3.30+ and Oracle 23.26.1+ take the combination.","sql":"SELECT rep, deal_id,\n       COUNT(*) FILTER (WHERE status = 'won') OVER (w) AS wins,\n       COUNT(*) OVER (w) AS deals\nFROM deals\nWINDOW w AS (PARTITION BY rep);"}]},"source_url":"https://sqlly.app/sql-functions/window-clause","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-default-frame","corpus":"sql-functions","engine":null,"language":"en","title":"SQL default window frame","description":"With ORDER BY and no frame clause the frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, peers included; the source of most window surprises.","body":{"slug":"window-default-frame","name":"Default Window Frame","h1":"SQL default window frame","category":"window","lede":"The implicit frame covers the partition up to and including the current row's peers, which is why LAST_VALUE disappoints and running sums include ties.","syntax":"SUM(x) OVER (ORDER BY d) | -- implicitly:\nSUM(x) OVER (ORDER BY d RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)","return_type":"implicit frame","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Without ORDER BY there is no frame at all: the aggregate covers the entire partition. Adding ORDER BY is what switches on the default frame.","Peers matter: rows sharing all ORDER BY values are in the same frame end, so tied rows show identical running aggregates: sometimes the intent, often a bug.","LAG/LEAD never read the frame: PostgreSQL, MySQL and SQLite accept a frame clause on them and ignore it, while SQL Server rejects it (error 10752). FIRST_VALUE and LAST_VALUE respect the frame, and NTH_VALUE does too where it exists; SQL Server has no NTH_VALUE."],"examples":[{"engine_slug":"all","sql":"-- both rows of a tie show 30, not 10 then 30\n-- amounts: 10, 20 on the same day\nSELECT day, amount,\n       SUM(amount) OVER (ORDER BY day) AS running\nFROM t;\n-- explicit form for row-by-row accumulation:\nSELECT day, amount,\n       SUM(amount) OVER (ORDER BY day, id ROWS UNBOUNDED PRECEDING) AS running_strict\nFROM t;"}],"faqs":[{"question":"What exactly is the default frame?","answer":"When OVER has ORDER BY: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (start of partition through the current row plus its peers). Without ORDER BY: the whole partition."},{"question":"How do I make the default frame row-by-row?","answer":"Declare ROWS instead of RANGE (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and add a unique tiebreaker to the ORDER BY."}],"related":["rows-vs-range","last-value","running-total"],"novel_uses":[{"body":"With duplicates in the ORDER BY, the default RANGE frame gives every row of a same-timestamp batch the total including its batch mates: consistent checkpoint values for events that really happened together. Writing ROWS here would invent an order inside the batch that does not exist.","sql":"SELECT device_id, reading_ts, temp,\n       AVG(temp) OVER (PARTITION BY device_id ORDER BY reading_ts) AS running_avg\nFROM readings;"},{"body":"COUNT(*) OVER (ORDER BY score) counts every row up to and including the current row's peers: the empirical distribution function scaled by n, computed for free. Divide by COUNT(*) OVER () to get the probability. It answers how many rows sit at or below this value with exactly the tie handling statisticians expect.","sql":"SELECT score,\n       COUNT(*) OVER (ORDER BY score) AS at_or_below\nFROM test_results;"}]},"source_url":"https://sqlly.app/sql-functions/window-default-frame","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-empty-over","corpus":"sql-functions","engine":null,"language":"en","title":"SQL empty OVER ()","description":"OVER () with nothing inside makes the entire result set the window: grand totals and row counts stamped on every row.","body":{"slug":"window-empty-over","name":"Empty OVER ()","h1":"SQL empty OVER ()","category":"window","lede":"An empty OVER () gives every row the aggregate of all rows, the simplest window form and the basis of shares, ratios and totals-inline reports.","syntax":"COUNT(*) OVER () | SUM(x) OVER ()","return_type":"whole-set aggregate","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["The set is 'all rows of the result after WHERE, GROUP BY and HAVING'; filters shrink it. An unfiltered denominator needs a separate subquery or CTE.","Over a GROUP BY query, OVER () covers the groups, not the base rows: COUNT(*) OVER () after grouping counts groups.","An empty OVER () needs no sort, so adding SUM(x) OVER () next to an ordered window costs little: SUM(x) OVER (ORDER BY d) / SUM(x) OVER () is the cumulative share."],"examples":[{"engine_slug":"all","sql":"SELECT product, price,\n       price * 1.0 / NULLIF(MAX(price) OVER (), 0) AS price_ratio,\n       COUNT(*) OVER () AS products_counted\nFROM products WHERE stock_qty > 0;"}],"faqs":[{"question":"Is OVER () the same as no OVER?","answer":"No: COUNT(*) without OVER collapses to one row; COUNT(*) OVER () keeps every row and repeats the count. Same number, opposite output shapes."},{"question":"How do I get a total that ignores my WHERE?","answer":"Windows see post-filter rows only. Compute the unfiltered total in a scalar subquery, or in a CTE you cross join."}],"related":["aggregate-over","percent-of-total","over-with-group-by"],"novel_uses":[{"body":"One hundred times the row over the empty-window average expresses every value as an index where 100 means exactly average, provided the average is not truncated. SQL Server returns an INT average for an INT column, so keep price DECIMAL or cast it, as the example does. It needs no baseline table.","sql":"SELECT product, price,\n       100.0 * price / NULLIF(AVG(CAST(price AS DECIMAL(18,4))) OVER (), 0) AS price_index\nFROM products;"},{"body":"Divide by MAX over the empty window and every score becomes its share of the leader, a 0 to 1 normalization for non-negative scores that stays meaningful as rows arrive. With negative scores the ratio goes below 0 or above 1, so use it only where scores cannot be negative. In live feeds remember that a new best rescales every historical row.","sql":"SELECT contestant_id, score,\n       score * 1.0 / NULLIF(MAX(score) OVER (), 0) AS share_of_best\nFROM contestants;"}]},"source_url":"https://sqlly.app/sql-functions/window-empty-over","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-exclude","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window frame EXCLUDE clause","description":"EXCLUDE CURRENT ROW, TIES, GROUP and NO OTHERS: remove the current row or its peers from any frame (PostgreSQL, SQLite and Oracle 21c+).","body":{"slug":"window-exclude","name":"EXCLUDE Clause","h1":"SQL window frame EXCLUDE clause","category":"window","lede":"Appended to a frame spec, EXCLUDE removes the current row and/or its peers from the frame: leave-one-out averages without subtracting the row by hand.","syntax":"AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND 6 FOLLOWING EXCLUDE CURRENT ROW)","return_type":"per-frame aggregate","support":[{"engine_slug":"sql-server","status":"no","note":"not supported, including SQL Server 2025"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 11+"},{"engine_slug":"mysql","status":"no","note":"not supported in MySQL 8.x"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.28+"},{"engine_slug":"oracle","status":"yes","note":"Oracle 21c+"}],"gotchas":["The four options: NO OTHERS (default), CURRENT ROW (drop this row), TIES (drop the peers, keep this row), GROUP (drop row and peers). Peers are defined by the ORDER BY values, so TIES and GROUP work in ROWS frames too.","The main use is leave-one-out statistics: the average of a row's neighbours without the row itself, for spotting outliers.","SQL Server and MySQL reject EXCLUDE. The rewrite for EXCLUDE CURRENT ROW is (SUM(x) OVER w - x) / NULLIF(COUNT(x) OVER w - 1, 0), with care when x is NULL (the rewrite then returns NULL where EXCLUDE returns the other rows' average); EXCLUDE GROUP needs the peers' sum and count subtracted too."],"examples":[{"engine_slug":"postgresql","sql":"-- average of the neighbours only\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND 6 FOLLOWING\n                        EXCLUDE CURRENT ROW) AS neighbourhood_avg\nFROM prices;"},{"engine_slug":"sqlite","sql":"-- 3.28+ for EXCLUDE: the high so far, not counting this row\nSELECT day, price,\n       MAX(price) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n                        EXCLUDE CURRENT ROW) AS high_before\nFROM prices;"},{"engine_slug":"oracle","sql":"-- 21c+ for EXCLUDE: average of the neighbours only\nSELECT day, price,\n       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND 6 FOLLOWING\n                        EXCLUDE CURRENT ROW) AS neighbourhood_avg\nFROM prices;"}],"faqs":[{"question":"How do I compute 'everything except this row' in a window?","answer":"EXCLUDE CURRENT ROW where supported; elsewhere subtract the current value from the frame total: SUM(x) OVER w - x. For AVG divide that by COUNT(x) OVER w - 1, guarded with NULLIF against single-row frames."},{"question":"What is the difference between EXCLUDE TIES and EXCLUDE GROUP?","answer":"TIES removes the current row's peers but keeps the row itself; GROUP removes both the row and all its peers. NO OTHERS keeps the frame as the boundaries define it."}],"related":["rows-vs-range","groups-frame-support","window-default-frame"],"novel_uses":[{"body":"EXCLUDE TIES over a RANGE band averages the neighbourhood without counting rows tied with yours, so a price repeated twenty times stops dominating its own band. This is the fair comparable-set average for duplicate-heavy data. PostgreSQL 11+, SQLite 3.28+ and Oracle 21c+.","sql":"SELECT product_id, price,\n       AVG(price) OVER (ORDER BY price RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING\n         EXCLUDE TIES) AS band_avg_without_peers\nFROM products;"},{"body":"EXCLUDE GROUP drops the current row and every row tied with it, which is leave-one-group-out baselining: judge each batch against the average of everything else in the frame. Batch effects stop grading themselves.","sql":"SELECT batch_id, measurement,\n       AVG(measurement) OVER (ORDER BY batch_id\n         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING\n         EXCLUDE GROUP) AS baseline_without_batch\nFROM lab_runs;"}]},"source_url":"https://sqlly.app/sql-functions/window-exclude","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-in-cte","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window functions in CTEs","description":"Windows cannot appear in WHERE, HAVING or JOIN ON: the CTE (or subquery) wrap that makes ranked results filterable, with what works in one pass.","body":{"slug":"window-in-cte","name":"Window Functions in CTEs","h1":"SQL window functions in CTEs","category":"window","lede":"Compute the window function in a CTE or derived table, then filter on its alias outside, the standard workaround for the WHERE restriction.","syntax":"WITH r AS (SELECT ..., ROW_NUMBER() OVER (...) AS rn FROM t)\nSELECT * FROM r WHERE rn = 1","return_type":"filtered rows","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["WHERE runs before windows, HAVING after grouping but still before windows, JOIN ON before both; none of them can see a window alias. SELECT and the outer ORDER BY can.","A derived table works the same as a CTE; the CTE is preferred for readability and lets several filters reference the same computed column.","You can filter on several window columns in the outer query too: compute rn and cnt in the CTE, then WHERE rn <= cnt / 2 outside (impossible in one pass)."],"examples":[{"engine_slug":"all","sql":"WITH r AS (\n  SELECT order_id, customer_id, amount,\n         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, order_id) AS rn\n  FROM orders\n)\nSELECT order_id, customer_id, amount\nFROM r WHERE rn = 1;"}],"faqs":[{"question":"Can I use a window function in WHERE if I repeat it?","answer":"No. SELECT x, RANK() OVER (...) ... WHERE RANK() OVER (...) = 1 is still invalid. The parser rejects any window function outside SELECT and the final ORDER BY; wrap it."},{"question":"Can the outer query have its own window functions?","answer":"Yes: the outer SELECT can rank or aggregate the CTE's output again; two-level windows are the standard way to do 'window of a window'."}],"related":["top-n-per-group","window-vs-group-by","qualify-alternatives"],"novel_uses":[{"body":"Rank the same customers twice in one SELECT, once by spend and once by visits, then subtract the two window expressions: large swings are customers whose activity and spending disagree. Two OVER clauses over the same rows are enough, so no CTE is needed. MySQL ranks are unsigned, so multiply by 1.0 before subtracting or a negative swing raises an error.","sql":"SELECT customer_id,\n       ROW_NUMBER() OVER (ORDER BY spend DESC) AS r_spend,\n       ROW_NUMBER() OVER (ORDER BY visits DESC) AS r_visits,\n       ROW_NUMBER() OVER (ORDER BY visits DESC) * 1.0 - ROW_NUMBER() OVER (ORDER BY spend DESC) AS swing\nFROM customers;"},{"body":"LAG hands you one column from the previous row; joining the ranked CTE to itself on rn + 1 hands you both full rows. Use it when the comparison needs columns from both sides, such as basket pairs or leg-by-leg race splits.","sql":"WITH r AS (\n  SELECT leg, runner, seconds, ROW_NUMBER() OVER (ORDER BY leg) AS rn\n  FROM relay\n)\nSELECT a.leg, a.runner, b.runner AS next_runner,\n       b.seconds - a.seconds AS swing\nFROM r a JOIN r b ON b.rn = a.rn + 1;"}]},"source_url":"https://sqlly.app/sql-functions/window-in-cte","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-in-order-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window function in ORDER BY","description":"Window functions appear in two places, the SELECT list and this final ORDER BY: ordering the result by a rank computed in the same SELECT, and its limits.","body":{"slug":"window-in-order-by","name":"Window in ORDER BY","h1":"SQL window function in ORDER BY","category":"window","lede":"The final ORDER BY may reference window functions (or their aliases) directly; the result is sorted after the windows compute.","syntax":"SELECT name, RANK() OVER (ORDER BY score DESC) AS r FROM players ORDER BY r","return_type":"ordered result","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["ORDER BY inside OVER orders rows within the window; the outer ORDER BY orders the final result. They are independent and usually must match for ranks to display in order.","The outer query of a subquery or CTE can only sort by window results the inner query projected as columns; it cannot reach the inner window expression itself.","All five engines accept a bare alias in ORDER BY (ORDER BY cat_rank). Inside an expression they differ: ORDER BY CASE WHEN cat_rank = 1 THEN 0 ELSE 1 END fails on SQL Server ('Invalid column name') and PostgreSQL ('column does not exist'), so repeat the window call or use a CTE."],"examples":[{"engine_slug":"all","sql":"SELECT product, category, price,\n       RANK() OVER (PARTITION BY category ORDER BY price DESC) AS cat_rank\nFROM products\nORDER BY category, cat_rank;"}],"faqs":[{"question":"Why can I sort by RANK in ORDER BY but not filter in WHERE?","answer":"Evaluation order: windows are computed after WHERE and before the final ORDER BY, so ORDER BY sees them and WHERE cannot. Filter through a CTE instead."},{"question":"Does ORDER BY inside OVER double-sort the query?","answer":"It defines the partition's logical order and usually forces a sort per window definition. Sharing one named window (WINDOW clause) for several functions lets the engine reuse it."}],"related":["over-order-by","over-vs-order-by","window-clause"],"novel_uses":[{"body":"TOP 1 WITH TIES ordered by a RANK computed in the same query keeps every first-place row without a CTE. PostgreSQL spells the same single-statement form FETCH FIRST 1 ROWS WITH TIES; MySQL and SQLite have no WITH TIES form and need a CTE.","sql":"SELECT TOP 1 WITH TIES name, score,\n       RANK() OVER (ORDER BY score DESC) AS r\nFROM players\nORDER BY r;"},{"body":"An alias for a window function in the outer ORDER BY sorts detail rows by their partition's count, so the biggest groups cluster at the top of a support queue without a CTE. Keep a secondary key so groups of equal size stay stable, and add a unique column so rows inside each group stay stable too.","sql":"SELECT department, employee_id, ticket_id,\n       COUNT(*) OVER (PARTITION BY department) AS dept_queue\nFROM tickets\nORDER BY dept_queue DESC, department, ticket_id;"}]},"source_url":"https://sqlly.app/sql-functions/window-in-order-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-in-update","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window functions in UPDATE","description":"No engine lets a window function appear directly in SET or WHERE of an UPDATE: the CTE-and-join rewrite that makes ranked updates possible.","body":{"slug":"window-in-update","name":"Window Functions in UPDATE","h1":"SQL window functions in UPDATE","category":"window","lede":"Wrap the windowed query in a CTE or derived table and join it in the UPDATE, the portable way to update rows chosen or numbered by a window (Oracle uses MERGE, see the notes).","syntax":"WITH r AS (SELECT id, ROW_NUMBER() OVER (...) AS rn FROM t)\nUPDATE t SET flag = 1 FROM r WHERE t.id = r.id AND r.rn = 1","return_type":"updated rows","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+; WITH r AS (...) UPDATE t JOIN r ON ... SET ..."},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.33+ for WITH ... UPDATE ... FROM; older versions use WHERE id IN (SELECT ...)"},{"engine_slug":"oracle","status":"yes","note":"no WITH before UPDATE; UPDATE ... FROM (windowed subquery) on 23ai, MERGE or WHERE id IN (subquery) on 19c"}],"gotchas":["Window functions cannot appear in the SET list, in UPDATE's WHERE, or in DELETE's targeting; every engine rejects them before any row changes. Only the CTE/derived-table route works.","The statement shape is engine-specific: SQL Server updates through the CTE or joins it; PostgreSQL and SQLite 3.33+ use UPDATE ... FROM; MySQL writes UPDATE t JOIN cte ... SET; Oracle 23ai accepts UPDATE t SET ... FROM (windowed subquery) r WHERE ..., and 19c uses MERGE INTO t USING (windowed subquery).","For 'update the top N rows' the windowed CTE replaces the classic TOP/LIMIT-with-subquery hacks and is safe against ties when a tiebreaker is included."],"examples":[{"engine_slug":"sql-server","sql":"WITH r AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders\n)\nUPDATE o SET is_primary = 1\nFROM orders o JOIN r ON o.id = r.id AND r.rn = 1;"},{"engine_slug":"postgresql","sql":"WITH r AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders\n)\nUPDATE orders o SET is_primary = true\nFROM r WHERE o.id = r.id AND r.rn = 1;"},{"engine_slug":"mysql","sql":"WITH r AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders\n)\nUPDATE orders o JOIN r ON o.id = r.id\nSET o.is_primary = 1\nWHERE r.rn = 1;"},{"engine_slug":"sqlite","sql":"-- 3.33+ for UPDATE ... FROM\nWITH r AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n  FROM orders\n)\nUPDATE orders SET is_primary = 1\nFROM r WHERE orders.id = r.id AND r.rn = 1;"},{"engine_slug":"oracle","sql":"-- no WITH before UPDATE: MERGE takes the windowed subquery\nMERGE INTO orders o\nUSING (SELECT id,\n              ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn\n       FROM orders) r\nON (o.id = r.id)\nWHEN MATCHED THEN\n  UPDATE SET o.is_primary = 1\n  WHERE r.rn = 1;"}],"faqs":[{"question":"Why can't I put ROW_NUMBER in my UPDATE's WHERE?","answer":"The standard allows window functions only in a SELECT list and ORDER BY, and UPDATE's WHERE is neither. Compute the numbers in a SELECT (CTE or subquery) and join it to the target."},{"question":"How do I delete duplicates on MySQL 8.0?","answer":"Put the numbering in a CTE named d (WITH d AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn FROM contacts)), then run a multi-table DELETE that joins it: DELETE c FROM contacts c JOIN d ON c.id = d.id WHERE d.rn > 1. Deleting directly from the CTE is not allowed (error 1288)."}],"related":["dedupe-rows","window-in-cte","top-n-per-group"],"novel_uses":[{"body":"UPDATE a deleted_at stamp on rn > 1 instead of deleting, and the dedupe becomes reversible. The winners keep the table's shape while the losers stay on disk for the audit nobody asks for until they do. PostgreSQL UPDATE ... FROM shown.","sql":"WITH d AS (\n  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn\n  FROM contacts\n)\nUPDATE contacts c SET deleted_at = now()\nFROM d\nWHERE c.id = d.id AND d.rn > 1;"},{"body":"Number the rows in a CTE and write the numbers into a position column, and drag-and-drop ordering survives restarts and re-queries. The window's ORDER BY is the stored sort; nothing at read time re-sorts by luck. PostgreSQL UPDATE ... FROM shown.","sql":"WITH r AS (\n  SELECT id, ROW_NUMBER() OVER (ORDER BY board_order, id) AS rn\n  FROM tasks\n)\nUPDATE tasks t SET list_pos = r.rn\nFROM r\nWHERE t.id = r.id;"}]},"source_url":"https://sqlly.app/sql-functions/window-in-update","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-nulls-order","corpus":"sql-functions","engine":null,"language":"en","title":"SQL NULLS FIRST and NULLS LAST","description":"Controlling where NULLs sort in OVER (ORDER BY ...): a keyword in PostgreSQL, SQLite and Oracle, a CASE sort key on SQL Server and MySQL.","body":{"slug":"window-nulls-order","name":"NULLS FIRST / NULLS LAST","h1":"SQL NULLS FIRST and NULLS LAST","category":"window","lede":"NULLS FIRST or NULLS LAST pins NULL ordering inside windows, where each engine's implicit rule otherwise decides, and they disagree.","syntax":"ORDER BY x NULLS LAST | ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x (portable emulation)","return_type":"ordered partition","support":[{"engine_slug":"sql-server","status":"no","note":"no NULLS FIRST/LAST clause; emulate NULLS FIRST with ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x"},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"no","note":"no NULLS FIRST/LAST clause; NULLs sort first ascending, last descending; emulate with the CASE trick"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.30+; default treats NULL as smallest"},{"engine_slug":"oracle","status":"yes","note":"default treats NULL as largest (last ascending, first descending), same as PostgreSQL"}],"gotchas":["Defaults split into two camps: PostgreSQL and Oracle treat NULL as larger than any value (last ascending, first descending); SQL Server, MySQL and SQLite treat it as smaller (first ascending, last descending).","In windows the placement changes results, not just display: ROW_NUMBER() OVER (ORDER BY score DESC) gives rn = 1 to a NULL score on PostgreSQL and Oracle, and to the highest real score on the other three.","ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x puts NULLs last on every engine; swap 1 and 0 for NULLs first. The shorter ORDER BY x IS NULL, x works on PostgreSQL, MySQL, SQLite and Oracle 23ai but not SQL Server."],"examples":[{"engine_slug":"postgresql","sql":"SELECT name, priority,\n       ROW_NUMBER() OVER (ORDER BY priority NULLS LAST) AS rn\nFROM tasks;"},{"engine_slug":"sql-server","sql":"SELECT name, priority,\n       ROW_NUMBER() OVER (ORDER BY CASE WHEN priority IS NULL THEN 1 ELSE 0 END, priority) AS rn\nFROM tasks;"},{"engine_slug":"sqlite","sql":"-- 3.30+ for NULLS LAST in a window ORDER BY\nSELECT name, score,\n       ROW_NUMBER() OVER (ORDER BY score DESC NULLS LAST) AS rn\nFROM players;"},{"engine_slug":"oracle","sql":"-- NULLs sort last ascending by default; NULLS FIRST pins them to the front\nSELECT name, priority,\n       ROW_NUMBER() OVER (ORDER BY priority NULLS FIRST) AS rn\nFROM tasks;"}],"faqs":[{"question":"Where do NULLs sort by default?","answer":"PostgreSQL and Oracle sort NULLs last ascending and first descending. SQL Server, MySQL and SQLite do the opposite: first ascending, last descending. Write NULLS FIRST/LAST where supported, or the CASE sort key elsewhere."},{"question":"Do NULLs affect LAG and LEAD?","answer":"LAG and LEAD return the neighbouring row's value even when it is NULL. To skip NULLs you need IGNORE NULLS (Oracle, SQL Server 2022+). PostgreSQL, MySQL and SQLite have no IGNORE NULLS. The COUNT/MAX fill-forward is a different thing: it returns the last non-null value up to and including the current row, so it fills gaps rather than giving LAG's previous non-null."}],"related":["over-order-by","ignore-nulls","deterministic-window-order"],"novel_uses":[{"body":"Sort a leaderboard descending and the engine defaults split: PostgreSQL and Oracle put NULL scores first unless you write NULLS LAST, while SQL Server, MySQL and SQLite already drop them to the bottom. Write the keyword where it exists or the CASE sort key where it does not, and the podium never seats an unplayed entry.","sql":"SELECT name, score,\n       ROW_NUMBER() OVER (ORDER BY score DESC NULLS LAST) AS rn\nFROM players;"},{"body":"Treat NULL priority as its own bucket with NULLS LAST ahead of the real sort keys, and unclaimed work lands after every priority tier instead of squatting at the top. On SQL Server and MySQL a leading CASE WHEN priority IS NULL THEN 1 ELSE 0 END key does the same job.","sql":"SELECT ticket_id, priority, severity\nFROM tickets\nORDER BY priority NULLS LAST, severity DESC, created_at;"}]},"source_url":"https://sqlly.app/sql-functions/window-nulls-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-performance","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window function performance","description":"Why windows get slow: per-window sorts, spools and frame sizes, and the index, shared-window and frame-shaping moves that fix them.","body":{"slug":"window-performance","name":"Window Function Performance","h1":"SQL window function performance","category":"window","lede":"Each distinct window definition may force a sort of the full input; frames and partitioning decide how much work each row costs.","syntax":"-- supporting index on (partition_col, order_col)\nCREATE INDEX ix ON orders (customer_id, order_date)","return_type":"n/a (performance)","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Sort cost multiplies: N different PARTITION BY/ORDER BY combinations can mean N sorts. Use the same combination wherever the meaning allows.","An ascending index on (partition columns, ORDER BY columns) lets PostgreSQL, SQLite and SQL Server read rows already in window order and skip the sort, provided the query can use that index for the scan. MySQL 8.4 still sorts even when a covering index is forced.","On SQL Server row-mode plans, frames written as ROWS use an in-memory window spool while the default RANGE frame uses an on-disk one, so writing ROWS UNBOUNDED PRECEDING explicitly can speed up running totals. Batch-mode Window Aggregate (2016+, columnstore or 2019 batch mode on rowstore) avoids the spool.","Filter early, window late: apply WHERE and pre-aggregate in a CTE before the window pass so the sort touches fewer, smaller rows."],"examples":[{"engine_slug":"all","sql":"-- pre-aggregate to shrink the windowed row set\nWITH daily AS (\n  SELECT order_date, customer_id, SUM(amount) AS amount\n  FROM orders\n  GROUP BY order_date, customer_id\n)\nSELECT customer_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running\nFROM daily;"}],"faqs":[{"question":"Why is my window query slower than GROUP BY?","answer":"GROUP BY collapses rows to one per group, by hashing on PostgreSQL and SQL Server and by sorting on SQLite; windows sort per partition and keep every row. If you only need one number per group, GROUP BY skips the per-row window pass, but joining those numbers back still reads every row."},{"question":"How do I make several window functions share one sort?","answer":"Give them the same PARTITION BY and ORDER BY (a named WINDOW makes that easy to keep). Functions with an identical window share one sort on every engine tested. Prefix sharing, where one ORDER BY extends another's, works on PostgreSQL and SQLite; SQL Server and MySQL sort again."}],"related":["over-clause","window-clause","moving-average"],"novel_uses":[{"body":"Compute ROW_NUMBER once in a CTE and derive every tier with CASE on the number, instead of three window functions with near-identical OVER clauses. Identical windows can share a sort; near-identical ones are the classic way to pay for three.","sql":"WITH r AS (\n  SELECT employee_id, department, salary,\n         ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn\n  FROM employees\n)\nSELECT *,\n       CASE WHEN rn = 1 THEN 'top' WHEN rn <= 3 THEN 'podium' ELSE 'rest' END AS tier\nFROM r;"},{"body":"PostgreSQL's EXPLAIN shows one Sort (or Incremental Sort) plus WindowAgg nodes per distinct window, and SQL Server's row-mode plan shows Segment and Window Spool steps (Sequence Project as well for ROWS frames); the default batch-mode plan shows a single Window Aggregate with no spool. Read the plan before tuning: the number of window passes is the cost model.","sql":"EXPLAIN ANALYZE\nSELECT customer_id, order_date,\n       SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running\nFROM orders;"}]},"source_url":"https://sqlly.app/sql-functions/window-performance","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-versions","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window functions: version support","description":"When each engine gained window features: SQL Server 2005/2012/2022, PostgreSQL 8.4/9.4/11, MySQL 8.0, SQLite 3.25/3.28/3.30, Oracle 8i and 21c.","body":{"slug":"window-versions","name":"Window Function Versions","h1":"SQL window functions: version support","category":"window","lede":"The version gates that decide whether a window query runs: base functions, frames, FILTER/EXCLUDE and IGNORE NULLS all arrived separately.","syntax":"n/a (version matrix)","return_type":"n/a","support":[{"engine_slug":"sql-server","status":"yes","note":"2005 ranking and partition aggregates; 2012 ORDER BY in aggregates, frames, LAG/LEAD; 2022 IGNORE NULLS and WINDOW (WINDOW needs compatibility level 160)"},{"engine_slug":"postgresql","status":"yes","note":"8.4+ base; FILTER 9.4+; GROUPS/EXCLUDE 11+"},{"engine_slug":"mysql","status":"yes","note":"8.0+; none in 5.7"},{"engine_slug":"sqlite","status":"yes","note":"3.25+ base; GROUPS/EXCLUDE 3.28+; FILTER and NULLS FIRST/LAST 3.30+"},{"engine_slug":"oracle","status":"yes","note":"analytic functions since 8i; GROUPS, EXCLUDE and WINDOW clause 21c; QUALIFY 23.26.0, FILTER 23.26.1"}],"gotchas":["The last of the five to get window functions was SQLite, with 3.25 (September 2018), a few months after MySQL 8.0 went GA in April 2018. A fleet that still has MySQL 5.7 needs the subquery and self-join fallbacks.","Frames matured at different speeds: SQL Server has had ROWS/RANGE frames since 2012 but still no GROUPS, EXCLUDE or RANGE offsets in 2025; SQLite got GROUPS and EXCLUDE in 2019, Oracle in 21c.","SQLite's version comes from whatever library the app or OS ships, not from a server upgrade, so check sqlite_version() on the actual target."],"examples":[{"engine_slug":"all","sql":"-- features outside the common core, and where they run:\n-- GROUPS/EXCLUDE: PostgreSQL 11+, SQLite 3.28+, Oracle 21c+\n-- FILTER:         PostgreSQL 9.4+, SQLite 3.30+, Oracle 23.26.1+\n-- IGNORE NULLS:   Oracle, SQL Server 2022+\n-- WINDOW clause:  all, but SQL Server 2022+ and Oracle 21c+"}],"faqs":[{"question":"Which engine has the most complete window support?","answer":"Oracle 21c and later: GROUPS, EXCLUDE, IGNORE NULLS, FROM LAST and the WINDOW clause, and QUALIFY and FILTER from the 23.26 release updates. PostgreSQL 11+ is next (no IGNORE NULLS). Cross-engine SQL should stick to ROWS frames, RANGE with UNBOUNDED/CURRENT ROW, and CASE conditionals."},{"question":"How do I check the SQLite version in production?","answer":"SELECT sqlite_version(), and check that it is at least 3.25 before deploying window queries; bundled builds vary by OS and app."}],"related":["mysql-8-window","sql-server-2022-window","postgres-window-features"],"novel_uses":[{"body":"Ranking functions, LAG and LEAD, and ROWS frames with UNBOUNDED or n PRECEDING bounds run on the oldest member of any modern fleet: SQL Server 2012, PostgreSQL 8.4, MySQL 8.0 and SQLite 3.25. Everything past that (GROUPS, EXCLUDE, FILTER, IGNORE NULLS, named windows on older servers) needs a per-engine plan.","sql":null},{"body":"Every engine answers a version probe: version() on MySQL and PostgreSQL, sqlite_version() in SQLite, SERVERPROPERTY('ProductVersion') on SQL Server, and the v$version view on Oracle. Check once per connection and route features accordingly.","sql":"SELECT version() AS v;"}]},"source_url":"https://sqlly.app/sql-functions/window-versions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/window-vs-group-by","corpus":"sql-functions","engine":null,"language":"en","title":"SQL window functions vs GROUP BY","description":"When to collapse rows with GROUP BY and when to annotate them with OVER, and how the two combine in one query.","body":{"slug":"window-vs-group-by","name":"Window vs GROUP BY","h1":"SQL window functions vs GROUP BY","category":"window","lede":"GROUP BY returns one row per group; window functions return every row with the group's aggregate attached. Pick per output shape, not per calculation.","syntax":"SELECT g, SUM(x) FROM t GROUP BY g | SELECT g, id, SUM(x) OVER (PARTITION BY g) FROM t","return_type":"rows or groups","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":"MySQL 8.0+"},{"engine_slug":"sqlite","status":"yes","note":"SQLite 3.25+"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Detail columns force the choice: SELECT g, id, SUM(x) FROM t GROUP BY g is rejected on SQL Server, PostgreSQL and MySQL 8 because id is not grouped; SQLite accepts it and returns an arbitrary id per group. The window form keeps id on every engine because nothing collapses.","Together they compose: with GROUP BY present, window functions evaluate over the grouped rows, so SUM(SUM(x)) OVER () totals the group sums.","HAVING filters groups before windows compute; to filter on a window result you need the CTE wrap, not HAVING."],"examples":[{"engine_slug":"all","sql":"-- collapsed\nSELECT department, SUM(salary) AS payroll\nFROM employees GROUP BY department;"},{"engine_slug":"all","sql":"-- annotated: detail rows plus their group's payroll\nSELECT department, employee_id, salary,\n       SUM(salary) OVER (PARTITION BY department) AS payroll\nFROM employees;"}],"faqs":[{"question":"Which is faster, GROUP BY or a window?","answer":"Different jobs: GROUP BY shrinks the result, windows sort per partition and keep it. If the caller only wants per-group numbers, GROUP BY (or a GROUP BY joined back) is usually cheaper; windows win when detail rows are the point."},{"question":"Can I use both in one query?","answer":"Yes, windows run after GROUP BY, so aggregates inside OVER see the grouped values: AVG(SUM(x)) OVER (ORDER BY dim) is a running average of group sums."}],"related":["aggregate-over","over-with-group-by","window-in-cte"],"novel_uses":[{"body":"HAVING runs before the windows, so a rank in the same query orders just the survivors: small departments never enter the payroll ranking. That prefilter is a feature when the ranking should ignore noise groups.","sql":"SELECT department, SUM(salary) AS payroll,\n       RANK() OVER (ORDER BY SUM(salary) DESC) AS payroll_rank\nFROM employees\nGROUP BY department\nHAVING SUM(salary) > 100000;"},{"body":"UNION a plain detail SELECT with the same table grouped, and the client renders one result set with totals beside rows. Keep a kind column so the renderer can style the rollup rows.","sql":"SELECT department, employee_id, salary, 'detail' AS kind FROM employees\nUNION ALL\nSELECT department, NULL, SUM(salary), 'rollup' FROM employees GROUP BY department\nORDER BY department, kind;"}]},"source_url":"https://sqlly.app/sql-functions/window-vs-group-by","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/word-similarity","corpus":"sql-functions","engine":null,"language":"en","title":"SQL WORD_SIMILARITY function","description":"How PostgreSQL's word_similarity and strict_word_similarity find the best-matching word inside longer text: thresholds, the <<% operator and trigram index support.","body":{"slug":"word-similarity","name":"WORD_SIMILARITY","h1":"SQL WORD_SIMILARITY function","category":"string","lede":"Scores the best similarity between a search term and any part of a longer text string.","syntax":"word_similarity(term, text)  |  strict_word_similarity(term, text)","return_type":"real","support":[{"engine_slug":"sql-server","status":"no","note":"Full-text search covers word lookup, not trigram scores."},{"engine_slug":"postgresql","status":"yes","note":"Requires the pg_trgm extension."},{"engine_slug":"mysql","status":"no","note":"FULLTEXT search is the word-based route."},{"engine_slug":"sqlite","status":"no","note":"No built-in equivalent."},{"engine_slug":"oracle","status":"no","note":"Oracle Text's CONTAINS with the FUZZY operator."}],"gotchas":["similarity compares whole strings; word_similarity asks how well the first argument matches the best stretch of the second, which suits searching names inside longer text.","strict_word_similarity only scores stretches that line up with word boundaries: word_similarity('smith', 'smithereens') is about 0.83, strict_word_similarity about 0.38.","'term' <<% col is true when strict_word_similarity('term', col) exceeds pg_trgm.strict_word_similarity_threshold (default 0.5); col %>> 'term' is the same test written the other way round. The word_similarity_threshold (default 0.6) governs the <% operator instead. Both can use a GIN or GiST trigram index."],"examples":[{"engine_slug":"postgresql","sql":"SELECT word_similarity('smith', 'john smith jr') AS score;  -- 1"},{"engine_slug":"postgresql","sql":"SELECT * FROM companies\nWHERE 'acme' <<% name  -- fuzzy word match, index-friendly\nORDER BY word_similarity('acme', name) DESC;"}],"faqs":[{"question":"When do I use word_similarity instead of similarity?","answer":"When the search term should match one word inside longer text, like 'nike' in 'Nike Sportswear Inc'. Plain similarity dilutes the score across the whole string."},{"question":"What does strict_word_similarity add?","answer":"Word-boundary alignment: the matched stretch must start and end at word boundaries, so a term inside a longer word scores lower."},{"question":"Can word_similarity use an index?","answer":"The operators can: a GIN or GiST index with gin_trgm_ops or gist_trgm_ops supports <<% and %>>. The function call alone does not use the index."}],"related":["similarity","levenshtein","soundex","regexp-match"],"novel_uses":[{"body":"With a GiST trigram index, ORDER BY 'term' <<-> name LIMIT 5 returns the nearest names using the index instead of scoring every row. Put the term first: name <<-> 'term' makes the name the needle, and the planner cannot use the index for that form.","sql":"SELECT name FROM companies\nORDER BY 'acme' <<-> name\nLIMIT 5;"},{"body":"The term can be several words: word_similarity('acme corp', body) finds the best-aligned stretch anywhere in the value, which surfaces company mentions inside long descriptions.","sql":"SELECT * FROM filings\nWHERE word_similarity('acme corp', body) > 0.8;"}]},"source_url":"https://sqlly.app/sql-functions/word-similarity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/xml-value","corpus":"sql-functions","engine":null,"language":"en","title":"SQL XML scalar extraction","description":"Scalar extraction from XML: SQL Server's .value() with XQuery types, Oracle's XMLCAST over XMLQUERY, and PostgreSQL's xpath() returning arrays.","body":{"slug":"xml-value","name":".value() / XMLCAST","h1":"SQL XML scalar extraction","category":"string","lede":"doc.value('(/order/total)[1]', 'decimal(10,2)') pulls one typed scalar out of XML. The .value side of SQL Server's pair, and its Oracle equivalent.","syntax":"column.value('xpath', 'sql_type')  -- SQL Server  |  XMLCAST(XMLQUERY(...) AS type)  -- Oracle","return_type":"scalar","support":[{"engine_slug":"sql-server","status":"yes","note":"the .value() method over xml columns"},{"engine_slug":"postgresql","status":"partial","note":"xpath() then subscript and cast"},{"engine_slug":"mysql","status":"partial","note":"ExtractValue(xml_text, xpath) returns the text"},{"engine_slug":"sqlite","status":"no","note":"no XML support"},{"engine_slug":"oracle","status":"partial","note":"XMLCAST + XMLQUERY; EXTRACTVALUE is deprecated"}],"gotchas":["SQL Server's .value() needs a path that is a singleton at compile time, so '/order/total' fails with \"'value()' requires a singleton\" even when only one node exists. Write '(/order/total)[1]'.",".value() must cast to a SQL type ('decimal(10,2)', 'nvarchar(max)'); .query() returns XML instead: the method pair splits scalars from fragments.","EXTRACTVALUE is Oracle's deprecated predecessor: prefer XMLCAST(XMLQUERY(...)) in new code, or migrate the column to JSON if you control the format."],"examples":[{"engine_slug":"sql-server","sql":"SELECT doc.value('(/order/total)[1]', 'decimal(10,2)') AS total\nFROM orders_xml;"},{"engine_slug":"oracle","sql":"SELECT XMLCAST(XMLQUERY('/order/total/text()'\n  PASSING doc RETURNING CONTENT) AS NUMBER) AS total\nFROM orders_xml;"},{"engine_slug":"mysql","sql":"SELECT ExtractValue(doc_text, '/order/total') AS total\nFROM orders_xml;"},{"engine_slug":"postgresql","sql":"SELECT (xpath('/order/total/text()', doc))[1]::text AS total\nFROM orders_xml;"}],"faqs":[{"question":".query() or .value()?","answer":".value() for one scalar, typed, with the mandatory [1] subscript; .query() for XML fragments. They pair like JSON_VALUE and JSON_QUERY."},{"question":"Why does .value() say it requires a singleton?","answer":"SQL Server checks the path's type before running it, and '/a/b' could match many nodes. Parenthesise and subscript, '(/a/b)[1]', to promise a single node."}],"related":["xmlquery","xmltable","for-xml","json-value"],"novel_uses":[{"body":"xpath() hands back an xml array, so a scalar needs (xpath('/order/total/text()', doc))[1]::text::numeric: select the text node, subscript, cast to text, cast to the number. Drop the /text() and the cast sees <total>12.50</total> and fails. Two casts, no XMLQUERY in sight.","sql":"SELECT (xpath('/order/total/text()', doc))[1]::text::numeric AS total FROM orders_xml;"},{"body":"The .exist() method answers 'is this node there' with 1 or 0, so WHERE clauses test presence without pulling a value. It pairs with .value and .query as SQL Server's third XML method.","sql":"SELECT id FROM orders_xml WHERE doc.exist('/order/rush') = 1;"}]},"source_url":"https://sqlly.app/sql-functions/xml-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/xmlquery","corpus":"sql-functions","engine":null,"language":"en","title":"SQL XMLQUERY function","description":"XMLQUERY runs XQuery against XML on Oracle; SQL Server has the .query() method, PostgreSQL xpath(), MySQL ExtractValue() for XPath, and SQLite nothing.","body":{"slug":"xmlquery","name":"XMLQUERY","h1":"SQL XMLQUERY function","category":"string","lede":"XMLQUERY('/order/total' PASSING doc RETURNING CONTENT) returns the matching XML fragment from an XMLType value. Only Oracle implements the SQL/XML function itself.","syntax":"XMLQUERY(xquery_string PASSING column RETURNING CONTENT)  -- Oracle  |  column.query('xpath')  -- SQL Server","return_type":"XML","support":[{"engine_slug":"sql-server","status":"partial","note":"the .query() method over xml columns"},{"engine_slug":"postgresql","status":"partial","note":"xml type with xpath(), not the XMLQUERY function"},{"engine_slug":"mysql","status":"no","note":"no XML type; ExtractValue(xml, xpath) returns text from an XPath"},{"engine_slug":"sqlite","status":"no","note":"no XML support"},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["Support varies widely: Oracle has XQuery, SQL Server a subset of XQuery (no following-sibling axis, no string-join()), PostgreSQL has XPath 1.0 over its xml type, MySQL has ExtractValue() and UpdateXML() over plain strings, and SQLite has nothing.","Oracle's XMLQUERY returns XML; add RETURNING CONTENT and XMLCAST for scalars. SQL Server splits the roles: .query() returns fragments, .value() extracts scalars.","PostgreSQL has an xml type with xpath() (XPath 1.0 only), capable for small jobs, short of the full SQL/XML XMLQUERY surface."],"examples":[{"engine_slug":"oracle","sql":"SELECT XMLQUERY('/order/total/text()'\n  PASSING doc RETURNING CONTENT) AS total\nFROM orders_xml;"},{"engine_slug":"sql-server","sql":"SELECT doc.query('/order/total') AS total\nFROM orders_xml;"},{"engine_slug":"postgresql","sql":"SELECT xpath('/order/total/text()', doc) AS total\nFROM orders_xml;"}],"faqs":[{"question":"Should I store XML in the database?","answer":"Only when the format is fixed by someone else. Every engine here has JSON functions, while SQLite has no XML support and MySQL's is limited to XPath over strings. If you control the format, store JSON."},{"question":"Why does xpath() return an array on PostgreSQL?","answer":"xpath() returns xml[], a set of nodes. Take subscript [1] for a single node, and remember it is XPath 1.0: no XQuery expressions like if/then."}],"related":["xmltable","xml-value","for-xml","json-extract"],"novel_uses":[{"body":"XQuery's count() runs inside the query: Oracle's XMLQUERY('count(/order/items/item)' RETURNING CONTENT) and SQL Server's .value('count(/order/items/item)', 'int') both return the element count in one call.","sql":"SELECT doc.value('count(/order/items/item)', 'int') AS n FROM orders_xml;"},{"body":"xpath() returns an empty xml[] when nothing matches, so array_length(xpath('/order/rush', doc), 1) > 0 is the presence test. No fragment is extracted, just checked.","sql":"SELECT id FROM orders_xml WHERE array_length(xpath('/order/rush', doc), 1) > 0;"}]},"source_url":"https://sqlly.app/sql-functions/xmlquery","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/xmltable","corpus":"sql-functions","engine":null,"language":"en","title":"SQL XMLTABLE function","description":"XMLTABLE turns repeating XML nodes into relational rows through a COLUMNS clause, on PostgreSQL 10+ and Oracle. SQL Server uses .nodes(); MySQL and SQLite have none.","body":{"slug":"xmltable","name":"XMLTABLE","h1":"SQL XMLTABLE function","category":"string","lede":"FROM XMLTABLE('/order/items/item' PASSING doc COLUMNS (...)) flattens repeating XML nodes into rows. XML's answer to JSON_TABLE.","syntax":"XMLTABLE(row_pattern PASSING doc COLUMNS col type PATH 'subpath', ...)","return_type":"rowset","support":[{"engine_slug":"sql-server","status":"no","note":"no XMLTABLE; CROSS APPLY doc.nodes() with .value(), or OPENXML"},{"engine_slug":"postgresql","status":"yes","note":"PostgreSQL 10+"},{"engine_slug":"mysql","status":"no","note":"no XMLTABLE; only the scalar ExtractValue() and UpdateXML() XPath functions"},{"engine_slug":"sqlite","status":"no","note":"no XML support"},{"engine_slug":"oracle","status":"yes","note":"XMLTABLE with the same COLUMNS clause"}],"gotchas":["The row pattern selects the repeating nodes; each column's PATH is relative to it. Namespaced documents need an XMLNAMESPACES clause before the row pattern.","The column list is not parenthesised: COLUMNS sku text PATH 'sku', qty int PATH 'qty'. Copying JSON_TABLE's COLUMNS (...) shape is a syntax error on both PostgreSQL and Oracle.","PASSING correlates outer columns: XMLTABLE('...' PASSING i.doc ...) shreds each row's own document, the per-row pattern you almost always want.","Without a PATH, a column reads the child element with the column's own name, so COLUMNS sku text, qty int works when the names match."],"examples":[{"engine_slug":"postgresql","sql":"SELECT xt.sku, xt.qty\nFROM imports i,\nXMLTABLE('/order/items/item'\n  PASSING i.doc\n  COLUMNS sku text PATH 'sku',\n          qty int PATH 'qty') xt;"},{"engine_slug":"oracle","sql":"SELECT xt.sku, xt.qty\nFROM imports i,\nXMLTABLE('/order/items/item'\n  PASSING i.doc\n  COLUMNS sku VARCHAR2(40) PATH 'sku',\n          qty NUMBER PATH 'qty') xt;"}],"faqs":[{"question":"How do I shred XML to rows on SQL Server?","answer":"CROSS APPLY the .nodes() method and read each node with .value(): FROM t CROSS APPLY t.doc.nodes('/order/items/item') AS x(n), then x.n.value('(sku)[1]', 'nvarchar(40)'). OPENXML still works but needs sp_xml_preparedocument first."},{"question":"XMLTABLE or JSON_TABLE?","answer":"Same design, different input format: XMLTABLE for XML on PostgreSQL and Oracle, JSON_TABLE for JSON on Oracle, MySQL and PostgreSQL 17. Note the COLUMNS list is parenthesised in JSON_TABLE and not in XMLTABLE."}],"related":["json-table","xmlquery","xml-value","openjson"],"novel_uses":[{"body":"A FOR ORDINALITY column numbers rows in document order, so the XML's own sequence survives the trip to rows and can drive ORDER BY for faithful round-trips.","sql":"SELECT xt.n, xt.sku FROM imports i, XMLTABLE('/order/items/item' PASSING i.doc COLUMNS n FOR ORDINALITY, sku text PATH 'sku') xt;"},{"body":"qty int PATH 'qty' DEFAULT 0 fills the column when its PATH matches no node, on PostgreSQL and Oracle, instead of letting NULLs flow into totals downstream. An empty or non-numeric value still raises a cast error, so DEFAULT is no substitute for cleaning bad data.","sql":"SELECT xt.sku, xt.qty FROM imports i, XMLTABLE('/order/items/item' PASSING i.doc COLUMNS sku text PATH 'sku', qty int PATH 'qty' DEFAULT 0) xt;"}]},"source_url":"https://sqlly.app/sql-functions/xmltable","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/xor","corpus":"sql-functions","engine":null,"language":"en","title":"SQL XOR operator","description":"Logical XOR between two conditions: MySQL's XOR operator, NULL propagation, and the boolean a <> b recipe for PostgreSQL, SQLite and Oracle 23ai, plus CASE on SQL Server.","body":{"slug":"xor","name":"XOR","h1":"SQL XOR operator","category":"conditional","lede":"True when exactly one of the two operands is true.","syntax":"a XOR b | a <> b | (cond1) <> (cond2)","return_type":"boolean","support":[{"engine_slug":"sql-server","status":"no","note":"no logical XOR and conditions are not values; compare two CASE expressions. ^ is bitwise"},{"engine_slug":"postgresql","status":"no","note":"no XOR keyword; a <> b on boolean values"},{"engine_slug":"mysql","status":"yes","note":"logical operator between two conditions"},{"engine_slug":"sqlite","status":"no","note":"no XOR keyword; (cond1) <> (cond2), since comparisons yield 0/1"},{"engine_slug":"oracle","status":"no","note":"23ai+: (cond1) <> (cond2) over BOOLEAN; older releases need CASE"}],"gotchas":["NULL propagates: NULL XOR anything is NULL, so a row with an unknown flag silently drops out of WHERE.","Chained XOR in MySQL counts parity: a XOR b XOR c is true when an odd number of operands is true, not 'exactly one'.","For booleans, a <> b is XOR whenever both sides are non-NULL. IS DISTINCT FROM never returns NULL, but it treats NULL as a third value (NULL IS DISTINCT FROM false is true), so it is not XOR on unknowns.","Bitwise ^ (T-SQL, MySQL) and # (PostgreSQL) are not logical XOR: they work on integers bit by bit, so 6 ^ 3 is 5, not true."],"examples":[{"engine_slug":"mysql","sql":"SELECT 1 XOR 1 AS f, 1 XOR 0 AS t, NULL XOR 1 AS n;"},{"engine_slug":"postgresql","sql":"SELECT true <> false AS t, true <> true AS f, NULL::bool <> true AS n;"},{"engine_slug":"sql-server","sql":"SELECT * FROM t WHERE CASE WHEN a = 1 THEN 1 ELSE 0 END <> CASE WHEN b = 1 THEN 1 ELSE 0 END;"}],"faqs":[{"question":"What is the XOR truth table?","answer":"1 XOR 0 = 1, 0 XOR 1 = 1, 0 XOR 0 = 0, 1 XOR 1 = 0, and any NULL operand makes the whole thing NULL."},{"question":"How do I write XOR in SQL Server?","answer":"T-SQL cannot compare two conditions directly, so turn each into 0/1 with CASE and compare those: CASE WHEN a = 1 THEN 1 ELSE 0 END <> CASE WHEN b = 1 THEN 1 ELSE 0 END. That form also treats NULL as false."},{"question":"Does a XOR b XOR c mean exactly one is true?","answer":"No, it is parity: true when an odd number of the operands is true."}],"related":["three-valued-logic","distinct-from","null-safe-equal","boolean"],"novel_uses":[{"body":"A CHECK over the two NULL-ness tests enforces fill one, not both, at the DDL level; MySQL spells it with XOR and enforces CHECKs from 8.0.16 on.","sql":"CREATE TABLE profiles (slack_handle TEXT, teams_handle TEXT, CHECK ((slack_handle IS NULL) XOR (teams_handle IS NULL)));"},{"body":"XOR with 1 turns 0 into 1 and back, so one UPDATE toggles a row without reading it first.","sql":"UPDATE preferences SET dark_mode = dark_mode XOR 1 WHERE user_id = 42;"},{"body":"MySQL: comparing OLD and NEW with XOR fires the audit write only when the boolean actually flipped, not on every no-op UPDATE.","sql":"IF (OLD.dark_mode IS TRUE) XOR (NEW.dark_mode IS TRUE) THEN INSERT INTO audit(user_id, changed) VALUES (NEW.user_id, NOW()); END IF"}]},"source_url":"https://sqlly.app/sql-functions/xor","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/year","corpus":"sql-functions","engine":null,"language":"en","title":"SQL YEAR function","description":"Get the year from a date: YEAR() on SQL Server and MySQL, EXTRACT(year FROM d) on PostgreSQL, MySQL and Oracle, strftime('%Y', d) on SQLite.","body":{"slug":"year","name":"YEAR","h1":"SQL YEAR function","category":"datetime","lede":"Returns the calendar year, the standard GROUP BY key for per-year reporting on every engine. SQL Server and MySQL return an integer; PostgreSQL returns numeric from EXTRACT and double precision from date_part; SQLite's strftime returns text.","syntax":"YEAR(d)  |  EXTRACT(year FROM d)  |  strftime('%Y', d)  -- SQLite, returns text","return_type":"integer","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"partial","note":"EXTRACT(year FROM d) or date_part('year', d)"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%Y', d) returns text; CAST it"},{"engine_slug":"oracle","status":"partial","note":"EXTRACT(year FROM d); there is no YEAR() function"}],"gotchas":["SQLite's strftime returns text: GROUP BY works, but comparing to a number fails until you CAST the result to INTEGER.","PostgreSQL and Oracle have no YEAR() function (Oracle raises ORA-00904); use EXTRACT. SQL Server is the opposite: YEAR() works, EXTRACT does not exist.","WHERE YEAR(created_at) = 2024 cannot seek an index on created_at (MySQL and SQL Server scan instead); created_at >= '2024-01-01' AND created_at < '2025-01-01' can."],"examples":[{"engine_slug":"postgresql","sql":"SELECT EXTRACT(year FROM created_at) AS yr FROM orders;"},{"engine_slug":"sql-server","sql":"SELECT YEAR(created_at) AS yr FROM orders;"},{"engine_slug":"sqlite","sql":"SELECT CAST(strftime('%Y', created_at) AS INTEGER) AS yr FROM orders;"},{"engine_slug":"mysql","sql":"SELECT YEAR(created_at) AS yr FROM orders;"},{"engine_slug":"oracle","sql":"SELECT EXTRACT(year FROM created_at) AS yr FROM orders;"}],"faqs":[{"question":"Is YEAR(d) the same as EXTRACT(year FROM d)?","answer":"Yes, both return the calendar year. YEAR() is the shorthand SQL Server and MySQL accept; EXTRACT is the standard form used by PostgreSQL, MySQL and Oracle."},{"question":"Why does my SQLite comparison return nothing?","answer":"strftime('%Y', d) yields text, so comparing to the number 2024 never matches. CAST(strftime('%Y', d) AS INTEGER) fixes it."}],"related":["extract","month","day"],"novel_uses":[{"body":"YEAR(created_at) is deterministic, so a persisted computed column plus an index gives cheap per-year filters without rewriting every query into a range form.","sql":"ALTER TABLE orders ADD order_year AS YEAR(created_at) PERSISTED;\nCREATE INDEX ix_orders_year ON orders (order_year);"},{"body":"MySQL accepts YEAR(created_at) as a RANGE partitioning function, so yearly partitions prune on the column while queries keep using plain date comparisons.","sql":"ALTER TABLE orders PARTITION BY RANGE (YEAR(created_at)) (\n    PARTITION p2023 VALUES LESS THAN (2024),\n    PARTITION p2024 VALUES LESS THAN (2025),\n    PARTITION pmax VALUES LESS THAN MAXVALUE);"}]},"source_url":"https://sqlly.app/sql-functions/year","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/yearweek","corpus":"sql-functions","engine":null,"language":"en","title":"SQL YEARWEEK function","description":"MySQL's YEARWEEK returns year and week as one number like 202403, with a mode argument picking Sunday-start or ISO weeks, so late-December dates land in the right year.","body":{"slug":"yearweek","name":"YEARWEEK","h1":"SQL YEARWEEK function","category":"datetime","lede":"Returns a combined year-week integer where the year follows the week, so December 30 can land in 202501 under ISO mode 3.","syntax":"YEARWEEK(d)  -- mode 0  |  YEARWEEK(d, 3)  -- ISO week  |  TO_CHAR(d, 'IYYYIW')  -- PostgreSQL equivalent","return_type":"integer","support":[{"engine_slug":"sql-server","status":"partial","note":"DATEPART(iso_week, d) plus a computed ISO year"},{"engine_slug":"postgresql","status":"partial","note":"to_char(d, 'IYYYIW')"},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"partial","note":"strftime('%G%V', d) on SQLite 3.46+"},{"engine_slug":"oracle","status":"partial","note":"TO_CHAR(d, 'IYYYIW')"}],"gotchas":["Without the year, week grouping merges across years: GROUP BY WEEK(d) pools week 3 of every year; YEARWEEK(d, 3) keeps years separate.","Mode 3 is ISO: weeks start Monday and week 1 holds the first Thursday. The default mode 0 starts weeks on Sunday, so YEARWEEK('2024-12-30') is 202452.","Before SQLite 3.46 there is no ISO week code: combining %Y with %W gives year 2024 for 2024-12-30 (202453) where ISO says 2025 (202501). Use %G%V on 3.46+."],"examples":[{"engine_slug":"mysql","sql":"SELECT YEARWEEK('2024-12-30', 3) AS iso_yw;  -- 202501"},{"engine_slug":"mysql","sql":"SELECT YEARWEEK(created_at, 3) AS wk, COUNT(*) FROM orders GROUP BY wk;"},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(d, 'IYYYIW') AS iso_yw FROM events;"},{"engine_slug":"sql-server","sql":"SELECT YEAR('2024-12-30') AS yr, DATEPART(ISO_WEEK, '2024-12-30') AS iso_wk;  -- 2024 vs 1, hence the computed ISO year"},{"engine_slug":"sqlite","sql":"SELECT strftime('%G%V', created_at) AS iso_yw FROM orders;  -- 3.46+"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(created_at, 'IYYYIW') AS iso_yw FROM orders;"}],"faqs":[{"question":"Why does YEARWEEK('2024-12-30', 3) return 202501?","answer":"Under ISO rules that date falls in the first week of 2025: the year follows the week, which is exactly the point of the function."},{"question":"What is the SQL Server equivalent?","answer":"There is no iso_year datepart. YEAR(DATEADD(day, 26 - DATEPART(iso_week, d), d)) * 100 + DATEPART(iso_week, d) reproduces YEARWEEK(d, 3)."}],"related":["week","date-trunc","extract"],"novel_uses":[{"body":"Split and repad the compound key: YEARWEEK(d, 3) DIV 100 is the year and MOD 100 with LPAD is the week, so 202501 renders as '2025-W01' for reports.","sql":"SELECT CONCAT(YEARWEEK(d, 3) DIV 100, '-W', LPAD(YEARWEEK(d, 3) % 100, 2, '0')) AS label FROM events;"},{"body":"Compare YEARWEEK(d, 3) against LAG of the same value over an ordered set and every first-event-of-the-week row flags true, with no GROUP BY needed.","sql":"SELECT d,\n       COALESCE(YEARWEEK(d, 3) <> LAG(YEARWEEK(d, 3)) OVER (ORDER BY d), TRUE) AS new_week\nFROM events;"}]},"source_url":"https://sqlly.app/sql-functions/yearweek","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/zero-pad","corpus":"sql-functions","engine":null,"language":"en","title":"SQL zero-padding pattern","description":"Pad numbers with leading zeros per engine: LPAD, printf, FORMAT and TO_CHAR patterns, and the truncation and cast-back traps of each.","body":{"slug":"zero-pad","name":"Zero-padding numbers","h1":"SQL zero-padding pattern","category":"string","lede":"Turn 42 into 00042 for codes and fixed-width exports. Every engine has a native route; LPAD (PostgreSQL, MySQL) and the RIGHT idiom (SQL Server) truncate values wider than the pad, while printf and FORMAT widen them instead.","syntax":"LPAD(n::text, 5, '0')  |  printf('%05d', n)  |  FORMAT(n, '00000')","return_type":"string","support":[{"engine_slug":"sql-server","status":"yes","note":null},{"engine_slug":"postgresql","status":"yes","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"yes","note":null},{"engine_slug":"oracle","status":"yes","note":null}],"gotchas":["LPAD truncates when the value is longer than the target width: LPAD('123456', 5, '0') is '12345', silently. Check lengths if the input is unbounded.","The output is a string; casting it back to a number drops the zeros, and CSV/Excel may do the same on import.","Oracle's TO_CHAR needs the FM prefix to suppress the sign placeholder: TO_CHAR(42, 'FM000000'), not '000000' which pads a leading blank.","SQL Server has no LPAD: FORMAT(n, '00000') or RIGHT('00000' + CAST(n AS varchar(10)), 5) are the idioms."],"examples":[{"engine_slug":"postgresql","sql":"SELECT LPAD(420::text, 5, '0') AS padded;  -- 00420"},{"engine_slug":"sqlite","sql":"SELECT printf('%05d', 42) AS padded;  -- 00042"},{"engine_slug":"sql-server","sql":"SELECT FORMAT(42, '00000') AS padded;  -- 00042"},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(42, 'FM000000') AS padded FROM dual;  -- 000042"},{"engine_slug":"mysql","sql":"SELECT LPAD(42, 5, '0') AS padded;  -- 00042"}],"faqs":[{"question":"Why does LPAD give me '12345' instead of '0012345'?","answer":"LPAD pads up to the target length and truncates anything longer. Widen the target or validate the input before padding."},{"question":"How do I zero-pad in SQL Server?","answer":"FORMAT(n, '00000') for numbers, or the classic RIGHT('00000' + CAST(n AS varchar(10)), 5) when FORMAT's cost matters on large sets. The RIGHT form puts the sign inside the zeros (-42 becomes 00-42), so use FORMAT for signed values (FORMAT(-42, '00000') gives -00042)."},{"question":"Why do my leading zeros disappear after export?","answer":"The zeros only exist in the string. Excel, casts and numeric columns all drop them. Keep the column textual end to end, or emit a format hint in CSV."}],"related":["lpad","printf","format","zerofill"],"novel_uses":[{"body":"LPAD pads the string you give it, so a negative number comes out as 00-42; pad the ABS and prepend the sign instead.","sql":"SELECT CASE WHEN n < 0 THEN '-' ELSE '' END || LPAD(ABS(n)::TEXT, 5, '0') AS padded FROM t;"},{"body":"A PostgreSQL expression index on LPAD(code::TEXT, 8, '0') lets ORDER BY and joins on the padded value use the index instead of computing it per row.","sql":"CREATE INDEX t_code_padded ON t ((LPAD(code::TEXT, 8, '0')));"}]},"source_url":"https://sqlly.app/sql-functions/zero-pad","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/zeroblob","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ZEROBLOB function","description":"SQLite's ZEROBLOB(N) makes an N-byte blob of zeros: the placeholder for incremental blob I/O and sized blobs, not random data.","body":{"slug":"zeroblob","name":"ZEROBLOB","h1":"SQL ZEROBLOB function","category":"conversion","lede":"zeroblob(1048576) inserts a megabyte of zero bytes. Its main job is reserving space that the C API's sqlite3_blob_write then fills in place.","syntax":"ZEROBLOB(N)","return_type":"blob","support":[{"engine_slug":"sql-server","status":"no","note":"no direct twin; CAST(0x AS binary(n)) pads with zeros"},{"engine_slug":"postgresql","status":"no","note":"no direct twin; decode(repeat('00', n), 'hex')"},{"engine_slug":"mysql","status":"no","note":"no direct twin; REPEAT(x'00', n) or CAST('' AS BINARY(n))"},{"engine_slug":"sqlite","status":"yes","note":"the native one"},{"engine_slug":"oracle","status":"no","note":"no direct twin; HEXTORAW(RPAD('0', 2 * n, '0')) up to 2000 bytes"}],"gotchas":["Its main use is the C API's incremental blob I/O: allocate a zeroblob, then write through sqlite3_blob_write in place instead of materialising the whole blob in SQL.","Zeros, not NULL: the blob contains N zero bytes and length(zeroblob(N)) is N, x'00' repeated, a real value that occupies space.","Elsewhere: REPEAT(x'00', N) approximates on MySQL, decode(repeat('00', n), 'hex') on PostgreSQL; neither has the incremental-write pairing."],"examples":[{"engine_slug":"sqlite","sql":"SELECT length(zeroblob(64)) AS n;"},{"engine_slug":"sqlite","sql":"INSERT INTO blobs (data)\nVALUES (zeroblob(1048576));"}],"faqs":[{"question":"Why preallocate zeros?","answer":"For sqlite3_blob_write: reserve N bytes in one step, then fill pages in place without rewriting ever-larger blobs through UPDATE. Also handy as explicit sized padding."},{"question":"Is zeroblob the same as NULL?","answer":"No, it is a blob of N zero bytes with length N. A NULL blob has no length; zeroblob(0) has length 0 and is still a value."}],"related":["randomblob","hex","binary-cast","length"],"novel_uses":null},"source_url":"https://sqlly.app/sql-functions/zeroblob","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-functions/zerofill","corpus":"sql-functions","engine":null,"language":"en","title":"SQL ZEROFILL attribute","description":"MySQL's ZEROFILL pads integer output with zeros to the column's display width, deprecated since 8.0.17, and replaceable with LPAD in the query.","body":{"slug":"zerofill","name":"ZEROFILL","h1":"SQL ZEROFILL attribute","category":"string","lede":"A column attribute, not a function: it left-pads SELECT output with zeros to at least the declared display width; wider values print in full., and implies UNSIGNED.","syntax":"region SMALLINT ZEROFILL","return_type":"string","support":[{"engine_slug":"sql-server","status":"no","note":null},{"engine_slug":"postgresql","status":"no","note":null},{"engine_slug":"mysql","status":"yes","note":null},{"engine_slug":"sqlite","status":"no","note":null},{"engine_slug":"oracle","status":"no","note":null}],"gotchas":["Deprecated as of MySQL 8.0.17: new schemas should not use it, and the paired display-width attribute is deprecated too.","ZEROFILL implies UNSIGNED: a signed column silently becomes unsigned the moment you add the keyword.","It pads in result formatting, not in storage: WHERE, joins and comparisons see the raw number; the padding also appears in CAST(... AS CHAR) output, so an LPAD on a ZEROFILL column adds nothing.","On a plain integer column the MySQL in-query replacement is LPAD(CAST(n AS CHAR), width, '0'); it is MySQL-specific, because bare CAST yields a one-character string on PostgreSQL, so use the portable forms in the FAQ instead."],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE codes (region SMALLINT(5) ZEROFILL);"},{"engine_slug":"mysql","sql":"SELECT LPAD(CAST(region AS CHAR), 5, '0') AS region_code FROM codes;  -- 00042"}],"faqs":[{"question":"Is ZEROFILL deprecated?","answer":"Yes. MySQL 8.0.17 deprecated ZEROFILL and display widths. Existing tables still work, but new schemas should pad in queries instead."},{"question":"Does ZEROFILL change stored values?","answer":"No. Storage is the plain unsigned integer; the zeros appear in query output and in CAST(... AS CHAR) text, formatted to the declared display width."},{"question":"How do I get the same effect portably?","answer":"LPAD(CAST(n AS CHAR), width, '0') on MySQL, LPAD(n::text, width, '0') on PostgreSQL, LPAD(TO_CHAR(n), width, '0') on Oracle, printf('%05d', n) on SQLite and FORMAT(n, '00000') on SQL Server. A bare CAST(n AS CHAR) means CHAR(1) on PostgreSQL and Oracle, so it does not port."}],"related":["zero-pad","lpad","format"],"novel_uses":[{"body":"information_schema.COLUMNS shows the attribute in COLUMN_TYPE, so one query lists every column the deprecated flag still touches.","sql":"SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = 'app' AND COLUMN_TYPE LIKE '%zerofill';"},{"body":"MODIFY redeclares the column and removes ZEROFILL and the display width together; SHOW CREATE TABLE before and after confirms nothing else moved.","sql":"ALTER TABLE codes MODIFY region SMALLINT UNSIGNED;  -- drops ZEROFILL and display width"}]},"source_url":"https://sqlly.app/sql-functions/zerofill","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
