{"id":"sql-dialects/add-column","corpus":"sql-dialects","engine":null,"language":"en","title":"Add a column to an existing table","description":"ALTER TABLE ADD COLUMN in five dialects, including multiple columns per statement and SQLite's single-column restriction.","body":{"slug":"add-column","name":"Add column","h1":"Add a column to an existing table","category":"ddl","lede":"The most common ALTER: extend the table without losing data.","intro":"Adding a nullable column without a default only changes metadata in all five engines, so it is instant even on huge tables. The differences: SQLite allows one column per statement, MySQL can position the column, and a NOT NULL column on a table with rows needs a DEFAULT to fill them.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE customers ADD phone VARCHAR(40) NULL;","note":"No COLUMN keyword; comma-separate several columns. Adding NOT NULL with a constant DEFAULT is metadata-only on Enterprise edition (2012+); other editions write the default into every row."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers ADD COLUMN phone TEXT;","note":"COLUMN is optional. Since 11, NOT NULL with a constant DEFAULT also skips the table rewrite; a volatile default such as random() still rewrites."},{"engine_slug":"mysql","sql":"ALTER TABLE customers ADD COLUMN phone VARCHAR(40) AFTER email;","note":"FIRST and AFTER position the column. ALGORITHM=INSTANT covers columns added last from 8.0.12 and at any position from 8.0.29."},{"engine_slug":"sqlite","sql":"ALTER TABLE customers ADD COLUMN phone TEXT;","note":"One column per statement, always appended last. It can't be PRIMARY KEY or UNIQUE, and NOT NULL needs a non-NULL default; defaults must be constants."},{"engine_slug":"oracle","sql":"ALTER TABLE customers ADD (phone VARCHAR2(40));","note":"The parenthesized list adds several columns at once. Adding a column with a DEFAULT is metadata-only too: for NOT NULL columns since 11g, for nullable ones since 12c."}],"verdict":"Same verb everywhere. The practical rules: a nullable column is instant, a NOT NULL column needs a DEFAULT, SQLite takes one column per statement, and only MySQL lets you choose the position.","faqs":[{"question":"Why does NOT NULL need a DEFAULT?","answer":"Existing rows must get some value for the new column. With a constant DEFAULT, most current versions record it once in the metadata instead of rewriting every row. On an empty table, NOT NULL without a default is accepted everywhere except SQLite."},{"question":"Can I add a column with a computed value?","answer":"Add the column, then fill it with an UPDATE, in batches on a big table. If the value should always be derived from other columns, declare a generated column instead (see generated-columns)."},{"question":"How do I add a column in the middle of the table?","answer":"Only MySQL (and MariaDB) offer FIRST and AFTER. Elsewhere you would have to rebuild the table, and column order only matters to SELECT *, which application code shouldn't rely on."}],"related":["drop-column","add-drop-default","generated-columns"]},"source_url":"https://sqlly.app/sql-dialects/add-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/add-constraint","corpus":"sql-dialects","engine":null,"language":"en","title":"Add a foreign key or check constraint","description":"ALTER TABLE ADD CONSTRAINT with ON DELETE CASCADE and CHECK everywhere but SQLite, which needs the table rebuilt.","body":{"slug":"add-constraint","name":"Add constraint","h1":"Add a foreign key or check constraint","category":"ddl","lede":"Wire tables together or give them a rule: one ALTER, unless you are on SQLite.","intro":"SQL Server, PostgreSQL, MySQL and Oracle share ADD CONSTRAINT for foreign keys (with ON DELETE CASCADE) and CHECK rules. SQLite has no ADD CONSTRAINT at all: constraints live in the CREATE TABLE, so adding one means rebuilding the table with it declared.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;\nALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0);","note":"ALTER TABLE orders WITH NOCHECK ADD CONSTRAINT … skips checking existing rows. It is fast, but the constraint stays untrusted, and the optimizer ignores it, until you run WITH CHECK CHECK CONSTRAINT."},{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;\nALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0);","note":"ADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT in a second (short-lock) transaction, keeps big tables available."},{"engine_slug":"mysql","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;\nALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0);","note":"InnoDB enforces both and creates an index on customer_id if none exists. CHECK is enforced since 8.0.16; older versions parsed it and ignored it."},{"engine_slug":"sqlite","sql":"PRAGMA foreign_keys = OFF;\nBEGIN;\nCREATE TABLE orders_new (id INTEGER PRIMARY KEY, customer_id INTEGER\n  REFERENCES customers (id) ON DELETE CASCADE, total REAL CHECK (total >= 0));\nINSERT INTO orders_new SELECT id, customer_id, total FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;\nCOMMIT;\nPRAGMA foreign_keys = ON;","note":"No ADD CONSTRAINT: constraints live in the CREATE TABLE, so rebuild. Foreign keys are only enforced when PRAGMA foreign_keys = ON, which is off by default on every new connection."},{"engine_slug":"oracle","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;\nALTER TABLE orders ADD CONSTRAINT ck_orders_total CHECK (total >= 0);","note":"Appending ENABLE NOVALIDATE adds the constraint without checking existing rows; RELY tells the optimizer to trust it anyway. Oracle has no ON UPDATE CASCADE."}],"verdict":"ADD CONSTRAINT reads the same on four engines; SQLite's rebuild is the price of keeping constraints in the stored CREATE TABLE text.","faqs":[{"question":"Why add a constraint NOT VALID first?","answer":"Validation scans the whole table while holding a lock. In PostgreSQL, ADD CONSTRAINT … NOT VALID applies the rule to new writes immediately with only a brief lock, and VALIDATE CONSTRAINT later checks old rows under a lock that still allows reads and writes."},{"question":"What does ON DELETE CASCADE do exactly?","answer":"Deleting a customers row deletes its orders automatically. SET NULL, NO ACTION and RESTRICT are the other actions (Oracle supports CASCADE and SET NULL only). SQLite supports them all, but only with PRAGMA foreign_keys = ON."},{"question":"Can I add a constraint without checking old data?","answer":"SQL Server: WITH NOCHECK. PostgreSQL: NOT VALID. Oracle: ENABLE NOVALIDATE. MySQL: SET foreign_key_checks = 0 before adding a foreign key skips the check; CHECK constraints are always checked unless declared NOT ENFORCED. SQLite checks nothing when copying rows during the rebuild; run PRAGMA foreign_key_check afterwards."}],"related":["truncate-vs-delete","generated-columns","delete-with-join"]},"source_url":"https://sqlly.app/sql-dialects/add-constraint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/add-days","corpus":"sql-dialects","engine":null,"language":"en","title":"Add days to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Plain number arithmetic in PostgreSQL and Oracle, DATEADD in SQL Server, INTERVAL units in MySQL, and a text modifier in SQLite.","body":{"slug":"add-days","name":"Add days to a date","h1":"Add days to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Five engines, five spellings of 'a week from today'.","intro":"Adding days is the most common date arithmetic, and it is the clearest window into each engine's model: real date types add numbers directly, while text-based or function-based engines need a dedicated call.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(DAY, 7, '2026-11-20');","note":"No + on DATE values: DATEADD covers every unit and keeps the input's type. A string literal is read as datetime, so this returns 2026-11-27 00:00:00.000."},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-11-20' + 7;","note":"An integer adds days to a date; add INTERVAL '7 days' to a timestamp instead."},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-11-20', INTERVAL 7 DAY);","note":"INTERVAL n DAY is the general mechanism. '2026-11-20' + 7 coerces the string to the number 2026 and returns 2033."},{"engine_slug":"sqlite","sql":"SELECT DATE(due_date, '+7 days') FROM invoices;","note":"Dates are text: modifiers like '+7 days' chain after the base time, e.g. DATE('now', '+7 days')."},{"engine_slug":"oracle","sql":"SELECT DATE '2026-11-20' + 7 FROM dual;","note":"Adding a number to a DATE adds that many days; fractions add time (1/24 is one hour)."}],"verdict":"PostgreSQL and Oracle read like arithmetic, MySQL and SQL Server read like function calls, and SQLite reads like a tiny language of modifiers. None of it ports without rewriting.","faqs":[{"question":"Can I add hours and minutes too?","answer":"Yes: DATEADD(HOUR, ...) in SQL Server, INTERVAL '7 hours' in PostgreSQL, INTERVAL 7 HOUR in MySQL, '+7 hours' in SQLite, and fractions of a day in Oracle (DATE + 4.5/24)."},{"question":"Why does MySQL '2026-11-20' + 7 return a number?","answer":"In numeric context MySQL reads the string's leading number, 2026, and returns 2033 with a warning. A real DATE fares no better: DATE '2026-11-20' + 7 is 20261127. Date arithmetic goes through DATE_ADD/DATE_SUB or + INTERVAL."},{"question":"Does adding days cross DST correctly?","answer":"PostgreSQL's timestamptz does: adding INTERVAL '1 day' across a DST change keeps the wall-clock time, while INTERVAL '24 hours' adds exactly 24 hours. SQL Server's DATEADD on datetimeoffset keeps the offset fixed, and naive date and timestamp types everywhere just add calendar days."}],"related":["add-months","interval-literals","timezone-convert"]},"source_url":"https://sqlly.app/sql-dialects/add-days","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/add-drop-default","corpus":"sql-dialects","engine":null,"language":"en","title":"Set or remove a column default","description":"SET DEFAULT and DROP DEFAULT in PostgreSQL, MySQL and Oracle; named DEFAULT constraints in SQL Server; a rebuild in SQLite.","body":{"slug":"add-drop-default","name":"Column defaults","h1":"Set or remove a column default","category":"ddl","lede":"Defaults are cheap to change, except where they are constraints or where they are frozen in the CREATE TABLE.","intro":"Three engines treat a default as a column attribute with SET / DROP DEFAULT (Oracle spells it MODIFY … DEFAULT). SQL Server models it as a named constraint you add and drop. SQLite can't change a default at all: it is part of the stored CREATE TABLE text, so changing it means rebuilding the table.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE customers\n  ADD CONSTRAINT df_customers_email DEFAULT 'unknown' FOR email;\nALTER TABLE customers DROP CONSTRAINT df_customers_email;","note":"A default is a constraint object: to change one, drop the old constraint and add a new one. There is no ALTER COLUMN SET DEFAULT."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers ALTER COLUMN email SET DEFAULT 'unknown';\nALTER TABLE customers ALTER COLUMN email DROP DEFAULT;","note":"Metadata-only and instant; only rows inserted afterwards are affected."},{"engine_slug":"mysql","sql":"ALTER TABLE customers ALTER COLUMN email SET DEFAULT 'unknown';\nALTER TABLE customers ALTER COLUMN email DROP DEFAULT;","note":"Same shape as PostgreSQL, with one difference: after DROP DEFAULT the column has no default at all, so in strict mode an INSERT that omits it fails with error 1364 even when the column is nullable. Expression defaults such as (UUID()) need 8.0.13+ and parentheses."},{"engine_slug":"sqlite","sql":"CREATE TABLE customers_new (id INTEGER PRIMARY KEY, email TEXT DEFAULT 'unknown');\nINSERT INTO customers_new SELECT id, email FROM customers;\nDROP TABLE customers;\nALTER TABLE customers_new RENAME TO customers;","note":"No ALTER for defaults: the default lives in the CREATE TABLE. This rebuild sets the default; removing it is the same rebuild without the DEFAULT clause. Run it in a transaction with PRAGMA foreign_keys = OFF."},{"engine_slug":"oracle","sql":"ALTER TABLE customers MODIFY (email DEFAULT 'unknown');\nALTER TABLE customers MODIFY (email DEFAULT NULL);","note":"MODIFY … DEFAULT sets it; DEFAULT NULL is how you remove it. Only new inserts are affected."}],"verdict":"PostgreSQL, MySQL and Oracle change a default in one short statement. SQL Server's constraint handling takes more ceremony but works; SQLite is the one engine where changing a default means rebuilding the table.","faqs":[{"question":"Does changing a default affect existing rows?","answer":"No, in every engine. Defaults apply when a row is inserted without that column; existing rows keep whatever they store. (Adding a new column with a default is different: that fills existing rows.)"},{"question":"Why is SQL Server's default a constraint?","answer":"SQL Server stores each default as an object in sys.default_constraints. If you don't name it, it gets a generated name like DF__customers__email__3B75D760, which differs per database, so migration scripts have to look the name up before dropping it. Name your defaults."},{"question":"Can a default be an expression?","answer":"PostgreSQL: any expression without subqueries or column references. SQL Server: constants and functions such as GETDATE() or NEWID(). MySQL: parenthesized expressions from 8.0.13. Oracle: expressions such as SYSDATE, plus sequence.NEXTVAL since 12c. SQLite: constants, CURRENT_TIMESTAMP and the like, or a constant expression in parentheses."}],"related":["add-column","alter-column-type","add-constraint"]},"source_url":"https://sqlly.app/sql-dialects/add-drop-default","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/add-months","corpus":"sql-dialects","engine":null,"language":"en","title":"Add months to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Month arithmetic clamps to the month end in most engines and overflows in SQLite: DATEADD, INTERVAL, date modifiers and ADD_MONTHS compared.","body":{"slug":"add-months","name":"Add months to a date","h1":"Add months to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Jan 31 plus one month is Feb 28 in four engines, Mar 3 in SQLite, and an error with Oracle's INTERVAL form.","intro":"Adding months is trickier than adding days because month lengths differ. Each engine has a rule for what Jan 31 + 1 month means, and they do not all agree.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(MONTH, 3, '2026-11-20');","note":"Adds calendar months and clamps: DATEADD(MONTH, 1, '2026-01-31') is 2026-02-28. It keeps the day number otherwise, so Feb 28 + 1 month is Mar 28."},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-11-20' + INTERVAL '3 months';","note":"Jan 31 + 1 month gives Feb 28: interval arithmetic clamps to the end of the target month."},{"engine_slug":"mysql","sql":"SELECT DATE_ADD('2026-11-20', INTERVAL 3 MONTH);","note":"Clamps to month end: Jan 31 + 1 month is Feb 28/29."},{"engine_slug":"sqlite","sql":"SELECT DATE(started_at, '+3 months') FROM subscriptions;","note":"Does not clamp: '+1 month' on 2026-01-31 builds Feb 31, which normalizes forward to 2026-03-03. SQLite 3.46+ accepts a 'floor' modifier, DATE(d, '+1 month', 'floor'), that clamps to Feb 28 instead."},{"engine_slug":"oracle","sql":"SELECT ADD_MONTHS(DATE '2026-11-20', 3) FROM dual;","note":"ADD_MONTHS clamps, and a month-end input always maps to the target month's last day (Feb 28 + 1 month is Mar 31). DATE '2026-01-31' + INTERVAL '1' MONTH raises ORA-01839 instead."}],"verdict":"SQL Server, PostgreSQL, MySQL and Oracle's ADD_MONTHS clamp Jan 31 + 1 month to Feb 28/29. SQLite rolls into March unless you add 'floor', and Oracle's INTERVAL form errors. ADD_MONTHS also snaps month-end inputs to month ends, so test month-end dates explicitly.","faqs":[{"question":"Why does SQLite give Mar 3 for Jan 31 + 1 month?","answer":"SQLite adds 1 to the month field and keeps day 31. Feb 31 does not exist, so it normalizes forward to Mar 3. On 3.46 and later, append the 'floor' modifier to clamp to Feb 28 instead."},{"question":"When does Oracle's INTERVAL month form fail?","answer":"SYSDATE + INTERVAL '1' MONTH raises ORA-01839 on a date whose day does not exist in the target month. ADD_MONTHS handles it by clamping, so most shops standardize on ADD_MONTHS."},{"question":"Do all engines agree on clamping otherwise?","answer":"SQL Server, PostgreSQL and MySQL clamp to the last day of the target month and otherwise keep the day number. Oracle's ADD_MONTHS also maps any month-end input to a month end, so ADD_MONTHS(DATE '2026-02-28', 1) is Mar 31 while DATEADD gives Mar 28. SQLite is the outlier that overflows."}],"related":["add-days","first-day-of-month","last-day-of-month"]},"source_url":"https://sqlly.app/sql-dialects/add-months","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/advisory-locks","corpus":"sql-dialects","engine":null,"language":"en","title":"Advisory and application locks in every SQL dialect","description":"Acquire a named lock unrelated to any row or table, to serialize application work like cron jobs or report generation.","body":{"slug":"advisory-locks","name":"Application locks","h1":"Advisory and application locks in every SQL dialect","category":"admin","lede":"Application locks let code coordinate across servers through the database: lock a name, do the work, release.","intro":"Four engines have one, each with a different shape: named locks with timeouts in MySQL, 64-bit-key locks in PostgreSQL, a stored procedure in SQL Server and a package in Oracle. SQLite has none.","rows":[{"engine_slug":"sql-server","sql":"BEGIN TRANSACTION;\nDECLARE @r INT;\nEXEC @r = sp_getapplock @Resource = 'report_job', @LockMode = 'Exclusive', @LockOwner = 'Transaction', @LockTimeout = 10000;\n-- @r >= 0 means acquired; do the work here\nCOMMIT; -- releases the lock","note":"Locks are per database. Owner 'Transaction' (the default) needs an open transaction, or the call fails with -999, and releases at COMMIT; 'Session' lasts until sp_releaseapplock or disconnect. Return codes: 0 granted, 1 granted after waiting, -1 timeout, -2 cancelled, -3 deadlock victim."},{"engine_slug":"postgresql","sql":"SELECT pg_advisory_lock(918273);\n-- ... serialized work ...\nSELECT pg_advisory_unlock(918273);","note":"Locks on a bigint (or two ints) key, held per session until unlocked or disconnect. Variants: pg_try_advisory_lock (non-blocking), xact variants released at commit, shared mode."},{"engine_slug":"mysql","sql":"SELECT GET_LOCK('report_job', 10);\n-- returns 1 = acquired, 0 = timeout\nSELECT RELEASE_LOCK('report_job');","note":"Named locks at connection scope; IS_FREE_LOCK and IS_USED_LOCK check state. Releasing happens implicitly when the connection drops."},{"engine_slug":"sqlite","sql":"-- no application locks; coordinate in application code or via a lock table","note":"No named-lock facility. A common trick: INSERT into a jobs/locks table with a UNIQUE column; the successful insert owns the work."},{"engine_slug":"oracle","sql":"DECLARE\n  h VARCHAR2(128);\nBEGIN\n  DBMS_LOCK.ALLOCATE_UNIQUE('report_job', h);\n  IF DBMS_LOCK.REQUEST(h, DBMS_LOCK.X_MODE, 10) = 0 THEN\n    -- ... serialized work ...\n    IF DBMS_LOCK.RELEASE(h) = 0 THEN NULL; END IF;\n  END IF;\nEND;\n/","note":"Needs EXECUTE on DBMS_LOCK. ALLOCATE_UNIQUE maps a name to a handle (and commits); REQUEST takes a mode and a timeout in seconds and returns 0 on success, 1 on timeout. Without RELEASE the lock lasts until the session ends."}],"verdict":"Four facilities, four APIs, and SQLite with none. PostgreSQL's advisory locks are the closest to a real API, MySQL's GET_LOCK is the simplest, and SQL Server and Oracle both wrap the feature in procedural code.","faqs":[{"question":"Why use these instead of a table lock?","answer":"They serialize application work without touching data: only one node runs the nightly job, without a scheduler column or polling races."},{"question":"What happens if my session dies holding one?","answer":"All four engines release the lock when the owning session ends, so crashes do not leave permanent locks behind. Transaction-scoped locks (SQL Server's default owner, PostgreSQL's pg_advisory_xact_lock) go even earlier, at commit or rollback."},{"question":"PostgreSQL lock key in two ints?","answer":"pg_advisory_lock takes one bigint or two int4 values; the two-int form is handy for namespaces like (app_id, job_id)."}],"related":["select-for-update","lock-timeout","kill-session"]},"source_url":"https://sqlly.app/sql-dialects/advisory-locks","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/alter-column-type","corpus":"sql-dialects","engine":null,"language":"en","title":"Change a column's type","description":"ALTER COLUMN, ALTER TYPE USING, MODIFY COLUMN, and the rebuilds Oracle and SQLite need: changing a column's type in five dialects.","body":{"slug":"alter-column-type","name":"Alter column type","h1":"Change a column's type","category":"ddl","lede":"Convert a column's data to a new type in place, with PostgreSQL's USING or the engine's implicit cast.","intro":"Each example turns a text zip column into an integer. SQL Server, PostgreSQL and MySQL convert existing data in one ALTER; PostgreSQL's USING clause lets you say exactly how. Oracle changes a column's datatype only when the column is empty, and SQLite has no ALTER for types at all, so both rebuild: copy into a new column or table, drop, rename.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE customers ALTER COLUMN zip INT NULL;","note":"Restate the full definition, including NULL or NOT NULL, or nullability can change. Fails if any value won't convert, or while an index, constraint or schema-bound view uses the column."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers\nALTER COLUMN zip TYPE INTEGER USING zip::integer;","note":"USING gives the conversion expression; without it, text to integer is refused because there is no implicit cast. The table and its indexes are rewritten."},{"engine_slug":"mysql","sql":"ALTER TABLE customers MODIFY COLUMN zip INT;","note":"MODIFY replaces the whole definition, so restate NOT NULL, DEFAULT and COMMENT or they are dropped. Type changes copy the table (ALGORITHM=COPY) and block writes meanwhile."},{"engine_slug":"sqlite","sql":"CREATE TABLE customers_new (zip INTEGER, email TEXT);\nINSERT INTO customers_new SELECT CAST(zip AS INTEGER), email FROM customers;\nDROP TABLE customers;\nALTER TABLE customers_new RENAME TO customers;","note":"No ALTER COLUMN TYPE. Run the rebuild in a transaction with PRAGMA foreign_keys = OFF, then recreate indexes, triggers and views."},{"engine_slug":"oracle","sql":"ALTER TABLE customers ADD (zip_num NUMBER(10));\nUPDATE customers SET zip_num = TO_NUMBER(zip);\nALTER TABLE customers DROP COLUMN zip;\nALTER TABLE customers RENAME COLUMN zip_num TO zip;","note":"MODIFY (zip NUMBER(10)) fails with ORA-01439 unless the column is empty. Within a type family, MODIFY works on data: widening VARCHAR2 is metadata-only, while shrinking NUMBER precision also needs an empty column."}],"verdict":"SQL Server, PostgreSQL and MySQL change the type in one statement, and PostgreSQL's USING is the only syntax that lets you transform the data as part of it. Oracle and SQLite need the add-copy-drop-rename pattern for a real type change, which is also what every engine uses for zero-downtime changes on big tables.","faqs":[{"question":"Why does SQLite force a rebuild?","answer":"SQLite stores the table definition as the original CREATE TABLE text, and ALTER TABLE can only rename, add or drop columns. Declared types are affinity hints, so a TEXT column already accepts integers; you rebuild when you need the new affinity or a stricter definition."},{"question":"What can go wrong narrowing a type?","answer":"SQL Server raises a conversion or truncation error and changes nothing. MySQL in strict mode (the 8.0 default) errors too; without strict mode it truncates with a warning. Oracle refuses with ORA-01441 or ORA-01440. Look for values that won't fit first, for example WHERE LEN(zip) > 10 or TRY_CAST(zip AS INT) IS NULL in SQL Server."},{"question":"How do I change a type on a huge table with no downtime?","answer":"Expand and contract: add a new column of the target type, backfill it in batches, keep it in sync with a trigger or the application, switch readers over, then drop the old column and rename. The same steps work on every engine."}],"related":["drop-column","add-column","generated-columns"]},"source_url":"https://sqlly.app/sql-dialects/alter-column-type","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/anti-join","corpus":"sql-dialects","engine":null,"language":"en","title":"Excluding rows: NOT IN vs NOT EXISTS vs LEFT JOIN","description":"Find customers with no orders: why NOT EXISTS is the safe default, when NOT IN lies, and the LEFT JOIN … IS NULL pattern.","body":{"slug":"anti-join","name":"Anti-join: NOT IN vs NOT EXISTS","h1":"Excluding rows: NOT IN vs NOT EXISTS vs LEFT JOIN","category":"query","lede":"NOT IN has a NULL trap that silently empties your result.","intro":"Three ways to write \"rows with no match\": NOT EXISTS (correlated subquery), NOT IN (subquery) and LEFT JOIN … WHERE right.key IS NULL. They return the same rows only while the subquery column holds no NULLs.","rows":[{"engine_slug":"sql-server","sql":"SELECT c.id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":"The optimizer plans NOT EXISTS as an anti semi join; NOT IN on a nullable column adds extra NULL checks to the plan."},{"engine_slug":"postgresql","sql":"SELECT c.id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":"Planned as a hash or merge anti join. NOT IN (SELECT …) can't use an anti join and gets slow on big subqueries, besides the NULL trap."},{"engine_slug":"mysql","sql":"SELECT c.id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":"8.0.17+ converts NOT EXISTS and NOT IN subqueries to antijoins. On older versions LEFT JOIN … WHERE o.id IS NULL was often faster."},{"engine_slug":"sqlite","sql":"SELECT c.id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":"Runs as a correlated lookup per customer, so an index on orders(customer_id) decides the speed."},{"engine_slug":"oracle","sql":"SELECT c.id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":"Planned as a hash anti join. 11g+ also has a null-aware anti join for NOT IN, which makes it fast, though not NULL-safe."}],"verdict":"NOT EXISTS is the default on all five engines: it is standard, says what you mean, and a NULL in orders.customer_id can't change its result. LEFT JOIN … IS NULL gives the same rows if you test the right side's key, and treat NOT IN over a nullable column as a bug waiting for its first NULL.","faqs":[{"question":"Why does NOT IN return no rows at all?","answer":"x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL, and the last comparison is unknown, so the whole predicate is never true. One NULL customer_id in orders empties the result. NOT EXISTS only asks whether a matching row exists, so NULLs don't affect it."},{"question":"When is LEFT JOIN … IS NULL preferable?","answer":"Mainly on MySQL before 8.0.17, where it often planned better, or when the query is already built from outer joins. Test a column that can't be NULL in a matched row, such as the right side's primary key (o.id IS NULL). Testing a nullable column also returns customers whose matching orders have NULL there."},{"question":"How do I make an anti-join fast?","answer":"Index the inner table's join column, orders.customer_id here. With that index all three forms probe or hash efficiently on current versions. Compare plans on your own data rather than trusting an old rule of thumb."}],"related":["null-safe-equality","cte-basics","date-diff-filter"]},"source_url":"https://sqlly.app/sql-dialects/anti-join","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/autocommit-toggle","corpus":"sql-dialects","engine":null,"language":"en","title":"Turning autocommit on or off in every SQL dialect","description":"Make every statement commit itself, or require explicit COMMITs, with autocommit settings in each engine.","body":{"slug":"autocommit-toggle","name":"Autocommit toggle","h1":"Turning autocommit on or off in every SQL dialect","category":"admin","lede":"Autocommit on means every statement is its own transaction. Turning it off groups statements until you COMMIT.","intro":"MySQL has a real autocommit variable. The others either never autocommit (Oracle), always autocommit without a server toggle (PostgreSQL, SQLite), or simulate it with implicit transactions (SQL Server).","rows":[{"engine_slug":"sql-server","sql":"SET IMPLICIT_TRANSACTIONS ON;\n-- a transaction opens implicitly at the next DML; COMMIT or ROLLBACK closes it\nSET IMPLICIT_TRANSACTIONS OFF;","note":"No direct autocommit off switch; implicit transactions is the inverse mode. @@TRANCOUNT tells you whether one is open."},{"engine_slug":"postgresql","sql":"-- no toggle: each statement autocommits; wrap multi-statement work in BEGIN/COMMIT","note":"Statements outside an explicit transaction each commit themselves, and BEGIN is the only way to group them. psql's \\set AUTOCOMMIT off and drivers such as psycopg emulate a toggle by sending BEGIN for you."},{"engine_slug":"mysql","sql":"SET autocommit = 0;\n-- statements now join an implicit transaction until COMMIT or ROLLBACK\nSET autocommit = 1;","note":"SET autocommit = 0 (or 1 to restore) applies to the session; SET GLOBAL autocommit changes the server default. START TRANSACTION suspends autocommit until that transaction ends."},{"engine_slug":"sqlite","sql":"-- no toggle: autocommit is always on unless an explicit BEGIN is open","note":"Every statement outside BEGIN/COMMIT autocommits. sqlite3_get_autocommit() reports the state; drivers like Python's sqlite3 emulate a toggle in the client."},{"engine_slug":"oracle","sql":"-- the database never autocommits: every DML needs an explicit COMMIT\nUPDATE accounts SET balance = 0 WHERE id = 1;\nCOMMIT;","note":"SQL*Plus SET AUTOCOMMIT ON and JDBC (autocommit on by default) commit from the client; the server never does. DDL issues an implicit COMMIT before and after."}],"verdict":"Only MySQL and the client libraries have a real toggle. The pattern is inverted across engines: PostgreSQL and SQLite autocommit unless you say BEGIN; Oracle never autocommits unless the driver does; SQL Server has a mode that stops autocommitting indirectly.","faqs":[{"question":"Why did my MySQL session lose autocommit = 0?","answer":"It is session-scoped and resets on reconnect. Connection pools often reset session variables; set it per transaction with START TRANSACTION instead."},{"question":"Is autocommit bad?","answer":"Not for single-statement writes. It becomes a bug when application logic assumes multi-statement atomicity without an explicit transaction; then autocommit silently converts one failure into a partial state."},{"question":"What does the driver's autocommit flag do?","answer":"JDBC, ADO.NET and friends manage it in the client: they issue BEGIN/COMMIT for you. That works uniformly, which is why most ORMs expose autocommit and leave server variables alone."}],"related":["begin-transaction","isolation-levels","savepoints"]},"source_url":"https://sqlly.app/sql-dialects/autocommit-toggle","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/autoincrement-column","corpus":"sql-dialects","engine":null,"language":"en","title":"Auto-incrementing primary keys","description":"IDENTITY, GENERATED ... AS IDENTITY, AUTO_INCREMENT, AUTOINCREMENT and rowid: declaring a self-numbering key in each engine.","body":{"slug":"autoincrement-column","name":"Auto-increment columns","h1":"Auto-incrementing primary keys","category":"ddl","lede":"Five engines, five spellings of the column that numbers itself.","intro":"SQL Server's IDENTITY predates the SQL standard's GENERATED … AS IDENTITY, which PostgreSQL (10+) and Oracle (12c+) use. MySQL keeps AUTO_INCREMENT. SQLite needs nothing extra: an INTEGER PRIMARY KEY column is an alias for the rowid and numbers itself, and AUTOINCREMENT only stops ids from being reused.","rows":[{"engine_slug":"sql-server","sql":"CREATE TABLE customers (\n  id INT IDENTITY(1, 1) PRIMARY KEY,\n  email VARCHAR(320)\n);","note":"IDENTITY(seed, step). Standalone SEQUENCE objects are the modern alternative when one counter must feed several tables."},{"engine_slug":"postgresql","sql":"CREATE TABLE customers (\n  id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  email TEXT\n);","note":"The SQL-standard form, preferred over legacy SERIAL. ALWAYS forbids explicit ids; BY DEFAULT permits them."},{"engine_slug":"mysql","sql":"CREATE TABLE customers (\n  id INT AUTO_INCREMENT PRIMARY KEY,\n  email VARCHAR(320)\n);","note":"One AUTO_INCREMENT column per table and it must be indexed (the PK does it). innodb_autoinc_lock_mode tunes concurrency."},{"engine_slug":"sqlite","sql":"CREATE TABLE customers (\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  email TEXT\n);","note":"Plain INTEGER PRIMARY KEY already numbers itself as an alias for rowid, but may reuse the id of a deleted last row. AUTOINCREMENT prevents that reuse at a small cost."},{"engine_slug":"oracle","sql":"CREATE TABLE customers (\n  id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  email VARCHAR2(320)\n);","note":"12c+. Before 12c the pattern was a SEQUENCE plus a BEFORE INSERT trigger; 12c also allows DEFAULT customers_seq.NEXTVAL on a plain column."}],"verdict":"Write GENERATED ALWAYS AS IDENTITY on PostgreSQL and Oracle, IDENTITY on SQL Server and AUTO_INCREMENT on MySQL. On SQLite, plain INTEGER PRIMARY KEY is enough unless ids must never be reused.","faqs":[{"question":"Is SERIAL deprecated in PostgreSQL?","answer":"Not deprecated, but identity columns (PostgreSQL 10+) are the recommended form: they are standard SQL, the sequence is owned and dropped with the column, and GRANTs on the table cover it. New tables should use GENERATED … AS IDENTITY."},{"question":"When does SQLite's AUTOINCREMENT matter?","answer":"Only when ids must never be reused. Without it, deleting the row with the highest id lets the next insert take that id again. AUTOINCREMENT records the highest id ever used in sqlite_sequence, which costs an extra write per insert."},{"question":"What is the difference between IDENTITY and SEQUENCE in SQL Server?","answer":"IDENTITY belongs to one column of one table, and you can't update the column. A SEQUENCE (2012+) is a separate object: several tables can draw from it, you can fetch the next value before inserting, and you can restart it, much like an Oracle sequence."}],"related":["insert-into-identity","generated-ids","truncate-vs-delete"]},"source_url":"https://sqlly.app/sql-dialects/autoincrement-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/begin-transaction","corpus":"sql-dialects","engine":null,"language":"en","title":"Explicit transactions in every SQL dialect","description":"Start, commit and roll back a transaction in SQL Server, PostgreSQL, MySQL, SQLite and Oracle.","body":{"slug":"begin-transaction","name":"BEGIN / COMMIT / ROLLBACK","h1":"Explicit transactions in every SQL dialect","category":"admin","lede":"The core transaction statements: BEGIN, COMMIT and ROLLBACK, with Oracle as the odd one out since its transactions start implicitly.","intro":"Four engines open explicit transactions with a statement; Oracle starts a transaction at your first DML and ends it only with COMMIT, ROLLBACK or session end.","rows":[{"engine_slug":"sql-server","sql":"BEGIN TRANSACTION;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nUPDATE accounts SET balance = balance + 10 WHERE id = 2;\nCOMMIT;","note":"Also spelled BEGIN TRAN. ROLLBACK undoes everything back to the start; SET XACT_ABORT ON makes any runtime error roll back automatically."},{"engine_slug":"postgresql","sql":"BEGIN;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nUPDATE accounts SET balance = balance + 10 WHERE id = 2;\nCOMMIT;","note":"START TRANSACTION is a synonym. After an error inside a transaction, statements fail until ROLLBACK (the transaction is aborted)."},{"engine_slug":"mysql","sql":"START TRANSACTION;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nUPDATE accounts SET balance = balance + 10 WHERE id = 2;\nCOMMIT;","note":"BEGIN also works unless inside a stored program. Most clients keep autocommit on; DDL statements commit implicitly."},{"engine_slug":"sqlite","sql":"BEGIN;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nUPDATE accounts SET balance = balance + 10 WHERE id = 2;\nCOMMIT;","note":"BEGIN DEFERRED is the default; BEGIN IMMEDIATE grabs the write lock at once, which avoids SQLITE_BUSY surprises on multi-statement writes."},{"engine_slug":"oracle","sql":"UPDATE accounts SET balance = balance - 10 WHERE id = 1;\nUPDATE accounts SET balance = balance + 10 WHERE id = 2;\nCOMMIT;","note":"No BEGIN: the transaction starts at the first DML. ROLLBACK undoes uncommitted work; keep transactions short, they hold undo space."}],"verdict":"Portable enough to memorize once: BEGIN/COMMIT/ROLLBACK everywhere, with two gotchas. Oracle has no BEGIN, and in MySQL and Oracle any DDL commits the transaction underneath you.","faqs":[{"question":"Do I need COMMIT for a SELECT?","answer":"No changes to commit, but in PostgreSQL and Oracle leaving read transactions open holds back cleanup; end them."},{"question":"What happens if I forget COMMIT?","answer":"The transaction stays open, holding locks: SQL Server/Oracle block other writers, MySQL's InnoDB waits or times out, PostgreSQL blocks cleanup. The connection dropping rolls it back."},{"question":"Which statements auto-commit?","answer":"DDL commits implicitly in MySQL and Oracle. SQL Server, PostgreSQL and SQLite run DDL inside the transaction, so a CREATE TABLE rolls back with everything else."}],"related":["savepoints","isolation-levels","autocommit-toggle"]},"source_url":"https://sqlly.app/sql-dialects/begin-transaction","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/blob-hex-literal","corpus":"sql-dialects","engine":null,"language":"en","title":"Binary and blob hex literals in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"0x literals, X'...' strings, bytea escapes and HEXTORAW: the four spellings of the same DEADBEEF bytes.","body":{"slug":"blob-hex-literal","name":"Binary and blob hex literals","h1":"Binary and blob hex literals in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"The same four bytes, four spellings, and the SQL Server form is not even quoted.","intro":"Writing literal bytes into a query surfaces each engine's binary model: SQL Server uses unquoted 0x literals, MySQL and SQLite use X'' strings, PostgreSQL escapes into bytea, and Oracle converts from a hex string.","rows":[{"engine_slug":"sql-server","sql":"SELECT 0xDEADBEEF;","note":"Bare 0x literal, no quotes, yields VARBINARY. CONVERT(VARBINARY(8), 'DEADBEEF', 2) parses a hex string; CONVERT(VARCHAR, 0xDEADBEEF, 2) renders it back."},{"engine_slug":"postgresql","sql":"SELECT '\\xDEADBEEF'::BYTEA;","note":"bytea accepts the escape format \\x inside a quoted string; DECODE('DEADBEEF', 'hex') is the string-based path, ENCODE(b, 'hex') the way out."},{"engine_slug":"mysql","sql":"SELECT X'DEADBEEF', 0xDEADBEEF;","note":"X'...' is a binary string (even digit count required); a bare 0xDEADBEEF is a numeric hex literal that behaves as bytes in string context."},{"engine_slug":"sqlite","sql":"SELECT X'DEADBEEF';","note":"X'...' is the only blob literal and must have an even digit count. unhex('DEADBEEF') (3.41+) parses a hex string, and ZEROBLOB, RANDOMBLOB or CAST of text build others."},{"engine_slug":"oracle","sql":"SELECT HEXTORAW('DEADBEEF') FROM dual;","note":"No binary literal syntax: HEXTORAW parses a hex string and RAWTOHEX renders one back. X'DEADBEEF' is a syntax error, 23ai included."}],"verdict":"Portability requires binding binary values as parameters rather than literals; inline, every engine spells the bytes differently, and PostgreSQL's \\x prefix makes it the easiest to misquote.","faqs":[{"question":"Why does my hex literal with odd digits fail?","answer":"X'' literals in MySQL and SQLite need two hex digits per byte, so X'D' is a syntax error; write X'0D'. Unquoted 0x literals are more forgiving: SQL Server and MySQL read 0xD as 0x0D."},{"question":"How do I view blob contents as text?","answer":"Round-trip through hex: CONVERT(VARCHAR, b, 2) in SQL Server, ENCODE(b, 'hex') in PostgreSQL, HEX(b) in MySQL and SQLite, RAWTOHEX(b) in Oracle."},{"question":"Is a bare 0xDEADBEEF the same in MySQL and SQL Server?","answer":"Yes, both treat an unquoted 0x literal as binary-typed; the difference is MySQL also allows it as a number in numeric context, while SQL Server's is strictly varbinary."}],"related":["char-vs-varchar","guid-column-type","cast-syntax"]},"source_url":"https://sqlly.app/sql-dialects/blob-hex-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/boolean-literal","corpus":"sql-dialects","engine":null,"language":"en","title":"Boolean literals: TRUE, 1 and 'Y' in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"PostgreSQL and Oracle 23ai have a real BOOLEAN type; SQL Server's BIT, MySQL's TINYINT(1) and SQLite integers stand in for it elsewhere.","body":{"slug":"boolean-literal","name":"Boolean literals: TRUE, 1 and 'Y'","h1":"Boolean literals: TRUE, 1 and 'Y' in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"TRUE is a keyword in four engines, but only PostgreSQL and Oracle 23ai back it with a real type. SQL Server has no TRUE at all.","intro":"How you write true and false depends entirely on the column type underneath. The rows below filter an active flag in each engine's native convention.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM t WHERE is_active = 1;","note":"The BIT type stores 0 and 1 only; TRUE and FALSE are not keywords, so the literal is the number."},{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE is_active = TRUE;","note":"A real BOOLEAN type accepts TRUE, FALSE, and the literals 't', 'f', 'yes', 'no', '1', '0' when quoted."},{"engine_slug":"mysql","sql":"SELECT * FROM t WHERE is_active = TRUE;","note":"TRUE is just an alias for 1; a BOOLEAN column is really TINYINT(1) and happily stores 7."},{"engine_slug":"sqlite","sql":"SELECT * FROM t WHERE is_active = 1;","note":"No boolean type: flags are integers. The TRUE and FALSE keywords are recognized (3.23+) and evaluate to 1 and 0."},{"engine_slug":"oracle","sql":"SELECT * FROM t WHERE is_active = 1;","note":"Before 23ai there is no SQL BOOLEAN, so flags are NUMBER(1) 0/1, as here, or CHAR(1) 'Y'/'N'. On a 23ai BOOLEAN column, WHERE is_active = TRUE and a bare WHERE is_active both work."}],"verdict":"PostgreSQL and Oracle 23ai are the only engines where TRUE is a literal of a real boolean type. MySQL and SQLite accept TRUE but store 1, and SQL Server filters BIT columns with = 1. The convention lives in the schema, so check the column type before writing the predicate.","faqs":[{"question":"Why did WHERE is_active = TRUE fail on SQL Server?","answer":"There is no TRUE keyword there. Use is_active = 1. A bare WHERE is_active fails too (Msg 4145): SQL Server wants a comparison even on BIT columns."},{"question":"Is MySQL's BOOLEAN a real type?","answer":"No. BOOLEAN is an alias for TINYINT(1), and any integer value is accepted. TRUE/FALSE literals simply mean 1/0."},{"question":"Should I use 'Y'/'N' flags in Oracle?","answer":"It is a widespread legacy convention and readable in data dumps, but NUMBER 0/1 or (from 23ai) BOOLEAN compares more naturally and indexes the same. Pick one convention and stick to it."}],"related":["guid-column-type","char-vs-varchar","null-vs-empty-string"]},"source_url":"https://sqlly.app/sql-dialects/boolean-literal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/bulk-insert-limits","corpus":"sql-dialects","engine":null,"language":"en","title":"How many rows one INSERT can take","description":"The 1000-row VALUES cap in SQL Server, max_allowed_packet in MySQL, SQLite's variable limit and the Oracle INSERT ALL shape.","body":{"slug":"bulk-insert-limits","name":"Bulk insert limits","h1":"How many rows one INSERT can take","category":"dml","lede":"Every engine caps a single INSERT somewhere. Here is where the ceilings are.","intro":"The limits differ in kind. SQL Server caps a VALUES list at 1,000 rows and a request at 2,100 parameters; MySQL bounds the statement's size in bytes by max_allowed_packet; SQLite caps bind parameters; PostgreSQL's wire protocol allows 65,535 parameters per statement. Past the cap, use INSERT ... SELECT from a staging table or the engine's bulk loader.","rows":[{"engine_slug":"sql-server","sql":"INSERT INTO logs (msg) VALUES ('a'), ('b'); -- 1000 rows max","note":"1,001 rows fail with error 10738. A parameterized request is also capped at 2,100 parameters. INSERT … SELECT has no row cap, and BULK INSERT or bcp handle large loads."},{"engine_slug":"postgresql","sql":"INSERT INTO logs (msg) VALUES ('a'), ('b'), ('c');","note":"No row cap. A parameterized statement can carry at most 65,535 parameters, so batch, or use COPY for big loads."},{"engine_slug":"mysql","sql":"INSERT INTO logs (msg) VALUES ('a'), ('b'), ('c');","note":"No row cap; max_allowed_packet (64 MB by default in 8.0) bounds the statement's bytes. Keep batches well under it."},{"engine_slug":"sqlite","sql":"INSERT INTO logs (msg) VALUES ('a'), ('b'), ('c');","note":"Bound parameters are capped by SQLITE_MAX_VARIABLE_NUMBER: 999 before 3.32, 32,766 since, changeable at compile time. Literal values don't count; the statement as a whole is capped at 1,000,000,000 bytes (SQLITE_MAX_SQL_LENGTH)."},{"engine_slug":"oracle","sql":"INSERT ALL\n  INTO logs (msg) VALUES ('a')\n  INTO logs (msg) VALUES ('b')\nSELECT * FROM dual;","note":"Works on every version; 23ai also takes a multi-row VALUES list. Large loads use INSERT /*+ APPEND */ … SELECT, array binds (FORALL in PL/SQL), SQL*Loader or external tables."}],"verdict":"None of these limits bite until you batch thousands of rows, and at that point a bulk loader is the right tool anyway: COPY, BULK INSERT, LOAD DATA or SQL*Loader, or a staging table plus INSERT ... SELECT.","faqs":[{"question":"Why 2,100 parameters in SQL Server?","answer":"It is SQL Server's documented maximum of parameters per stored procedure or parameterized request, which is what drivers send. Batching libraries therefore cap a batch at about 2,000 parameters: a 10-column insert fits about 200 rows per statement."},{"question":"Is a huge multi-row INSERT one transaction?","answer":"It is one statement, and statements are atomic, so on transactional tables either every row lands or none do. A giant statement therefore holds locks and log or undo space like a giant transaction."},{"question":"What is the fastest bulk path per engine?","answer":"PostgreSQL: COPY. MySQL: LOAD DATA INFILE. SQL Server: BULK INSERT, bcp or the driver's bulk-copy API. SQLite: one prepared INSERT executed repeatedly inside a single transaction. Oracle: SQL*Loader direct path or INSERT /*+ APPEND */."}],"related":["multi-row-insert","insert-from-select","truncate-vs-delete"]},"source_url":"https://sqlly.app/sql-dialects/bulk-insert-limits","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/case-insensitive-compare","corpus":"sql-dialects","engine":null,"language":"en","title":"Case-insensitive string comparison","description":"Match 'Ana@Example.com' regardless of casing: default collations, lower(), ILIKE, COLLATE NOCASE and NLS_SORT.","body":{"slug":"case-insensitive-compare","name":"Case-insensitive comparison","h1":"Case-insensitive string comparison","category":"query","lede":"Whether = ignores case depends entirely on the column's collation.","intro":"SQL Server and MySQL compare case-insensitively by default; PostgreSQL, SQLite and Oracle do not. The portable habit is lower(x) = lower(y), backed by an expression index so it stays fast.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM users WHERE email = 'Ana@Example.com';","note":"The default collations (SQL_Latin1_General_CP1_CI_AS and friends) are case-insensitive, so this matches any casing. COLLATE Latin1_General_CS_AS on the column or the comparison makes it case-sensitive."},{"engine_slug":"postgresql","sql":"SELECT * FROM users WHERE lower(email) = 'ana@example.com';","note":"Case-sensitive by default. email ILIKE 'ana@example.com' also works; an index on lower(email), the citext type or a nondeterministic ICU collation (12+) keep it indexable."},{"engine_slug":"mysql","sql":"SELECT * FROM users WHERE email = 'Ana@Example.com';","note":"Default *_ci collations match any casing, and utf8mb4_0900_ai_ci ignores accents too. A _bin or _cs collation makes the comparison case-sensitive."},{"engine_slug":"sqlite","sql":"SELECT * FROM users WHERE email = 'Ana@Example.com' COLLATE NOCASE;","note":"= on TEXT is case-sensitive by default. NOCASE folds ASCII letters only; declare the column (or an index) COLLATE NOCASE so the comparison can use an index."},{"engine_slug":"oracle","sql":"SELECT * FROM users WHERE LOWER(email) = 'ana@example.com';","note":"Case-sensitive by default. NLS_COMP=LINGUISTIC with NLS_SORT=BINARY_CI makes a session case-insensitive; 12.2+ also allows a column-level COLLATE BINARY_CI."}],"verdict":"lower(email) = 'ana@example.com', backed by an index on the expression, is the only form that behaves the same on all five engines. Relying on defaults means the same query is case-insensitive on SQL Server and MySQL and case-sensitive on the other three. Watch SQLite's NOCASE and lower(): both fold ASCII only, so 'Ä' never matches 'ä'.","faqs":[{"question":"Why does my query match on one server but not another?","answer":"The collations differ. SQL Server and MySQL install with case-insensitive defaults; PostgreSQL, SQLite and Oracle compare case-sensitively. Collation can also differ per database and per column. Check sys.columns.collation_name in SQL Server, information_schema.columns.collation_name in MySQL and PostgreSQL, and NLS_COMP/NLS_SORT in Oracle."},{"question":"How do I keep a lower() comparison indexed?","answer":"Index the exact expression the query uses: CREATE INDEX ix_users_email_lower ON users (LOWER(email)) works in PostgreSQL, Oracle and SQLite; MySQL 8.0.13+ needs the expression in double parentheses, ((LOWER(email))); SQL Server needs a computed column with an index on it. Without one the predicate scans the table."},{"question":"What is citext?","answer":"A PostgreSQL extension type (CREATE EXTENSION citext) that stores the original text but compares it case-insensitively, so plain = and ordinary indexes just work. It changes equality for the whole column, including joins, DISTINCT and unique constraints."}],"related":["like-escape","distinct-on-expression","regex-matching","string-concatenation"]},"source_url":"https://sqlly.app/sql-dialects/case-insensitive-compare","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/cast-string-to-number","corpus":"sql-dialects","engine":null,"language":"en","title":"Cast text to a number in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Turning '42' into 42: one CAST in most engines, TO_NUMBER plus a format mask in Oracle when the text is not machine-clean.","body":{"slug":"cast-string-to-number","name":"Cast text to a number","h1":"Cast text to a number in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Text '42' becomes 42 everywhere, but 'abc' raises an error in three engines and quietly becomes 0 in two.","intro":"Every engine converts text to numbers, and every engine has different rules for what happens when the text is not a number. The casts below are the happy path; see safe-cast for what 'abc' does.","rows":[{"engine_slug":"sql-server","sql":"SELECT CAST('42' AS INT) + 1;","note":"Leading and trailing spaces are tolerated. 'abc' raises a conversion error, and so does '4.2' when the target is INT; cast to DECIMAL for decimals."},{"engine_slug":"postgresql","sql":"SELECT '42'::INTEGER + 1;","note":"Use NUMERIC instead of INTEGER for decimals: '42'::NUMERIC. 'abc' raises an error."},{"engine_slug":"mysql","sql":"SELECT CAST('42' AS SIGNED) + 1;","note":"'42abc' casts to 42 and 'abc' to 0, each with warning 1292 instead of an error."},{"engine_slug":"sqlite","sql":"SELECT CAST('42' AS INTEGER) + 1;","note":"CAST reads the longest numeric prefix: '42abc' becomes 42, 'abc' becomes 0. It never errors."},{"engine_slug":"oracle","sql":"SELECT TO_NUMBER('42') + 1 FROM dual;","note":"TO_NUMBER accepts a mask: TO_NUMBER('1,234', '9G999'). Unparseable text raises ORA-01722."}],"verdict":"Identical syntax, opposite failure modes: SQL Server, PostgreSQL and Oracle refuse bad input, while MySQL and SQLite quietly give you 0 or the numeric prefix. Validate in the app or use a safe cast.","faqs":[{"question":"Why did my string become 0 in MySQL?","answer":"CAST('abc' AS SIGNED) yields 0 and only raises a warning, even in strict mode, because strict mode governs writes rather than SELECT expressions. Check warnings or guard with a regex."},{"question":"How do I parse a decimal string?","answer":"Cast to NUMERIC in PostgreSQL, DECIMAL in SQL Server and MySQL (CAST('4.2' AS DECIMAL(9,2))), REAL in SQLite, and TO_NUMBER('4.2') in Oracle."},{"question":"Does CAST strip currency symbols?","answer":"No, in any engine. Strip them yourself or use a format mask such as Oracle's TO_NUMBER('$1,234', 'L9G999')."}],"related":["safe-cast","cast-syntax","number-to-text-format"]},"source_url":"https://sqlly.app/sql-dialects/cast-string-to-number","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/cast-syntax","corpus":"sql-dialects","engine":null,"language":"en","title":"Cast syntax in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"CAST works everywhere, but PostgreSQL has the :: shorthand, SQL Server has CONVERT with style codes, and Oracle leans on the TO_CHAR/TO_NUMBER family.","body":{"slug":"cast-syntax","name":"Cast syntax","h1":"Cast syntax in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"CAST runs on all five engines; the native forms add format masks, style codes or a shorter spelling.","intro":"ANSI CAST is the portable baseline: all five engines accept it. Beyond that, each engine has its own idiom, and picking the engine-native form usually buys you format masks or a shorter syntax. The examples below convert the same text to a number and back.","rows":[{"engine_slug":"sql-server","sql":"SELECT CAST('42' AS INT) AS Ansi, CONVERT(INT, '42') AS ConvertSyntax;","note":"CAST is ANSI and has no extras. CONVERT is SQL Server-only and takes a style argument for dates. TRY_CONVERT exists for safe casts."},{"engine_slug":"postgresql","sql":"SELECT CAST('42' AS INTEGER), '42'::INTEGER, 42::TEXT;","note":"The :: shorthand is PostgreSQL-specific and shorter than CAST; it binds tightly, so parenthesize around operators."},{"engine_slug":"mysql","sql":"SELECT CAST('42' AS SIGNED), CONVERT('42', SIGNED), CAST(42 AS CHAR);","note":"CAST and CONVERT accept a fixed list of targets (SIGNED, UNSIGNED, DECIMAL, DOUBLE, CHAR, DATE, DATETIME, JSON and a few more), not column types such as INT or VARCHAR(20)."},{"engine_slug":"sqlite","sql":"SELECT CAST('42' AS INTEGER), CAST(42 AS TEXT);","note":"CAST is the only explicit conversion; everything else happens silently through type affinity."},{"engine_slug":"oracle","sql":"SELECT CAST('42' AS NUMBER), TO_NUMBER('42'), TO_CHAR(42) FROM dual;","note":"CAST exists, but the TO_NUMBER/TO_CHAR/TO_DATE family is what you reach for, because it takes format masks."}],"verdict":"Write CAST when portability matters, but learn the native shorthand: :: in PostgreSQL, CONVERT for styled conversions in SQL Server, and the TO_ family with masks in Oracle.","faqs":[{"question":"Is CAST fully portable across all five engines?","answer":"For simple conversions yes: CAST(expr AS type) parses in all five. The target type names still differ per engine (INT vs INTEGER vs NUMBER), so portable SQL uses each engine's spelling."},{"question":"Why does PostgreSQL have two cast syntaxes?","answer":":: predates full ANSI support and stuck because it is short and plays well in generated SQL. CAST exists alongside it and both compile to the same operation."},{"question":"Does MySQL CAST support format masks?","answer":"No. MySQL CAST only converts to fixed types. For masks you use FORMAT(), DATE_FORMAT(), LPAD() and similar functions instead."}],"related":["cast-string-to-number","number-to-text-format","safe-cast"]},"source_url":"https://sqlly.app/sql-dialects/cast-syntax","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/char-vs-varchar","corpus":"sql-dialects","engine":null,"language":"en","title":"CHAR versus VARCHAR semantics in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"CHAR blank-pads to full length in SQL Server, PostgreSQL and Oracle, does nothing in SQLite, and depends on the collation in MySQL.","body":{"slug":"char-vs-varchar","name":"CHAR versus VARCHAR semantics","h1":"CHAR versus VARCHAR semantics in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Blank-padding is invisible until a join compares CHAR to VARCHAR and stops matching.","intro":"CHAR(n) pads short values with spaces; VARCHAR does not. What happens to those spaces on read and in comparisons is where the dialects quietly disagree, and SQLite never pads at all.","rows":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (c CHAR(10), v VARCHAR(10));","note":"CHAR pads on storage; trailing spaces are ignored in equality ('a' = 'a ' is true), and ANSI_PADDING is effectively always ON in modern versions."},{"engine_slug":"postgresql","sql":"CREATE TABLE t (c CHAR(10), v VARCHAR(10));","note":"CHAR(n) (bpchar) stores and displays the padding, but treats trailing spaces as insignificant: they vanish when the value is cast to text or concatenated, and comparisons ignore them. TEXT or VARCHAR is the idiomatic choice; CHAR is not faster."},{"engine_slug":"mysql","sql":"CREATE TABLE t (c CHAR(10), v VARCHAR(10));","note":"CHAR pads on disk and strips trailing spaces on retrieval. VARCHAR keeps them, and whether 'a ' = 'a' depends on the collation: MySQL 8's default utf8mb4_0900_ai_ci is NO PAD, so they differ, while PAD SPACE collations such as utf8mb4_general_ci ignore trailing spaces."},{"engine_slug":"sqlite","sql":"CREATE TABLE t (c TEXT, v TEXT);","note":"CHAR(n)/VARCHAR(n) are just TEXT affinity: no padding, no stripping, declared lengths ignored. Any length rule lives in a CHECK constraint."},{"engine_slug":"oracle","sql":"CREATE TABLE t (c CHAR(10), v VARCHAR2(10));","note":"CHAR(10) pads. CHAR against CHAR or a literal uses blank-padded comparison, so c = 'a ' is true, but CHAR against a VARCHAR2 column does not pad, so c = v is false when both hold 'a'. Use VARCHAR2 for real strings."}],"verdict":"CHAR buys nothing in modern engines except fixed-width semantics you almost never want; TEXT/VARCHAR2/VARCHAR is the default everywhere. If you inherit CHAR columns, test comparisons against VARCHAR values: trailing-space rules differ per engine and, in MySQL, per collation.","faqs":[{"question":"When is CHAR actually the right choice?","answer":"Rarely. Fixed-length codes such as a two-letter country code are the textbook case, and even there VARCHAR(2) stores the same data without the padding rules."},{"question":"Why does 'a' = 'a ' return true on some engines?","answer":"SQL Server and PostgreSQL ignore trailing spaces when comparing character values. Oracle does when both sides are CHAR or literals, but not CHAR against VARCHAR2. MySQL does only under PAD SPACE collations, and SQLite never does (the default BINARY collation compares bytes)."},{"question":"Does CHAR(n) reject longer values?","answer":"Overlength values error (or truncate, depending on mode) just as with VARCHAR. Shorter values are padded to n on storage, so SQL Server, PostgreSQL and Oracle return 'a' plus nine spaces from a CHAR(10) column; MySQL strips them on the way out."}],"related":["null-vs-empty-string","guid-column-type","blob-hex-literal"]},"source_url":"https://sqlly.app/sql-dialects/char-vs-varchar","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/comment-on","corpus":"sql-dialects","engine":null,"language":"en","title":"Comment on a table or column","description":"COMMENT ON in PostgreSQL and Oracle, extended properties in SQL Server, inline COMMENT clauses in MySQL, and SQL comments kept in SQLite's schema text.","body":{"slug":"comment-on","name":"Comments on tables and columns","h1":"Comment on a table or column","category":"ddl","lede":"Store documentation with the schema so tools and later readers can find it.","intro":"PostgreSQL and Oracle have a COMMENT ON statement. SQL Server stores comments as extended properties named MS_Description. MySQL keeps them as COMMENT clauses in CREATE and ALTER, so changing a column comment means restating the column definition. SQLite has no comment feature, but it keeps the original CREATE TABLE text, SQL comments included.","rows":[{"engine_slug":"sql-server","sql":"EXEC sp_addextendedproperty\n  @name = N'MS_Description', @value = N'Orders placed by customers',\n  @level0type = N'SCHEMA', @level0name = N'dbo',\n  @level1type = N'TABLE', @level1name = N'orders';","note":"Comments are extended properties; add @level2type = N'COLUMN', @level2name = N'total' for a column. sp_updateextendedproperty changes one. SSMS shows MS_Description as the description."},{"engine_slug":"postgresql","sql":"COMMENT ON TABLE orders IS 'Orders placed by customers';\nCOMMENT ON COLUMN orders.total IS 'Order total incl. tax';","note":"Stored in pg_description; psql's \\d+ shows it. COMMENT ON … IS NULL (or an empty string) removes it."},{"engine_slug":"mysql","sql":"ALTER TABLE orders COMMENT = 'Orders placed by customers';\nALTER TABLE orders MODIFY COLUMN total DECIMAL(10,2)\n  COMMENT 'Order total incl. tax';","note":"The column comment rides on MODIFY, so restate the exact type, NOT NULL and DEFAULT, or you change them too. A comment-only change is metadata-only in 8.0."},{"engine_slug":"sqlite","sql":"CREATE TABLE orders (\n  id INTEGER PRIMARY KEY,\n  total REAL -- order total incl. tax\n);\nSELECT sql FROM sqlite_schema WHERE name = 'orders';","note":"No comment storage, but sqlite_schema (sqlite_master before 3.33) keeps the CREATE TABLE text with its -- comments. Changing one means rebuilding the table."},{"engine_slug":"oracle","sql":"COMMENT ON TABLE orders IS 'Orders placed by customers';\nCOMMENT ON COLUMN orders.total IS 'Order total incl. tax';","note":"Same statement as PostgreSQL; IS '' removes the comment. Read them back from USER_TAB_COMMENTS and USER_COL_COMMENTS."}],"verdict":"PostgreSQL and Oracle make schema comments a one-liner. MySQL works but makes you restate the column to comment it, SQL Server needs a stored procedure call per comment, and SQLite only has the comments you wrote into the CREATE TABLE.","faqs":[{"question":"How do I read comments back?","answer":"PostgreSQL: obj_description() and col_description(), or psql \\d+. Oracle: the USER_ / ALL_TAB_COMMENTS and _COL_COMMENTS views. SQL Server: sys.extended_properties or fn_listextendedproperty. MySQL: the TABLE_COMMENT and COLUMN_COMMENT columns of information_schema.TABLES and COLUMNS."},{"question":"Do comments appear in dumps?","answer":"pg_dump writes COMMENT ON statements, mysqldump keeps COMMENT clauses inside the CREATE statements, and Oracle Data Pump exports comments with the tables. SQL Server's Generate Scripts wizard includes extended properties when its 'Script extended properties' option is on."},{"question":"Does a MySQL comment change rebuild the table?","answer":"Not in 8.0: changing only a column's comment is a metadata change. The risk is in the statement itself: MODIFY replaces the whole column definition, so a forgotten NOT NULL or DEFAULT really changes the column."}],"related":["rename-table","create-schema","add-column"]},"source_url":"https://sqlly.app/sql-dialects/comment-on","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/concat-number-string","corpus":"sql-dialects","engine":null,"language":"en","title":"Concatenate a number to a string in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Gluing 'Order ' to 42: || in PostgreSQL, SQLite, Oracle and SQL Server 2025, CONCAT() everywhere, and + only after a CAST in SQL Server.","body":{"slug":"concat-number-string","name":"Concatenate a number to a string","h1":"Concatenate a number to a string in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"query","lede":"CONCAT('Order ', 42) runs on all five engines. The operators are where they split.","intro":"The porting trap: 'Order ' || 42 works in PostgreSQL, SQLite, Oracle and SQL Server 2025, but MySQL reads || as logical OR and returns 1. Older SQL Server only has +, and 'Order ' + 42 tries to turn 'Order ' into a number and fails. CONCAT() converts its arguments in every engine.","rows":[{"engine_slug":"sql-server","sql":"SELECT CONCAT('Order ', 42), 'Order ' + CAST(42 AS VARCHAR(10));","note":"With an int operand, + means addition, so 'Order ' + 42 fails with Msg 245. CONCAT() converts everything and treats NULL operands as empty. SQL Server 2025 and Azure SQL also accept 'Order ' || 42."},{"engine_slug":"postgresql","sql":"SELECT 'Order ' || 42;","note":"|| converts the non-text operand to text. 'Order ' + 42 errors, because PostgreSQL tries to read 'Order ' as an integer."},{"engine_slug":"mysql","sql":"SELECT CONCAT('Order ', 42);","note":"CONCAT converts every argument but returns NULL if any argument is NULL. || is logical OR unless sql_mode includes PIPES_AS_CONCAT, and 'Order ' + 42 is numeric addition that returns 42."},{"engine_slug":"sqlite","sql":"SELECT 'Order ' || 42;","note":"|| is the only concatenation operator and converts numbers to their text form automatically."},{"engine_slug":"oracle","sql":"SELECT 'Order ' || 42 FROM dual;","note":"|| implicitly converts numbers (and dates, using NLS settings). CONCAT() accepts any number of arguments from 23ai; earlier releases take exactly two, so older code nests the calls."}],"verdict":"CONCAT() is the one spelling that runs on all five. Among the operators, || covers PostgreSQL, SQLite, Oracle and SQL Server 2025; MySQL reads it as OR, and SQL Server before 2025 needs a CAST before +.","faqs":[{"question":"Why does 'Order ' + 42 work in MySQL but not SQL Server?","answer":"In MySQL + is purely numeric addition: 'Order ' converts to 0 with a warning and the result is 42. No error, but no concatenation either. SQL Server tries to convert 'Order ' to int and raises Msg 245."},{"question":"How do the operators treat NULL operands?","answer":"NULL || 'x' is NULL in PostgreSQL, SQLite and SQL Server 2025, but 'x' in Oracle, which treats NULL as an empty string when concatenating. CONCAT() skips NULLs in SQL Server, PostgreSQL and Oracle but returns NULL in MySQL, and SQL Server's + returns NULL."},{"question":"What about dates in concatenation?","answer":"PostgreSQL's || renders a date in ISO form and Oracle's uses NLS_DATE_FORMAT. SQLite stores dates as text already. SQL Server's + needs a CONVERT first, though CONCAT() accepts dates directly, and MySQL's CONCAT renders the ISO form."}],"related":["cast-syntax","cast-string-to-number","regex-replace"]},"source_url":"https://sqlly.app/sql-dialects/concat-number-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/conditional-expression","corpus":"sql-dialects","engine":null,"language":"en","title":"Conditional expressions: CASE, IIF, IF and DECODE","description":"Turn a score into a grade inside the SELECT list: the standard CASE and each engine's shorter conditional.","body":{"slug":"conditional-expression","name":"Conditional expressions (CASE / IIF / DECODE)","h1":"Conditional expressions: CASE, IIF, IF and DECODE","category":"query","lede":"CASE is everywhere; IIF, IF and DECODE are the local shortcuts.","intro":"CASE WHEN … THEN … ELSE … END is the SQL-standard conditional and works in all five engines. Each engine except PostgreSQL also has a shorthand: IIF in SQL Server and SQLite, IF in MySQL, DECODE in Oracle.","rows":[{"engine_slug":"sql-server","sql":"SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM exams;","note":"IIF(score >= 90, 'A', 'C') is a two-branch shorthand (2012+) that SQL Server rewrites into CASE; more than two outcomes means nesting IIFs."},{"engine_slug":"postgresql","sql":"SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM exams;","note":"CASE is the only built-in conditional: no IIF, no IF, no DECODE."},{"engine_slug":"mysql","sql":"SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM exams;","note":"IF(score >= 90, 'A', 'C') is the MySQL shorthand; IFNULL and NULLIF cover the NULL cases."},{"engine_slug":"sqlite","sql":"SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM exams;","note":"iif(cond, a, b) exists since 3.32 and is exactly a two-branch CASE."},{"engine_slug":"oracle","sql":"SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM exams;","note":"DECODE(score, 100, 'A', 90, 'A', 'C') tests equality only, so it can't express ranges; CASE can."}],"verdict":"Use CASE. It is standard, handles ranges and NULL branches explicitly, and ports with no edits. The shorthands save a few characters but tie the query to one engine, and DECODE's equality-only matching plus its NULL-equals-NULL rule change results when someone translates it to CASE by hand.","faqs":[{"question":"Why does my CASE return NULL when I have no ELSE?","answer":"A CASE without ELSE yields NULL when no branch matches. Add an explicit ELSE when you want a fallback value."},{"question":"What is DECODE's NULL surprise?","answer":"DECODE treats two NULLs as equal, so DECODE(col, NULL, 'none', 'other') returns 'none' for NULL rows. The direct translation CASE col WHEN NULL THEN 'none' ELSE 'other' END never matches, because it tests col = NULL. Translate it as CASE WHEN col IS NULL THEN 'none' ELSE 'other' END."},{"question":"Can CASE return different types per branch?","answer":"The engine picks one result type for the whole expression, and the rules differ. SQL Server uses data type precedence, so CASE … THEN 'A' ELSE 95 END fails when it tries to convert 'A' to int. PostgreSQL tries to read 'A' as an integer and fails, Oracle rejects the mix with ORA-00932, and MySQL and SQLite return the values as they are. Cast every branch to the same type."}],"related":["custom-sort-order","null-substitution","null-safe-equality"]},"source_url":"https://sqlly.app/sql-dialects/conditional-expression","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/covering-index","corpus":"sql-dialects","engine":null,"language":"en","title":"Covering indexes and INCLUDE columns in every SQL dialect","description":"Add INCLUDE columns so a query is answered from the index alone; INCLUDE syntax exists in SQL Server and PostgreSQL, others use composite indexes.","body":{"slug":"covering-index","name":"Covering index (INCLUDE)","h1":"Covering indexes and INCLUDE columns in every SQL dialect","category":"indexes","lede":"A covering index answers a query without touching the table. SQL Server and PostgreSQL have an INCLUDE clause that keeps extra columns out of the key; the rest use composite indexes.","intro":"INCLUDE columns are stored in the index leaf pages but are not part of the key, so they do not affect ordering or uniqueness. If the engine has no INCLUDE, a composite index covers the same query, at the cost of making those columns part of the key.","rows":[{"engine_slug":"sql-server","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (total, status);","note":"INCLUDE has existed since SQL Server 2005. A query that touches only customer_id, total and status is answered by an index seek with no key lookup."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (total, status);","note":"INCLUDE supported since PostgreSQL 11. Index-only scans additionally need the visibility map warmed by VACUUM."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);","note":"No INCLUDE clause. Put the extra columns into a composite index; they become part of the key (and of uniqueness, if the index is UNIQUE). InnoDB secondary indexes also carry the primary key, so id is covered for free."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);","note":"No INCLUDE clause. A composite index covers the query when EXPLAIN QUERY PLAN shows the table access disappearing."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);","note":"No INCLUDE clause; a composite index serves the same purpose. A B-tree index holds at most 32 columns."}],"verdict":"SQL Server and PostgreSQL get a true INCLUDE clause; MySQL, SQLite and Oracle express the same idea with composite indexes. Functionally you can cover a query everywhere, but with INCLUDE the extra columns stay out of uniqueness and sort order.","faqs":[{"question":"How do I confirm an index covers a query?","answer":"Check the plan: SQL Server shows a seek with no Key Lookup, PostgreSQL says Index Only Scan, MySQL says Using index in Extra, SQLite EXPLAIN QUERY PLAN drops the table step, Oracle shows INDEX range scan with no TABLE ACCESS."},{"question":"Why not just put everything in one index?","answer":"Key columns cost more on every write and widen the index. INCLUDE keeps a narrow key for seeking while still carrying payload columns."},{"question":"Does a covering index stay covering forever?","answer":"No. Add a new column to the query and it stops being covered; re-check the plan after query changes."}],"related":["create-index","create-index-concurrently","rebuild-index"]},"source_url":"https://sqlly.app/sql-dialects/covering-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/create-index","corpus":"sql-dialects","engine":null,"language":"en","title":"CREATE INDEX in every SQL dialect","description":"How to create a plain B-tree index on one or more columns in SQL Server, PostgreSQL, MySQL, SQLite and Oracle.","body":{"slug":"create-index","name":"CREATE INDEX","h1":"CREATE INDEX in every SQL dialect","category":"indexes","lede":"The bread-and-butter index statement: nearly identical everywhere, with a few differences in naming and locking.","intro":"Every engine builds a B-tree index with the same core statement. The differences are around what happens to concurrent writers while the index is being built.","rows":[{"engine_slug":"sql-server","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":"An offline build holds a shared lock: readers continue, writers wait. WITH (ONLINE = ON) keeps writes flowing (Enterprise and Enterprise Developer editions, Azure SQL; not Standard)."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":"Defaults to B-tree. CREATE INDEX CONCURRENTLY avoids blocking writes but cannot run inside a transaction."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":"InnoDB builds B-tree indexes; InnoDB Online DDL allows concurrent reads and usually writes while it builds."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":"Only B-tree indexes exist. The database is locked to other writers while the index builds."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":"B-tree by default. Without ONLINE, DML on the table waits for the build; CREATE INDEX ... ONLINE (Enterprise Edition) keeps it writable."}],"verdict":"This is one of the most portable statements in SQL: identical syntax in all five engines. The real differences hide in concurrency options, which every engine spells differently.","faqs":[{"question":"Do I need an index on every column I filter?","answer":"No. Indexes slow down writes and take space. Index columns that appear in frequent WHERE, JOIN and ORDER BY clauses where the query currently scans too many rows."},{"question":"Does the index update itself?","answer":"Yes. Every engine maintains the index automatically on INSERT, UPDATE and DELETE. REBUILD or REINDEX is only needed for bloat or corruption."},{"question":"Is a primary key automatically indexed?","answer":"Yes, every engine backs a primary key with an index. InnoDB and SQL Server (by default) go further and store the table itself in primary-key order, as do SQLite tables keyed by INTEGER PRIMARY KEY and Oracle index-organized tables. Ordinary PostgreSQL and Oracle tables are heaps with a separate key index."}],"related":["create-index-concurrently","unique-index","covering-index","drop-index"]},"source_url":"https://sqlly.app/sql-dialects/create-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/create-index-concurrently","corpus":"sql-dialects","engine":null,"language":"en","title":"Build an index without blocking writes","description":"CREATE INDEX CONCURRENTLY, ONLINE = ON, ALGORITHM=INPLACE with LOCK=NONE and Oracle's ONLINE, plus what SQLite users do instead: wait.","body":{"slug":"create-index-concurrently","name":"Index without blocking writes","h1":"Build an index without blocking writes","category":"ddl","lede":"Indexes on live tables: keep writes flowing while the index builds.","intro":"A plain CREATE INDEX blocks writes for the whole build in PostgreSQL, SQL Server and Oracle. PostgreSQL's CONCURRENTLY, SQL Server's ONLINE = ON and Oracle's ONLINE lift that; MySQL's InnoDB builds secondary indexes online by default. SQLite holds the database write lock for the whole build and has no alternative.","rows":[{"engine_slug":"sql-server","sql":"CREATE INDEX ix_orders_total ON orders (total) WITH (ONLINE = ON);","note":"Enterprise and Developer editions and Azure SQL only. The build takes a short shared lock at the start and a schema-modification lock at the end; in between, DML continues."},{"engine_slug":"postgresql","sql":"CREATE INDEX CONCURRENTLY ix_orders_total ON orders (total);","note":"Two table scans, slower, and it cannot run inside a transaction block. A failed build leaves an INVALID index you should DROP INDEX CONCURRENTLY."},{"engine_slug":"mysql","sql":"ALTER TABLE orders ADD INDEX ix_orders_total (total),\n  ALGORITHM = INPLACE, LOCK = NONE;","note":"InnoDB online DDL. Secondary index builds are INPLACE with concurrent DML by default; spelling out ALGORITHM and LOCK (also accepted by CREATE INDEX) makes the statement fail instead of silently blocking if online isn't possible."},{"engine_slug":"sqlite","sql":"CREATE INDEX ix_orders_total ON orders (total);","note":"No online build: the database write lock is held until the index is done. In WAL mode readers keep working; other writers wait or get SQLITE_BUSY."},{"engine_slug":"oracle","sql":"CREATE INDEX ix_orders_total ON orders (total) ONLINE;","note":"ONLINE needs Enterprise Edition. Add PARALLEL n for big builds. If an online build is interrupted, DBMS_REPAIR.ONLINE_INDEX_CLEAN tidies up before you retry."}],"verdict":"PostgreSQL's CONCURRENTLY works in every edition; SQL Server and Oracle reserve online builds for their enterprise editions; MySQL's InnoDB builds online by default; SQLite is the one engine where you schedule the pause.","faqs":[{"question":"Why is CONCURRENTLY slower in PostgreSQL?","answer":"It scans the table twice and waits for every transaction that might still use the old snapshot to finish, so it can take much longer than a plain build. It also can't run inside a transaction block."},{"question":"What is an INVALID index?","answer":"A PostgreSQL index left behind by a failed CONCURRENTLY build. Queries ignore it but every write still maintains it. Find them with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid, then DROP INDEX CONCURRENTLY and rebuild."},{"question":"Does online index creation cost anything in MySQL?","answer":"The build still uses I/O and buffer pool, and concurrent changes are logged and replayed at the end. The DDL also needs a brief exclusive metadata lock at its start and end, so a long-running transaction on the table can stall it, and new queries queue behind it."}],"related":["autoincrement-column","add-constraint","alter-column-type"]},"source_url":"https://sqlly.app/sql-dialects/create-index-concurrently","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/create-schema","corpus":"sql-dialects","engine":null,"language":"en","title":"Create a schema (namespace)","description":"CREATE SCHEMA in three engines, CREATE DATABASE as a synonym in MySQL, ATTACH DATABASE in SQLite, a user in Oracle.","body":{"slug":"create-schema","name":"Create a schema","h1":"Create a schema (namespace)","category":"ddl","lede":"Namespaces for tables: schemas, or whatever each engine calls the idea.","intro":"PostgreSQL, SQL Server and Oracle have schemas as named namespaces inside one database; in Oracle a schema is what a user owns. MySQL treats schema and database as the same thing. SQLite has no schemas inside a file; attaching another database file under a name is the closest equivalent.","rows":[{"engine_slug":"sql-server","sql":"CREATE SCHEMA sales AUTHORIZATION dbo;","note":"Must be the only statement in its batch. Objects are addressed as sales.orders, and each user's default schema (usually dbo) resolves unqualified names."},{"engine_slug":"postgresql","sql":"CREATE SCHEMA sales;","note":"search_path decides how unqualified names resolve. CREATE SCHEMA IF NOT EXISTS keeps migration scripts rerunnable."},{"engine_slug":"mysql","sql":"CREATE DATABASE sales;","note":"CREATE SCHEMA sales means exactly the same. A database is the only namespace level, and queries can join across databases on the same server."},{"engine_slug":"sqlite","sql":"ATTACH DATABASE 'sales.db' AS sales;","note":"Opens (or creates) another file and names it; qualify tables as sales.orders. The built-in names are main and temp. DETACH DATABASE sales closes it."},{"engine_slug":"oracle","sql":"CREATE USER sales IDENTIFIED BY sales_pwd QUOTA 100M ON users;","note":"Creating the user creates the schema of the same name. 18c+ also offers schema-only accounts with NO AUTHENTICATION, which own objects but can't log in. Grant CREATE TABLE before it can hold objects."}],"verdict":"PostgreSQL and SQL Server use schemas as everyday namespaces; Oracle has them too but ties each to a user; MySQL's schema is the database; SQLite replaces the idea with attached files.","faqs":[{"question":"Why does Oracle say every user has a schema?","answer":"Each Oracle user owns exactly one schema with the same name, and objects are created in it. Other schemas' objects are reached as sales.orders after a GRANT, and synonyms can hide the prefix. 23ai adds schema-level privileges such as GRANT SELECT ANY TABLE ON SCHEMA sales."},{"question":"Schema vs database in PostgreSQL?","answer":"A database is a separate connection target with its own catalogs; schemas are namespaces inside it. Queries across schemas are plain SQL, while queries across databases need postgres_fdw or dblink."},{"question":"What replaces schemas in SQLite?","answer":"Attached databases. Each connection can attach up to 10 files by default (the compile-time maximum is 125), and a single query can join tables across them by name, with transactions covering all of them."}],"related":["rename-table","temp-tables","comment-on"]},"source_url":"https://sqlly.app/sql-dialects/create-schema","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/cte-basics","corpus":"sql-dialects","engine":null,"language":"en","title":"CTE basics: WITH … AS across dialects","description":"Name a subquery and reference it in the next statement: the portable WITH form, version floors, and the extensions each dialect adds.","body":{"slug":"cte-basics","name":"CTE basics (WITH)","h1":"CTE basics: WITH … AS across dialects","category":"query","lede":"WITH works in all five engines; the details around it don't.","intro":"WITH name AS (SELECT …) defines a named result for the one statement that follows. The basic form is identical in all five engines. They differ in version floors (MySQL 8.0, SQLite 3.8.3), the RECURSIVE keyword, materialization control and data-modifying CTEs.","rows":[{"engine_slug":"sql-server","sql":"WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;","note":"The statement before WITH must end with a semicolon. Recursive CTEs use plain WITH; the RECURSIVE keyword is a syntax error."},{"engine_slug":"postgresql","sql":"WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;","note":"MATERIALIZED / NOT MATERIALIZED (12+) control inlining. WITH d AS (DELETE … RETURNING *) makes a data-modifying CTE."},{"engine_slug":"mysql","sql":"WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;","note":"8.0+ only; on 5.7 rewrite it as a derived table."},{"engine_slug":"sqlite","sql":"WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;","note":"Since 3.8.3, recursive CTEs included. MATERIALIZED / NOT MATERIALIZED hints since 3.35."},{"engine_slug":"oracle","sql":"WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;","note":"WITH has been supported since 9i. 12c adds WITH FUNCTION for inline PL/SQL, and the /*+ MATERIALIZE */ hint forces materialization."}],"verdict":"The basic WITH runs unchanged on all five engines, given MySQL 8.0+. The differences sit at the edges: PostgreSQL's data-modifying CTEs and materialization keywords, Oracle's WITH FUNCTION, and which engines want the RECURSIVE keyword.","faqs":[{"question":"Is a CTE a performance feature or just syntax?","answer":"Mostly syntax: it names a subquery. Whether it is computed once or inlined depends on the engine. PostgreSQL 12+ inlines a CTE referenced once and materializes one referenced several times; SQL Server always inlines, like a view, so a CTE referenced three times can run three times. Check the plan when it matters."},{"question":"Can I reuse a CTE across two queries?","answer":"No. A WITH clause belongs to one statement. To reuse a result across statements, put it in a temp table or a view, or repeat the WITH."},{"question":"How does a recursive CTE work?","answer":"An anchor SELECT, UNION ALL, then a SELECT that references the CTE's own name, repeated until it returns no rows. PostgreSQL and MySQL require WITH RECURSIVE; SQLite accepts it with or without the keyword; SQL Server and Oracle (11gR2+) use plain WITH and reject RECURSIVE. Oracle also has its older CONNECT BY syntax."}],"related":["select-into-temp","top-n-per-group","row-numbering"]},"source_url":"https://sqlly.app/sql-dialects/cte-basics","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/current-session-info","corpus":"sql-dialects","engine":null,"language":"en","title":"Current user, database and session id in every SQL dialect","description":"Show which user you are, which database you are connected to and your session id, per engine.","body":{"slug":"current-session-info","name":"Current session info","h1":"Current user, database and session id in every SQL dialect","category":"admin","lede":"The identity card query: who am I logged in as, where am I, and what is my session id.","intro":"Every engine has its own functions; there is zero shared syntax here. The concepts map cleanly though: user, database and session identifier.","rows":[{"engine_slug":"sql-server","sql":"SELECT SUSER_SNAME() AS login_name, DB_NAME() AS database_name, @@SPID AS session_id;","note":"USER_NAME() gives the database user (vs the login), ORIGINAL_LOGIN() the pre-execution-as login."},{"engine_slug":"postgresql","sql":"SELECT current_user, session_user, current_database(), pg_backend_pid();","note":"current_user is the effective role (after SET ROLE), session_user the original login; pg_backend_pid is the OS-level backend pid."},{"engine_slug":"mysql","sql":"SELECT CURRENT_USER() AS account, USER() AS host_detail, DATABASE() AS db, CONNECTION_ID() AS session_id;","note":"CURRENT_USER() shows the matched account, USER() includes the client host; CONNECTION_ID() matches ids used by KILL."},{"engine_slug":"sqlite","sql":"SELECT name, file FROM pragma_database_list;","note":"Embedded database: no logins and no session ids. The database_list pragma names the open schemas (main, temp and any attached files) and their paths, which is as close as it gets."},{"engine_slug":"oracle","sql":"SELECT USER AS username,\n  SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS current_schema,\n  SYS_CONTEXT('USERENV', 'SID') AS sid,\n  SYS_CONTEXT('USERENV', 'DB_NAME') AS db\nFROM dual;","note":"SYS_CONTEXT('USERENV', ...) is the general tool: also CLIENT_IDENTIFIER, CURRENT_SCHEMA, OS_USER and dozens more."}],"verdict":"No portability at all: five function families. Oracle's SYS_CONTEXT is by far the richest, SQLite has almost nothing to report, and the rest each have a user/database/session triple with slightly different semantics.","faqs":[{"question":"user vs login?","answer":"SQL Server separates server logins from database users; PostgreSQL separates session_user from effective current_user (SET ROLE); Oracle separates session user from current schema. MySQL's two functions capture the same distinction."},{"question":"How do I get my session id for KILL?","answer":"SQL Server @@SPID, MySQL CONNECTION_ID(), PostgreSQL pg_backend_pid(), Oracle SYS_CONTEXT('USERENV','SID')."},{"question":"What if the connection is pooled?","answer":"Session id changes per pooled connection, so do not cache it; re-read it when you need it."}],"related":["kill-session","server-version","list-connections"]},"source_url":"https://sqlly.app/sql-dialects/current-session-info","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/current-timestamp-precision","corpus":"sql-dialects","engine":null,"language":"en","title":"Current timestamp and its precision in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"GETDATE rounds, SYSDATETIME does not; NOW() is frozen per transaction in PostgreSQL until you call CLOCK_TIMESTAMP().","body":{"slug":"current-timestamp-precision","name":"Current timestamp and its precision","h1":"Current timestamp and its precision in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"The now() you call is not always the now you think: rounding and transaction freezing both apply.","intro":"Two subtleties hide in 'current timestamp': how many fractional digits you get, and whether repeated calls in one statement or transaction agree. Both differ by engine and by function.","rows":[{"engine_slug":"sql-server","sql":"SELECT SYSDATETIME(), GETDATE();","note":"GETDATE rounds to ~3ms (datetime); SYSDATETIME gives datetime2(7) at 100ns. There is also SYSUTCDATETIME() for UTC."},{"engine_slug":"postgresql","sql":"SELECT NOW(), CLOCK_TIMESTAMP();","note":"NOW()/transaction_timestamp() is fixed for the whole transaction, so every row in one INSERT gets the same value; CLOCK_TIMESTAMP() reads the actual clock each call."},{"engine_slug":"mysql","sql":"SELECT NOW(6), NOW();","note":"NOW() defaults to second precision; NOW(6) gives microseconds. NOW() returns the time the statement started, while SYSDATE() reads the real clock at each call."},{"engine_slug":"sqlite","sql":"SELECT DATETIME('now', 'subsec'), STRFTIME('%f', 'now');","note":"'now' is fixed for the duration of one statement; 'subsec' (3.42+) and the %f specifier both render the fractional seconds (SS.SSS)."},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP, SYSDATE FROM dual;","note":"SYSDATE has second resolution; SYSTIMESTAMP carries fractional seconds and a zone. SYSDATE and SYSTIMESTAMP use the database server's OS time zone; LOCALTIMESTAMP and CURRENT_TIMESTAMP use the session time zone."}],"verdict":"Know both knobs: precision (SYSDATETIME, NOW(6), SYSTIMESTAMP) and semantics (PostgreSQL freezes per transaction, MySQL's SYSDATE does not). For ordering events, pick the finest precision your engine offers.","faqs":[{"question":"Why do all rows in my PostgreSQL batch share a timestamp?","answer":"NOW() and CURRENT_TIMESTAMP are transaction timestamps, deliberately stable within the transaction for consistency. CLOCK_TIMESTAMP() varies per call if you need wall-clock sampling."},{"question":"Why does GETDATE() repeat values across rows?","answer":"datetime only has ~3ms resolution, so fast inserts collide. Use SYSDATETIME() with a datetime2 column for finer ordering."},{"question":"Which function gives UTC?","answer":"SYSUTCDATETIME() in SQL Server, NOW() AT TIME ZONE 'UTC' in PostgreSQL, UTC_TIMESTAMP() in MySQL, DATETIME('now') in SQLite (already UTC), and SYS_EXTRACT_UTC(SYSTIMESTAMP) in Oracle."}],"related":["extract-epoch","timezone-convert","date-truncate"]},"source_url":"https://sqlly.app/sql-dialects/current-timestamp-precision","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/custom-sort-order","corpus":"sql-dialects","engine":null,"language":"en","title":"Custom sort order: CASE, FIELD and DECODE","description":"Order rows by a business ranking (critical, high, low) instead of alphabetically, using mapped sort keys in each dialect.","body":{"slug":"custom-sort-order","name":"Custom sort order","h1":"Custom sort order: CASE, FIELD and DECODE","category":"query","lede":"Alphabetical order is wrong for statuses; map them to a rank instead.","intro":"Sort on an expression that maps each value to its position: a CASE expression works everywhere, MySQL's FIELD() lists the values directly, and Oracle's DECODE does the same in one line.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;","note":"Unknown values fall into ELSE; put the mapping in a lookup table with a sort_order column if it grows."},{"engine_slug":"postgresql","sql":"SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;","note":"An enum type sorts by its declaration order, an alternative worth knowing for fixed sets."},{"engine_slug":"mysql","sql":"SELECT * FROM tickets ORDER BY FIELD(severity, 'low', 'high', 'critical') DESC;","note":"FIELD() returns the 1-based position and 0 for values not in the list. Listing the values in reverse and sorting DESC puts critical first and unknown values (0) last, like the ELSE 3 in the other rows."},{"engine_slug":"sqlite","sql":"SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;","note":"No FIELD(); CASE is the only option."},{"engine_slug":"oracle","sql":"SELECT * FROM tickets ORDER BY DECODE(severity, 'critical', 0, 'high', 1, 'low', 2, 3);","note":"The last DECODE argument is the default for unmatched values; CASE reads the same."}],"verdict":"CASE is the portable form and states the mapping in readable SQL; FIELD and DECODE are terser engine dialects. If the ranking changes at runtime or has more than a handful of values, stop encoding it in ORDER BY and give the table a sort_order column.","faqs":[{"question":"How do I sort in a custom order but keep a secondary key?","answer":"List several keys: ORDER BY CASE … END, created_at. The CASE ranks first, and rows inside each rank are ordered by created_at, like any other multi-key sort."},{"question":"Why do unmatched values sort first with FIELD?","answer":"FIELD returns 0 when the value isn't in the list, and 0 sorts before 1, 2, 3 in ascending order. Either list the values in reverse and sort DESC, as the MySQL row does, or sort on FIELD(…) = 0 first: ORDER BY FIELD(severity, 'critical', 'high', 'low') = 0, FIELD(severity, 'critical', 'high', 'low'). A CASE with an explicit ELSE also works."},{"question":"Should I store the sort rank in the table instead?","answer":"Usually yes once the list is stable: a sort_order smallint column (or a PostgreSQL enum) sorts with a plain ORDER BY, uses a normal index, and lets the application reorder values without editing every query."}],"related":["conditional-expression","nulls-first-last","order-by-coalesce"]},"source_url":"https://sqlly.app/sql-dialects/custom-sort-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/date-diff-filter","corpus":"sql-dialects","engine":null,"language":"en","title":"Date difference filters in WHERE","description":"Select orders from the last 30 days: interval arithmetic per engine, and why DATEDIFF-style predicates defeat indexes.","body":{"slug":"date-diff-filter","name":"Date difference filters in WHERE","h1":"Date difference filters in WHERE","category":"query","lede":"Compute the cutoff first, then compare. Don't wrap the column in a function.","intro":"\"Created in the last 30 days\" is a range predicate: created_at >= cutoff. Every engine has its own cutoff arithmetic (DATEADD, intervals, SYSDATE - 30) and its own date-difference function, which belongs in the SELECT list rather than the WHERE clause.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM orders WHERE created_at >= DATEADD(DAY, -30, SYSDATETIME());","note":"DATEDIFF(DAY, created_at, SYSDATETIME()) <= 30 can't seek an index on created_at; the bare-column range can."},{"engine_slug":"postgresql","sql":"SELECT * FROM orders WHERE created_at >= now() - INTERVAL '30 days';","note":"Interval subtraction keeps the column bare; age(now(), created_at) <= INTERVAL '30 days' does not."},{"engine_slug":"mysql","sql":"SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL 30 DAY;","note":"DATEDIFF(NOW(), created_at) <= 30 can't use an index on created_at. DATE_SUB(NOW(), INTERVAL 30 DAY) is the same cutoff written as a function."},{"engine_slug":"sqlite","sql":"SELECT * FROM orders WHERE created_at >= datetime('now', '-30 days');","note":"datetime('now') is UTC text in 'YYYY-MM-DD HH:MM:SS' form, so stored values must use the same zone and layout. julianday(created_at) in the predicate defeats an index."},{"engine_slug":"oracle","sql":"SELECT * FROM orders WHERE created_at >= SYSDATE - 30;","note":"DATE arithmetic counts days. For TIMESTAMP columns, SYSTIMESTAMP - INTERVAL '30' DAY keeps fractional seconds."}],"verdict":"All five use the same shape, column >= computed constant, because that is the form an index on the column can serve. The DATEDIFF and age() versions read more naturally but evaluate a function per row. Put the arithmetic on the constant side.","faqs":[{"question":"Why is DATEDIFF(DAY, col, now()) <= 30 slow?","answer":"The function wraps the column, so the optimizer can't use an index on it and has to compute the function for every row. Rearranged as col >= cutoff, it becomes a range seek with the same result."},{"question":"How do date-difference functions differ across engines?","answer":"SQL Server's DATEDIFF counts boundaries crossed, so Dec 31 23:59 to Jan 1 00:01 is 1 day. MySQL's DATEDIFF subtracts the date parts. Oracle DATE subtraction returns fractional days, and PostgreSQL date subtraction returns an integer while timestamp subtraction returns an interval. Don't port these expressions without checking the numbers."},{"question":"Should I filter on 'last 30 days' or 'this month'?","answer":"They are different predicates: >= now() - 30 days is rolling, >= the first of the month is calendar-based. Compute the boundary from the current time with DATETRUNC(month, SYSDATETIME()) in SQL Server 2022+, date_trunc('month', now()) in PostgreSQL, DATE_FORMAT(NOW(), '%Y-%m-01') in MySQL, date('now', 'start of month') in SQLite or TRUNC(SYSDATE, 'MM') in Oracle."}],"related":["timestamp-range-filter","extract-part-sargable","implicit-cast-comparison"]},"source_url":"https://sqlly.app/sql-dialects/date-diff-filter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/date-to-text-format","corpus":"sql-dialects","engine":null,"language":"en","title":"Format a date as text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"One timestamp, four mask syntaxes: TO_CHAR in PostgreSQL and Oracle, % masks in MySQL, strftime in SQLite, .NET masks in SQL Server.","body":{"slug":"date-to-text-format","name":"Format a date as text","h1":"Format a date as text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"The same format call does not translate across engines: the masks themselves are different languages.","intro":"Formatting a date for display is a per-engine dialect of its own. Each row renders the current date and time as yyyy-mm-dd hh:mi (for example 2026-11-20 14:30) in that engine's native idiom.","rows":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm'), CONVERT(VARCHAR(16), GETDATE(), 120);","note":"FORMAT uses .NET masks and is slow. CONVERT style 120 is the ODBC canonical yyyy-mm-dd hh:mi:ss layout; VARCHAR(16) cuts off the seconds."},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(NOW(), 'YYYY-MM-DD HH24:MI');","note":"24-hour hours are HH24, not HH (HH is 12-hour). Minutes are MI."},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i');","note":"% masks with a twist: minutes are %i (%m is month)."},{"engine_slug":"sqlite","sql":"SELECT STRFTIME('%Y-%m-%d %H:%M', 'now');","note":"C-style strftime masks; only a fixed set of specifiers exists."},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI') FROM dual;","note":"Same mask family as PostgreSQL. Without a mask, TO_CHAR uses NLS_DATE_FORMAT."}],"verdict":"PostgreSQL and Oracle share TO_CHAR masks, MySQL and SQLite each have their own %-dialect, and SQL Server splits between fast style codes and slow .NET masks. Format at the presentation layer when possible.","faqs":[{"question":"Why does HH give me 02 when I expect 14?","answer":"In PostgreSQL and Oracle, HH is the 12-hour clock; HH24 is the 24-hour clock. MySQL's %H is already 24-hour."},{"question":"What is the fastest way to format in SQL Server?","answer":"CONVERT with a style code: it is a built-in conversion with no CLR call. FORMAT is flexible but invokes .NET for every row."},{"question":"Can one format string work everywhere?","answer":"Only by normalizing to a fixed ISO layout like yyyy-mm-dd, and even then you are choosing per engine between CONVERT style 120, TO_CHAR, DATE_FORMAT and strftime."}],"related":["parse-text-to-date","number-to-text-format","date-truncate"]},"source_url":"https://sqlly.app/sql-dialects/date-to-text-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/date-truncate","corpus":"sql-dialects","engine":null,"language":"en","title":"Truncate a date to day, month or year in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"DATE_TRUNC, TRUNC and SQL Server 2022's DATETRUNC take a unit argument; MySQL rebuilds the date from parts and SQLite uses modifiers.","body":{"slug":"date-truncate","name":"Truncate a date to day, month or year","h1":"Truncate a date to day, month or year in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Grouping by month starts with truncation; MySQL and pre-2022 SQL Server make you build the result by hand.","intro":"Truncation zeroes the sub-unit fields: truncate to month and you get the first of the month at midnight. It is the standard GROUP BY building block, and the engines split between one general function and hand-assembly.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(month, GETDATE()), CAST(GETDATE() AS DATE);","note":"DATETRUNC (2022+) takes year, quarter, month, week, day, hour and finer parts. Before 2022, day truncation is a CAST to DATE and month or year needs a DATEFROMPARTS(YEAR(d), MONTH(d), 1) rebuild."},{"engine_slug":"postgresql","sql":"SELECT DATE_TRUNC('month', NOW());","note":"One function for every unit: 'day', 'week' (Monday-start), 'month', 'quarter', 'year', plus finer ones like 'hour'."},{"engine_slug":"mysql","sql":"SELECT DATE(NOW());","note":"DATE() truncates to day only; month and year are DATE_FORMAT(d, '%Y-%m-01') rebuilds, or DATE_FORMAT(d, '%Y-01-01') for years."},{"engine_slug":"sqlite","sql":"SELECT DATE(paid_at, 'start of month') AS month, COUNT(*) FROM orders GROUP BY month;","note":"The modifier truncates the column; 'start of day', 'start of month' and 'start of year' cover the common units, and the result is TEXT in ISO form."},{"engine_slug":"oracle","sql":"SELECT TRUNC(paid_at, 'MM'), COUNT(*) FROM orders GROUP BY TRUNC(paid_at, 'MM');","note":"TRUNC mirrors PostgreSQL's generality: 'DD' (day, the default), 'MM', 'YYYY', 'IW' (ISO week) and more. Group on the expression itself; Oracle does not accept the select-list alias in GROUP BY."}],"verdict":"PostgreSQL, Oracle and SQL Server 2022+ take a unit argument. Elsewhere day truncation is easy and month or year truncation is assembly work, and that difference shapes every GROUP BY on a time bucket.","faqs":[{"question":"How do I group rows by month?","answer":"Group on the truncation: DATE_TRUNC('month', created_at) in PostgreSQL, TRUNC(created_at, 'MM') in Oracle, DATE_FORMAT(created_at, '%Y-%m') in MySQL, strftime('%Y-%m', created_at) in SQLite, and DATETRUNC(month, created_at) in SQL Server 2022+ (YEAR(created_at), MONTH(created_at) before that)."},{"question":"Does truncation hurt index use?","answer":"Yes. Wrapping the column in a function makes the predicate non-sargable. For range scans, compare created_at >= first-of-month AND < first-of-next-month instead of truncating the column."},{"question":"What does 'week' truncate to?","answer":"In PostgreSQL, Monday. In Oracle, TRUNC(d, 'IW') is the ISO Monday, while 'WW' counts weeks from January 1, whatever weekday that is. SQL Server's DATETRUNC(week, d) follows SET DATEFIRST, which is Sunday under us_english."}],"related":["first-day-of-month","last-day-of-month","date-to-text-format"]},"source_url":"https://sqlly.app/sql-dialects/date-truncate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/deadlock-inspection","corpus":"sql-dialects","engine":null,"language":"en","title":"Finding deadlock victims and blocked sessions in every SQL dialect","description":"Find which sessions block each other and pull recent deadlock reports, from system_health to SHOW ENGINE INNODB STATUS.","body":{"slug":"deadlock-inspection","name":"Deadlock investigation","h1":"Finding deadlock victims and blocked sessions in every SQL dialect","category":"admin","lede":"When transactions block each other, the engine kills one victim and logs the evidence. Here is where that evidence lives in each engine.","intro":"The four server engines detect deadlocks and break them; the work is finding the report afterwards. Live lock-wait chains are queryable in all four (MySQL through performance_schema). SQLite never waits in a cycle: it returns SQLITE_BUSY instead.","rows":[{"engine_slug":"sql-server","sql":"SELECT blocking_session_id, wait_type, wait_time, wait_resource\nFROM sys.dm_exec_requests\nWHERE blocking_session_id <> 0;\n-- deadlock graphs: system_health session, event xml_deadlock_report","note":"Live blocking via sys.dm_exec_requests; deadlock graphs are in the always-on system_health XEvent session (or SQL Server Profiler's Deadlock graph event)."},{"engine_slug":"postgresql","sql":"SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, wait_event, query\nFROM pg_stat_activity\nWHERE wait_event_type = 'Lock';","note":"pg_blocking_pids() names the blockers. Deadlocks are checked after deadlock_timeout (1s by default) and written to the server log with both queries; log_lock_waits = on also logs any lock wait longer than deadlock_timeout."},{"engine_slug":"mysql","sql":"SHOW ENGINE INNODB STATUS;\n-- section: LATEST DETECTED DEADLOCK","note":"The InnoDB monitor prints only the latest deadlock (both transactions and the victim); innodb_print_all_deadlocks = 1 logs every one to the error log. Live waits are in sys.innodb_lock_waits and performance_schema.data_lock_waits (8.0+)."},{"engine_slug":"sqlite","sql":"-- no deadlock reports: one writer at a time, no row locks","note":"A transaction that cannot get the lock it needs gets SQLITE_BUSY, immediately when waiting could deadlock (two readers both trying to upgrade). Start write transactions with BEGIN IMMEDIATE and use WAL mode to cut contention."},{"engine_slug":"oracle","sql":"SELECT sid, serial#, blocking_session, event, seconds_in_wait\nFROM v$session\nWHERE blocking_session IS NOT NULL;","note":"ORA-00060 rolls back only the statement that hit the deadlock, not its transaction, and writes a trace file with both sessions' SQL; the application must still commit or roll back. Live blocking chains are in v$session.blocking_session."}],"verdict":"Every server engine breaks deadlocks itself; the difference is where the report lands. SQL Server's system_health and MySQL's LATEST DETECTED DEADLOCK are the fastest reads, PostgreSQL and Oracle write server logs and trace files, and SQLite has no deadlock to report.","faqs":[{"question":"Who is the deadlock victim?","answer":"SQL Server picks the transaction cheapest to roll back unless SET DEADLOCK_PRIORITY says otherwise, InnoDB the one that changed fewer rows, and PostgreSQL the transaction whose deadlock check found the cycle. Oracle rolls back one statement in the session that detected it. Only SQL Server lets the application set priorities."},{"question":"How do I prevent deadlocks?","answer":"Touch tables and rows in the same order in every code path, keep transactions short, index the columns your UPDATE and DELETE statements filter on so they lock fewer rows, and retry the victim with backoff. Under real concurrency some deadlocks will happen, so the retry is not optional."},{"question":"Why does the report show my UPDATE twice?","answer":"Deadlock graphs show each transaction's held locks and current statement; both sides usually touched the same rows in different orders."}],"related":["kill-session","lock-timeout","select-for-update"]},"source_url":"https://sqlly.app/sql-dialects/deadlock-inspection","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/delete-limit","corpus":"sql-dialects","engine":null,"language":"en","title":"Delete only the first N rows","description":"MySQL has DELETE ... ORDER BY ... LIMIT built in; everywhere else you pick the victims in an ordered subquery first.","body":{"slug":"delete-limit","name":"DELETE with LIMIT","h1":"Delete only the first N rows","category":"dml","lede":"Prune a log table 100 rows at a time: the statement only MySQL writes natively.","intro":"Batched deletes are the standard trick to keep big clean-ups from holding long locks. MySQL is the only engine with first-class DELETE ... ORDER BY ... LIMIT; the rest target the same rows through an ordered subquery over the key or row id.","rows":[{"engine_slug":"sql-server","sql":"DELETE FROM events\nWHERE id IN (SELECT TOP (100) id FROM events\n             WHERE logged_at < '2024-01-01'\n             ORDER BY logged_at);","note":"DELETE TOP (100) exists but cannot take ORDER BY; the subquery form picks which rows go."},{"engine_slug":"postgresql","sql":"DELETE FROM events\nWHERE ctid IN (SELECT ctid FROM events\n               WHERE logged_at < '2024-01-01'\n               ORDER BY logged_at\n               LIMIT 100);","note":"No DELETE LIMIT. Target rows by primary key instead of ctid if a concurrent process may rewrite them."},{"engine_slug":"mysql","sql":"DELETE FROM events\nWHERE logged_at < '2024-01-01'\nORDER BY logged_at\nLIMIT 100;","note":"The only native DELETE ... ORDER BY ... LIMIT. An index on logged_at keeps each batch cheap to find; without ORDER BY, LIMIT is unsafe for statement-based replication."},{"engine_slug":"sqlite","sql":"DELETE FROM events\nWHERE rowid IN (SELECT rowid FROM events\n                WHERE logged_at < '2024-01-01'\n                ORDER BY logged_at\n                LIMIT 100);","note":"DELETE ... LIMIT exists only in builds compiled with SQLITE_ENABLE_UPDATE_DELETE_LIMIT; the subquery works everywhere."},{"engine_slug":"oracle","sql":"DELETE FROM events\nWHERE rowid IN (SELECT rowid FROM events\n                WHERE logged_at < DATE '2024-01-01'\n                ORDER BY logged_at\n                FETCH FIRST 100 ROWS ONLY);","note":"Pick the victims with FETCH FIRST (12c+) and address them by rowid."}],"verdict":"Selecting the victims' keys in a subquery is the portable pattern, and it is worth knowing even on MySQL because it extends to 'delete the oldest N per group' with a window function. Run it in a loop until it deletes zero rows.","faqs":[{"question":"Why batch big deletes at all?","answer":"One giant DELETE holds its locks and undo or log space until it finishes. Batches of a few thousand rows with a commit between them keep locks short, keep the log small and let replicas keep up."},{"question":"What are ctid and rowid?","answer":"Physical row addresses: PostgreSQL's ctid, Oracle's ROWID and SQLite's rowid point straight at the rows the subquery picked. ctid changes whenever a row is updated, so in busy tables prefer the primary key."},{"question":"Why not delete straight from a SELECT … LIMIT?","answer":"Only MySQL accepts ORDER BY and LIMIT on DELETE itself (SQLite only in special builds). Elsewhere the statement needs a way to say which rows, and the subquery over a key or row address is that list, written explicitly."}],"related":["delete-with-join","truncate-vs-delete","multi-row-insert"]},"source_url":"https://sqlly.app/sql-dialects/delete-limit","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/delete-with-join","corpus":"sql-dialects","engine":null,"language":"en","title":"DELETE rows matched in another table","description":"DELETE ... USING, DELETE with a FROM join, and the IN / EXISTS subqueries that stand in where joins are not allowed.","body":{"slug":"delete-with-join","name":"DELETE with a join","h1":"DELETE rows matched in another table","category":"dml","lede":"Remove the orders of deleted customers: two tables, one DELETE, four syntaxes.","intro":"SQL Server and MySQL let a DELETE carry a join, naming the target alias right after DELETE. PostgreSQL has a USING clause, and Oracle 23ai a FROM clause. SQLite and older Oracle accept no join in DELETE, so they use an IN or EXISTS subquery, which runs on all five.","rows":[{"engine_slug":"sql-server","sql":"DELETE o\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nWHERE c.deleted = 1;","note":"The alias after DELETE names the table whose rows go; extra joined tables stay read-only."},{"engine_slug":"postgresql","sql":"DELETE FROM orders o\nUSING customers c\nWHERE c.id = o.customer_id\n  AND c.deleted = 1;","note":"USING is PostgreSQL's join clause for DELETE; only rows of the target table are ever removed."},{"engine_slug":"mysql","sql":"DELETE o\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nWHERE c.deleted = 1;","note":"Same shape as SQL Server. MySQL also allows listing two targets (DELETE o, c FROM ...) to delete from both tables at once."},{"engine_slug":"sqlite","sql":"DELETE FROM orders\nWHERE customer_id IN (SELECT id FROM customers\n                      WHERE deleted = 1);","note":"No join in DELETE. The IN subquery is the portable form and reads just as well."},{"engine_slug":"oracle","sql":"DELETE FROM orders o\nWHERE EXISTS (SELECT 1 FROM customers c\n              WHERE c.id = o.customer_id\n                AND c.deleted = 1);","note":"Correlated EXISTS runs on every version. 23ai also accepts a join: DELETE orders o FROM customers c WHERE c.id = o.customer_id AND c.deleted = 1."}],"verdict":"PostgreSQL's USING is tidy, SQL Server and MySQL share the DELETE-alias join, and Oracle 23ai has its own FROM form. The subquery is the only version that runs unchanged on all five engines.","faqs":[{"question":"Is the subquery form slower than the join?","answer":"Rarely. Current optimizers turn IN and EXISTS into the same semi-join an explicit join produces, so the plans usually match. Check the plan on very old MySQL versions, which handled IN subqueries in DELETE poorly."},{"question":"Can I delete from two tables in one statement?","answer":"MySQL can, with a multi-table DELETE (DELETE o, c FROM …). PostgreSQL can chain data-modifying CTEs: WITH gone AS (DELETE FROM customers WHERE deleted = 1 RETURNING id) DELETE FROM orders WHERE customer_id IN (SELECT id FROM gone). Elsewhere, run two DELETEs in one transaction."},{"question":"What about ON DELETE CASCADE instead?","answer":"If the foreign key is declared with ON DELETE CASCADE, deleting the parent rows removes the children with no join at all (see add-constraint). In SQLite that also requires PRAGMA foreign_keys = ON."}],"related":["update-with-join","delete-limit","add-constraint"]},"source_url":"https://sqlly.app/sql-dialects/delete-with-join","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/descending-index","corpus":"sql-dialects","engine":null,"language":"en","title":"DESC in index definitions across every SQL dialect","description":"Store an index column in descending order so mixed ASC/DESC ORDER BY queries avoid a sort, in all five engines.","body":{"slug":"descending-index","name":"Descending index","h1":"DESC in index definitions across every SQL dialect","category":"indexes","lede":"A descending index reverses the stored order of a column, letting ORDER BY a ASC, b DESC walk the index without a sort step.","intro":"The syntax is the same everywhere; the catch is MySQL, where DESC in the index definition was parsed and silently ignored before 8.0, so the mixed-direction optimization only exists on modern versions.","rows":[{"engine_slug":"sql-server","sql":"CREATE INDEX idx_orders_customer_created ON orders (customer_id ASC, created_at DESC);","note":"DESC/ASC per key column, fully supported. The usual fix for ORDER BY customer_id, created_at DESC avoiding a sort."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);","note":"Supported, plus NULLS FIRST/LAST control inside the index definition. A single-column index is scanned backwards for free, so DESC only matters in mixed-direction keys."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);","note":"Descending key parts are real since 8.0 (before that DESC was accepted and ignored). EXPLAIN shows Using filesort when the index cannot supply the order."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);","note":"Supported since 3.3, and SQLite scans single-column indexes backward at no cost, so DESC matters only in multi-column keys."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);","note":"Oracle implements a DESC key column as a function-based index; the column shows up in USER_IND_EXPRESSIONS. A single-column DESC index is pointless because the optimizer can scan an ascending one backwards."}],"verdict":"Same syntax everywhere and MySQL finally honors it since 8.0. Remember the free trick: any engine can read a single-column ASC index backwards, so a plain DESC index is rarely worth it on its own.","faqs":[{"question":"When does DESC actually matter?","answer":"Only with mixed directions, like ORDER BY a ASC, b DESC. A single-column DESC index buys nothing over scanning an ASC index backwards."},{"question":"My MySQL 5.7 ignores DESC?","answer":"Correct: 5.7 parses DESC in CREATE INDEX and discards it, building an ascending index. Upgrade to 8.0+ for real descending key parts."},{"question":"How do I verify the sort was avoided?","answer":"Look for the missing step: no Sort operator in SQL Server's plan, no Sort node in PostgreSQL's EXPLAIN, no Using filesort in MySQL, no USE TEMP B-TREE FOR ORDER BY in SQLite's EXPLAIN QUERY PLAN, and no SORT ORDER BY in Oracle's plan."}],"related":["create-index","covering-index","expression-index"]},"source_url":"https://sqlly.app/sql-dialects/descending-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/disable-triggers","corpus":"sql-dialects","engine":null,"language":"en","title":"Disabling and enabling triggers in every SQL dialect","description":"Turn triggers off for bulk loads or maintenance, and back on, in SQL Server, PostgreSQL, Oracle and elsewhere.","body":{"slug":"disable-triggers","name":"Disable triggers","h1":"Disabling and enabling triggers in every SQL dialect","category":"admin","lede":"Triggers run for every row or statement of a bulk load. SQL Server, PostgreSQL and Oracle can switch them off; MySQL and SQLite cannot.","intro":"SQL Server, PostgreSQL and Oracle have first-class disable statements. MySQL and SQLite have none: you either drop and recreate the trigger, or build a kill-switch into the trigger body.","rows":[{"engine_slug":"sql-server","sql":"DISABLE TRIGGER trg_audit ON orders;\n-- re-enable:\nENABLE TRIGGER trg_audit ON orders;","note":"DISABLE TRIGGER ... ON DATABASE or ON ALL SERVER covers DDL triggers, and sys.triggers shows is_disabled. BULK INSERT and bcp skip triggers anyway unless you pass FIRE_TRIGGERS."},{"engine_slug":"postgresql","sql":"ALTER TABLE orders DISABLE TRIGGER trg_audit;\n-- all triggers on the table: ALTER TABLE orders DISABLE TRIGGER ALL;","note":"DISABLE TRIGGER ALL also disables FK-checking triggers, which is the documented bulk-load path. ENABLE TRIGGER ALL brings them back; superuser needed for system triggers. SET session_replication_role = replica skips ordinary triggers for one session instead."},{"engine_slug":"mysql","sql":"-- no disable: guard the trigger body with a session flag\nSET @disable_triggers = 1;\n-- inside the trigger body: IF @disable_triggers = 1 THEN LEAVE trig; END IF;\nSET @disable_triggers = NULL;","note":"The convention: every trigger checks a session variable first and exits. DROP TRIGGER and re-CREATE also works, but rows other sessions write in between skip the trigger."},{"engine_slug":"sqlite","sql":"-- no disable; drop and recreate, or add a WHEN guard","note":"No enable/disable. DROP TRIGGER then re-create from your schema source, or design triggers with WHEN conditions you can satisfy/skip."},{"engine_slug":"oracle","sql":"ALTER TRIGGER trg_audit DISABLE;\n-- all triggers on a table:\nALTER TABLE orders DISABLE ALL TRIGGERS;","note":"Mirrored by ENABLE / ENABLE ALL TRIGGERS. user_triggers shows status (ENABLED/DISABLED); disabled triggers still compile but never fire."}],"verdict":"Three engines have real statements, two do not. The MySQL session-variable guard is the only pattern that survives code review there; in SQLite, dropping and recreating from version-controlled schema is normal.","faqs":[{"question":"Do disabled triggers still fire for FK enforcement?","answer":"PostgreSQL's DISABLE TRIGGER ALL covers internal FK triggers too, which is why it needs superuser. SQL Server and Oracle foreign keys are constraints, not triggers, and stay enforced."},{"question":"What happens to data written while disabled?","answer":"Nothing retroactive: the trigger simply does not run. After re-enabling, backfill anything the disabled period skipped."},{"question":"Why is my bulk load slow even with triggers off?","answer":"Usually the indexes. Drop or disable nonessential indexes too, load, then rebuild them; index maintenance is often the bigger cost."}],"related":["drop-index","rebuild-index","vacuum-analyze"]},"source_url":"https://sqlly.app/sql-dialects/disable-triggers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/distinct-on-expression","corpus":"sql-dialects","engine":null,"language":"en","title":"DISTINCT on an expression","description":"Deduplicate the result of a function (distinct lowercased emails, distinct years of a date) in each dialect, and where collation already does it.","body":{"slug":"distinct-on-expression","name":"DISTINCT on an expression","h1":"DISTINCT on an expression","category":"query","lede":"DISTINCT works on computed values the same way it works on columns.","intro":"Any expression can follow DISTINCT and the engine deduplicates the computed values. The syntax is identical in all five engines. What differs is how the comparison treats case: on SQL Server and MySQL's default collations, DISTINCT email already merges 'Ana@x.com' and 'ana@x.com'.","rows":[{"engine_slug":"sql-server","sql":"SELECT DISTINCT LOWER(email) FROM users;","note":"With the default case-insensitive collation, DISTINCT email returns the same count, and which casing you see for each group is arbitrary."},{"engine_slug":"postgresql","sql":"SELECT DISTINCT LOWER(email) FROM users;","note":"Comparison is case-sensitive, so LOWER() changes the result. DISTINCT ON (LOWER(email)) * … ORDER BY LOWER(email), id keeps one full row per value."},{"engine_slug":"mysql","sql":"SELECT DISTINCT LOWER(email) FROM users;","note":"Default *_ci collations already fold case (utf8mb4_0900_ai_ci also folds accents), so DISTINCT email gives the same count."},{"engine_slug":"sqlite","sql":"SELECT DISTINCT lower(email) FROM users;","note":"Case-sensitive by default. lower() folds ASCII letters only unless the ICU extension is loaded."},{"engine_slug":"oracle","sql":"SELECT DISTINCT LOWER(email) FROM users;","note":"Case-sensitive by default. SELECT UNIQUE is an old Oracle synonym for DISTINCT."}],"verdict":"The query itself is fully portable. The result is not: the same DISTINCT email returns fewer rows on SQL Server and MySQL than on PostgreSQL, SQLite and Oracle, because their default collations ignore case. Write the folding expression explicitly when the count matters. DISTINCT ON exists only in PostgreSQL.","faqs":[{"question":"Does DISTINCT apply to one column or the whole row?","answer":"The whole result row. SELECT DISTINCT a, b returns distinct (a, b) pairs; there is no way to deduplicate on one column while returning others. For that, use GROUP BY with aggregates, ROW_NUMBER() … WHERE rn = 1, or PostgreSQL's DISTINCT ON."},{"question":"Why does DISTINCT email return different counts on different engines?","answer":"Collation. SQL Server's and MySQL's default collations compare 'Ana@x.com' and 'ana@x.com' as equal, so DISTINCT keeps one. PostgreSQL, SQLite and Oracle compare bytes by default and keep both. DISTINCT LOWER(email) gives the same count everywhere (for ASCII data)."},{"question":"What does DISTINCT ON give me that GROUP BY doesn't?","answer":"A complete row per group without aggregating every other column. The ORDER BY decides which row wins: DISTINCT ON (customer_id) * … ORDER BY customer_id, created_at DESC keeps each customer's newest order. The leading ORDER BY expressions must match the DISTINCT ON list."}],"related":["top-n-per-group","case-insensitive-compare","custom-sort-order"]},"source_url":"https://sqlly.app/sql-dialects/distinct-on-expression","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/drop-column","corpus":"sql-dialects","engine":null,"language":"en","title":"Drop a column from a table","description":"One ALTER TABLE for most engines; SQLite needs 3.35+ and refuses when indexes or views use the column, so plan the rebuild.","body":{"slug":"drop-column","name":"Drop column","h1":"Drop a column from a table","category":"ddl","lede":"Remove a column and its data: trivial in four engines, sometimes a rebuild in SQLite.","intro":"Four engines drop a column with the same one-liner. SQLite added DROP COLUMN in 3.35 (2021) and still refuses when the column is a key, indexed, or used by a constraint, view or trigger. Those cases need the rebuild: create the new table, copy, drop, rename.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE customers DROP COLUMN fax;","note":"Drop several comma-separated columns in one statement. Any DEFAULT, CHECK or foreign key constraint and any index on the column must be dropped first."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers DROP COLUMN fax;","note":"Instant: the column is hidden and its space is reclaimed as rows are rewritten. Indexes on it go with it; views that use it block the drop unless you add CASCADE, which drops them too."},{"engine_slug":"mysql","sql":"ALTER TABLE customers DROP COLUMN fax;","note":"DROP fax without COLUMN also works. The column is removed from any index that contains it, and an index left with no columns is dropped. 8.0.29+ can drop columns with ALGORITHM=INSTANT."},{"engine_slug":"sqlite","sql":"ALTER TABLE customers DROP COLUMN fax;","note":"3.35+, and only if the column isn't a PRIMARY KEY, UNIQUE, indexed, or used in a CHECK, foreign key, generated column, view or trigger. Otherwise rebuild the table."},{"engine_slug":"oracle","sql":"ALTER TABLE customers DROP COLUMN fax;","note":"On big tables, SET UNUSED COLUMN fax hides the column at once and DROP UNUSED COLUMNS removes the data later; CHECKPOINT n limits undo during that pass."}],"verdict":"The one-liner works on all five current versions. For SQLite, check the version and the column's dependents first, and use the rebuild when it refuses.","faqs":[{"question":"Is dropping a column recoverable?","answer":"Not with SQL: the data is gone once the statement commits, even where the space is reclaimed later. PostgreSQL and SQL Server can roll back the DROP inside an open transaction; otherwise you restore from a backup."},{"question":"What is Oracle's SET UNUSED for?","answer":"It removes the column from the table definition immediately, without touching the rows, which matters on huge tables. A later ALTER TABLE customers DROP UNUSED COLUMNS rewrites the blocks and reclaims the space when convenient."},{"question":"Why does SQLite reject my DROP COLUMN?","answer":"The column is a key, is indexed, or is used by a constraint, generated column, view or trigger. Drop the dependent index, view or trigger first, or rebuild the table (alter-column-type shows the pattern)."}],"related":["add-column","alter-column-type","rename-column"]},"source_url":"https://sqlly.app/sql-dialects/drop-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/drop-index","corpus":"sql-dialects","engine":null,"language":"en","title":"DROP INDEX in every SQL dialect","description":"Remove an index; SQL Server and MySQL need the table name, the rest drop it by index name alone.","body":{"slug":"drop-index","name":"DROP INDEX","h1":"DROP INDEX in every SQL dialect","category":"indexes","lede":"Dropping an index is nearly universal, with one twist: SQL Server and MySQL require the table name in the statement.","intro":"Dropping an index is quick everywhere because it only frees pages; the cost shows up later if a query needed it. The portability question is whether the statement needs the table name.","rows":[{"engine_slug":"sql-server","sql":"DROP INDEX idx_orders_customer ON orders;","note":"Requires the table name. DROP INDEX IF EXISTS works since 2016. An index that enforces a PRIMARY KEY or UNIQUE constraint refuses to drop (Msg 3723); use ALTER TABLE ... DROP CONSTRAINT."},{"engine_slug":"postgresql","sql":"DROP INDEX idx_orders_customer;","note":"Drops by name alone, taking an ACCESS EXCLUSIVE lock on the table. DROP INDEX CONCURRENTLY avoids blocking reads and writes but cannot run inside a transaction."},{"engine_slug":"mysql","sql":"DROP INDEX idx_orders_customer ON orders;","note":"Requires the table name. Also spelled ALTER TABLE orders DROP INDEX idx_orders_customer."},{"engine_slug":"sqlite","sql":"DROP INDEX idx_orders_customer;","note":"Simple name-based drop. The sqlite_autoindex_* indexes behind UNIQUE and PRIMARY KEY constraints cannot be dropped; removing the constraint means rebuilding the table."},{"engine_slug":"oracle","sql":"DROP INDEX idx_orders_customer;","note":"Name-based. An index that enforces a primary or unique key raises ORA-02429; drop or disable the constraint first."}],"verdict":"Three engines drop by name alone; SQL Server and MySQL want the table. Indexes that enforce constraints are protected in SQL Server, PostgreSQL, SQLite and Oracle: drop the constraint instead.","faqs":[{"question":"What happens to running queries when I drop an index?","answer":"The drop needs an exclusive lock on the table (a metadata lock in MySQL), so it waits for running statements on that table and blocks new ones while it waits. The drop itself is fast; avoid running it under a long report. PostgreSQL's CONCURRENTLY avoids the blocking."},{"question":"Can I get the index back without rebuilding?","answer":"No. DROP removes the definition and data; the only path back is CREATE INDEX again."},{"question":"How do I find what an index was on first?","answer":"Check catalog views: sys.indexes + sys.index_columns in SQL Server, pg_indexes in PostgreSQL, SHOW CREATE TABLE in MySQL, PRAGMA index_info in SQLite, user_ind_columns in Oracle."}],"related":["create-index","rebuild-index","unique-index"]},"source_url":"https://sqlly.app/sql-dialects/drop-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/escape-single-quotes","corpus":"sql-dialects","engine":null,"language":"en","title":"Escaping single quotes in string literals","description":"Write O'Brien inside a SQL literal: doubled quotes everywhere, plus dollar-quoting, q-quotes and backslash rules per engine.","body":{"slug":"escape-single-quotes","name":"Escaping single quotes","h1":"Escaping single quotes in string literals","category":"query","lede":"Doubling the quote works everywhere; three engines offer nicer ways out.","intro":"In every dialect, a single quote inside a literal is written as two single quotes: 'O''Brien'. MySQL also accepts a backslash escape, PostgreSQL has dollar-quoting and E'' strings, and Oracle has q-quoted literals. SQL Server and SQLite have only the doubling rule.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM users WHERE last_name = 'O''Brien';","note":"Doubling is the only escape. QUOTENAME(@s, '''') produces a quoted, doubled literal when building dynamic SQL, but it returns NULL for input over 128 characters."},{"engine_slug":"postgresql","sql":"SELECT * FROM users WHERE last_name = 'O''Brien';","note":"Dollar-quoting skips the doubling: $$O'Brien$$. E'O\\'Brien' is the backslash-escape form; in a plain literal, backslash is an ordinary character."},{"engine_slug":"mysql","sql":"SELECT * FROM users WHERE last_name = 'O''Brien';","note":"'O\\'Brien' also works unless sql_mode includes NO_BACKSLASH_ESCAPES. Double-quoted strings work too unless ANSI_QUOTES is set."},{"engine_slug":"sqlite","sql":"SELECT * FROM users WHERE last_name = 'O''Brien';","note":"Doubling is the only escape; a backslash in a literal is just a backslash."},{"engine_slug":"oracle","sql":"SELECT * FROM users WHERE last_name = 'O''Brien';","note":"q'[O'Brien]' lets you pick the delimiters ([], {}, <>, () or any single character), which helps with text full of quotes."}],"verdict":"'O''Brien' is the one form that runs on all five engines. In application code, bind the value as a parameter and the question goes away. The engine-specific literal styles are for scripts, migrations and debugging, not for escaping user input by hand, which is how SQL injection happens.","faqs":[{"question":"Why does one quote break the whole query?","answer":"The parser takes the quote in O'Brien as the end of the literal, so 'O' becomes the string and Brien' becomes the start of a syntax error. That same mechanism is what SQL injection exploits. Two quotes in a row ('') put one literal quote in the string."},{"question":"What is dollar-quoting?","answer":"A PostgreSQL literal: $$O'Brien$$ ends only at the closing $$, so nothing inside needs escaping. Add a tag, as in $body$…$body$, when the text itself contains $$. It is PostgreSQL-only and mostly used for function bodies."},{"question":"Shouldn't I just sanitize quotes in application code?","answer":"No. Bind parameters. Hand escaping breaks on edge cases such as MySQL's backslash mode or multibyte encodings, and it is the classic injection hole. Keep it for one-off scripts you type yourself."}],"related":["string-concatenation","like-escape","regex-matching"]},"source_url":"https://sqlly.app/sql-dialects/escape-single-quotes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/expression-index","corpus":"sql-dialects","engine":null,"language":"en","title":"Indexes on expressions like LOWER(col) in every SQL dialect","description":"Index the result of a function such as LOWER(email) so case-insensitive lookups use an index, in all five engines.","body":{"slug":"expression-index","name":"Expression / functional index","h1":"Indexes on expressions like LOWER(col) in every SQL dialect","category":"indexes","lede":"An expression index stores a function result instead of the raw column, which makes WHERE LOWER(email) = ? use an index.","intro":"PostgreSQL, SQLite and Oracle index expressions directly. MySQL 8.0.13+ accepts parenthesized functional key parts. SQL Server needs a detour: a persisted computed column that you then index.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE users ADD email_lower AS LOWER(email) PERSISTED;\nCREATE INDEX idx_users_email_lower ON users (email_lower);","note":"No direct expression indexes. Add a computed column (PERSISTED is optional when the expression is deterministic) and index it. The optimizer matches WHERE LOWER(email) = ... to the computed column, so queries need not name it. The session needs QUOTED_IDENTIFIER ON."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_users_email_lower ON users (LOWER(email));","note":"Direct support. The expression must be immutable, and the query must repeat the exact expression to use the index."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_users_email_lower ON users ((LOWER(email)));","note":"Functional key parts since 8.0.13; note the double parentheses. Older versions need a generated column + index. Queries must repeat the expression."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_users_email_lower ON users (LOWER(email));","note":"Expression indexes since 3.9.0. The query must spell the expression identically to use it."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_users_email_lower ON users (LOWER(email));","note":"Function-based indexes, available since 8i. The function must be deterministic; gather statistics afterwards so the optimizer can cost the hidden virtual column."}],"verdict":"Three engines do it inline, MySQL does it with double parens, SQL Server makes you add a computed column first. All five can do it; the query must repeat the expression exactly in every one of them.","faqs":[{"question":"Why does my expression index not get used?","answer":"The WHERE clause must contain the same expression. WHERE email = 'x' will not use an index on LOWER(email); the query has to say LOWER(email) = 'x'."},{"question":"Does lower() beat a case-insensitive collation?","answer":"Not necessarily. CI collations in SQL Server, MySQL and Oracle make plain indexes case-insensitive without expressions; lower() is the portable route that behaves identically everywhere."},{"question":"Any restrictions on the expression?","answer":"It must be deterministic/immutable. LOWER, SUBSTR and arithmetic are fine; anything depending on session state or time is not."}],"related":["create-index","covering-index","unique-index"]},"source_url":"https://sqlly.app/sql-dialects/expression-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/extract-epoch","corpus":"sql-dialects","engine":null,"language":"en","title":"Get the Unix timestamp of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Seconds since 1970: EXTRACT(EPOCH ...) in PostgreSQL, UNIX_TIMESTAMP in MySQL, unixepoch() in SQLite, and arithmetic from 1970 in SQL Server and Oracle.","body":{"slug":"extract-epoch","name":"Get the Unix timestamp of a date","h1":"Get the Unix timestamp of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Three engines have a function for it; in SQL Server and Oracle you count from 1970 yourself.","intro":"Unix timestamps (seconds since 1970-01-01 UTC) are the interchange format for everything non-SQL, so each engine offers some path to them. Watch the time zone: only the UTC-based forms are unambiguous.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATEDIFF(SECOND, '1970-01-01', SYSUTCDATETIME());","note":"Count seconds from the epoch against the UTC clock; GETDATE() would mix local time into the number. DATEDIFF returns int, which runs out in 2038, so use DATEDIFF_BIG for milliseconds or far-future dates."},{"engine_slug":"postgresql","sql":"SELECT EXTRACT(EPOCH FROM NOW());","note":"EXTRACT(EPOCH ...) works on timestamps and dates, returning a numeric with fractional seconds. NOW() is time-zone aware, so the result is correct UTC epoch."},{"engine_slug":"mysql","sql":"SELECT UNIX_TIMESTAMP(NOW());","note":"Dedicated function; interprets the input in the session time zone and returns an integer second count."},{"engine_slug":"sqlite","sql":"SELECT unixepoch(), STRFTIME('%s', 'now');","note":"unixepoch() (3.38+) returns an integer; STRFTIME('%s', ...) returns the same value as text and works on older versions. 'now' is UTC, and date strings without an offset are read as UTC."},{"engine_slug":"oracle","sql":"SELECT (CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE) - DATE '1970-01-01') * 86400 FROM dual;","note":"No built-in: date subtraction yields days, so multiply by 86400. SYS_EXTRACT_UTC keeps the base UTC."}],"verdict":"PostgreSQL, MySQL and SQLite name the operation. SQL Server and Oracle are epoch arithmetic that works but needs discipline about UTC, and SQL Server's int-returning DATEDIFF needs DATEDIFF_BIG for milliseconds.","faqs":[{"question":"Why do I get a local-time epoch on MySQL?","answer":"UNIX_TIMESTAMP interprets naive input in the session time zone. If the column stores local wall time, the epoch follows that zone's offset; pin the session zone or store UTC."},{"question":"How do I get milliseconds?","answer":"EXTRACT(EPOCH FROM CLOCK_TIMESTAMP()) * 1000 in PostgreSQL, DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME()) in SQL Server (plain DATEDIFF overflows), UNIX_TIMESTAMP(NOW(3)) * 1000 in MySQL, unixepoch('now', 'subsec') * 1000 in SQLite 3.42+, and SYS_EXTRACT_UTC(SYSTIMESTAMP) arithmetic in Oracle."},{"question":"Is EXTRACT(EPOCH FROM date) timezone-affected?","answer":"From a date or a timestamp without time zone, no: the value is taken at face value as if it were UTC. From timestamptz it converts the instant correctly."}],"related":["from-unix-timestamp","timezone-convert","current-timestamp-precision"]},"source_url":"https://sqlly.app/sql-dialects/extract-epoch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/extract-part-sargable","corpus":"sql-dialects","engine":null,"language":"en","title":"Filtering by year or month without losing the index","description":"WHERE YEAR(col) = 2026 scans the table; the equivalent range predicate seeks. Both forms, and expression indexes when you can't rewrite.","body":{"slug":"extract-part-sargable","name":"Sargable year/month filtering","h1":"Filtering by year or month without losing the index","category":"query","lede":"YEAR() or EXTRACT() on the column hides it from its index. Rewrite as a range.","intro":"Filtering on a date part tempts you into YEAR(col) = 2026 or EXTRACT(YEAR FROM col) = 2026. Both wrap the column and defeat its index. The sargable form is a half-open range on the column itself; expression indexes are the fallback when the function form must stay.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01';","note":"YEAR(created_at) = 2026 can't seek an index on created_at. A computed column (ALTER TABLE orders ADD order_year AS YEAR(created_at)) with its own index makes the function form seekable."},{"engine_slug":"postgresql","sql":"SELECT * FROM orders WHERE created_at >= DATE '2026-01-01' AND created_at < DATE '2027-01-01';","note":"EXTRACT(YEAR FROM created_at) = 2026 needs an expression index: CREATE INDEX ON orders ((EXTRACT(YEAR FROM created_at))). That index is rejected on timestamptz, where EXTRACT depends on the session time zone."},{"engine_slug":"mysql","sql":"SELECT * FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01';","note":"YEAR(created_at) = 2026 can't use an index on created_at; an 8.0.13+ functional index on ((YEAR(created_at))) can serve it."},{"engine_slug":"sqlite","sql":"SELECT * FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01';","note":"Works when created_at holds ISO-8601 text, which sorts chronologically. strftime('%Y', created_at) = '2026' can't use an index on the column."},{"engine_slug":"oracle","sql":"SELECT * FROM orders WHERE created_at >= DATE '2026-01-01' AND created_at < DATE '2027-01-01';","note":"EXTRACT(YEAR FROM created_at) = 2026 needs a function-based index on exactly that expression."}],"verdict":"The half-open range wins on every engine: it can use the plain index on the column, it ports with only the literal syntax changing, and it needs nothing extra. Use function-form predicates only where a matching expression index already exists, and spell the expression exactly as it was indexed.","faqs":[{"question":"What does 'sargable' mean?","answer":"Search-argument-able: a predicate the optimizer can answer with an index seek because the indexed column stands bare on one side of the comparison. YEAR(col) = 2026 hides the column inside a function, so the engine evaluates it row by row."},{"question":"How do I filter 'this month' sargably?","answer":"Compute the boundaries first, as in created_at >= '2026-11-01' AND created_at < '2026-12-01'. Functions that build the boundary (DATEFROMPARTS or DATETRUNC in T-SQL, date_trunc in PostgreSQL, TRUNC(SYSDATE, 'MM') in Oracle) go on the constant side and wrap the current date, never the column."},{"question":"When is an expression index the better fix?","answer":"When you can't change the query (third-party or ORM-generated SQL) or many queries use the function form. The index adds write cost and only matches the exact expression, so treat it as the fallback."}],"related":["timestamp-range-filter","date-diff-filter","implicit-cast-comparison"]},"source_url":"https://sqlly.app/sql-dialects/extract-part-sargable","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/first-day-of-month","corpus":"sql-dialects","engine":null,"language":"en","title":"Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"From DATE_TRUNC and DATETRUNC to a start-of-month modifier to rebuilding the date from parts: every engine rounds down differently.","body":{"slug":"first-day-of-month","name":"Get the first day of the month","h1":"Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"A staple of reporting SQL, computed five different ways.","intro":"Rounding a date down to the first of its month is bread-and-butter reporting SQL. PostgreSQL, Oracle and SQL Server 2022+ have a truncation function; MySQL rebuilds the date and SQLite uses a modifier.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATETRUNC(month, GETDATE()),\n  DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1);","note":"DATETRUNC (SQL Server 2022+) truncates to any datepart and keeps the input's type, datetime here. On older versions rebuild the date with DATEFROMPARTS, which returns a DATE."},{"engine_slug":"postgresql","sql":"SELECT DATE_TRUNC('month', NOW())::DATE;","note":"DATE_TRUNC takes the unit as text ('day', 'month', 'year') and returns a timestamp; cast to DATE for a pure date."},{"engine_slug":"mysql","sql":"SELECT DATE_FORMAT(CURDATE(), '%Y-%m-01');","note":"Formats the day as literal 01, returning text; wrap in CAST(... AS DATE) if you need a date type."},{"engine_slug":"sqlite","sql":"SELECT DATE('now', 'start of month');","note":"The start of month modifier does exactly this and chains with others, e.g. DATE('now', 'start of month', '-1 day')."},{"engine_slug":"oracle","sql":"SELECT TRUNC(SYSDATE, 'MM') FROM dual;","note":"TRUNC with 'MM' truncates to the month; 'DD' (the default) truncates the time, 'YYYY' to the year."}],"verdict":"PostgreSQL's DATE_TRUNC, Oracle's TRUNC and SQL Server 2022's DATETRUNC take a unit argument, and SQLite's modifier chains with others. MySQL, and SQL Server before 2022, make you assemble the date by hand.","faqs":[{"question":"Which form should I use on SQL Server?","answer":"DATETRUNC(month, d) on 2022 and later. Before that, DATEFROMPARTS(YEAR(d), MONTH(d), 1) reads clearly; DATEADD(DAY, 1, EOMONTH(d, -1)) also works but reads backwards."},{"question":"How do I get the first day of last month?","answer":"Chain one step back: PostgreSQL DATE_TRUNC('month', NOW()) - INTERVAL '1 month'; SQLite DATE('now', 'start of month', '-1 month'); Oracle TRUNC(ADD_MONTHS(SYSDATE, -1), 'MM')."},{"question":"Does this preserve the time part?","answer":"No. TRUNC, DATE_TRUNC and DATETRUNC set the time to midnight, DATEFROMPARTS returns a DATE with no time part, and MySQL's DATE_FORMAT returns the text '2026-11-01', which becomes midnight once cast to DATETIME."}],"related":["last-day-of-month","date-truncate","add-months"]},"source_url":"https://sqlly.app/sql-dialects/first-day-of-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/from-unix-timestamp","corpus":"sql-dialects","engine":null,"language":"en","title":"Convert a Unix timestamp to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"TO_TIMESTAMP, FROM_UNIXTIME, DATEADD from 1970, or SQLite's unixepoch modifier: the trip from a Unix timestamp back to a real date.","body":{"slug":"from-unix-timestamp","name":"Convert a Unix timestamp to a date","h1":"Convert a Unix timestamp to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"The inverse of extract-epoch, and just as engine-specific.","intro":"Turning 1763600000 back into a timestamp (2025-11-20 00:53:20 UTC): two engines name it, three do arithmetic or a modifier. As with the forward direction, the time zone semantics decide whether you get the instant you meant.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(SECOND, 1763600000, '1970-01-01');","note":"Adds seconds to 1970 and returns the UTC wall time as datetime. DATEADD's number argument is an int, so convert millisecond values to seconds first. For a zone, chain AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time'."},{"engine_slug":"postgresql","sql":"SELECT TO_TIMESTAMP(1763600000);","note":"Returns timestamptz, so it renders in the session zone; cast to timestamp for UTC wall time."},{"engine_slug":"mysql","sql":"SELECT FROM_UNIXTIME(1763600000);","note":"Interprets in the session time zone; FROM_UNIXTIME(1763600000, '%Y-%m-%d') formats in one step."},{"engine_slug":"sqlite","sql":"SELECT DATETIME(1763600000, 'unixepoch');","note":"The unixepoch modifier is mandatory: without it the number is read as a Julian day and the result is NULL. Returns UTC text."},{"engine_slug":"oracle","sql":"SELECT DATE '1970-01-01' + 1763600000 / 86400 FROM dual;","note":"Seconds / 86400 is a fractional day count, and DATE keeps whole seconds, so this returns 2025-11-20 00:53:20 as UTC wall time."}],"verdict":"PostgreSQL and MySQL name the operation; SQL Server and Oracle add seconds or fractions of days to 1970; SQLite needs the unixepoch keyword or it silently misreads the number as a Julian day.","faqs":[{"question":"Why does SQLite return NULL for my timestamp?","answer":"Without a modifier, DATETIME(1763600000) reads the number as a Julian day number, far outside the supported years 0000 to 9999, so the result is NULL. Pass 'unixepoch' (or 'auto' on recent versions)."},{"question":"How do I handle millisecond timestamps?","answer":"Divide by 1000 first for the engines without fractional support, or pass seconds as a real: TO_TIMESTAMP(1763600000.5) in PostgreSQL keeps sub-second precision."},{"question":"Which time zone does the result land in?","answer":"PostgreSQL renders timestamptz in the session zone and MySQL follows the session zone; SQL Server and Oracle arithmetic gives you the raw UTC instant; SQLite gives UTC text you convert with modifiers."}],"related":["extract-epoch","timezone-convert","interval-literals"]},"source_url":"https://sqlly.app/sql-dialects/from-unix-timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/full-text-index","corpus":"sql-dialects","engine":null,"language":"en","title":"Full-text search basics in every SQL dialect","description":"Build a full-text index for word searches in SQL Server, PostgreSQL, MySQL, SQLite and Oracle; syntax and querying differ wildly.","body":{"slug":"full-text-index","name":"Full-text search index","h1":"Full-text search basics in every SQL dialect","category":"indexes","lede":"Full-text search indexes words so LIKE '%term%' scans give way to real relevance searches. Every engine has one, and every engine spells it differently.","intro":"This is the least portable feature in this section. Creating the index is half the work; each engine also has its own query syntax, shown in the notes.","rows":[{"engine_slug":"sql-server","sql":"CREATE FULLTEXT CATALOG ft_catalog AS DEFAULT;\nCREATE FULLTEXT INDEX ON articles (title, body) KEY INDEX PK_articles;","note":"Query with CONTAINS(body, 'warrior') or FREETEXT. Requires the Full-Text Search feature and a unique key index on the table."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_articles_body ON articles USING GIN (to_tsvector('english', body));","note":"Query with body @@ to_tsquery('english', 'warrior'). Match the exact to_tsvector call in the query or the index is ignored."},{"engine_slug":"mysql","sql":"CREATE FULLTEXT INDEX idx_articles_body ON articles (body);","note":"InnoDB full-text (MyISAM also had it). Query with MATCH(body) AGAINST('warrior') in natural language or boolean mode."},{"engine_slug":"sqlite","sql":"CREATE VIRTUAL TABLE articles_fts USING fts5(body, content='articles', content_rowid='id');","note":"No index on an ordinary table; use a separate FTS5 virtual table. Query with SELECT rowid FROM articles_fts WHERE articles_fts MATCH 'warrior'."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_articles_body ON articles (body) INDEXTYPE IS CTXSYS.CONTEXT;","note":"Oracle Text (CTXSYS). Query with CONTAINS(body, 'warrior') > 0. CONTEXT indexes need syncing (ON COMMIT or manual) to see new rows."}],"verdict":"Five engines, five completely different APIs: catalogs and CONTAINS, GIN plus to_tsvector, InnoDB FULLTEXT, an FTS5 virtual table, and Oracle Text with an indextype clause. Porting full-text code means rewriting it, not translating syntax.","faqs":[{"question":"Can I just use LIKE '%word%'?","answer":"It works but scans the whole table and cannot use an index. Fine for small tables; full-text indexes are the real answer once scans hurt."},{"question":"Which engine handles stemming and ranking?","answer":"PostgreSQL stems through the text search configuration ('english'), and SQL Server stems in FREETEXT and CONTAINS(... FORMSOF(INFLECTIONAL, ...)). InnoDB full-text does not stem at all. FTS5 stems only with tokenize='porter', and Oracle Text stems through its lexer preferences."},{"question":"Does a full-text index update itself?","answer":"SQL Server and PostgreSQL track changes automatically, InnoDB does too, Oracle Text CONTEXT indexes need a SYNC policy, and SQLite FTS5 keeps its virtual table in sync only via triggers on the content table."}],"related":["create-index","prefix-index"]},"source_url":"https://sqlly.app/sql-dialects/full-text-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/generated-columns","corpus":"sql-dialects","engine":null,"language":"en","title":"Generated / computed columns","description":"Computed columns, GENERATED ALWAYS AS, MySQL virtual columns and SQLite 3.31+ generated columns: values the engine derives.","body":{"slug":"generated-columns","name":"Generated columns","h1":"Generated / computed columns","category":"ddl","lede":"Columns the engine computes from other columns, stored on write or computed on read.","intro":"Generated columns remove a class of stale-data bugs: the engine derives the value, so nobody can forget to update it. The real choice is storage. VIRTUAL computes the value on every read; STORED (PERSISTED in SQL Server) computes it on write and keeps it on disk. Oracle offers only virtual, and PostgreSQL only stored before version 18.","rows":[{"engine_slug":"sql-server","sql":"CREATE TABLE products (\n  price DECIMAL(10,2), qty INT,\n  total AS price * qty PERSISTED\n);","note":"Computed on read unless PERSISTED. Either kind can be indexed if the expression is deterministic; a non-persisted one must also be precise (no float)."},{"engine_slug":"postgresql","sql":"CREATE TABLE products (\n  price NUMERIC(10,2), qty INT,\n  total NUMERIC(10,2) GENERATED ALWAYS AS (price * qty) STORED\n);","note":"12+. PostgreSQL 18 adds VIRTUAL and makes it the default when neither keyword is given. Virtual columns can't be indexed yet."},{"engine_slug":"mysql","sql":"CREATE TABLE products (\n  price DECIMAL(10,2), qty INT,\n  total DECIMAL(10,2) AS (price * qty) VIRTUAL\n);","note":"5.7+. VIRTUAL (the default) computes on read, STORED on write. InnoDB can index either; an index on a virtual column stores the computed values."},{"engine_slug":"sqlite","sql":"CREATE TABLE products (\n  price REAL, qty INT,\n  total REAL GENERATED ALWAYS AS (price * qty) VIRTUAL\n);","note":"3.31+. VIRTUAL (the default) or STORED. Expressions must be deterministic, and ALTER TABLE ADD COLUMN can only add VIRTUAL ones."},{"engine_slug":"oracle","sql":"CREATE TABLE products (\n  price NUMBER(10,2), qty INT,\n  total AS (price * qty) VIRTUAL\n);","note":"Virtual columns since 11g: computed on read, with no stored option. They can be indexed, constrained and used as partition keys."}],"verdict":"The feature exists everywhere now. The portability trap is storage: Oracle has no stored generated columns, PostgreSQL had no virtual ones before 18, and only SQL Server, MySQL, SQLite and PostgreSQL 18 let you pick per column.","faqs":[{"question":"VIRTUAL or STORED?","answer":"VIRTUAL costs nothing on write and no disk space, but recomputes on every read; STORED costs write time and space and reads like a normal column. Pick STORED for expensive expressions read often, or when the engine can only index stored values (PostgreSQL)."},{"question":"Can a generated column reference other generated columns?","answer":"In MySQL and SQLite, yes, as long as there is no cycle (MySQL also requires the referenced column to be defined earlier). PostgreSQL, SQL Server and Oracle refuse; repeat the expression instead."},{"question":"Are generated columns good for indexing expressions?","answer":"Yes. Index the generated column and queries that filter on it use the index. MySQL and SQL Server go further and can match a query that spells out the same expression to an indexed generated column. In PostgreSQL and Oracle a plain expression index does the same job without the extra column."}],"related":["alter-column-type","add-column","autoincrement-column"]},"source_url":"https://sqlly.app/sql-dialects/generated-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/generated-ids","corpus":"sql-dialects","engine":null,"language":"en","title":"Get the id of the row you just inserted","description":"OUTPUT, RETURNING, LAST_INSERT_ID() and last_insert_rowid(): fetching the auto-generated key of a fresh INSERT in all five engines.","body":{"slug":"generated-ids","name":"Generated ids","h1":"Get the id of the row you just inserted","category":"dml","lede":"You inserted the row; now get back the key the engine picked for it.","intro":"Every engine can hand back a generated key. SQL Server's OUTPUT and the RETURNING clause of PostgreSQL and SQLite 3.35+ return a result set from the INSERT itself, which also works for multi-row inserts. MySQL needs a second statement, and Oracle's RETURNING INTO writes into a bind variable.","rows":[{"engine_slug":"sql-server","sql":"INSERT INTO customers (email)\nOUTPUT INSERTED.id\nVALUES ('ann@example.com');","note":"Returns one row per inserted row. On a table with triggers, plain OUTPUT fails; use OUTPUT … INTO a table variable. SCOPE_IDENTITY() returns the last identity value in the current scope."},{"engine_slug":"postgresql","sql":"INSERT INTO customers (email)\nVALUES ('ann@example.com')\nRETURNING id;","note":"RETURNING is a real result clause: multi-row, and available on UPDATE and DELETE too."},{"engine_slug":"mysql","sql":"INSERT INTO customers (email) VALUES ('ann@example.com');\nSELECT LAST_INSERT_ID();","note":"Per connection, so other sessions' inserts don't affect it. After a multi-row insert it returns the first id generated, not the last. No RETURNING clause."},{"engine_slug":"sqlite","sql":"INSERT INTO customers (email) VALUES ('ann@example.com');\nSELECT last_insert_rowid();","note":"Per-connection scalar. SQLite 3.35+ also supports RETURNING directly on the INSERT."},{"engine_slug":"oracle","sql":"INSERT INTO customers (email)\nVALUES ('ann@example.com')\nRETURNING id INTO :new_id;","note":"RETURNING INTO fills a bind or PL/SQL variable (use RETURNING BULK COLLECT INTO for many rows); it does not return a result set. Identity columns need 12c+."}],"verdict":"RETURNING in PostgreSQL and SQLite 3.35+ and OUTPUT in SQL Server get the key in the same statement. MySQL's LAST_INSERT_ID() works fine as long as you read it on the same connection, right after the insert.","faqs":[{"question":"Is LAST_INSERT_ID() safe with connection pooling?","answer":"Yes, if you read it on the same connection before returning it to the pool. It is scoped to the connection, not global. Most drivers expose it directly after the insert (for example, the insert id on the result object)."},{"question":"How do I get ids for a batch insert in SQL Server?","answer":"OUTPUT INSERTED.id returns one row per inserted row, so a 500-row insert gives 500 ids. SCOPE_IDENTITY() only knows the last one. Add other OUTPUT columns (OUTPUT INSERTED.id, INSERTED.email) to tell the rows apart."},{"question":"What about sequences in Oracle or PostgreSQL?","answer":"Oracle: sequence_name.CURRVAL after a NEXTVAL in the same session. PostgreSQL: currval('sequence_name') or lastval(). With identity columns, RETURNING is simpler and can't pick up a value from a different sequence."}],"related":["insert-into-identity","upsert-syntax","autoincrement-column"]},"source_url":"https://sqlly.app/sql-dialects/generated-ids","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/guid-column-type","corpus":"sql-dialects","engine":null,"language":"en","title":"Column types for UUIDs and GUIDs in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"UNIQUEIDENTIFIER and UUID are native 16-byte types; MySQL and Oracle store raw bytes; SQLite stores text or a blob.","body":{"slug":"guid-column-type","name":"Column types for UUIDs and GUIDs","h1":"Column types for UUIDs and GUIDs in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Where the UUID can be a real type, and where it is 16 bytes wearing a costume.","intro":"A UUID is 16 bytes, and how each engine stores those bytes decides index size and join speed. Two engines have native types; the others store BINARY, RAW, TEXT or BLOB.","rows":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (id UNIQUEIDENTIFIER DEFAULT NEWID());","note":"Native 16-byte type with a readable format. Consider NEWSEQUENTIALID() as the default to reduce index fragmentation."},{"engine_slug":"postgresql","sql":"CREATE TABLE t (id UUID DEFAULT GEN_RANDOM_UUID());","note":"Native uuid type: 16 bytes stored, validates the literal, compares efficiently. Avoid TEXT-stored UUIDs unless you need portability."},{"engine_slug":"mysql","sql":"CREATE TABLE t (id BINARY(16) DEFAULT (UUID_TO_BIN(UUID(), 1)));","note":"No native type: CHAR(36) stores the readable form (36 bytes) and BINARY(16) with UUID_TO_BIN stores compact bytes; flag 1 reorders time bits for InnoDB locality."},{"engine_slug":"sqlite","sql":"CREATE TABLE t (id TEXT);","note":"No UUID type: store the 36-char text form, or a 16-byte BLOB you format in the app. Declared types only set affinity, so nothing validates the value."},{"engine_slug":"oracle","sql":"CREATE TABLE t (id RAW(16) DEFAULT SYS_GUID());","note":"RAW(16) is the native fit and SYS_GUID() is the natural default; display with RAWTOHEX. CHAR(32) text doubles the size."}],"verdict":"PostgreSQL's uuid and SQL Server's UNIQUEIDENTIFIER are real types with byte storage; MySQL and Oracle need BINARY/RAW discipline; SQLite leaves the choice entirely to you. Compact 16-byte storage wins on every index that will hold millions of them.","faqs":[{"question":"CHAR(36) or BINARY(16) in MySQL?","answer":"CHAR(36) is human-readable and joins fine at moderate scale. BINARY(16) is less than half the size, and InnoDB copies the primary key into every secondary index, so the saving multiplies on big tables. Use UUID_TO_BIN/BIN_TO_UUID so you never hand-roll conversions."},{"question":"Does the GUID order matter for indexes?","answer":"Yes: random v4 values scatter inserts across a B-tree, causing page splits. Sequential ids (NEWSEQUENTIALID, UUID_TO_BIN(...,1), or UUIDv7 app-side) keep inserts append-mostly."},{"question":"Can I use a UUID as a primary key everywhere?","answer":"Functionally yes; performance-wise sequential or time-ordered UUIDs (or a bigint surrogate with a uuid lookup) scale better on large tables in every engine."}],"related":["uuid-generation","autoincrement-column","char-vs-varchar"]},"source_url":"https://sqlly.app/sql-dialects/guid-column-type","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/implicit-cast-comparison","corpus":"sql-dialects","engine":null,"language":"en","title":"Implicit casts in comparisons","description":"What happens when you compare a VARCHAR column to a number: silent conversion, a lost index, 'abc' equal to 0, or a type error.","body":{"slug":"implicit-cast-comparison","name":"Implicit casts in comparisons","h1":"Implicit casts in comparisons","category":"query","lede":"Four engines convert silently, one refuses, and the conversions differ.","intro":"Compare unlike types and most engines convert one side, each by its own rules. SQL Server, MySQL and Oracle convert the string column to a number; SQLite converts the number to text when the column has TEXT affinity; PostgreSQL raises a type error.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM items WHERE varchar_code = '123';","note":"varchar_code = 123 converts the column to int, because int outranks varchar. One non-numeric value fails the query, and an index on the column can't be used for a seek."},{"engine_slug":"postgresql","sql":"SELECT * FROM items WHERE varchar_code = '123';","note":"varchar_code = 123 fails with 'operator does not exist: character varying = integer'. Quote the literal or cast explicitly."},{"engine_slug":"mysql","sql":"SELECT * FROM items WHERE varchar_code = '123';","note":"varchar_code = 123 converts every value to a number ('abc' becomes 0, '12abc' becomes 12) with only a warning, and can't use the index."},{"engine_slug":"sqlite","sql":"SELECT * FROM items WHERE varchar_code = '123';","note":"varchar_code = 123 also matches here: the column has TEXT affinity, so SQLite converts 123 to '123' before comparing. Values in a column with no declared type are not converted."},{"engine_slug":"oracle","sql":"SELECT * FROM items WHERE varchar_code = '123';","note":"varchar_code = 123 applies TO_NUMBER to the column, so one row holding 'A12' fails the query with ORA-01722, and a normal index on the column is skipped."}],"verdict":"Write the literal in the column's type and the query behaves the same on all five engines. PostgreSQL is the only engine that refuses the mismatch, which is why code that worked elsewhere breaks there. On the others, a number compared with a text column is either a runtime error waiting for bad data or a full scan.","faqs":[{"question":"Why is my indexed varchar column suddenly doing a table scan?","answer":"The query compares it with a number, and SQL Server, MySQL and Oracle convert the column side, not the literal. The index holds text, so it can't be searched for converted values. Write the literal as a string: WHERE varchar_code = '123'."},{"question":"Is MySQL's 'abc' = 0 behavior really silent?","answer":"Almost: MySQL converts non-numeric strings to 0 and issues warning 1292 ('Truncated incorrect DOUBLE value'), which most clients never show. So WHERE varchar_code = 0 matches every value that doesn't start with a digit."},{"question":"How does SQLite decide what equals what?","answer":"By affinity. If one operand is a column with INTEGER, REAL or NUMERIC affinity, SQLite tries to convert the other to a number; if it has TEXT affinity, numbers are converted to text. A column declared with no type does no conversion, so '123' and 123 differ there. In sort order, NULL comes first, then numbers, then text, then BLOBs."}],"related":["extract-part-sargable","timestamp-range-filter","null-safe-equality"]},"source_url":"https://sqlly.app/sql-dialects/implicit-cast-comparison","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/insert-from-select","corpus":"sql-dialects","engine":null,"language":"en","title":"Insert rows copied from another table","description":"INSERT INTO ... SELECT is nearly identical in all five engines; the differences are hints, upsert options and date literals.","body":{"slug":"insert-from-select","name":"Insert from SELECT","h1":"Insert rows copied from another table","category":"dml","lede":"The most portable statement in SQL: copy rows from one table into another in a single statement.","intro":"INSERT ... SELECT is where the dialects agree most. The column lists and query shapes are identical; the differences are Oracle's direct-path hint for big copies, the upsert clauses that can follow the SELECT, and the date literal syntax.","rows":[{"engine_slug":"sql-server","sql":"INSERT INTO archive_orders (id, total)\nSELECT id, total FROM orders\nWHERE created_at < '2024-01-01';","note":"No VALUES clause. INSERT … EXEC also lets a stored procedure's result set feed the insert."},{"engine_slug":"postgresql","sql":"INSERT INTO archive_orders (id, total)\nSELECT id, total FROM orders\nWHERE created_at < DATE '2024-01-01';","note":"ON CONFLICT (id) DO NOTHING can follow the SELECT to skip rows already archived."},{"engine_slug":"mysql","sql":"INSERT INTO archive_orders (id, total)\nSELECT id, total FROM orders\nWHERE created_at < '2024-01-01';","note":"Selecting from the target table itself is allowed; MySQL buffers the rows in a temporary table first. ON DUPLICATE KEY UPDATE can follow the SELECT."},{"engine_slug":"sqlite","sql":"INSERT INTO archive_orders (id, total)\nSELECT id, total FROM orders\nWHERE created_at < '2024-01-01';","note":"Identical shape. When copying in many statements, wrap them in one transaction: each separate commit waits for a disk sync."},{"engine_slug":"oracle","sql":"INSERT /*+ APPEND */ INTO archive_orders (id, total)\nSELECT id, total FROM orders\nWHERE created_at < DATE '2024-01-01';","note":"APPEND loads direct-path above the high-water mark: much faster for big copies, but it locks the table against other DML, and the session can't read the table until it commits."}],"verdict":"Use one INSERT ... SELECT per copy on every engine; row-by-row loops are slower by orders of magnitude. The one engine-specific lever worth knowing at scale is Oracle's APPEND hint.","faqs":[{"question":"Can the SELECT read the table being inserted into?","answer":"Yes, in all five engines. The statement sees the rows as they were before it started, so INSERT INTO t SELECT … FROM t copies each existing row once rather than looping."},{"question":"What happens to generated ids in the copied rows?","answer":"If the target has an identity or serial column and you leave it out of the column list, the engine generates new ids. To keep the source ids, list the column; insert-into-identity covers the overrides SQL Server, PostgreSQL and Oracle need."},{"question":"How do I copy rows across databases?","answer":"SQL Server: database.schema.table on the same instance. MySQL: database.table. SQLite: ATTACH the other file and use alias.table. PostgreSQL databases can't see each other directly; use postgres_fdw or dblink. Oracle uses a database link: table@link_name."}],"related":["multi-row-insert","insert-into-identity","truncate-vs-delete"]},"source_url":"https://sqlly.app/sql-dialects/insert-from-select","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/insert-into-identity","corpus":"sql-dialects","engine":null,"language":"en","title":"Insert an explicit id into an identity column","description":"SET IDENTITY_INSERT, OVERRIDING SYSTEM VALUE, Oracle's BY DEFAULT switch and the engines that simply let you type the id.","body":{"slug":"insert-into-identity","name":"Insert into identity columns","h1":"Insert an explicit id into an identity column","category":"dml","lede":"Migrating data with its original ids: three engines make you ask first, two just accept the value.","intro":"Identity columns are meant to be numbered by the engine, but seed data and migrations need the original ids. SQL Server gates it behind a session switch, PostgreSQL needs OVERRIDING SYSTEM VALUE for GENERATED ALWAYS columns, Oracle refuses explicit values for GENERATED ALWAYS outright, and MySQL and SQLite accept them.","rows":[{"engine_slug":"sql-server","sql":"SET IDENTITY_INSERT customers ON;\nINSERT INTO customers (id, email) VALUES (7, 'ann@example.com');\nSET IDENTITY_INSERT customers OFF;","note":"One table per session at a time, and it needs ownership or ALTER permission on the table. If the explicit id is above the current identity value, the counter moves up to it."},{"engine_slug":"postgresql","sql":"INSERT INTO customers (id, email)\nOVERRIDING SYSTEM VALUE VALUES (7, 'ann@example.com');","note":"Required for GENERATED ALWAYS; GENERATED BY DEFAULT and serial columns take explicit ids without it. The sequence does not move, so call setval() afterwards or the next generated id collides."},{"engine_slug":"mysql","sql":"INSERT INTO customers (id, email) VALUES (7, 'ann@example.com');","note":"Just insert it. The AUTO_INCREMENT counter moves past the largest value inserted, so numbering continues safely."},{"engine_slug":"sqlite","sql":"INSERT INTO customers (id, email) VALUES (7, 'ann@example.com');","note":"Allowed even with AUTOINCREMENT; the sqlite_sequence counter jumps up if the explicit id is larger."},{"engine_slug":"oracle","sql":"ALTER TABLE customers MODIFY id GENERATED BY DEFAULT AS IDENTITY;\nINSERT INTO customers (id, email) VALUES (7, 'ann@example.com');\nALTER TABLE customers MODIFY id GENERATED ALWAYS AS IDENTITY (START WITH LIMIT VALUE);","note":"Oracle has no OVERRIDING SYSTEM VALUE: an explicit id in a GENERATED ALWAYS column fails with ORA-32795. Switch the column to BY DEFAULT for the load, then back; START WITH LIMIT VALUE moves the counter past the highest id."}],"verdict":"MySQL and SQLite are the easy ones. In SQL Server the switch is per session and per table; in PostgreSQL the override clause is only needed for GENERATED ALWAYS; in Oracle a GENERATED ALWAYS column has to be altered to BY DEFAULT for the load. SQL Server, MySQL and SQLite move the counter for you, PostgreSQL and Oracle don't.","faqs":[{"question":"Why is IDENTITY_INSERT limited to one table?","answer":"That is a documented restriction: turning it on for a second table while it is on for another fails with an error naming the first table. Turn it on and off around each table's load."},{"question":"How do I fix the counter after a migration?","answer":"SQL Server: DBCC CHECKIDENT ('customers', RESEED) if you need to change it. PostgreSQL: SELECT setval(pg_get_serial_sequence('customers', 'id'), max(id)) FROM customers. MySQL and SQLite adjust on their own. Oracle: ALTER TABLE customers MODIFY id GENERATED ALWAYS AS IDENTITY (START WITH LIMIT VALUE)."},{"question":"Should I use GENERATED ALWAYS or BY DEFAULT?","answer":"ALWAYS blocks accidental explicit ids from application code, at the cost of an extra step in migrations: OVERRIDING SYSTEM VALUE in PostgreSQL, an ALTER in Oracle. BY DEFAULT is more convenient for tables that are often seeded with fixed ids."}],"related":["generated-ids","autoincrement-column","insert-from-select"]},"source_url":"https://sqlly.app/sql-dialects/insert-into-identity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/integer-division","corpus":"sql-dialects","engine":null,"language":"en","title":"Integer and decimal division in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"7 / 2 is 3 in three engines and 3.5 in the other two; here is how to force the result you actually want in each one.","body":{"slug":"integer-division","name":"Integer and decimal division","h1":"Integer and decimal division in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"The most common silent bug when porting SQL: three engines truncate, two do not.","intro":"Whether / truncates depends on the engine and the operand types. SQL Server, PostgreSQL and SQLite truncate integer / integer; MySQL and Oracle always return the exact quotient. Each row shows both the trap and the fix.","rows":[{"engine_slug":"sql-server","sql":"SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;","note":"int / int truncates to 3. Make either operand a decimal (2.0) or CAST it, and you get 3.500000."},{"engine_slug":"postgresql","sql":"SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;","note":"Same rule: integer operands truncate, and a NUMERIC literal promotes the expression to 3.5000000000000000. div(7, 2) is the explicit integer-division function."},{"engine_slug":"mysql","sql":"SELECT 7 DIV 2 AS IntDiv, 7 / 2 AS ExactDiv, 7 % 2 AS Remainder;","note":"Inverted convention: / is always exact (3.5000) and DIV is the explicit integer division. MOD is a reserved word, so it cannot be an unquoted alias."},{"engine_slug":"sqlite","sql":"SELECT 7 / 2 AS IntDiv, 7 / 2.0 AS ExactDiv, 7 % 2 AS Remainder;","note":"int / int truncates to 3; a REAL operand promotes. Watch out for SUM()/COUNT() patterns on integer columns."},{"engine_slug":"oracle","sql":"SELECT 7 / 2 AS ExactDiv, MOD(7, 2) AS Remainder FROM dual;","note":"Always exact NUMBER division (3.5); there is no integer-division operator, so TRUNC(7/2) when you want 3."}],"verdict":"Know which side of the divide your engine is on: SQL Server, PostgreSQL and SQLite truncate integer division; MySQL and Oracle never do. Hand-written averages and ratios that divide two integer columns are where this bites.","faqs":[{"question":"Why does SUM(a)/COUNT(*) return an integer?","answer":"Because both operands are integers in the truncating engines. Cast one side: SUM(a) * 1.0 / COUNT(*), or CAST(SUM(a) AS DECIMAL) / COUNT(*)."},{"question":"Is there a portable integer division?","answer":"Not as a single operator: DIV exists only in MySQL, and PostgreSQL has div(a, b). FLOOR(a * 1.0 / b) differs from truncation for negatives (FLOOR(-3.5) is -4, truncation gives -3), so decide which semantics you want for negative operands."},{"question":"How do percentages usually go wrong?","answer":"share * 100 / total on integer columns truncates every share to 0. Multiply by 100.0 first, or cast before dividing."}],"related":["cast-string-to-number","number-to-text-format","cast-syntax"]},"source_url":"https://sqlly.app/sql-dialects/integer-division","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/interval-literals","corpus":"sql-dialects","engine":null,"language":"en","title":"Interval literals for date arithmetic in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"PostgreSQL's INTERVAL '3 days' reads like English; MySQL has INTERVAL n UNIT; SQL Server and SQLite have no interval type at all.","body":{"slug":"interval-literals","name":"Interval literals for date arithmetic","h1":"Interval literals for date arithmetic in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Two engines have real interval types; three fake it with functions and modifiers.","intro":"An interval is a duration as a value, not just an argument. PostgreSQL and Oracle have interval types you can store and multiply; MySQL has interval literals usable only in expressions; SQL Server and SQLite have neither.","rows":[{"engine_slug":"sql-server","sql":"SELECT DATEADD(HOUR, 2, DATEADD(DAY, 3, GETDATE()));","note":"No interval type or literal: units appear only as DATEADD/DATEDIFF arguments, so a compound duration means nesting DATEADD calls. DATEDIFF between two dates is the closest thing to a duration."},{"engine_slug":"postgresql","sql":"SELECT NOW() + INTERVAL '3 days 2 hours';","note":"A real interval type: literals like INTERVAL '3 days', storable in columns and multipliable (INTERVAL '1 hour' * 8). Internally one value keeps months, days and microseconds as separate fields."},{"engine_slug":"mysql","sql":"SELECT NOW() + INTERVAL '3' DAY + INTERVAL '2' HOUR;","note":"INTERVAL n UNIT works in expressions but is not a column type. Compound units read strings: INTERVAL '1-2' YEAR_MONTH."},{"engine_slug":"sqlite","sql":"SELECT DATETIME('now', '+3 days', '+2 hours');","note":"No interval type: durations are modifier strings chained onto the date functions."},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP + INTERVAL '3 2:00:00' DAY TO SECOND FROM dual;","note":"Two interval types: INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND, both storable in columns and usable in literals like INTERVAL '1-2' YEAR TO MONTH."}],"verdict":"If durations are data in your model (sla_hours, contract lengths), PostgreSQL and Oracle store them natively; everywhere else you store a number and a unit convention, and add via functions.","faqs":[{"question":"Can I store an interval in a column?","answer":"In PostgreSQL and Oracle yes (INTERVAL / INTERVAL DAY TO SECOND columns). MySQL, SQL Server and SQLite store numbers with an agreed unit, or two datetimes whose difference is the duration."},{"question":"Why are '1 month' and '30 days' different intervals?","answer":"A month is 28 to 31 days and a day can be 23 or 25 hours across DST, so PostgreSQL stores months, days and microseconds separately and applies each against the calendar when you add the interval. Oracle goes further and makes year-month and day-second intervals two separate types that cannot be mixed."},{"question":"What is the portable way to say 'one week'?","answer":"There is none: DATEADD(DAY, 7, d) in SQL Server, d + INTERVAL '7 days' in PostgreSQL, DATE_ADD(d, INTERVAL 7 DAY) in MySQL, DATE(d, '+7 days') in SQLite, d + 7 in Oracle."}],"related":["add-days","add-months","extract-epoch"]},"source_url":"https://sqlly.app/sql-dialects/interval-literals","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/isolation-levels","corpus":"sql-dialects","engine":null,"language":"en","title":"SET TRANSACTION ISOLATION LEVEL in every SQL dialect","description":"Choose READ UNCOMMITTED to SERIALIZABLE per transaction; SQLite has no dial and PostgreSQL has no READ UNCOMMITTED.","body":{"slug":"isolation-levels","name":"Isolation levels","h1":"SET TRANSACTION ISOLATION LEVEL in every SQL dialect","category":"admin","lede":"Isolation levels trade concurrency for correctness: dirty reads, non-repeatable reads and phantoms shift between levels.","intro":"SET TRANSACTION ISOLATION LEVEL exists in four engines but the accepted values differ, and SQLite has exactly one behavior.","rows":[{"engine_slug":"sql-server","sql":"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n-- levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE, SNAPSHOT","note":"All four classic levels plus SNAPSHOT, and the setting lasts for the session until changed. READ COMMITTED takes shared locks unless READ_COMMITTED_SNAPSHOT is on for the database (it is on by default in Azure SQL Database)."},{"engine_slug":"postgresql","sql":"BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n-- levels: READ COMMITTED (default), REPEATABLE READ, SERIALIZABLE","note":"SET TRANSACTION works only inside a transaction block; outside one it warns and does nothing. READ UNCOMMITTED is accepted but behaves as READ COMMITTED. SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ... sets the session default."},{"engine_slug":"mysql","sql":"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n-- levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE","note":"REPEATABLE READ is the default. Without SESSION or GLOBAL, SET TRANSACTION applies only to the next transaction; SET SESSION TRANSACTION ISOLATION LEVEL ... lasts for the connection."},{"engine_slug":"sqlite","sql":"-- no isolation levels; transactions run with serializable isolation","note":"SQLite serializes writes (a single writer at a time), so transactions show serializable isolation; WAL mode adds snapshot isolation, where a reader keeps the snapshot taken when its transaction started. The only knob is PRAGMA read_uncommitted, and it applies only to connections sharing a cache."},{"engine_slug":"oracle","sql":"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n-- levels: READ COMMITTED (default), SERIALIZABLE, plus SET TRANSACTION READ ONLY","note":"SET TRANSACTION must be the first statement of a transaction and covers only that one; ALTER SESSION SET ISOLATION_LEVEL = SERIALIZABLE changes the session. SERIALIZABLE reads a snapshot from transaction start and raises ORA-08177 if it updates a row changed since. READ ONLY gives reports a consistent snapshot."}],"verdict":"Four levels in SQL Server (plus SNAPSHOT) and MySQL, three effective levels in PostgreSQL, two plus READ ONLY in Oracle, none to pick in SQLite. Scope differs too: SQL Server's SET lasts for the session, while Oracle's and PostgreSQL's SET TRANSACTION and MySQL's bare SET TRANSACTION cover a single transaction.","faqs":[{"question":"Which level should I use?","answer":"READ COMMITTED, the default in SQL Server, PostgreSQL and Oracle, suits most work. Escalate to REPEATABLE READ or SERIALIZABLE only where a specific anomaly hurts, and verify the cost under load."},{"question":"Why does SQL Server block readers at READ COMMITTED?","answer":"Classic locking behavior: readers take shared locks that wait on writers. Turning on READ_COMMITTED_SNAPSHOT gives PostgreSQL- and Oracle-style statement snapshots and usually removes reader-writer blocking."},{"question":"What is MySQL's default again?","answer":"REPEATABLE READ, unlike PostgreSQL, Oracle and SQL Server which default to READ COMMITTED."}],"related":["begin-transaction","select-for-update","lock-timeout"]},"source_url":"https://sqlly.app/sql-dialects/isolation-levels","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/kill-session","corpus":"sql-dialects","engine":null,"language":"en","title":"KILL, pg_terminate_backend and friends in every SQL dialect","description":"Terminate a stuck or runaway session, with KILL in SQL Server and MySQL, pg_terminate_backend in PostgreSQL and ALTER SYSTEM KILL SESSION in Oracle.","body":{"slug":"kill-session","name":"Kill a session","h1":"KILL, pg_terminate_backend and friends in every SQL dialect","category":"admin","lede":"When a session holds locks or burns CPU and nothing else works, terminate it. The verbs differ per engine.","intro":"All four server engines can kill a session; SQLite has no server, so you close the offending connection from the application side.","rows":[{"engine_slug":"sql-server","sql":"KILL 52;","note":"Session id from sys.dm_exec_sessions. KILL 52 WITH STATUSONLY shows rollback progress; killing a session rolls back its transaction, which can take a while."},{"engine_slug":"postgresql","sql":"SELECT pg_terminate_backend(12345);","note":"Hard kill; pg_cancel_backend(pid) first sends a cancel that lets the session clean up gracefully. pg_stat_activity lists the pids."},{"engine_slug":"mysql","sql":"KILL 12345;","note":"KILL CONNECTION 12345 is explicit; KILL QUERY 12345 aborts only the running statement, keeping the connection. Ids from SHOW PROCESSLIST."},{"engine_slug":"sqlite","sql":"-- no server-side sessions; close the connection in your code","note":"The library owns the connection; interrupt long queries with sqlite3_interrupt() or by closing the handle. Nothing to do on the server."},{"engine_slug":"oracle","sql":"ALTER SYSTEM KILL SESSION '123,4567';\n-- sid, serial# from v$session","note":"Takes sid,serial# because sids are reused. The session is marked killed and cleaned up shortly after; add IMMEDIATE to roll back and release it at once."}],"verdict":"One job, four syntaxes: KILL by id twice, pg_terminate_backend as a function, ALTER SYSTEM KILL SESSION with a composite id. Killing usually rolls back the victim's open transaction, so check rollback progress before assuming nothing happened.","faqs":[{"question":"Kill or cancel?","answer":"Prefer cancel (pg_cancel_backend, KILL QUERY) when you only want to stop a statement; terminate drops the connection and rolls back everything."},{"question":"Why does Oracle need the serial number?","answer":"Oracle reuses sids after sessions exit; sid plus serial# uniquely identifies one incarnation of a session."},{"question":"Can I kill my own session?","answer":"PostgreSQL allows pg_terminate_backend(pg_backend_pid()) and MySQL allows KILL CONNECTION_ID(). SQL Server refuses (Cannot use KILL to kill your own process) and Oracle raises ORA-00027; disconnect from the client instead."}],"related":["list-connections","deadlock-inspection","current-session-info"]},"source_url":"https://sqlly.app/sql-dialects/kill-session","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/last-day-of-month","corpus":"sql-dialects","engine":null,"language":"en","title":"Get the last day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"EOMONTH and LAST_DAY are one-liners; the other engines chain modifiers or intervals to land on the final day.","body":{"slug":"last-day-of-month","name":"Get the last day of the month","h1":"Get the last day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Three engines have a named function; PostgreSQL and SQLite make you derive it.","intro":"The last day of a month depends on the month: 28, 29, 30 or 31. SQL Server, MySQL and Oracle ship a dedicated function; PostgreSQL and SQLite compose one.","rows":[{"engine_slug":"sql-server","sql":"SELECT EOMONTH(GETDATE());","note":"EOMONTH (2012+) returns a DATE and takes an optional month offset: EOMONTH(GETDATE(), 1) is next month's last day."},{"engine_slug":"postgresql","sql":"SELECT (DATE_TRUNC('month', NOW()) + INTERVAL '1 month - 1 day')::DATE;","note":"Truncate, step one month forward, one day back; the composed interval '1 month - 1 day' is a single literal with two fields."},{"engine_slug":"mysql","sql":"SELECT LAST_DAY(CURDATE());","note":"Dedicated LAST_DAY function, returns a DATE, and gracefully returns NULL for invalid input."},{"engine_slug":"sqlite","sql":"SELECT DATE('now', 'start of month', '+1 month', '-1 day');","note":"Chained modifiers read like a sentence: start of this month, forward one, back one day."},{"engine_slug":"oracle","sql":"SELECT LAST_DAY(SYSDATE) FROM dual;","note":"Dedicated LAST_DAY, keeps the time-of-day of the input, and handles leap years correctly."}],"verdict":"SQL Server, MySQL and Oracle all have a named function. In PostgreSQL you compose truncate plus an interval, and in SQLite a modifier chain, which is verbose but combines with every other modifier.","faqs":[{"question":"How do I get the number of days in the month?","answer":"Take the last day's day-of-month: DAY(EOMONTH(d)) in SQL Server, EXTRACT(DAY FROM LAST_DAY(d)) in MySQL and Oracle, EXTRACT(DAY FROM DATE_TRUNC('month', d) + INTERVAL '1 month - 1 day') in PostgreSQL, and strftime('%d', DATE(d, 'start of month', '+1 month', '-1 day')) in SQLite."},{"question":"Does EOMONTH keep the time part?","answer":"No, it returns a pure DATE. MySQL's LAST_DAY returns a DATE too, while Oracle's returns a DATE that keeps the input's time of day."},{"question":"How do I test whether a date is the month's last day?","answer":"Compare directly: d = EOMONTH(d) in SQL Server, d = LAST_DAY(d) in MySQL and Oracle, d = (DATE_TRUNC('month', d) + INTERVAL '1 month - 1 day')::DATE in PostgreSQL."}],"related":["first-day-of-month","add-months","date-truncate"]},"source_url":"https://sqlly.app/sql-dialects/last-day-of-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/last-query","corpus":"sql-dialects","engine":null,"language":"en","title":"Finding a session's last (or current) SQL in every dialect","description":"Retrieve the most recent statement a session ran, per engine, from most_recent_sql_handle to performance_schema.","body":{"slug":"last-query","name":"Last query of a session","h1":"Finding a session's last (or current) SQL in every dialect","category":"admin","lede":"What did that session just run? Useful when debugging a support ticket or a stuck connection.","intro":"Every server engine keeps recent SQL somewhere, but shapes differ: current statement, last statement, or a history ring buffer. SQLite records nothing.","rows":[{"engine_slug":"sql-server","sql":"SELECT text\nFROM sys.dm_exec_connections c\nCROSS APPLY sys.dm_exec_sql_text(c.most_recent_sql_handle)\nWHERE c.session_id = 52;","note":"most_recent_sql_handle holds the last batch text even after it finished. Query Store (sys.query_store_runtime_stats) gives longer history per database."},{"engine_slug":"postgresql","sql":"SELECT pid, state, query\nFROM pg_stat_activity\nWHERE pid = 12345;","note":"Shows the last statement for idle sessions and the current one for active. Install pg_stat_statements for aggregate history with timings."},{"engine_slug":"mysql","sql":"SELECT THREAD_ID, SQL_TEXT\nFROM performance_schema.events_statements_history\nORDER BY EVENT_ID DESC\nLIMIT 10;","note":"The ring buffer keeps the last N statements per thread (needs the statement instruments enabled, default in 5.7+). events_statements_current for the live one."},{"engine_slug":"sqlite","sql":"-- no server memory of statements; your app is the source of truth","note":"Nothing is recorded. Wrap sqlite3_trace_v2 in your application or use a debug build to log executed SQL."},{"engine_slug":"oracle","sql":"SELECT q.sql_text\nFROM v$session s\nJOIN v$sql q ON q.sql_id = s.prev_sql_id\nWHERE s.sid = 123;","note":"prev_sql_id/prev_child_number is the last executed statement; sql_id is the currently running one. Needs dictionary access, and v$sql may age entries out."}],"verdict":"All four server engines can show recent SQL, but each stores something different: last batch, last statement, ring buffer, or dictionary cache. Only PostgreSQL shows it for your own sessions without extra privileges; MySQL's history needs performance_schema enabled.","faqs":[{"question":"Why is the text truncated?","answer":"SHOW PROCESSLIST truncates at 100 chars; use SHOW FULL PROCESSLIST or performance_schema. SQL Server's sys.dm_exec_sql_text returns the full batch."},{"question":"Does this show prepared statements?","answer":"Mostly the text without values. SQL Server shows the parameterized statement sent through sp_executesql, PostgreSQL's query column shows $1, $2 placeholders but never the bound values, and Oracle's v$sql shows the bind names (:1, :name)."},{"question":"How long is 'last'?","answer":"Server-dependent: PostgreSQL and SQL Server keep the last statement per live session, MySQL keeps a bounded history buffer, Oracle caches until aged out of the shared pool."}],"related":["list-connections","kill-session","current-session-info"]},"source_url":"https://sqlly.app/sql-dialects/last-query","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/like-escape","corpus":"sql-dialects","engine":null,"language":"en","title":"Pattern matching with LIKE and ESCAPE","description":"Search for a literal percent or underscore without it acting as a wildcard: the ESCAPE clause in all five engines.","body":{"slug":"like-escape","name":"LIKE with literal % or _","h1":"Pattern matching with LIKE and ESCAPE","category":"query","lede":"% and _ are wildcards until you declare an escape character, and backslash is the worst choice for one.","intro":"To match a literal % or _, put an escape character in front of it and name that character with ESCAPE. The clause is standard and works in all five engines. Pick a character other than backslash and the same SQL text runs everywhere.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';","note":"T-SQL also lets you bracket the wildcard: LIKE '100[%]' matches a literal % without ESCAPE."},{"engine_slug":"postgresql","sql":"SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';","note":"Backslash is the default escape even without ESCAPE, so '100\\%' works on its own. ILIKE takes the same ESCAPE clause."},{"engine_slug":"mysql","sql":"SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';","note":"Backslash is the default escape. Writing ESCAPE '\\' fails here because the string parser treats \\' as an escaped quote; ESCAPE '\\\\' is the working spelling."},{"engine_slug":"sqlite","sql":"SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';","note":"No default escape character: without ESCAPE, a pattern cannot match a literal % or _."},{"engine_slug":"oracle","sql":"SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';","note":"No default escape character. The same clause covers _, as in 'file!_x'."}],"verdict":"LIKE '100!%' ESCAPE '!' runs unchanged on all five engines. The backslash version does not: MySQL's string parser reads ESCAPE '\\' as an unterminated literal, and backslash is a silent default escape in MySQL and PostgreSQL but an ordinary character in SQL Server, SQLite and Oracle. Choose a character that never appears in your data, and escape it too when it does.","faqs":[{"question":"Why doesn't my '100\\%' pattern match anything?","answer":"In SQL Server, SQLite and Oracle, backslash means nothing in LIKE unless you declare it with ESCAPE, so the pattern looks for a literal backslash. In MySQL the string parser may consume the backslash before LIKE sees it. A declared non-backslash escape character avoids both problems."},{"question":"Do I need ESCAPE for the underscore too?","answer":"Yes. _ matches any single character, so LIKE 'file_x' also matches 'fileAx'. Use LIKE 'file!_x' ESCAPE '!'. Underscores are common in identifiers and file names, so this bites more often than %."},{"question":"How do I make a LIKE search case-insensitive?","answer":"It follows the collation. SQL Server and MySQL default collations already ignore case. PostgreSQL has ILIKE. SQLite's LIKE ignores case for ASCII letters by default (PRAGMA case_sensitive_like turns that off). Oracle is case-sensitive: compare UPPER(name) LIKE UPPER(:pattern)."}],"related":["case-insensitive-compare","regex-matching","escape-single-quotes"]},"source_url":"https://sqlly.app/sql-dialects/like-escape","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/limit","corpus":"sql-dialects","engine":null,"language":"en","title":"Row paging: LIMIT, TOP, OFFSET-FETCH and ROWNUM","description":"Return one page of rows (rows 21 to 30 of an ordered result) in SQL Server, PostgreSQL, MySQL, SQLite and Oracle.","body":{"slug":"limit","name":"Row paging (LIMIT / OFFSET)","h1":"Row paging: LIMIT, TOP, OFFSET-FETCH and ROWNUM","category":"query","lede":"Five engines, two spellings of \"give me rows 21 to 30\", plus Oracle's old ROWNUM wrapper.","intro":"Paging pairs an ORDER BY with a row-range clause. PostgreSQL, MySQL and SQLite use LIMIT … OFFSET; SQL Server (2012+) and Oracle (12c+) use the standard OFFSET … FETCH, which PostgreSQL also accepts. Oracle before 12c needs a ROWNUM subquery.","rows":[{"engine_slug":"sql-server","sql":"SELECT id, name FROM customers ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;","note":"No LIMIT. OFFSET … FETCH is part of the ORDER BY clause in T-SQL, so leaving out ORDER BY is a syntax error."},{"engine_slug":"postgresql","sql":"SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;","note":"The standard OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY works too."},{"engine_slug":"mysql","sql":"SELECT id, name FROM customers ORDER BY id LIMIT 20, 10;","note":"LIMIT offset, count. LIMIT 10 OFFSET 20 also works; there is no FETCH syntax."},{"engine_slug":"sqlite","sql":"SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;","note":"Also accepts the MySQL-style LIMIT 20, 10. No FETCH syntax."},{"engine_slug":"oracle","sql":"SELECT id, name FROM customers ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;","note":"12c+. Before 12c, number a sorted subquery with ROWNUM and filter the outer query."}],"verdict":"LIMIT … OFFSET is the shortest and covers three engines; OFFSET … FETCH is the standard and covers SQL Server, Oracle and PostgreSQL. No single spelling runs on all five, so this is one clause a portable query layer has to generate per engine. The real trap is pre-12c Oracle, where ROWNUM applied in the same query as ORDER BY numbers the rows before they are sorted.","faqs":[{"question":"Do I need an ORDER BY to page?","answer":"SQL Server requires one: OFFSET … FETCH without ORDER BY is a syntax error. The other four accept a page of an unordered result, but without a sort the engine may return different rows for the same page on every run. Order by a unique key so pages neither overlap nor skip rows."},{"question":"How do I page on old Oracle versions?","answer":"Sort in the innermost query, apply ROWNUM one level up, and filter the low end outside: SELECT * FROM (SELECT t.*, ROWNUM rn FROM (SELECT id, name FROM customers ORDER BY id) t WHERE ROWNUM <= 30) WHERE rn > 20. ROWNUM is assigned before ORDER BY runs, which is why it can't sit in the same query as the sort."},{"question":"Is deep paging slow?","answer":"Yes, on every engine: OFFSET 100000 still reads and throws away 100,000 rows. For large result sets use keyset paging: remember the last id you showed and ask for WHERE id > :last_seen ORDER BY id with a limit of 10."}],"related":["top-n","top-n-per-group","row-numbering","random-sample"]},"source_url":"https://sqlly.app/sql-dialects/limit","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/list-connections","corpus":"sql-dialects","engine":null,"language":"en","title":"SHOW PROCESSLIST and session views in every SQL dialect","description":"See who is connected and what they are running, from SHOW PROCESSLIST to pg_stat_activity to v$session.","body":{"slug":"list-connections","name":"List connections","h1":"SHOW PROCESSLIST and session views in every SQL dialect","category":"admin","lede":"The who-is-connected view, including state and the current statement, needed before you kill anything.","intro":"Server engines all expose a session table; the columns and names differ. SQLite has no sessions to list because there is no server.","rows":[{"engine_slug":"sql-server","sql":"SELECT session_id, login_name, host_name, program_name, status\nFROM sys.dm_exec_sessions\nWHERE is_user_process = 1;","note":"Pair with sys.dm_exec_requests for running statements, or sys.dm_exec_connections for network details. sp_who2 still works but the DMVs are the real API."},{"engine_slug":"postgresql","sql":"SELECT pid, usename, application_name, client_addr, state, query\nFROM pg_stat_activity;","note":"state = active means a running statement; idle in transaction is the state to hunt for. Requires pg_monitor or similar for other users' queries."},{"engine_slug":"mysql","sql":"SHOW PROCESSLIST;\n-- equivalent: SELECT * FROM information_schema.processlist;","note":"PROCESSLIST privilege shows all connections, otherwise only your own. Time and State columns point at long-running or stuck sessions."},{"engine_slug":"sqlite","sql":"-- no server, no connections to list","note":"Embedded: the process holding the file is invisible to the database. Check open file handles (lsof on the .db file) if you must."},{"engine_slug":"oracle","sql":"SELECT sid, serial#, username, status, machine, program\nFROM v$session\nWHERE username IS NOT NULL;","note":"Rows with username NULL are background processes. Join v$process for OS pids; status ACTIVE means currently executing."}],"verdict":"Four session views with the same shape (id, user, source, state, statement) and no portable column names. pg_stat_activity is the most query-friendly; v$session and sys.dm_exec_sessions need joins for the current SQL.","faqs":[{"question":"Which sessions matter most?","answer":"idle in transaction (PostgreSQL), sleeping with open transactions (SQL Server via sys.dm_tran_session_transactions), and long Time rows in MySQL: they hold locks and block cleanup."},{"question":"Can I see the running SQL too?","answer":"Yes: join sys.dm_exec_sql_text in SQL Server, read the query column of pg_stat_activity, join v$session to v$sql in Oracle, and in MySQL use SHOW FULL PROCESSLIST, since plain SHOW PROCESSLIST cuts the Info column at 100 characters."},{"question":"Why fewer rows than expected in pg_stat_activity?","answer":"Non-superusers only see their own sessions plus generic details of others; grant pg_monitor for full visibility."}],"related":["kill-session","last-query","current-session-info"]},"source_url":"https://sqlly.app/sql-dialects/list-connections","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/lock-timeout","corpus":"sql-dialects","engine":null,"language":"en","title":"Lock wait and lock timeouts in every SQL dialect","description":"Cap how long a statement waits for a lock, from SET LOCK_TIMEOUT to innodb_lock_wait_timeout to FOR UPDATE WAIT.","body":{"slug":"lock-timeout","name":"Lock wait timeout","h1":"Lock wait and lock timeouts in every SQL dialect","category":"admin","lede":"A lock timeout keeps one blocked statement from freezing a queue behind it. Units differ: milliseconds in SQL Server and SQLite (and PostgreSQL without a unit), seconds in MySQL and Oracle.","intro":"No shared syntax: SQL Server uses a session SET, MySQL and PostgreSQL use session variables, Oracle puts WAIT on the statement, and SQLite's pragma is about the database file lock.","rows":[{"engine_slug":"sql-server","sql":"SET LOCK_TIMEOUT 5000;\n-- next statements wait at most 5s for a lock, then error 1222","note":"Milliseconds, per session, sticky until changed. A timeout raises error 1222; handle it in the client rather than retrying blindly."},{"engine_slug":"postgresql","sql":"SET lock_timeout = '5s';\n-- also: SET statement_timeout, SET idle_in_transaction_session_timeout","note":"Takes a unit ('5s', '500ms'); a bare number means milliseconds. Set it per session, role or database; a statement that waits longer fails with SQLSTATE 55P03."},{"engine_slug":"mysql","sql":"SET SESSION innodb_lock_wait_timeout = 5;\n-- seconds; error 1205 on timeout","note":"InnoDB row-lock waits in seconds (default 50). SELECT ... FOR UPDATE NOWAIT / SKIP LOCKED skip the wait entirely per statement."},{"engine_slug":"sqlite","sql":"PRAGMA busy_timeout = 5000;\n-- milliseconds; SQLITE_BUSY becomes an error after this","note":"Controls how long a connection waits for the database file lock (SQLITE_BUSY), not row locks, since SQLite has none."},{"engine_slug":"oracle","sql":"SELECT * FROM accounts WHERE id = 1 FOR UPDATE WAIT 5;\n-- ORA-30006 after 5 seconds (or NOWAIT to fail at once)","note":"No session-wide lock timeout; the WAIT n clause is per statement. ddl_lock_timeout applies to DDL waiting for locks."}],"verdict":"Five different mechanisms with different granularity and scope. Statement-level control (Oracle's WAIT) is the most precise; session variables (SQL Server, PostgreSQL, MySQL) are the practical default; SQLite's busy_timeout solves a different, file-level problem.","faqs":[{"question":"Lock timeout vs deadlock?","answer":"A lock timeout is you giving up while waiting. A deadlock is the engine detecting a cycle and killing one victim; they are unrelated mechanisms."},{"question":"Should my app retry on a lock timeout?","answer":"Usually yes, with jitter and a bounded count. Timeouts often mean contention spikes; immediate blind retries make them worse."},{"question":"What is the default?","answer":"SQL Server waits forever (-1), MySQL 50s, PostgreSQL no lock_timeout (but statement_timeout may apply), SQLite 0ms by default via busy_timeout, Oracle waits forever without WAIT."}],"related":["select-for-update","isolation-levels","deadlock-inspection"]},"source_url":"https://sqlly.app/sql-dialects/lock-timeout","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/merge-statement","corpus":"sql-dialects","engine":null,"language":"en","title":"MERGE: match, update, insert and delete","description":"ANSI MERGE with WHEN MATCHED / WHEN NOT MATCHED in SQL Server, PostgreSQL 15+ and Oracle, plus the closest MySQL and SQLite emulations.","body":{"slug":"merge-statement","name":"MERGE","h1":"MERGE: match, update, insert and delete","category":"dml","lede":"One pass over a source table: update what matches, insert what does not, delete what should be gone.","intro":"MERGE is the batch version of the one-row upsert: it joins a source (a staging table, a query, a VALUES list) to the target and applies a different action to matched and unmatched rows. Each example adds the day's stock movements and deletes items whose stock drops to zero or below. MySQL and SQLite have no MERGE, so their rows run the upsert and then a DELETE for the items that moved and hit zero.","rows":[{"engine_slug":"sql-server","sql":"MERGE INTO stock WITH (HOLDLOCK) AS t\nUSING daily_moves AS s ON t.sku = s.sku\nWHEN MATCHED AND t.qty + s.qty <= 0 THEN DELETE\nWHEN MATCHED THEN UPDATE SET t.qty = t.qty + s.qty\nWHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty);","note":"MERGE must end with a semicolon. HOLDLOCK keeps concurrent merges from inserting the same new key twice."},{"engine_slug":"postgresql","sql":"MERGE INTO stock t\nUSING daily_moves s ON t.sku = s.sku\nWHEN MATCHED AND t.qty + s.qty <= 0 THEN DELETE\nWHEN MATCHED THEN UPDATE SET qty = t.qty + s.qty\nWHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty);","note":"PostgreSQL 15+. The SET target can't be qualified with the alias. Before 15, use INSERT … ON CONFLICT plus a separate DELETE."},{"engine_slug":"mysql","sql":"INSERT INTO stock (sku, qty)\nSELECT sku, qty FROM daily_moves AS m\nON DUPLICATE KEY UPDATE qty = stock.qty + m.qty;\nDELETE FROM stock\nWHERE qty <= 0 AND sku IN (SELECT sku FROM daily_moves);","note":"No MERGE. INSERT … SELECT … ON DUPLICATE KEY UPDATE covers the matched and unmatched cases and the DELETE removes the items that hit zero; run both in one transaction."},{"engine_slug":"sqlite","sql":"INSERT INTO stock (sku, qty)\nSELECT sku, qty FROM daily_moves WHERE true\nON CONFLICT (sku) DO UPDATE SET qty = qty + excluded.qty;\nDELETE FROM stock\nWHERE qty <= 0 AND sku IN (SELECT sku FROM daily_moves);","note":"No MERGE. The WHERE true is required: without it, SQLite reads ON as the start of a join constraint and the statement fails. Run the INSERT and the DELETE in one transaction."},{"engine_slug":"oracle","sql":"MERGE INTO stock t\nUSING daily_moves s ON (t.sku = s.sku)\nWHEN MATCHED THEN UPDATE SET t.qty = t.qty + s.qty\n  DELETE WHERE t.qty <= 0\nWHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty);","note":"Oracle has had MERGE since 9i. Its DELETE WHERE clause is part of the update branch and tests the values after the update, so only rows that were just updated can be deleted."}],"verdict":"MERGE is standard SQL in SQL Server, Oracle and PostgreSQL 15+, and the three spellings differ only in details. Teams that distrust SQL Server's MERGE under concurrency often write an UPDATE followed by an INSERT … WHERE NOT EXISTS in one transaction instead.","faqs":[{"question":"Why is SQL Server MERGE considered risky?","answer":"Without HOLDLOCK (serializable) on the target, two concurrent merges can both decide a key is missing and both insert it, and one fails with a duplicate-key error. Older builds also had a list of MERGE bugs around filtered indexes and triggers, so some shops ban it in favor of UPDATE then INSERT."},{"question":"Does MERGE need a unique index?","answer":"Not formally, but each target row must match at most one source row. If two source rows match the same target row, SQL Server (error 8672), PostgreSQL and Oracle (ORA-30926) abort the statement. A unique key on the join columns of the source prevents that."},{"question":"What replaces MERGE in MySQL?","answer":"INSERT … SELECT … ON DUPLICATE KEY UPDATE for the matched and unmatched cases, with a DELETE before or after it in the same transaction for the removal case."}],"related":["upsert-syntax","update-with-join","truncate-vs-delete"]},"source_url":"https://sqlly.app/sql-dialects/merge-statement","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/multi-row-insert","corpus":"sql-dialects","engine":null,"language":"en","title":"Insert several rows in one statement","description":"Multi-row VALUES lists work in four engines and Oracle 23ai; older Oracle needs INSERT ALL or an INSERT ... SELECT with a UNION ALL.","body":{"slug":"multi-row-insert","name":"Multi-row insert","h1":"Insert several rows in one statement","category":"dml","lede":"One round trip, many rows: the VALUES list that is a one-liner everywhere except older Oracle.","intro":"Listing several row tuples in one VALUES clause is the normal way to batch small inserts. Oracle accepted it only from 23ai; earlier versions need INSERT ALL or a SELECT-based insert. Each engine also caps the statement in its own way, covered in bulk-insert-limits.","rows":[{"engine_slug":"sql-server","sql":"INSERT INTO customers (email) VALUES\n  ('ann@example.com'),\n  ('bob@example.com'),\n  ('cyd@example.com');","note":"Up to 1000 row-value expressions per INSERT; beyond that, switch to INSERT ... SELECT."},{"engine_slug":"postgresql","sql":"INSERT INTO customers (email) VALUES\n  ('ann@example.com'),\n  ('bob@example.com'),\n  ('cyd@example.com');","note":"No fixed row cap; the practical limit is the parameter count if you parameterize each value."},{"engine_slug":"mysql","sql":"INSERT INTO customers (email) VALUES\n  ('ann@example.com'),\n  ('bob@example.com'),\n  ('cyd@example.com');","note":"Statement size is bounded by max_allowed_packet; ON DUPLICATE KEY UPDATE applies per row."},{"engine_slug":"sqlite","sql":"INSERT INTO customers (email) VALUES\n  ('ann@example.com'),\n  ('bob@example.com'),\n  ('cyd@example.com');","note":"Multi-row VALUES since 3.7.11. Bound parameters count against SQLITE_MAX_VARIABLE_NUMBER: 999 before 3.32, 32,766 since."},{"engine_slug":"oracle","sql":"INSERT INTO customers (email)\nSELECT 'ann@example.com' FROM dual UNION ALL\nSELECT 'bob@example.com' FROM dual UNION ALL\nSELECT 'cyd@example.com' FROM dual;","note":"Works on every version. 23ai also accepts the multi-row VALUES list used by the other four. INSERT ALL is the other classic form, but it generates one identity or sequence value per source row, so three branches into a table with an identity key collide."}],"verdict":"SQL Server, PostgreSQL, MySQL, SQLite and Oracle 23ai share identical syntax. Older Oracle needs INSERT … SELECT … FROM dual UNION ALL, which is wordier but does the same job in one statement.","faqs":[{"question":"How many rows should one INSERT carry?","answer":"A few hundred to a few thousand is comfortable on every engine, and SQL Server stops at 1,000. Beyond that, statement size limits and parse time make a bulk loader or INSERT … SELECT from a staging table the better tool."},{"question":"What about Oracle's INSERT ALL?","answer":"INSERT ALL INTO t VALUES (…) INTO t VALUES (…) SELECT * FROM dual is a multi-table insert driven by a subquery: each INTO branch runs once per row the subquery returns, and dual has one row. Because identity and NEXTVAL values are generated once per source row, every branch gets the same id, and inserts into an identity-keyed table fail with ORA-00001."},{"question":"Is a multi-row insert all-or-nothing?","answer":"Yes on transactional tables: it is one statement, so a failing row (say, a duplicate key) rolls back the whole insert. MySQL's INSERT IGNORE turns such errors into warnings and skips the bad rows instead."}],"related":["insert-from-select","bulk-insert-limits","upsert-syntax"]},"source_url":"https://sqlly.app/sql-dialects/multi-row-insert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/null-safe-equality","corpus":"sql-dialects","engine":null,"language":"en","title":"NULL-safe equality: IS NOT DISTINCT FROM, <=> and IS","description":"Compare values where NULL should equal NULL: the standard IS NOT DISTINCT FROM, MySQL's <=>, SQLite's IS and Oracle's DECODE.","body":{"slug":"null-safe-equality","name":"NULL-safe equality","h1":"NULL-safe equality: IS NOT DISTINCT FROM, <=> and IS","category":"query","lede":"NULL = NULL is unknown, not true, unless you use a null-safe operator.","intro":"Ordinary = returns unknown when either side is NULL, so NULLs never match. The SQL standard answer is IS NOT DISTINCT FROM, which SQL Server (2022+), PostgreSQL and SQLite (3.39+) support. MySQL has <=>, SQLite also has IS, and Oracle needs a workaround.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM tasks WHERE assignee IS NOT DISTINCT FROM @v;","note":"SQL Server 2022+. On older versions write (assignee = @v OR (assignee IS NULL AND @v IS NULL))."},{"engine_slug":"postgresql","sql":"SELECT * FROM tasks WHERE assignee IS NOT DISTINCT FROM $1;","note":"The negation is IS DISTINCT FROM. $1 is a bind parameter."},{"engine_slug":"mysql","sql":"SELECT * FROM tasks WHERE assignee <=> @v;","note":"<=> returns 1 for NULL <=> NULL and 0 for NULL <=> 5, never NULL. No IS NOT DISTINCT FROM."},{"engine_slug":"sqlite","sql":"SELECT * FROM tasks WHERE assignee IS :v;","note":"IS and IS NOT are null-safe for any value, not just NULL. IS NOT DISTINCT FROM also works from 3.39."},{"engine_slug":"oracle","sql":"SELECT * FROM tasks WHERE DECODE(assignee, :v, 1, 0) = 1;","note":"DECODE treats two NULLs as equal, which makes it the compact Oracle idiom. Even 23ai rejects IS NOT DISTINCT FROM."}],"verdict":"IS NOT DISTINCT FROM is the standard and now runs on three of the five engines; MySQL's <=> and SQLite's IS are fine local spellings. Oracle is the holdout: use DECODE or the paired (a = b OR (a IS NULL AND b IS NULL)) test, which works on every engine.","faqs":[{"question":"When does this matter?","answer":"Whenever either side can be NULL: detecting changed rows during a sync (WHERE t.col IS DISTINCT FROM s.col), comparing audit snapshots, or joining on nullable columns. With plain =, rows with NULL on either side silently drop out."},{"question":"Is SQLite's IS the same as IS NOT DISTINCT FROM?","answer":"Yes. SQLite documents IS as equality that treats two NULLs as equal and NULL versus a value as false, which is exactly the standard predicate. 3.39 added the standard spelling as an alias."},{"question":"Can the null-safe form still use an index?","answer":"It depends on the engine. MySQL's <=> and SQLite's IS can use an index on the column. PostgreSQL does not use a B-tree index for IS NOT DISTINCT FROM, so on large tables rewrite it as (col = $1 OR (col IS NULL AND $1 IS NULL)), or branch in the application on whether the value is NULL. Check the plan on your own engine."}],"related":["null-substitution","conditional-expression","anti-join"]},"source_url":"https://sqlly.app/sql-dialects/null-safe-equality","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/null-substitution","corpus":"sql-dialects","engine":null,"language":"en","title":"Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL","description":"Show 0 instead of NULL, or a fallback name: the portable COALESCE and every engine's two-argument shorthand.","body":{"slug":"null-substitution","name":"NULL substitution in output","h1":"Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL","category":"query","lede":"COALESCE everywhere; ISNULL, IFNULL and NVL are the same idea with local names.","intro":"COALESCE(a, b, c) returns the first non-NULL argument and works in all five engines. Each engine also ships a two-argument version under a different name, which is the usual porting friction.","rows":[{"engine_slug":"sql-server","sql":"SELECT COALESCE(nickname, name) AS display_name FROM users;","note":"ISNULL(nickname, name) is the T-SQL shorthand; its return type follows the first argument, COALESCE uses type precedence."},{"engine_slug":"postgresql","sql":"SELECT COALESCE(nickname, name) AS display_name FROM users;","note":"COALESCE is the only built-in option, and the standard one."},{"engine_slug":"mysql","sql":"SELECT IFNULL(nickname, name) AS display_name FROM users;","note":"IFNULL is the two-argument shorthand; COALESCE takes many arguments."},{"engine_slug":"sqlite","sql":"SELECT IFNULL(nickname, name) AS display_name FROM users;","note":"IFNULL and COALESCE are both built in; no NVL."},{"engine_slug":"oracle","sql":"SELECT NVL(nickname, name) AS display_name FROM users;","note":"NVL is the two-argument shorthand; NVL2(a, b, c) returns b when a is not NULL and c when it is."}],"verdict":"Write COALESCE and the query runs everywhere; the shorthands only matter when reading existing code. One real behavioral difference to know: in SQL Server, ISNULL's result type comes from the first argument, so ISNULL(varchar_col, longer_default) silently truncates where COALESCE does not.","faqs":[{"question":"COALESCE or ISNULL: which should I use?","answer":"COALESCE. It is standard, takes any number of arguments, and its result type follows the normal precedence rules. ISNULL, IFNULL and NVL are fine to read in existing code, but portable code uses COALESCE."},{"question":"Why is COALESCE slow with a subquery in SQL Server?","answer":"SQL Server expands COALESCE((SELECT …), 0) into CASE WHEN (SELECT …) IS NOT NULL THEN (SELECT …) ELSE 0 END, so the subquery can run twice. ISNULL((SELECT …), 0) evaluates it once. Oracle's NVL, by contrast, evaluates both arguments every time, while its COALESCE stops at the first non-NULL one."},{"question":"How do I replace NULL in an aggregate?","answer":"Wrap the aggregate: COALESCE(SUM(x), 0). SUM over zero rows, or over only NULLs, returns NULL rather than 0. Writing SUM(COALESCE(x, 0)) does not fix that case, because SUM already skips NULL rows."}],"related":["order-by-coalesce","string-concatenation","null-safe-equality"]},"source_url":"https://sqlly.app/sql-dialects/null-substitution","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/null-vs-empty-string","corpus":"sql-dialects","engine":null,"language":"en","title":"NULL versus empty string in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Four engines treat '' as a real value; Oracle folds it into NULL, which changes how you write every NULL check on text columns.","body":{"slug":"null-vs-empty-string","name":"NULL versus empty string","h1":"NULL versus empty string in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"In Oracle, '' IS NULL is true. Everywhere else it is false. That one fact rewrites your WHERE clauses.","intro":"For the four engines the empty string and NULL are different values, and both checks are needed when text columns can hold either. Oracle makes the distinction impossible to express because zero-length text simply is NULL.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM t WHERE note = '' OR note IS NULL;","note":"'' and NULL are distinct values, so a column that allows both needs both checks, unless a NOT NULL or CHECK (note <> '') constraint rules one out."},{"engine_slug":"postgresql","sql":"SELECT * FROM t WHERE note = '' OR note IS NULL;","note":"Distinct values, as ANSI intends. IS NOT DISTINCT FROM compares them without the three-valued-logic trap."},{"engine_slug":"mysql","sql":"SELECT * FROM t WHERE note = '' OR note IS NULL;","note":"Distinct values. Note that NULL fails both = '' and <> '' comparisons."},{"engine_slug":"sqlite","sql":"SELECT * FROM t WHERE note = '' OR note IS NULL;","note":"Distinct values. In ascending order NULL sorts first, then '', then 'a'."},{"engine_slug":"oracle","sql":"SELECT * FROM t WHERE note IS NULL;","note":"'' IS NULL evaluates to true: Oracle treats zero-length character values as NULL, so you cannot store an empty string in a column at all."}],"verdict":"The same SQL is right on four engines and redundant on the fifth. A bare IS NULL check is complete on Oracle but misses '' rows everywhere else; NULLIF(note, '') IS NULL catches both cases on all five.","faqs":[{"question":"Why does Oracle treat '' as NULL?","answer":"A long-standing implementation choice, documented and never changed because real code depends on it. VARCHAR2 columns cannot distinguish empty from missing."},{"question":"How do I normalize mixed data before migrating to Oracle?","answer":"Collapse '' to NULL first (UPDATE t SET note = NULL WHERE note = '';), or comparisons that matched empty strings will silently start matching NULL semantics."},{"question":"Does this affect VARCHAR in other engines?","answer":"No. SQL Server, PostgreSQL, MySQL and SQLite all store '' as a real value. Only Oracle collapses it, in VARCHAR2 and CHAR columns alike."}],"related":["char-vs-varchar","boolean-literal","cast-syntax"]},"source_url":"https://sqlly.app/sql-dialects/null-vs-empty-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/nulls-first-last","corpus":"sql-dialects","engine":null,"language":"en","title":"Sorting NULLs first or last","description":"Control where NULL rows land in an ordered result: the NULLS FIRST/LAST keywords, and the CASE/IS NULL emulation where they are missing.","body":{"slug":"nulls-first-last","name":"Sorting NULLs first or last","h1":"Sorting NULLs first or last","category":"query","lede":"Three engines support the keywords; two need a sort-key trick.","intro":"The standard NULLS FIRST / NULLS LAST modifiers work in PostgreSQL, Oracle and SQLite 3.30+. SQL Server and MySQL don't have them, so you sort on a computed key (CASE or col IS NULL) ahead of the real column.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM employees ORDER BY CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END, deleted_at;","note":"No NULLS FIRST/LAST. SQL Server treats NULL as the lowest value, so it sorts first ascending; the CASE key pushes it last."},{"engine_slug":"postgresql","sql":"SELECT * FROM employees ORDER BY deleted_at NULLS LAST;","note":"PostgreSQL treats NULL as the highest value: NULLS LAST is already the ascending default and NULLS FIRST the descending one."},{"engine_slug":"mysql","sql":"SELECT * FROM employees ORDER BY deleted_at IS NULL, deleted_at;","note":"No NULLS keyword. NULLs sort first ascending; deleted_at IS NULL is 0 or 1, so sorting on it first pushes NULLs last."},{"engine_slug":"sqlite","sql":"SELECT * FROM employees ORDER BY deleted_at NULLS LAST;","note":"NULLS FIRST/LAST since 3.30; before that, sort on deleted_at IS NULL first. SQLite sorts NULLs first ascending by default."},{"engine_slug":"oracle","sql":"SELECT * FROM employees ORDER BY deleted_at NULLS LAST;","note":"Same defaults as PostgreSQL: NULLs last ascending, first descending."}],"verdict":"NULLS FIRST/LAST says exactly what you mean; use it on PostgreSQL, Oracle and SQLite 3.30+. The IS NULL or CASE sort key works on all five and is worth knowing, because the defaults disagree: SQL Server, MySQL and SQLite treat NULL as the smallest value, PostgreSQL and Oracle as the largest, and a ported query silently reorders.","faqs":[{"question":"What are the defaults in each engine?","answer":"Ascending: SQL Server, MySQL and SQLite put NULLs first; PostgreSQL and Oracle put them last. Descending reverses each engine's order, so DESC puts NULLs last in SQL Server, MySQL and SQLite and first in PostgreSQL and Oracle. The standard leaves this to the implementation."},{"question":"Why does ORDER BY … DESC LIMIT 10 show NULLs first on PostgreSQL?","answer":"Because PostgreSQL and Oracle treat NULL as larger than any value, a descending sort starts with them. On SQL Server, MySQL and SQLite the same query shows them last. Add NULLS LAST, or a CASE key, so the top ten mean the same thing everywhere."},{"question":"Does the emulation hurt performance?","answer":"The extra sort key means an index on deleted_at can no longer deliver rows in order, so the engine sorts. If that matters, index the expression (PostgreSQL, Oracle, MySQL 8.0.13+) or a computed column (SQL Server). PostgreSQL can also build the index itself with NULLS FIRST or LAST to match the query."}],"related":["order-by-coalesce","custom-sort-order","top-n"]},"source_url":"https://sqlly.app/sql-dialects/nulls-first-last","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/number-to-text-format","corpus":"sql-dialects","engine":null,"language":"en","title":"Convert a number to formatted text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"Thousand separators and fixed decimals: TO_CHAR masks in PostgreSQL and Oracle, FORMAT() in SQL Server and MySQL, printf-style in SQLite.","body":{"slug":"number-to-text-format","name":"Convert a number to formatted text","h1":"Convert a number to formatted text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Five engines, four different formatting idioms for the same 1,234,567.89.","intro":"Casting a number to text is easy; formatting it with thousand separators and decimals is where the dialects diverge completely. Each row formats the same number to 1,234,567.89 in its engine's native idiom.","rows":[{"engine_slug":"sql-server","sql":"SELECT FORMAT(1234567.891, 'N2');","note":"FORMAT uses .NET format strings ('N2' = thousands separators and 2 decimals) and calls into the CLR for every row, so it is much slower than CONVERT(VARCHAR, x), which has no mask."},{"engine_slug":"postgresql","sql":"SELECT TO_CHAR(1234567.891, 'FM9,999,999.00');","note":"Mask syntax: 9 is a digit, 0 is a forced digit, FM trims padding. TO_CHAR is the idiomatic tool."},{"engine_slug":"mysql","sql":"SELECT FORMAT(1234567.891, 2);","note":"FORMAT always adds thousands separators and rounds to the given decimals; CAST(42 AS CHAR) is the plain, maskless conversion."},{"engine_slug":"sqlite","sql":"SELECT FORMAT('%,.2f', 1234567.891);","note":"FORMAT (3.38+, the new name for printf) takes C-style masks. The ',' flag is a SQLite extension that adds thousands separators, so this returns 1,234,567.89."},{"engine_slug":"oracle","sql":"SELECT TO_CHAR(1234567.891, 'FM9,999,999.00') FROM dual;","note":"Same mask family as PostgreSQL. Group separator and decimal character follow NLS settings."}],"verdict":"There is no portable formatted conversion: TO_CHAR masks in PostgreSQL and Oracle, a costly FORMAT in SQL Server, a FORMAT in MySQL that always adds separators, and printf-style FORMAT in SQLite.","faqs":[{"question":"Why does my TO_CHAR output have leading spaces?","answer":"9 placeholders reserve room for a sign and pad to the mask width. Prefix the mask with FM to trim the padding."},{"question":"How do I control the decimal character?","answer":"In Oracle and PostgreSQL the D and G mask characters follow NLS_NUMERIC_CHARACTERS and lc_numeric. MySQL's FORMAT takes an optional locale, FORMAT(x, 2, 'de_DE'), and defaults to en_US. SQL Server's FORMAT takes an optional culture such as 'de-DE' and otherwise follows the session language."},{"question":"Is SQL Server FORMAT() suitable for big result sets?","answer":"No. It invokes the .NET runtime per row. Use CONVERT for plain casts and reserve FORMAT for display-level queries."}],"related":["cast-syntax","date-to-text-format","cast-string-to-number"]},"source_url":"https://sqlly.app/sql-dialects/number-to-text-format","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/order-by-coalesce","corpus":"sql-dialects","engine":null,"language":"en","title":"Sorting with COALESCE in ORDER BY","description":"Sort rows as if NULL held a concrete value: order by the promo price when there is one, otherwise the normal price.","body":{"slug":"order-by-coalesce","name":"COALESCE in ORDER BY","h1":"Sorting with COALESCE in ORDER BY","category":"query","lede":"Fold NULL into the value order, or park it deliberately.","intro":"ORDER BY COALESCE(nullable_col, fallback) sorts on the substituted value instead of using the engine's default NULL placement. It is the portable way to say \"treat NULL as X\"; the NULLS FIRST/LAST keywords only move NULLs to one end.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM plans ORDER BY COALESCE(promo_price, price);","note":"Without COALESCE, plans with no promo price would sort first, because SQL Server treats NULL as the lowest value."},{"engine_slug":"postgresql","sql":"SELECT * FROM plans ORDER BY COALESCE(promo_price, price);","note":"If you only want NULLs at one end, ORDER BY promo_price NULLS LAST says that directly."},{"engine_slug":"mysql","sql":"SELECT * FROM plans ORDER BY COALESCE(promo_price, price);","note":"MySQL sorts NULLs first ascending; IFNULL(promo_price, price) is the two-argument equivalent."},{"engine_slug":"sqlite","sql":"SELECT * FROM plans ORDER BY COALESCE(promo_price, price);","note":"SQLite sorts NULLs first ascending; IFNULL works the same here."},{"engine_slug":"oracle","sql":"SELECT * FROM plans ORDER BY NVL(promo_price, price);","note":"NVL is the Oracle spelling; COALESCE gives the same order. Without it, NULLs sort last ascending."}],"verdict":"COALESCE in ORDER BY runs on every engine and does one thing: it sorts each NULL as a value you choose. When you only care whether NULLs come first or last, NULLS FIRST/LAST (PostgreSQL, Oracle, SQLite 3.30+) states that more directly.","faqs":[{"question":"When should I use COALESCE instead of NULLS LAST?","answer":"When a NULL should sort among the values. COALESCE(promo_price, price) places a plan without a promo at its normal price, somewhere in the middle; NULLS FIRST/LAST can only push it to an end."},{"question":"Can I mix COALESCE with other sort keys?","answer":"Yes: ORDER BY COALESCE(promo_price, price), name. Each key is independent, so COALESCE keys combine with plain columns, CASE keys and NULLS FIRST/LAST on other keys."},{"question":"Does sorting on an expression lose the index?","answer":"Usually. A B-tree on promo_price does not match COALESCE(promo_price, price). PostgreSQL, Oracle, SQLite and MySQL 8.0.13+ can index the exact expression; SQL Server can index a computed column. For reports over a few thousand rows the sort is cheap anyway."}],"related":["nulls-first-last","null-substitution","custom-sort-order"]},"source_url":"https://sqlly.app/sql-dialects/order-by-coalesce","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/parse-text-to-date","corpus":"sql-dialects","engine":null,"language":"en","title":"Parse text into a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"ISO 'YYYY-MM-DD' text parses everywhere; anything else needs a mask: TO_DATE, STR_TO_DATE with % masks, or a CONVERT style code.","body":{"slug":"parse-text-to-date","name":"Parse text into a date","h1":"Parse text into a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"ISO format is the universal language; every other layout needs engine-specific parsing.","intro":"The rule of thumb: send ISO 8601 ('2026-11-20') and all five engines parse it without help. For text in other layouts, each engine wants its own parsing function and mask syntax.","rows":[{"engine_slug":"sql-server","sql":"SELECT CAST('2026-11-20' AS DATE), TRY_CONVERT(DATE, '20/11/2026', 103);","note":"Casting ISO text to DATE is safe under any language setting, but to DATETIME it is not: under SET LANGUAGE british, '2026-11-05' becomes May 11. CONVERT's third argument is a style code; 103 is dd/mm/yyyy."},{"engine_slug":"postgresql","sql":"SELECT DATE '2026-11-20', TO_DATE('20/11/2026', 'DD/MM/YYYY');","note":"ISO input parses regardless of session settings; TO_DATE handles other masks. Ambiguous input like 03/04/2026 follows the DateStyle setting."},{"engine_slug":"mysql","sql":"SELECT STR_TO_DATE('20/11/2026', '%d/%m/%Y'), CAST('2026-11-20' AS DATE);","note":"STR_TO_DATE takes %-masks (%d day, %m month, %Y 4-digit year). Invalid input returns NULL with a warning."},{"engine_slug":"sqlite","sql":"SELECT DATE('2026-11-20');","note":"The date functions accept only a handful of ISO-style formats; there is no arbitrary-mask parser. Normalize in SQL or the app first."},{"engine_slug":"oracle","sql":"SELECT TO_DATE('20/11/2026', 'DD/MM/YYYY') FROM dual;","note":"Always pass the mask: TO_DATE('20/11/2026') without one depends on the session's NLS_DATE_FORMAT and breaks on other machines."}],"verdict":"ISO text is the only portable input. For anything else the mask syntaxes differ enough that parsing code does not survive an engine switch, so fix the format at the source when you can.","faqs":[{"question":"Why did my date parse on one machine and fail on another?","answer":"Session language settings (SQL Server's LANGUAGE, PostgreSQL's DateStyle, Oracle's NLS_DATE_FORMAT) decide how ambiguous text is read. Passing an explicit mask or ISO text removes the dependency."},{"question":"How do I parse a timestamp with time?","answer":"Same functions: TO_DATE becomes TO_TIMESTAMP in Oracle, STR_TO_DATE takes %H:%i:%s masks in MySQL, and CONVERT(DATETIME, ..., 120) reads ISO text in SQL Server."},{"question":"Is '03/04/2026' March 4 or April 3?","answer":"Engine- and session-dependent, which is exactly why you never parse ambiguous layouts implicitly. Demand a mask or ISO text."}],"related":["date-to-text-format","safe-cast","timezone-convert"]},"source_url":"https://sqlly.app/sql-dialects/parse-text-to-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/partial-index","corpus":"sql-dialects","engine":null,"language":"en","title":"Partial (filtered) indexes in every SQL dialect","description":"Index only the rows you actually query, with WHERE-filtered indexes in SQL Server, PostgreSQL and SQLite, and workarounds in MySQL and Oracle.","body":{"slug":"partial-index","name":"Partial / filtered index","h1":"Partial (filtered) indexes in every SQL dialect","category":"indexes","lede":"A partial index covers only rows matching a WHERE clause, keeping it small and fast when you always filter the same way.","intro":"Three engines take the WHERE clause directly on CREATE INDEX. MySQL has no partial indexes; Oracle gets close with a function-based index that indexes NULL for the rows you do not care about.","rows":[{"engine_slug":"sql-server","sql":"CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';","note":"Called a filtered index. The WHERE clause allows only simple comparisons (=, <>, <, >, IN, IS NULL) joined by AND: no OR, LIKE or functions. A parameterized query (WHERE status = @s) usually cannot use it, because the plan must work for any value. Creating it requires SET QUOTED_IDENTIFIER ON, which sqlcmd leaves off unless you pass -I."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';","note":"Any immutable predicate is allowed, including expressions over several columns. Typical uses: an open-orders queue, or WHERE deleted_at IS NULL on soft-deleted tables."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_orders_status ON orders (status, created_at);","note":"No partial indexes. The nearest alternative is a composite index led by the filter column; it still holds an entry for every row, whatever its status."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';","note":"Partial indexes supported since SQLite 3.8.0, with a documented set of restrictions on the WHERE clause."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_orders_pending ON orders (CASE WHEN status = 'pending' THEN created_at END);","note":"No partial indexes. A function-based index stores NULL for non-matching rows (NULLs are not indexed), so it behaves like a partial index; queries must repeat the CASE expression."}],"verdict":"PostgreSQL, SQLite and SQL Server index a row subset directly; MySQL cannot, and Oracle fakes it with a CASE-based function index. If hot-queue queries dominate your workload, this is one of the most effective size reducers available.","faqs":[{"question":"Why use a partial index instead of a normal one?","answer":"It is much smaller, since it only stores the rows you query, and writes to other rows do not touch it at all."},{"question":"Why is my partial index not being used?","answer":"The query predicate has to imply the index predicate. WHERE status = 'pending' uses it; WHERE status IN ('pending') may or may not depending on the engine, and mismatched literals never will."},{"question":"Can the WHERE clause reference other columns?","answer":"Yes, any column of the table. PostgreSQL and SQLite also allow deterministic expressions; SQL Server allows only simple comparisons joined by AND. MySQL has no partial indexes, and Oracle's CASE trick can reference any column inside the CASE."}],"related":["create-index","expression-index","unique-index"]},"source_url":"https://sqlly.app/sql-dialects/partial-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/prefix-index","corpus":"sql-dialects","engine":null,"language":"en","title":"Column-prefix indexes in every SQL dialect","description":"Index only the first N characters of a long string column to keep the index small; native in MySQL, expression-based elsewhere.","body":{"slug":"prefix-index","name":"Prefix index","h1":"Column-prefix indexes in every SQL dialect","category":"indexes","lede":"A prefix index stores just the first N characters of a varchar, cutting index size dramatically on long text columns.","intro":"MySQL has native prefix syntax with (col(N)). Everyone else approximates it with an expression on the first N characters, which works as long as the query repeats the expression or the prefix is selective enough.","rows":[{"engine_slug":"sql-server","sql":"ALTER TABLE products ADD name_prefix AS LEFT(name, 20);\nCREATE INDEX idx_products_name_prefix ON products (name_prefix);","note":"No prefix indexes. Index a computed column holding LEFT(name, 20), as here, or index the whole column if it fits the 1,700-byte nonclustered key limit."},{"engine_slug":"postgresql","sql":"CREATE INDEX idx_products_name ON products (LEFT(name, 20));","note":"No prefix syntax; an expression index on LEFT(name, 20) is the closest. Queries must repeat LEFT(name, 20) = ? to use it, and verify the prefix is selective."},{"engine_slug":"mysql","sql":"CREATE INDEX idx_products_name ON products (name(20));","note":"Native prefix syntax, required for BLOB and TEXT and optional for CHAR and VARCHAR. WHERE name = 'x' uses it directly. A prefix index can never cover a query, because the full value is not stored in it."},{"engine_slug":"sqlite","sql":"CREATE INDEX idx_products_name ON products (SUBSTR(name, 1, 20));","note":"No prefix syntax; index the SUBSTR expression. The query must filter on SUBSTR(name, 1, 20) to hit the index."},{"engine_slug":"oracle","sql":"CREATE INDEX idx_products_name ON products (SUBSTR(name, 1, 20));","note":"No prefix syntax; a function-based index on SUBSTR does it. The query must repeat the same SUBSTR expression."}],"verdict":"Only MySQL has real prefix indexes. An expression index or computed column on LEFT/SUBSTR substitutes in the other four, but the indexed value is not the column, so a plain WHERE name = 'x' or a range on name will not use it (SQL Server's computed-column matching is the exception for the exact expression).","faqs":[{"question":"How do I pick the prefix length?","answer":"Compare COUNT(DISTINCT col) with COUNT(DISTINCT LEFT(col, N)) for growing N; pick the smallest N that keeps selectivity close to the full column."},{"question":"Does a prefix index work for ORDER BY?","answer":"No, in MySQL and in the expression-based variants. Sorting on the full column still needs the data or a full index on it."},{"question":"Why does my query ignore the expression index?","answer":"Because WHERE name = 'x' does not mention SUBSTR(name, 1, 20). Only queries written against the expression use the index."}],"related":["expression-index","create-index","full-text-index"]},"source_url":"https://sqlly.app/sql-dialects/prefix-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/random-sample","corpus":"sql-dialects","engine":null,"language":"en","title":"Random sample of rows","description":"Fetch N random rows, or a percentage of the table: ORDER BY random(), NEWID, RAND, SAMPLE and TABLESAMPLE compared.","body":{"slug":"random-sample","name":"Random sample of rows","h1":"Random sample of rows","category":"query","lede":"ORDER BY random() works on every engine and gets slower with every row you add.","intro":"The quick form gives every row a random sort key and keeps the first N. The scalable form samples pages or a percentage of rows (TABLESAMPLE in SQL Server and PostgreSQL, SAMPLE in Oracle) and returns roughly, not exactly, the size you asked for.","rows":[{"engine_slug":"sql-server","sql":"SELECT TOP 10 * FROM users ORDER BY NEWID();","note":"Sorts the whole table by a fresh GUID. TABLESAMPLE (1 PERCENT) reads whole pages cheaply, so the row count varies and rows cluster."},{"engine_slug":"postgresql","sql":"SELECT * FROM users ORDER BY random() LIMIT 10;","note":"Same full-table cost. TABLESAMPLE BERNOULLI (1) samples 1% of rows and SYSTEM (1) 1% of pages; both scale to huge tables."},{"engine_slug":"mysql","sql":"SELECT * FROM users ORDER BY RAND() LIMIT 10;","note":"No sampling clause. RAND() is computed for every row before the sort, so this is fine on small tables and slow on big ones."},{"engine_slug":"sqlite","sql":"SELECT * FROM users ORDER BY random() LIMIT 10;","note":"No sampling clause; ORDER BY random() is the only built-in option."},{"engine_slug":"oracle","sql":"SELECT * FROM users ORDER BY DBMS_RANDOM.VALUE FETCH FIRST 10 ROWS ONLY;","note":"12c+; before that, wrap the sorted query and filter ROWNUM <= 10. SAMPLE (1) keeps about 1% of rows but still scans the table; SAMPLE BLOCK (1) reads about 1% of blocks."}],"verdict":"ORDER BY random() with a row cap is portable and returns exactly N rows, but it reads and sorts the whole table, which is fine up to a few hundred thousand rows. For bigger tables use the engine's sampler (TABLESAMPLE or SAMPLE) and accept an approximate size, or keep an indexed random-key column.","faqs":[{"question":"Why is ORDER BY random() slow on large tables?","answer":"The engine has to generate a random key for every row before it can know which ten are smallest, so the cost grows with the table, not with N. A top-N sort keeps memory small, but the full scan remains."},{"question":"How do I get exactly N rows fast from a huge table?","answer":"Oversample, then cap: SELECT * FROM users TABLESAMPLE SYSTEM (1) LIMIT 10 in PostgreSQL may return fewer than 10 on a small table, so retry or sample more. Or store an indexed random_key column and query WHERE random_key >= :r ORDER BY random_key LIMIT 10."},{"question":"Does TABLESAMPLE give each row an equal chance?","answer":"BERNOULLI includes each row independently with probability p. SYSTEM picks whole pages, so every row still has probability p but rows from the same page arrive together, which skews small samples. SQL Server's TABLESAMPLE is page-based like SYSTEM."}],"related":["limit","row-numbering","top-n"]},"source_url":"https://sqlly.app/sql-dialects/random-sample","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/rebuild-index","corpus":"sql-dialects","engine":null,"language":"en","title":"REINDEX and ALTER INDEX REBUILD in every SQL dialect","description":"Rebuild a bloated or fragmented index: ALTER INDEX REBUILD in SQL Server and Oracle, REINDEX in PostgreSQL and SQLite, a table rebuild in MySQL.","body":{"slug":"rebuild-index","name":"Rebuild index","h1":"REINDEX and ALTER INDEX REBUILD in every SQL dialect","category":"indexes","lede":"Indexes bloat after churn. Each engine has its own rebuild verb, and one of them (MySQL) rebuilds the whole table instead.","intro":"Rebuilding rewrites the index structure compactly. The portability story is mixed: same idea, five different commands, and concurrency guarantees differ per engine.","rows":[{"engine_slug":"sql-server","sql":"ALTER INDEX idx_orders_customer ON orders REBUILD;","note":"Online with ONLINE = ON, else the table is locked. REORGANIZE is the lightweight online alternative for light fragmentation."},{"engine_slug":"postgresql","sql":"REINDEX INDEX idx_orders_customer;","note":"Takes an exclusive lock while building; REINDEX INDEX CONCURRENTLY avoids blocking writes (PostgreSQL 12+)."},{"engine_slug":"mysql","sql":"ALTER TABLE orders ENGINE=InnoDB;","note":"InnoDB has no per-index rebuild command. A null ALTER TABLE ... ENGINE=InnoDB, or OPTIMIZE TABLE (which InnoDB maps to the same recreate), rebuilds the table and all its indexes as online DDL."},{"engine_slug":"sqlite","sql":"REINDEX idx_orders_customer;","note":"REINDEX works on an index, table or the whole database (REINDEX; with no argument)."},{"engine_slug":"oracle","sql":"ALTER INDEX idx_orders_customer REBUILD;","note":"Add ONLINE to keep DML running (Enterprise Edition). For light cleanup, ALTER INDEX ... COALESCE merges sparse leaf blocks without a rebuild, and SHRINK SPACE also releases space in ASSM tablespaces."}],"verdict":"Five engines, four commands and one workaround: ALTER INDEX REBUILD (SQL Server, Oracle), REINDEX (PostgreSQL, SQLite), and MySQL only rebuilds via table-level DDL. Concurrency needs the ONLINE/CONCURRENTLY keyword on each.","faqs":[{"question":"How do I know an index needs rebuilding?","answer":"SQL Server: sys.dm_db_index_physical_stats avg_fragmentation_in_percent. PostgreSQL: pgstattuple bloat. InnoDB: innodb_index_stats. In practice, rebuild after bulk loads and large deletes, not on a schedule."},{"question":"Is REORGANIZE better than REBUILD?","answer":"For SQL Server light fragmentation: yes, it is always online and cheaper. Rebuild for heavy fragmentation, changing fillfactor, or switching compression."},{"question":"Does rebuilding update statistics?","answer":"SQL Server rebuild does (reorganize does not). PostgreSQL REINDEX does not; run ANALYZE. Oracle REBUILD recomputes stats by default."}],"related":["create-index","drop-index","vacuum-analyze"]},"source_url":"https://sqlly.app/sql-dialects/rebuild-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/regex-matching","corpus":"sql-dialects","engine":null,"language":"en","title":"Regular expression matching: ~, REGEXP and REGEXP_LIKE","description":"Match a pattern with real regex support: where each engine has it, what the operator looks like, and what to do where none exists.","body":{"slug":"regex-matching","name":"Regular expression matching","h1":"Regular expression matching: ~, REGEXP and REGEXP_LIKE","category":"query","lede":"Four engines ship regex today, SQL Server only since 2025; SQLite leaves it to the application.","intro":"PostgreSQL uses the ~ operator, MySQL the REGEXP keyword, Oracle and SQL Server 2025 the REGEXP_LIKE function. SQLite parses REGEXP but it only works if the application registers a regexp() function. Older SQL Server has only LIKE character classes.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM logs WHERE message LIKE '%[0-9][0-9][0-9]%';","note":"LIKE character classes run on every version. SQL Server 2025 and Azure SQL add REGEXP_LIKE(message, '[0-9]{3}'), which needs database compatibility level 170."},{"engine_slug":"postgresql","sql":"SELECT * FROM logs WHERE message ~ '[0-9]{3}';","note":"~ is case-sensitive, ~* case-insensitive, !~ negates. Both [[:digit:]] and \\d work."},{"engine_slug":"mysql","sql":"SELECT * FROM logs WHERE message REGEXP '[0-9]{3}';","note":"REGEXP, RLIKE and REGEXP_LIKE() are equivalent. 8.0 uses the ICU library; 5.7 used Henry Spencer's POSIX library."},{"engine_slug":"sqlite","sql":"SELECT * FROM logs WHERE message REGEXP '[0-9]{3}';","note":"Parses, then fails with 'no such function: REGEXP' unless the host registers a regexp() function (the sqlite3 shell ships one)."},{"engine_slug":"oracle","sql":"SELECT * FROM logs WHERE REGEXP_LIKE(message, '[0-9]{3}');","note":"REGEXP_LIKE, REGEXP_SUBSTR, REGEXP_REPLACE and REGEXP_INSTR since 10g; REGEXP_COUNT since 11g."}],"verdict":"The function names differ but simple patterns like [0-9]{3} port as written. The flavors split on advanced features: lookahead and lookbehind work in PostgreSQL and MySQL 8.0, not in Oracle or SQL Server 2025, which uses the RE2 library. Don't rely on REGEXP in SQLite, since its behavior depends on whichever function the client registered.","faqs":[{"question":"How do I write a case-insensitive regex?","answer":"PostgreSQL: ~* or the (?i) prefix. MySQL: REGEXP follows the collation, so it is already case-insensitive on *_ci columns; REGEXP_LIKE(message, 'pattern', 'c') forces case-sensitive and 'i' insensitive. Oracle and SQL Server 2025: REGEXP_LIKE(message, 'pattern', 'i')."},{"question":"Why does the same regex behave differently on MySQL 5.7 and 8.0?","answer":"8.0 replaced the Henry Spencer library with ICU. Lookarounds, lazy quantifiers and \\d work in 8.0 and not in 5.7, and 8.0 is stricter about invalid patterns. Test patterns against the server version you deploy."},{"question":"Can an index serve a regex filter?","answer":"Usually not. PostgreSQL can turn an anchored pattern such as '^abc' into a B-tree range when the index uses the C collation or text_pattern_ops; other patterns scan. For hot lookups, index a normalized column, or in PostgreSQL use a pg_trgm GIN index, which speeds up both LIKE and regex."}],"related":["like-escape","case-insensitive-compare","escape-single-quotes"]},"source_url":"https://sqlly.app/sql-dialects/regex-matching","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/regex-replace","corpus":"sql-dialects","engine":null,"language":"en","title":"Regular expression replace in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"REGEXP_REPLACE is native in PostgreSQL, MySQL 8, Oracle and SQL Server 2025; SQLite's core library has no regex functions at all.","body":{"slug":"regex-replace","name":"Regular expression replace","h1":"Regular expression replace in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"query","lede":"PostgreSQL, MySQL and Oracle have had it for years, SQL Server added it in 2025, and SQLite's core still has none.","intro":"Regex replace fixes dirty data in one line if your engine has it. PostgreSQL, MySQL 8 and Oracle do, SQL Server gained it in SQL Server 2025 and Azure SQL, and SQLite's core library has none. Each row replaces digit runs in 'abc123def45'.","rows":[{"engine_slug":"sql-server","sql":"SELECT REGEXP_REPLACE('abc123def45', '[0-9]+', '#');","note":"SQL Server 2025 and Azure SQL. Replaces every match by default (abc#def#). REGEXP_REPLACE works at any compatibility level, while REGEXP_LIKE needs level 170. Older releases need PATINDEX tricks or a CLR function."},{"engine_slug":"postgresql","sql":"SELECT REGEXP_REPLACE('abc123def45', '[0-9]+', '#', 'g');","note":"Without the 'g' flag only the first match is replaced (abc#def45); with it you get abc#def#. PostgreSQL uses its own advanced regex flavor, which supports lookahead."},{"engine_slug":"mysql","sql":"SELECT REGEXP_REPLACE('abc123def45', '[0-9]+', '#');","note":"MySQL 8.0.4+ with the ICU regex library; replaces every occurrence by default (abc#def#). Earlier versions had REGEXP matching but no replace."},{"engine_slug":"sqlite","sql":"SELECT REPLACE('abc123def45', '123', '#');","note":"The core library has no regex functions. X REGEXP Y calls a user function named regexp that nobody defines by default (the sqlite3 shell loads one), and there is no REGEXP_REPLACE. Load an extension, register a function from your driver, or fall back to literal REPLACE as here, which only handles a known string: this returns abc#def45, not abc#def#."},{"engine_slug":"oracle","sql":"SELECT REGEXP_REPLACE('abc123def45', '[0-9]+', '#') FROM dual;","note":"POSIX regex with Perl-style shortcuts such as \\d, since 10g. Replaces every match by default (abc#def#), with position and occurrence arguments for finer control."}],"verdict":"The function name is the same in four engines, but the default differs: PostgreSQL replaces the first match unless you pass 'g', while MySQL, Oracle and SQL Server replace all. SQLite is the holdout, so keep regex cleanup in the app for engine-neutral code.","faqs":[{"question":"Why does PostgreSQL replace only the first match?","answer":"REGEXP_REPLACE defaults to one substitution; add the flag argument: REGEXP_REPLACE(s, '[0-9]+', '#', 'g'). MySQL, Oracle and SQL Server replace every match by default, so SQL ported to PostgreSQL must add the 'g'."},{"question":"Which regex flavor is which?","answer":"PostgreSQL uses its own advanced regex engine and MySQL uses ICU; both support lookahead. Oracle is POSIX ERE with Perl-style shortcuts like \\d, SQL Server 2025 uses RE2 (no lookaround or backreferences), and SQLite extensions vary. Anchors and character classes port; lookaround does not."},{"question":"What is the pre-2025 answer on SQL Server?","answer":"Compose PATINDEX + STUFF for single simple patterns, push the cleanup to the app, or use a SQL CLR regex function. All are clunky enough that most teams did this cleanup outside the database."}],"related":["concat-number-string","case-insensitive-compare","cast-syntax"]},"source_url":"https://sqlly.app/sql-dialects/regex-replace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/rename-column","corpus":"sql-dialects","engine":null,"language":"en","title":"Rename a column","description":"ALTER TABLE ... RENAME COLUMN is standard now; SQL Server only has sp_rename, and MySQL 5.7 only has CHANGE COLUMN.","body":{"slug":"rename-column","name":"Rename column","h1":"Rename a column","category":"ddl","lede":"A metadata-only rename, if your engine has the standard syntax.","intro":"ALTER TABLE … RENAME COLUMN works in every engine here except SQL Server, which uses the sp_rename procedure. sp_rename does not update views, procedures or functions that mention the old name, so renames there need a search through the dependent code.","rows":[{"engine_slug":"sql-server","sql":"EXEC sp_rename 'customers.email', 'contact_email', 'COLUMN';","note":"No ALTER … RENAME COLUMN. sp_rename warns that changing an object name can break scripts and stored procedures, and leaves them unchanged; they fail when next run."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers RENAME COLUMN email TO contact_email;","note":"Metadata-only. Views, indexes and constraints follow automatically because they store column references, not names. Function bodies are stored as text and break."},{"engine_slug":"mysql","sql":"ALTER TABLE customers RENAME COLUMN email TO contact_email;","note":"8.0+. MySQL 5.7 and MariaDB before 10.5.2 need CHANGE COLUMN email contact_email VARCHAR(320), restating the full definition. Views that use the old name are not updated and fail with error 1356 until you recreate them."},{"engine_slug":"sqlite","sql":"ALTER TABLE customers RENAME COLUMN email TO contact_email;","note":"3.25+. SQLite also rewrites references in the table's indexes, triggers and views."},{"engine_slug":"oracle","sql":"ALTER TABLE customers RENAME COLUMN email TO contact_email;","note":"Metadata change. Indexes and constraints follow; views and PL/SQL that use the old name become invalid and fail to recompile."}],"verdict":"Use RENAME COLUMN wherever it exists. On SQL Server, and for function bodies in PostgreSQL, views in MySQL, or views and PL/SQL in Oracle, search the dependent code for the old name before you rename.","faqs":[{"question":"Why is sp_rename on SQL Server frowned upon?","answer":"It changes the name and nothing else: views, procedures, functions and application SQL that mention the old name keep doing so and fail at run time. Find the dependents first with sys.sql_expression_dependencies or a text search of sys.sql_modules."},{"question":"Does renaming break indexes or constraints?","answer":"No. Indexes and constraints reference the column internally, so they follow the rename on all five engines. What breaks is code that stores the name as text: SQL Server modules, PostgreSQL function bodies, MySQL views, Oracle views and PL/SQL, and application queries."},{"question":"What about a view that selects the column?","answer":"PostgreSQL and SQLite update the view, and PostgreSQL even keeps the view's output column name. On SQL Server, MySQL and Oracle, recreate the view after the rename (on SQL Server, sp_refreshview is not enough when the name changed)."}],"related":["rename-table","drop-column","alter-column-type"]},"source_url":"https://sqlly.app/sql-dialects/rename-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/rename-table","corpus":"sql-dialects","engine":null,"language":"en","title":"Rename a table","description":"sp_rename versus ALTER TABLE ... RENAME TO, plus MySQL's atomic RENAME TABLE swap trick.","body":{"slug":"rename-table","name":"Rename table","h1":"Rename a table","category":"ddl","lede":"Point a new name at the same table, and swap two tables' names without a gap.","intro":"Table renames only change metadata, so they are instant even on huge tables. For zero-downtime swaps, MySQL's RENAME TABLE takes several renames in one atomic statement; SQL Server, PostgreSQL and SQLite get the same effect by running two renames in one transaction.","rows":[{"engine_slug":"sql-server","sql":"EXEC sp_rename 'customers', 'clients';","note":"Prints a caution that renaming can break scripts and procedures. Two sp_rename calls inside BEGIN TRAN … COMMIT swap names atomically."},{"engine_slug":"postgresql","sql":"ALTER TABLE customers RENAME TO clients;","note":"Instant. Views and foreign keys keep working because they reference the table by OID. DDL is transactional, so two renames in one transaction swap names atomically."},{"engine_slug":"mysql","sql":"RENAME TABLE customers TO clients;","note":"Several renames in one statement are atomic: RENAME TABLE customers TO customers_old, customers_new TO customers swaps with no gap. ALTER TABLE … RENAME TO also works."},{"engine_slug":"sqlite","sql":"ALTER TABLE customers RENAME TO clients;","note":"3.25+ also rewrites references in triggers and views; PRAGMA legacy_alter_table = ON restores the old behavior, which left them alone."},{"engine_slug":"oracle","sql":"ALTER TABLE customers RENAME TO clients;","note":"Indexes, grants and constraints follow the table. Views, synonyms and PL/SQL that use the old name become invalid. DDL commits implicitly, so there is no atomic two-table swap."}],"verdict":"ALTER TABLE … RENAME TO works on PostgreSQL, MySQL, SQLite and Oracle; SQL Server needs sp_rename. For an atomic swap, use MySQL's multi-table RENAME TABLE or two renames in one transaction on SQL Server, PostgreSQL or SQLite. Oracle can't swap atomically.","faqs":[{"question":"Do foreign keys survive a table rename?","answer":"Yes, on every engine, including SQL Server's sp_rename: constraints reference the table internally, not by name. What breaks is code that names the table as text, such as views and procedures on SQL Server and Oracle."},{"question":"How does the atomic swap help migrations?","answer":"Build customers_new, backfill it in batches, then swap: RENAME TABLE customers TO customers_old, customers_new TO customers in MySQL, or both renames in one transaction where DDL is transactional. Queries never see a moment where customers is missing."},{"question":"Can I move a table to another schema?","answer":"PostgreSQL: ALTER TABLE customers SET SCHEMA archive. SQL Server: ALTER SCHEMA archive TRANSFER dbo.customers. MySQL: RENAME TABLE shop.customers TO archive.customers moves it to another database. Oracle has no rename across schemas: copy with CREATE TABLE … AS SELECT or Data Pump. SQLite can't move tables between attached databases."}],"related":["rename-column","create-schema","drop-column"]},"source_url":"https://sqlly.app/sql-dialects/rename-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/row-numbering","corpus":"sql-dialects","engine":null,"language":"en","title":"Numbering rows: ROW_NUMBER, ROWNUM and rowid","description":"Attach a 1, 2, 3… sequence to result rows: the ROW_NUMBER window function, Oracle's ROWNUM and SQLite's rowid compared.","body":{"slug":"row-numbering","name":"Numbered rows (ROW_NUMBER / ROWNUM / rowid)","h1":"Numbering rows: ROW_NUMBER, ROWNUM and rowid","category":"query","lede":"One portable window function, and two Oracle and SQLite features that look similar but do something else.","intro":"ROW_NUMBER() OVER (ORDER BY …) numbers rows after sorting and works in all five engines. Oracle's ROWNUM is assigned before sorting, and SQLite's rowid is the table's storage key rather than a position in the result.","rows":[{"engine_slug":"sql-server","sql":"SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;","note":"Ties get arbitrary numbers unless the ORDER BY is unique, so append a tiebreaker column."},{"engine_slug":"postgresql","sql":"SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;","note":"No rowid. The ctid system column is a physical location that changes on every UPDATE."},{"engine_slug":"mysql","sql":"SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;","note":"8.0+. On 5.7 the @rn := @rn + 1 user-variable trick was the workaround; its evaluation order is not guaranteed, and assigning variables inside expressions is deprecated in 8.0."},{"engine_slug":"sqlite","sql":"SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;","note":"Window functions since 3.25. Every table except WITHOUT ROWID tables also has a rowid, which is a key, not a result position."},{"engine_slug":"oracle","sql":"SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;","note":"The old form, SELECT ROWNUM AS rn, name FROM (SELECT name FROM employees ORDER BY hired_at), needs the subquery because ROWNUM is assigned before ORDER BY."}],"verdict":"ROW_NUMBER() is the portable answer, with identical syntax on all five engines. Don't confuse it with row identifiers: Oracle's ROWNUM numbers rows before the sort, and SQLite's rowid, PostgreSQL's ctid and Oracle's ROWID identify stored rows, not positions in a result.","faqs":[{"question":"What is the difference between ROWNUM and ROW_NUMBER in Oracle?","answer":"ROWNUM is a pseudo-column assigned as rows are fetched, before ORDER BY runs, so SELECT ROWNUM, name FROM employees ORDER BY hired_at shows scrambled numbers. ROW_NUMBER() OVER (ORDER BY hired_at) numbers the sorted result. ROWNUM also can't be filtered with WHERE ROWNUM > 1, which never returns a row."},{"question":"Can I use rowid or ctid as a stable key?","answer":"No. PostgreSQL's ctid changes on every UPDATE and on VACUUM FULL. SQLite's rowid can change on VACUUM unless it is aliased by an INTEGER PRIMARY KEY column. Oracle's ROWID changes when a row moves, for example after ALTER TABLE … MOVE or a partition key update. Declare a real primary key."},{"question":"Why do my ROW_NUMBER values differ between runs?","answer":"The ORDER BY inside OVER isn't unique, so tied rows get numbers in whatever order the engine reads them. Add a unique tiebreaker: OVER (ORDER BY hired_at, id)."}],"related":["top-n-per-group","limit","random-sample"]},"source_url":"https://sqlly.app/sql-dialects/row-numbering","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/safe-cast","corpus":"sql-dialects","engine":null,"language":"en","title":"Safe cast that returns NULL instead of an error in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"TRY_CAST, pg_input_is_valid and ON CONVERSION ERROR: what each engine gives you when text will not convert, from an error to NULL to a silent 0.","body":{"slug":"safe-cast","name":"Safe cast (NULL on failure)","h1":"Safe cast that returns NULL instead of an error in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"A plain CAST of 'abc' errors in SQL Server, PostgreSQL and Oracle and quietly returns 0 in MySQL and SQLite.","intro":"One failed cast can kill a whole batch job. SQL Server and Oracle have a cast that returns NULL instead of failing, PostgreSQL 16 added a validity test to run before the cast, and MySQL and SQLite never fail at all, which is its own problem.","rows":[{"engine_slug":"sql-server","sql":"SELECT TRY_CAST('abc' AS INT), TRY_CONVERT(INT, 'abc');","note":"TRY_CAST/TRY_CONVERT return NULL on failure instead of raising. Available since SQL Server 2012."},{"engine_slug":"postgresql","sql":"SELECT CASE WHEN pg_input_is_valid(s, 'integer') THEN s::INTEGER END\nFROM (VALUES ('abc'), ('42')) AS v(s);","note":"No TRY_CAST. pg_input_is_valid (PostgreSQL 16+) tests the text first; on older versions use a regex guard (s ~ '^[0-9]+$') or a PL/pgSQL function that traps the error. Guard a column, not a literal: PostgreSQL converts a quoted literal such as 'abc'::INTEGER while parsing, so it errors even inside a CASE branch that never runs."},{"engine_slug":"mysql","sql":"SELECT CAST('abc' AS SIGNED);","note":"No TRY_CAST and no error either: you get 0 plus a warning, which is worse than a failure if you are not checking."},{"engine_slug":"sqlite","sql":"SELECT CAST('abc' AS INTEGER);","note":"Never errors: 'abc' becomes 0, '42abc' becomes 42. Validation is entirely your job."},{"engine_slug":"oracle","sql":"SELECT TO_NUMBER('abc' DEFAULT NULL ON CONVERSION ERROR) FROM dual;","note":"The DEFAULT ... ON CONVERSION ERROR clause (12.2+) returns a chosen value instead of ORA-01722, and works in TO_DATE and CAST too. VALIDATE_CONVERSION('abc' AS NUMBER) returns 0 or 1 if you only want to test."}],"verdict":"SQL Server's TRY_CAST and Oracle's DEFAULT ... ON CONVERSION ERROR are true safe casts. PostgreSQL 16+ gets close with pg_input_is_valid inside a CASE. MySQL and SQLite never raise, so bad text arrives as 0 unless you screen it with a regex first.","faqs":[{"question":"Why not just try the cast and catch the error?","answer":"In a SELECT over many rows, one bad value fails the entire statement, and inside a PostgreSQL transaction it also aborts the transaction until you roll back. Screening the data or using a safe cast keeps the batch running."},{"question":"What does CAST('abc' AS SIGNED) return in MySQL?","answer":"0, with only a warning. Strict mode does not change SELECT expressions, so a silent zero can flow into aggregates and reports."},{"question":"Can I use regex to screen numbers in MySQL too?","answer":"Yes: WHERE col REGEXP '^[0-9]+([.][0-9]+)?$' before casting, or write a stored function mirroring TRY_CAST."}],"related":["cast-string-to-number","parse-text-to-date","cast-syntax"]},"source_url":"https://sqlly.app/sql-dialects/safe-cast","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/savepoints","corpus":"sql-dialects","engine":null,"language":"en","title":"SAVEPOINT and ROLLBACK TO in every SQL dialect","description":"Roll back part of a transaction with SAVEPOINT, ROLLBACK TO and RELEASE SAVEPOINT in the five engines.","body":{"slug":"savepoints","name":"Savepoints","h1":"SAVEPOINT and ROLLBACK TO in every SQL dialect","category":"admin","lede":"Savepoints let you undo the last steps of a transaction without discarding everything, the standard tool for per-row error recovery in bulk loads.","intro":"PostgreSQL, MySQL, SQLite and Oracle share the SAVEPOINT / ROLLBACK TO syntax, and Oracle skips RELEASE. SQL Server uses SAVE TRANSACTION with a name.","rows":[{"engine_slug":"sql-server","sql":"BEGIN TRANSACTION;\nSAVE TRANSACTION sp1;\nUPDATE accounts SET balance = 0 WHERE id = 1;\nROLLBACK TRANSACTION sp1;\nCOMMIT;","note":"SAVE TRANSACTION names a point; ROLLBACK TRANSACTION sp1 undoes just the work after it and leaves the transaction open. Under SET XACT_ABORT ON most errors roll back the whole transaction, savepoint or not."},{"engine_slug":"postgresql","sql":"BEGIN;\nSAVEPOINT sp1;\nUPDATE accounts SET balance = 0 WHERE id = 1;\nROLLBACK TO sp1;\nRELEASE SAVEPOINT sp1;\nCOMMIT;","note":"Any error aborts the whole PostgreSQL transaction, so a savepoint is how you recover: ROLLBACK TO sp1 clears the error and the transaction carries on. Drivers use this for statement-level retry."},{"engine_slug":"mysql","sql":"BEGIN;\nSAVEPOINT sp1;\nUPDATE accounts SET balance = 0 WHERE id = 1;\nROLLBACK TO sp1;\nRELEASE SAVEPOINT sp1;\nCOMMIT;","note":"Standard syntax; works in InnoDB. Savepoints disappear when the transaction commits or rolls back."},{"engine_slug":"sqlite","sql":"BEGIN;\nSAVEPOINT sp1;\nUPDATE accounts SET balance = 0 WHERE id = 1;\nROLLBACK TO sp1;\nRELEASE SAVEPOINT sp1;\nCOMMIT;","note":"Fully supported, including RELEASE sp1 collapsing the savepoint. Even usable outside an explicit BEGIN, acting as its own transaction."},{"engine_slug":"oracle","sql":"SAVEPOINT sp1;\nUPDATE accounts SET balance = 0 WHERE id = 1;\nROLLBACK TO sp1;\nCOMMIT;","note":"Supported in SQL and PL/SQL. Names are reused within a transaction (re-declaring moves the point). No RELEASE statement; points vanish at COMMIT/ROLLBACK."}],"verdict":"Every engine can partially roll back; only the spelling differs. SQL Server says SAVE TRANSACTION, the other four say SAVEPOINT. Savepoints matter most in PostgreSQL, where an error otherwise aborts the entire transaction.","faqs":[{"question":"Savepoint vs nested transaction?","answer":"SQL Server counts nested BEGIN TRANSACTION calls in @@TRANCOUNT: an inner COMMIT only decrements the counter, and a ROLLBACK without a savepoint name undoes everything. Savepoints are the only way to undo part of a transaction, in SQL Server and everywhere else."},{"question":"Can I release a savepoint and keep the changes?","answer":"RELEASE keeps the changes made since the savepoint but removes the ability to roll back to it. SQL Server has no RELEASE; the point is only discarded at commit."},{"question":"Do savepoints survive a rollback?","answer":"ROLLBACK TO sp1 keeps sp1 and earlier points but discards later ones. A full ROLLBACK discards all of them."}],"related":["begin-transaction","isolation-levels","deadlock-inspection"]},"source_url":"https://sqlly.app/sql-dialects/savepoints","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/select-for-update","corpus":"sql-dialects","engine":null,"language":"en","title":"SELECT FOR UPDATE and SQL Server's UPDLOCK in every SQL dialect","description":"Lock rows before updating them: FOR UPDATE in PostgreSQL, MySQL and Oracle, the UPDLOCK hint in SQL Server, and BEGIN IMMEDIATE in SQLite.","body":{"slug":"select-for-update","name":"SELECT FOR UPDATE (row locks)","h1":"SELECT FOR UPDATE and SQL Server's UPDLOCK in every SQL dialect","category":"admin","lede":"Read rows with an intent to update and other writers will wait: the pessimistic locking pattern for queues and balance updates.","intro":"PostgreSQL, MySQL and Oracle say FOR UPDATE; SQL Server uses a table hint. SQLite has no row locks at all: the whole database is the unit.","rows":[{"engine_slug":"sql-server","sql":"BEGIN TRANSACTION;\nSELECT * FROM accounts WITH (UPDLOCK, ROWLOCK) WHERE id = 1;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;","note":"No FOR UPDATE. UPDLOCK takes update locks (plain readers still read, another UPDLOCK waits) held to the end of the transaction; ROWLOCK asks for row granularity. Add READPAST to skip locked rows or NOWAIT to fail at once."},{"engine_slug":"postgresql","sql":"BEGIN;\nSELECT * FROM accounts WHERE id = 1 FOR UPDATE;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;","note":"FOR UPDATE row-locks the selected rows until commit. Variants: FOR NO KEY UPDATE (weaker: foreign-key checks from inserts into child tables do not wait), FOR SHARE, and NOWAIT or SKIP LOCKED."},{"engine_slug":"mysql","sql":"BEGIN;\nSELECT * FROM accounts WHERE id = 1 FOR UPDATE;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;","note":"FOR UPDATE works in InnoDB inside a transaction. Also supports NOWAIT and SKIP LOCKED (8.0+), the basis for many job-queue patterns."},{"engine_slug":"sqlite","sql":"BEGIN IMMEDIATE;\n-- read then write; other writers block until COMMIT\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;","note":"No row locks and no FOR UPDATE. BEGIN IMMEDIATE starts the write transaction up front and blocks all other writers until COMMIT or ROLLBACK; in WAL mode readers keep reading their snapshot meanwhile."},{"engine_slug":"oracle","sql":"SELECT * FROM accounts WHERE id = 1 FOR UPDATE;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;","note":"FOR UPDATE plus WAIT n, NOWAIT or SKIP LOCKED. Rows stay locked across the transaction; the transaction starts implicitly with the SELECT."}],"verdict":"FOR UPDATE is the shared spelling in PostgreSQL, MySQL and Oracle. SQL Server uses the WITH (UPDLOCK) hint, and SQLite locks the whole database with BEGIN IMMEDIATE. NOWAIT and SKIP LOCKED exist in PostgreSQL, MySQL 8 and Oracle; SQL Server spells them as the NOWAIT and READPAST hints.","faqs":[{"question":"What is the deadlock risk here?","answer":"Two transactions locking the same rows in different orders deadlock. Always touch rows in a consistent order, and keep the lock window short."},{"question":"What does SKIP LOCKED do?","answer":"It skips rows already locked by others instead of waiting, which lets many workers safely pull from the same queue table without coordination."},{"question":"Does FOR UPDATE lock the gaps too?","answer":"InnoDB at REPEATABLE READ also takes next-key (gap) locks on the scanned range, which blocks inserts into it. PostgreSQL and Oracle lock only the rows returned."}],"related":["begin-transaction","isolation-levels","lock-timeout"]},"source_url":"https://sqlly.app/sql-dialects/select-for-update","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/select-into-temp","corpus":"sql-dialects","engine":null,"language":"en","title":"SELECT INTO vs CREATE TEMP TABLE AS","description":"Materialize a query into a temp table: T-SQL's SELECT … INTO #tmp, CREATE TEMP TABLE … AS elsewhere, and Oracle's private temporary tables.","body":{"slug":"select-into-temp","name":"SELECT INTO / temp result tables","h1":"SELECT INTO vs CREATE TEMP TABLE AS","category":"query","lede":"SQL Server says SELECT INTO, three engines say CREATE TEMP TABLE AS, and Oracle needs a special prefix.","intro":"SQL Server builds a temp table with SELECT … INTO #tmp. PostgreSQL, MySQL and SQLite use CREATE TEMP(ORARY) TABLE … AS SELECT. Oracle 18c+ has private temporary tables, whose names must start with ORA$PTT_; before that, a global temporary table had to exist in advance.","rows":[{"engine_slug":"sql-server","sql":"SELECT id, total INTO #big_orders FROM orders WHERE total > 1000;","note":"# marks a session-local temp table in tempdb, dropped when the session ends; ## makes it global. There is no CREATE TEMP TABLE … AS."},{"engine_slug":"postgresql","sql":"CREATE TEMP TABLE big_orders AS SELECT id, total FROM orders WHERE total > 1000;","note":"Lives until the session ends. ON COMMIT DROP or DELETE ROWS ties it to the transaction instead. SELECT … INTO TEMP big_orders FROM … also works."},{"engine_slug":"mysql","sql":"CREATE TEMPORARY TABLE big_orders AS SELECT id, total FROM orders WHERE total > 1000;","note":"MySQL's SELECT … INTO writes to variables or files, not tables. A TEMPORARY table is visible only to its session and hides a permanent table of the same name."},{"engine_slug":"sqlite","sql":"CREATE TEMP TABLE big_orders AS SELECT id, total FROM orders WHERE total > 1000;","note":"TEMP tables live in the connection's separate temp database. Without TEMP the table is permanent."},{"engine_slug":"oracle","sql":"CREATE PRIVATE TEMPORARY TABLE ora$ptt_big_orders ON COMMIT PRESERVE DEFINITION AS SELECT id, total FROM orders WHERE total > 1000;","note":"18c+. The ORA$PTT_ prefix is required by default; ON COMMIT DROP DEFINITION (the default) removes it at commit. A plain CREATE TABLE … AS makes a permanent table."}],"verdict":"CREATE TEMPORARY TABLE … AS SELECT covers PostgreSQL, MySQL and SQLite; SQL Server's SELECT INTO #name is its own dialect. Oracle can do the same since 18c with a private temporary table, but the required ORA$PTT_ name prefix means the statement never ports as is.","faqs":[{"question":"How long does a temp table live?","answer":"SQL Server #tables: the session, or the stored procedure that created them. PostgreSQL: the session, or the transaction with ON COMMIT DROP. MySQL and SQLite: the connection. Oracle private temporary tables: the transaction or the session, per ON COMMIT; global temporary tables have a permanent definition with per-session rows."},{"question":"Why does my CTAS temp table have no indexes or constraints?","answer":"CREATE TABLE … AS (and SELECT INTO) copies column names, types and data, not indexes, primary keys or defaults, on every engine. Add the indexes afterwards, or create the table first and fill it with INSERT INTO … SELECT."},{"question":"Is a CTE a substitute for a temp table?","answer":"For a single statement, often. A CTE exists only inside that statement, can't be indexed, and depending on the engine may be recomputed for each reference. Multi-step work that reads the intermediate result several times is better served by a temp table."}],"related":["cte-basics","table-alias-syntax","limit"]},"source_url":"https://sqlly.app/sql-dialects/select-into-temp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/server-version","corpus":"sql-dialects","engine":null,"language":"en","title":"SELECT @@VERSION and version() in every SQL dialect","description":"Print the engine version string, from @@VERSION to version() to sqlite_version().","body":{"slug":"server-version","name":"Server version","h1":"SELECT @@VERSION and version() in every SQL dialect","category":"admin","lede":"The first thing any support engineer asks for: exact engine and version. Every engine has a one-liner.","intro":"One line each, no shared spelling. The version string contents also differ: some include the OS build, some just the number.","rows":[{"engine_slug":"sql-server","sql":"SELECT @@VERSION;","note":"One string with edition, version number, OS and architecture. SERVERPROPERTY('ProductVersion') (for example 17.0.4035.5) and SERVERPROPERTY('Edition') give structured fields."},{"engine_slug":"postgresql","sql":"SELECT version();","note":"Full banner string. SHOW server_version gives just the number; current_setting('server_version_num') returns it as an integer string such as 180006, which casts cleanly for comparisons."},{"engine_slug":"mysql","sql":"SELECT VERSION();","note":"Just the version number, such as 8.4.11, sometimes with a distribution suffix (8.0.36-0ubuntu0.22.04.1). @@version_comment names the build, and SHOW VARIABLES LIKE 'version%' adds the compile OS and machine."},{"engine_slug":"sqlite","sql":"SELECT sqlite_version();","note":"Library version like 3.45.1. PRAGMA compile_options lists build-time flags; sqlite_source_id() the exact source snapshot."},{"engine_slug":"oracle","sql":"SELECT banner FROM v$version;\n-- or: SELECT BANNER_FULL FROM v$version;","note":"From 18c on, v$version returns one row and BANNER_FULL adds the release update (Version 23.26.3.0.0); older releases list a row per component. Reading it needs dictionary access such as SELECT_CATALOG_ROLE."}],"verdict":"Trivial everywhere, just five different spellings. If you are branching application logic on the version, prefer the structured sources (SERVERPROPERTY, server_version_num, v$version) over parsing the banner string.","faqs":[{"question":"Why do I need the exact version?","answer":"Syntax and behavior differ by release: PostgreSQL INCLUDE since 11, MySQL descending indexes honored since 8.0, SQL Server DROP IF EXISTS since 2016. Version detection avoids runtime errors."},{"question":"Does version() work while connected?","answer":"Yes, all of these are session-local reads with no locking; safe to call any time, including from health checks."},{"question":"Oracle says table or view does not exist?","answer":"You lack SELECT on v$version (it is a dictionary view). Ask for SELECT_CATALOG_ROLE or use the data dictionary alternative product_component_version."}],"related":["current-session-info","list-connections"]},"source_url":"https://sqlly.app/sql-dialects/server-version","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/string-concatenation","corpus":"sql-dialects","engine":null,"language":"en","title":"String concatenation in SELECT: || vs + vs CONCAT","description":"Join first and last name into a display column: the || operator, T-SQL's +, and CONCAT/CONCAT_WS behavior with NULLs.","body":{"slug":"string-concatenation","name":"String concatenation","h1":"String concatenation in SELECT: || vs + vs CONCAT","category":"query","lede":"Same task, three operators, and the NULL rules differ between them.","intro":"PostgreSQL, SQLite and Oracle use the standard || operator. SQL Server uses + (|| arrived only in SQL Server 2025 and Azure SQL), and MySQL uses CONCAT(). The porting bug is NULL handling: || and + return NULL when any operand is NULL, except in Oracle.","rows":[{"engine_slug":"sql-server","sql":"SELECT first_name + ' ' + last_name AS full_name FROM users;","note":"+ returns NULL if any operand is NULL; CONCAT() treats NULL as an empty string. SQL Server 2025 and Azure SQL also accept ||."},{"engine_slug":"postgresql","sql":"SELECT first_name || ' ' || last_name AS full_name FROM users;","note":"|| returns NULL on a NULL operand; CONCAT() and CONCAT_WS() skip NULLs."},{"engine_slug":"mysql","sql":"SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;","note":"|| means logical OR unless sql_mode includes PIPES_AS_CONCAT. CONCAT returns NULL if any argument is NULL; CONCAT_WS skips NULLs."},{"engine_slug":"sqlite","sql":"SELECT first_name || ' ' || last_name AS full_name FROM users;","note":"|| returns NULL on a NULL operand. concat() and concat_ws(), which skip NULLs, arrived in 3.44."},{"engine_slug":"oracle","sql":"SELECT first_name || ' ' || last_name AS full_name FROM users;","note":"Oracle treats NULL as an empty string here, so 'Ana' || ' ' || NULL is 'Ana '. CONCAT() took exactly two arguments before 23ai."}],"verdict":"|| is the standard and the most widely supported, but MySQL needs CONCAT() and SQL Server before 2025 needs +. NULL handling splits further: Oracle ignores NULLs in ||, SQL Server's CONCAT ignores them, MySQL's CONCAT does not, and every other operator returns NULL. Wrap nullable operands in COALESCE(…, '') or use CONCAT_WS when a missing last name must not blank the whole value.","faqs":[{"question":"Why is my concatenated column NULL?","answer":"One operand is NULL and the operator propagates it: + in SQL Server, || in PostgreSQL and SQLite, CONCAT() in MySQL. Use COALESCE(last_name, ''), or CONCAT_WS(' ', first_name, last_name), which skips NULLs in SQL Server 2017+, PostgreSQL, MySQL and SQLite 3.44+."},{"question":"Can I concatenate numbers?","answer":"|| converts numbers to text in PostgreSQL, SQLite and Oracle, and CONCAT() does in every engine. SQL Server's + does not: 'Order ' + 42 tries to convert the string to int and fails, so use CONCAT or CAST. The text form also varies: 1.0 || '' gives '1.0' in PostgreSQL and SQLite but '1' in Oracle."},{"question":"How do I concatenate many rows into one string?","answer":"That is string aggregation: STRING_AGG(name, ', ') in SQL Server 2017+ and PostgreSQL, GROUP_CONCAT(name SEPARATOR ', ') in MySQL, group_concat() or string_agg() (3.44+) in SQLite, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) in Oracle."}],"related":["null-substitution","escape-single-quotes","conditional-expression"]},"source_url":"https://sqlly.app/sql-dialects/string-concatenation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/table-alias-syntax","corpus":"sql-dialects","engine":null,"language":"en","title":"Table alias syntax: where AS is optional (and where it fails)","description":"FROM orders o or FROM orders AS o: the rules per engine, including Oracle's rule that table aliases must not use AS.","body":{"slug":"table-alias-syntax","name":"Table alias syntax","h1":"Table alias syntax: where AS is optional (and where it fails)","category":"query","lede":"AS is optional almost everywhere, and a syntax error in one place.","intro":"All five engines accept FROM orders o; four also accept FROM orders AS o. Oracle rejects AS before a table alias. Column aliases accept AS everywhere, and SQL Server adds its own alias = expression form.","rows":[{"engine_slug":"sql-server","sql":"SELECT o.id, o.total FROM orders AS o WHERE o.total > 100;","note":"AS is optional for tables and columns. The T-SQL-only form SELECT order_total = o.total also names a column."},{"engine_slug":"postgresql","sql":"SELECT o.id, o.total FROM orders o WHERE o.total > 100;","note":"AS is optional. A column alias written without AS can't be a reserved keyword, so SELECT 1 AS from works and SELECT 1 from does not."},{"engine_slug":"mysql","sql":"SELECT o.id, o.total FROM orders o WHERE o.total > 100;","note":"AS is optional. Column aliases may be quoted with backticks, double quotes or even single quotes ('Order Total')."},{"engine_slug":"sqlite","sql":"SELECT o.id, o.total FROM orders o WHERE o.total > 100;","note":"AS is optional. SQLite also lets a SELECT-list alias be used in WHERE, which no other engine here allows."},{"engine_slug":"oracle","sql":"SELECT o.id, o.total FROM orders o WHERE o.total > 100;","note":"FROM orders AS o fails with a syntax error. Column aliases may use AS or omit it."}],"verdict":"Write table aliases without AS and column aliases with AS; that parses on all five engines. The traps are Oracle, where AS before a table alias fails, and SQL Server's alias = expression form, which no other engine accepts.","faqs":[{"question":"Why does my query fail on Oracle but not SQL Server?","answer":"Most likely the AS in FROM orders AS o: Oracle accepts AS only for column aliases. Write FROM orders o and the query runs on every engine."},{"question":"Can I reference a SELECT-list alias in the WHERE clause?","answer":"Not portably. SQL Server, PostgreSQL, MySQL and Oracle reject it because WHERE is evaluated before the SELECT list; SQLite allows it. All five accept aliases in ORDER BY, and MySQL, PostgreSQL, SQLite and Oracle 23ai also in GROUP BY. Elsewhere, repeat the expression or wrap the query in a subquery or CTE."},{"question":"When is a table alias required?","answer":"On derived tables in SQL Server and MySQL: FROM (SELECT …) AS x. PostgreSQL 16+, SQLite and Oracle accept an unnamed subquery, but naming it is portable. You also need aliases when the same table appears twice, as in a self-join."}],"related":["cte-basics","select-into-temp","limit"]},"source_url":"https://sqlly.app/sql-dialects/table-alias-syntax","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/temp-tables","corpus":"sql-dialects","engine":null,"language":"en","title":"Temporary tables for session work","description":"SELECT INTO #temp, CREATE TEMP TABLE, CREATE TEMPORARY TABLE and Oracle's global temporary tables: session-scoped scratch data.","body":{"slug":"temp-tables","name":"Temporary tables","h1":"Temporary tables for session work","category":"ddl","lede":"Scratch tables only your session can see, for staging, deduplication and multi-step queries.","intro":"Every engine has session-private temp tables, but their lifecycles differ. SQL Server's #temp, MySQL's and SQLite's TEMPORARY tables end with the session; PostgreSQL's can end with the transaction (ON COMMIT DROP). Oracle's classic global temporary table has a permanent, shared definition with session-private rows, and 18c added private temporary tables that behave like the others.","rows":[{"engine_slug":"sql-server","sql":"CREATE TABLE #stage_sessions (\n  session_id NVARCHAR(64) NOT NULL PRIMARY KEY,\n  hit_count INT NOT NULL\n);\nINSERT INTO #stage_sessions (session_id, hit_count)\nSELECT session_id, COUNT(*) FROM raw_hits GROUP BY session_id;","note":"#temp is private to the session, ##temp visible to all. Creating the table first and INSERTing lets you set types and keys up front; SELECT INTO #tmp does both in one step."},{"engine_slug":"postgresql","sql":"CREATE TEMP TABLE stage_sessions (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  hit_count INT NOT NULL\n);\nINSERT INTO stage_sessions (session_id, hit_count)\nSELECT session_id, COUNT(*) FROM raw_hits GROUP BY session_id;","note":"Lives until the session ends; ON COMMIT DROP, inside an explicit transaction, ties it to the transaction instead. Each session gets its own pg_temp schema."},{"engine_slug":"mysql","sql":"CREATE TEMPORARY TABLE stage_sessions (\n  session_id VARCHAR(64) NOT NULL PRIMARY KEY,\n  hit_count INT NOT NULL\n);\nINSERT INTO stage_sessions (session_id, hit_count)\nSELECT session_id, COUNT(*) FROM raw_hits GROUP BY session_id;","note":"Visible only to the creating session, survives commits, dropped at disconnect. Two sessions can create same-named temp tables without conflict, but one query can't reference the same temp table twice (error 1137)."},{"engine_slug":"sqlite","sql":"CREATE TEMP TABLE stage_sessions (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  hit_count INT NOT NULL\n);\nINSERT INTO stage_sessions (session_id, hit_count)\nSELECT session_id, COUNT(*) FROM raw_hits GROUP BY session_id;","note":"TEMP and TEMPORARY are synonyms; the table lives in a separate temp database and vanishes with the connection."},{"engine_slug":"oracle","sql":"CREATE GLOBAL TEMPORARY TABLE stage_sessions (\n  session_id VARCHAR2(64) NOT NULL,\n  hit_count NUMBER,\n  PRIMARY KEY (session_id)\n) ON COMMIT PRESERVE ROWS;\nINSERT INTO stage_sessions\nSELECT session_id, COUNT(*) FROM raw_hits GROUP BY session_id;","note":"The definition is permanent and shared, so create it once at deploy time; each session sees only its own rows. For ad-hoc work, 18c+ private temporary tables (named ORA$PTT_…) are created and dropped per session."}],"verdict":"PostgreSQL's ON COMMIT options give the finest lifecycle control. Oracle's global temporary tables are the odd one out, with a permanent definition and per-session data, so they reward planning at deploy time rather than creation on the fly.","faqs":[{"question":"Why does Oracle make temp table definitions permanent?","answer":"Global temporary tables are ordinary schema objects whose rows happen to be private and temporary, so they are created once, like any table, and every session uses the same definition. Since 18c, private temporary tables cover the create-on-the-fly case."},{"question":"Do temp tables cost anything?","answer":"Yes. SQL Server temp tables live in tempdb, which every database on the instance shares, so heavy use can contend there. PostgreSQL buffers temp tables in temp_buffers per session and writes larger ones to disk; MySQL 8.0 stores them in InnoDB temporary tablespaces. They are also not crash-safe anywhere, which is fine for scratch data."},{"question":"Can I index a temp table?","answer":"Yes, on all five engines, and the index is as private as the table. Index after loading the data; in PostgreSQL also run ANALYZE, because autovacuum never analyzes temp tables."}],"related":["create-schema","multi-row-insert","insert-from-select"]},"source_url":"https://sqlly.app/sql-dialects/temp-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/timestamp-range-filter","corpus":"sql-dialects","engine":null,"language":"en","title":"Timestamp range filters: half-open intervals","description":"Select every event on one day: why >= start AND < next-start beats BETWEEN, and the literal syntax in each engine.","body":{"slug":"timestamp-range-filter","name":"Timestamp range filters","h1":"Timestamp range filters: half-open intervals","category":"query","lede":"BETWEEN with a date-only upper bound keeps midnight and drops the rest of the day.","intro":"A day's data is occurred_at >= '2026-03-01' AND occurred_at < '2026-03-02'. The half-open upper bound is exact at any precision. BETWEEN '2026-03-01' AND '2026-03-01' matches only midnight, and BETWEEN … AND '2026-03-01 23:59:59' still loses 23:59:59.5 on columns with fractional seconds.","rows":[{"engine_slug":"sql-server","sql":"SELECT * FROM events WHERE occurred_at >= '2026-03-01' AND occurred_at < '2026-03-02';","note":"datetime2 stores up to 100 ns, so a 23:59:59 upper bound misses 23:59:59.003. With the old datetime type, '23:59:59.999' rounds up to the next midnight."},{"engine_slug":"postgresql","sql":"SELECT * FROM events WHERE occurred_at >= TIMESTAMP '2026-03-01' AND occurred_at < TIMESTAMP '2026-03-02';","note":"For timestamptz columns the bounds are read in the session time zone; use TIMESTAMPTZ '2026-03-01 00:00+00' to pin the zone."},{"engine_slug":"mysql","sql":"SELECT * FROM events WHERE occurred_at >= '2026-03-01' AND occurred_at < '2026-03-02';","note":"A date literal compared with DATETIME means midnight. Plain DATETIME stores whole seconds, but DATETIME(3) or (6) columns make a 23:59:59 upper bound lossy."},{"engine_slug":"sqlite","sql":"SELECT * FROM events WHERE occurred_at >= '2026-03-01' AND occurred_at < '2026-03-02';","note":"ISO-8601 text sorts chronologically, so string comparison works as long as every stored value uses the same layout."},{"engine_slug":"oracle","sql":"SELECT * FROM events WHERE occurred_at >= DATE '2026-03-01' AND occurred_at < DATE '2026-03-02';","note":"Oracle DATE has a time part, so occurred_at = DATE '2026-03-01' matches only rows stamped exactly at midnight."}],"verdict":"Half-open ranges, start inclusive and next start exclusive, are correct at any precision on every engine, and the bare column can use its index. BETWEEN is only safe when the values carry no time part; on timestamps it is usually a quiet bug.","faqs":[{"question":"Why is BETWEEN wrong for timestamps?","answer":"BETWEEN is inclusive at both ends, so you have to name the last instant of the day, and that instant depends on the column's precision: 23:59:59 for whole seconds, 23:59:59.999999 for microseconds. Anything after your bound and before midnight is lost. < next midnight needs no such guess."},{"question":"Do string comparisons work on timestamps in SQLite?","answer":"Yes, if every stored value uses the same ISO-8601 layout ('YYYY-MM-DD HH:MM:SS'), because then text order equals time order. Mixing layouts (a 'T' separator in some rows, a zone suffix in others) misorders silently, so normalize on write."},{"question":"What about time zones in the bounds?","answer":"PostgreSQL reads zone-less literals in the session zone when comparing with timestamptz; MySQL converts TIMESTAMP values using the connection's time_zone; SQL Server datetime2 and Oracle DATE carry no zone at all. Compute the bounds in one explicit zone in the application and pass them as parameters."}],"related":["date-diff-filter","extract-part-sargable","implicit-cast-comparison"]},"source_url":"https://sqlly.app/sql-dialects/timestamp-range-filter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/timezone-convert","corpus":"sql-dialects","engine":null,"language":"en","title":"Convert a timestamp to another timezone in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"AT TIME ZONE twice in SQL Server, once in PostgreSQL; CONVERT_TZ needs the tz tables loaded; SQLite only does fixed offsets.","body":{"slug":"timezone-convert","name":"Convert a timestamp to another timezone","h1":"Convert a timestamp to another timezone in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Named zones versus fixed offsets, and which engines know the difference at all.","intro":"Real timezone conversion needs a zone database (DST rules change). PostgreSQL, Oracle and SQL Server know named zones; MySQL does if you loaded the tables; SQLite never does.","rows":[{"engine_slug":"sql-server","sql":"SELECT SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time';","note":"AT TIME ZONE (2016+) converts a value that has an offset; on a naive datetime it labels the value as that zone. Windows zone names only ('Pacific Standard Time', not IANA), listed in sys.time_zone_info."},{"engine_slug":"postgresql","sql":"SELECT NOW() AT TIME ZONE 'America/Los_Angeles';","note":"On timestamptz it converts and returns a naive timestamp in that zone; applying it to a naive timestamp instead labels the value. IANA zone names."},{"engine_slug":"mysql","sql":"SELECT CONVERT_TZ(UTC_TIMESTAMP(), '+00:00', 'America/Los_Angeles');","note":"Named zones need the time zone tables in the mysql schema loaded; without them CONVERT_TZ returns NULL. '+00:00' style offsets always work but know nothing about DST."},{"engine_slug":"sqlite","sql":"SELECT DATETIME('now', '-8 hours');","note":"No zone database: only fixed-offset modifiers. DST transitions must be computed by hand or in the app."},{"engine_slug":"oracle","sql":"SELECT SYSTIMESTAMP AT TIME ZONE 'America/Los_Angeles',\n  FROM_TZ(TIMESTAMP '2026-11-20 12:00:00', 'UTC') AT TIME ZONE 'America/Los_Angeles'\nFROM dual;","note":"TIMESTAMP WITH TIME ZONE values carry the zone and AT TIME ZONE converts them; FROM_TZ labels a naive timestamp first. IANA names come from the database's time zone file, so DST rules are only as current as that file."}],"verdict":"PostgreSQL and Oracle have the most honest model: store the instant with its zone, convert at the edges. SQL Server's double AT TIME ZONE idiom works but trips people up, MySQL depends on loaded tables, and SQLite leaves zones to the application.","faqs":[{"question":"Why does SQL Server need AT TIME ZONE twice?","answer":"The first call tells SQL Server what zone a naive datetime is in (it gains an offset); the second converts to the target. GETUTCDATE() AT TIME ZONE 'Pacific Standard Time' would mislabel the UTC time as Pacific."},{"question":"Are MySQL's named zones available by default?","answer":"No. The tz tables must be populated (mysql_tzinfo_to_sql on Linux). On untouched Windows servers or hosted setups, only offset-based CONVERT_TZ is guaranteed."},{"question":"Should I store UTC or store the zone with the timestamp?","answer":"Store UTC when only one instant matters; store timestamptz/timestamp with time zone when events happen in a region and you must preserve which zone they were scheduled in (e.g. recurring meetings)."}],"related":["from-unix-timestamp","add-days","current-timestamp-precision"]},"source_url":"https://sqlly.app/sql-dialects/timezone-convert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/top-n","corpus":"sql-dialects","engine":null,"language":"en","title":"First N rows: TOP vs LIMIT vs FETCH FIRST","description":"Get the cheapest, newest or best-ranked handful of rows in each of the five engines.","body":{"slug":"top-n","name":"First N rows (TOP-N query)","h1":"First N rows: TOP vs LIMIT vs FETCH FIRST","category":"query","lede":"The same query written three ways, depending on the engine.","intro":"A TOP-N query is an ORDER BY plus a row cap. SQL Server puts TOP before the column list, MySQL/SQLite/PostgreSQL put LIMIT after the query, and the SQL standard spelling is FETCH FIRST … ROWS ONLY.","rows":[{"engine_slug":"sql-server","sql":"SELECT TOP 5 name, price FROM products ORDER BY price DESC;","note":"TOP 5 WITH TIES also returns rows tied with the fifth. OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY works too, but T-SQL has no FETCH … WITH TIES."},{"engine_slug":"postgresql","sql":"SELECT name, price FROM products ORDER BY price DESC LIMIT 5;","note":"FETCH FIRST 5 ROWS ONLY also works, and FETCH FIRST 5 ROWS WITH TIES since PostgreSQL 13."},{"engine_slug":"mysql","sql":"SELECT name, price FROM products ORDER BY price DESC LIMIT 5;","note":"LIMIT is the only syntax: no TOP, no FETCH."},{"engine_slug":"sqlite","sql":"SELECT name, price FROM products ORDER BY price DESC LIMIT 5;","note":"LIMIT is the only syntax: no TOP, no FETCH."},{"engine_slug":"oracle","sql":"SELECT name, price FROM products ORDER BY price DESC FETCH FIRST 5 ROWS ONLY;","note":"12c+. Before 12c: SELECT * FROM (… ORDER BY price DESC) WHERE ROWNUM <= 5."}],"verdict":"LIMIT covers PostgreSQL, MySQL and SQLite; FETCH FIRST is the standard and covers PostgreSQL and Oracle; TOP is SQL Server only. Ties are where they differ most: SQL Server has TOP … WITH TIES, PostgreSQL 13+ and Oracle have FETCH FIRST … WITH TIES, and MySQL and SQLite need a RANK() subquery.","faqs":[{"question":"Why does my TOP-N query return different rows every run?","answer":"ORDER BY price DESC leaves rows with equal prices in no particular order, so the engine can hand back any of them for the last slots. Add a unique tiebreaker: ORDER BY price DESC, id."},{"question":"How do I include rows tied with fifth place?","answer":"SQL Server: TOP 5 WITH TIES. PostgreSQL 13+ and Oracle 12c+: FETCH FIRST 5 ROWS WITH TIES. MySQL 8.0+ and SQLite have no WITH TIES; rank in a subquery and filter outside it, because window functions are not allowed in WHERE: SELECT name, price FROM (SELECT name, price, RANK() OVER (ORDER BY price DESC) AS rk FROM products) r WHERE rk <= 5."}],"related":["limit","top-n-per-group","nulls-first-last"]},"source_url":"https://sqlly.app/sql-dialects/top-n","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/top-n-per-group","corpus":"sql-dialects","engine":null,"language":"en","title":"First N rows per group: ROW_NUMBER vs DISTINCT ON","description":"The three highest-paid employees per department, the five newest posts per tag: per-group TOP-N in all five engines.","body":{"slug":"top-n-per-group","name":"First N rows per group","h1":"First N rows per group: ROW_NUMBER vs DISTINCT ON","category":"query","lede":"One window-function query that runs everywhere, plus PostgreSQL's DISTINCT ON shortcut for one row per group.","intro":"Number rows with ROW_NUMBER() OVER (PARTITION BY group ORDER BY …) in a subquery or CTE and keep the low numbers. The same text runs on all five engines. PostgreSQL also has DISTINCT ON for the one-row-per-group case.","rows":[{"engine_slug":"sql-server","sql":"WITH ranked AS (SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT name, department, salary FROM ranked WHERE rn <= 3;","note":"CROSS APPLY (SELECT TOP 3 … ORDER BY salary DESC) against a departments table is the other common T-SQL form."},{"engine_slug":"postgresql","sql":"WITH ranked AS (SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT name, department, salary FROM ranked WHERE rn <= 3;","note":"For one row per group, SELECT DISTINCT ON (department) department, name, salary FROM employees ORDER BY department, salary DESC is shorter. A LATERAL join is the other N-per-group form."},{"engine_slug":"mysql","sql":"WITH ranked AS (SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT name, department, salary FROM ranked WHERE rn <= 3;","note":"CTEs and window functions need MySQL 8.0+. On 5.7, use the correlated COUNT subquery in the FAQ below."},{"engine_slug":"sqlite","sql":"WITH ranked AS (SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT name, department, salary FROM ranked WHERE rn <= 3;","note":"Window functions need SQLite 3.25+."},{"engine_slug":"oracle","sql":"WITH ranked AS (SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT name, department, salary FROM ranked WHERE rn <= 3;","note":"Analytic functions date back to Oracle 8i. 12c+ can also use CROSS APPLY or LATERAL with FETCH FIRST 3 ROWS ONLY."}],"verdict":"ROW_NUMBER() in a CTE is the one form that runs unchanged on all five engines and works for any N. DISTINCT ON is a neat PostgreSQL-only shortcut for N = 1; when porting, rewrite it as ROW_NUMBER() … WHERE rn = 1.","faqs":[{"question":"What is the difference between ROW_NUMBER, RANK and DENSE_RANK here?","answer":"ROW_NUMBER returns at most N rows per group and breaks ties arbitrarily. RANK keeps ties and skips numbers (1, 1, 3); DENSE_RANK keeps ties without gaps (1, 1, 2). Both can return more than N rows when salaries tie. Use ROW_NUMBER for exactly N, RANK when everyone tied at the cut-off should be included."},{"question":"How do I do this on MySQL 5.7?","answer":"Count how many rows in the same group beat each row: SELECT * FROM employees e WHERE (SELECT COUNT(*) FROM employees e2 WHERE e2.department = e.department AND e2.salary > e.salary) < 3. Ties behave like RANK, and the cost grows with the square of the group size, so index (department, salary)."},{"question":"Can I just use GROUP BY with MAX?","answer":"Only for N = 1, and only if you need nothing but the value. SELECT department, MAX(salary) tells you the top salary, not who earns it; adding name to the GROUP BY returns every employee instead of the top one."}],"related":["limit","top-n","row-numbering","distinct-on-expression"]},"source_url":"https://sqlly.app/sql-dialects/top-n-per-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/truncate-vs-delete","corpus":"sql-dialects","engine":null,"language":"en","title":"TRUNCATE vs DELETE: emptying a table","description":"Speed, identity reset, triggers, rollback and foreign keys: what TRUNCATE really does in each engine, and SQLite's DELETE-only world.","body":{"slug":"truncate-vs-delete","name":"TRUNCATE vs DELETE","h1":"TRUNCATE vs DELETE: emptying a table","category":"dml","lede":"Two ways to empty a table that differ in speed, triggers, identity counters and rollback.","intro":"TRUNCATE deallocates the table's storage instead of deleting row by row, so it is near-instant. It fires no DELETE triggers, resets identity counters in SQL Server and MySQL, and commits implicitly in MySQL and Oracle. SQLite has no TRUNCATE; an unfiltered DELETE takes a similar fast path.","rows":[{"engine_slug":"sql-server","sql":"TRUNCATE TABLE orders;","note":"Near-instant, resets IDENTITY, fires no triggers, and can be rolled back inside a transaction. Fails while any foreign key references the table, even from an empty table."},{"engine_slug":"postgresql","sql":"TRUNCATE TABLE orders RESTART IDENTITY CASCADE;","note":"Can truncate several tables in one call. RESTART IDENTITY resets sequences; CASCADE reaches referencing tables that would otherwise block it."},{"engine_slug":"mysql","sql":"TRUNCATE TABLE orders;","note":"Implicit commit, so it can't be rolled back. Resets AUTO_INCREMENT. Fails while another table's foreign key references this one, unless foreign_key_checks = 0."},{"engine_slug":"sqlite","sql":"DELETE FROM orders;\nDELETE FROM sqlite_sequence WHERE name = 'orders';","note":"No TRUNCATE. An unfiltered DELETE uses the truncate optimization unless the table has triggers. The second statement resets the counter and only applies to AUTOINCREMENT tables."},{"engine_slug":"oracle","sql":"TRUNCATE TABLE orders;","note":"DDL, so it commits implicitly and can't be rolled back. Frees the space by default; REUSE STORAGE keeps it. 12c+ adds TRUNCATE … CASCADE for ON DELETE CASCADE foreign keys."}],"verdict":"Use TRUNCATE when you mean all of it and no DELETE triggers need to run; use DELETE when you need a WHERE, per-row triggers or a rollback on MySQL and Oracle. SQLite picks the fast path for you.","faqs":[{"question":"Can TRUNCATE roll back?","answer":"In SQL Server and PostgreSQL, yes, inside an explicit transaction. MySQL and Oracle treat it as DDL with an implicit commit, so the rows are gone once it runs."},{"question":"Does TRUNCATE reset the identity counter?","answer":"Yes in SQL Server and MySQL. PostgreSQL keeps the sequence unless you add RESTART IDENTITY. Oracle keeps it too; reset it with ALTER TABLE orders MODIFY id GENERATED ALWAYS AS IDENTITY (START WITH 1)."},{"question":"Why does TRUNCATE fail with foreign keys?","answer":"It skips row-by-row processing, so the engine can't check child rows one at a time and refuses when another table's foreign key points at this one. Truncate the child tables first (PostgreSQL's CASCADE does it in one call), drop the constraint, or use DELETE."}],"related":["delete-with-join","autoincrement-column","insert-into-identity"]},"source_url":"https://sqlly.app/sql-dialects/truncate-vs-delete","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/unique-index","corpus":"sql-dialects","engine":null,"language":"en","title":"CREATE UNIQUE INDEX in every SQL dialect","description":"Enforce uniqueness on a column with CREATE UNIQUE INDEX, and how NULLs and duplicates behave per engine.","body":{"slug":"unique-index","name":"Unique index","h1":"CREATE UNIQUE INDEX in every SQL dialect","category":"indexes","lede":"A unique index both speeds up lookups and rejects duplicate values. Syntax is universal; NULL handling is where engines disagree.","intro":"All five engines support CREATE UNIQUE INDEX with the same syntax. The subtle part is NULLs: most engines treat NULLs as distinct from each other, so multiple NULL rows are allowed.","rows":[{"engine_slug":"sql-server","sql":"CREATE UNIQUE INDEX idx_users_email ON users (email);","note":"NULLs are treated as equal, so a unique index allows only one NULL. Filtered indexes can scope uniqueness: WHERE email IS NOT NULL."},{"engine_slug":"postgresql","sql":"CREATE UNIQUE INDEX idx_users_email ON users (email);","note":"Multiple NULLs are allowed (they are not equal). PostgreSQL 15+ adds NULLS NOT DISTINCT to reject them."},{"engine_slug":"mysql","sql":"CREATE UNIQUE INDEX idx_users_email ON users (email);","note":"Multiple NULLs are allowed; a unique index on a nullable column does not enforce a single NULL."},{"engine_slug":"sqlite","sql":"CREATE UNIQUE INDEX idx_users_email ON users (email);","note":"Multiple NULLs are allowed, matching the SQL standard."},{"engine_slug":"oracle","sql":"CREATE UNIQUE INDEX idx_users_email ON users (email);","note":"Multiple NULLs are allowed; rows where every indexed column is NULL do not even enter the index."}],"verdict":"Same statement everywhere. One-NULL-only semantics are the difference: SQL Server enforces them by default, PostgreSQL 15+ offers NULLS NOT DISTINCT, and MySQL, SQLite and Oracle have no switch for it. To allow many NULLs in SQL Server, add WHERE email IS NOT NULL to the index.","faqs":[{"question":"Unique index or UNIQUE constraint?","answer":"A UNIQUE constraint creates a unique index under the hood. Prefer the constraint in DDL so the intent is visible in metadata; the index form is useful when adding uniqueness to an existing busy table."},{"question":"Can I make a case-insensitive unique index?","answer":"Yes: index LOWER(email) instead of email (an expression index), or use a case-insensitive collation so duplicate spellings collide."},{"question":"What error do duplicate rows raise?","answer":"SQL Server error 2601/2627, PostgreSQL error 23505, MySQL error 1062 (ER_DUP_ENTRY), SQLite constraint SQLITE_CONSTRAINT_UNIQUE, Oracle ORA-00001."}],"related":["create-index","expression-index","partial-index"]},"source_url":"https://sqlly.app/sql-dialects/unique-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/update-same-table-subquery","corpus":"sql-dialects","engine":null,"language":"en","title":"Update from an aggregate on the same table","description":"Updating a column from a COUNT or SUM over the same table: derived tables, correlated subqueries and MySQL's error 1093 workaround.","body":{"slug":"update-same-table-subquery","name":"Update from same-table aggregate","h1":"Update from an aggregate on the same table","category":"dml","lede":"Recompute a column from a GROUP BY over the very table you are updating.","intro":"Each example stores every employee's department headcount on the employee row, which means aggregating the table being updated. The trap is MySQL: it refuses to update a table that a subquery in the same statement reads (error 1093), so the aggregate goes in a derived table, which MySQL materializes first. The other engines accept the direct correlated subquery.","rows":[{"engine_slug":"sql-server","sql":"UPDATE e\nSET e.dept_headcount = t.cnt\nFROM employees e\nJOIN (SELECT department, COUNT(*) AS cnt\n      FROM employees GROUP BY department) t\n  ON t.department = e.department;","note":"The derived-table join computes each count once. A correlated subquery in SET also works; SQL Server has no error 1093."},{"engine_slug":"postgresql","sql":"UPDATE employees e\nSET dept_headcount = t.cnt\nFROM (SELECT department, COUNT(*) AS cnt\n      FROM employees GROUP BY department) t\nWHERE t.department = e.department;","note":"The ordinary UPDATE … FROM shape. The subquery sees the table as it was before the update started."},{"engine_slug":"mysql","sql":"UPDATE employees e\nJOIN (SELECT department, COUNT(*) AS cnt\n      FROM employees GROUP BY department) t\n  ON t.department = e.department\nSET e.dept_headcount = t.cnt;","note":"Writing SET dept_headcount = (SELECT COUNT(*) FROM employees e2 WHERE …) fails with error 1093. The GROUP BY derived table is materialized before the update, which makes it legal."},{"engine_slug":"sqlite","sql":"UPDATE employees\nSET dept_headcount = (SELECT COUNT(*) FROM employees e2\n                      WHERE e2.department = employees.department);","note":"The correlated subquery is the simplest form; UPDATE … FROM a derived table works too from 3.33."},{"engine_slug":"oracle","sql":"UPDATE employees e\nSET e.dept_headcount = (SELECT COUNT(*) FROM employees e2\n                        WHERE e2.department = e.department);","note":"Correlated subquery, evaluated per row. MERGE with the GROUP BY query as its USING source does the same in one pass."}],"verdict":"SQL Server, PostgreSQL and MySQL read best with the derived-table join; SQLite and Oracle with the correlated subquery. Only MySQL rejects the direct form, so the derived-table join is the version that runs on the most engines.","faqs":[{"question":"Why does MySQL raise error 1093?","answer":"MySQL won't let a subquery read the table that the same UPDATE or DELETE is modifying ('You can't specify target table for update in FROM clause'). A derived table with GROUP BY is materialized into a temporary table before the update starts, so the restriction no longer applies."},{"question":"Should the aggregate be NULL or zero for missing rows?","answer":"For COUNT it is always at least 1 here, since each employee counts itself. With SUM over another table, a correlated subquery yields NULL for rows with no matches, so wrap it in COALESCE((SELECT …), 0); the derived-table join simply leaves those rows untouched."},{"question":"Is MERGE an option here?","answer":"In SQL Server, Oracle and PostgreSQL 15+, yes: use the GROUP BY query as the USING source and WHEN MATCHED THEN UPDATE. It is equivalent to the derived-table join, not faster."}],"related":["update-with-join","multi-row-insert","generated-ids"]},"source_url":"https://sqlly.app/sql-dialects/update-same-table-subquery","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/update-with-join","corpus":"sql-dialects","engine":null,"language":"en","title":"UPDATE with a join to another table","description":"UPDATE ... FROM, UPDATE ... JOIN and the correlated subqueries that older Oracle and SQLite need.","body":{"slug":"update-with-join","name":"UPDATE with a join","h1":"UPDATE with a join to another table","category":"dml","lede":"Set a column based on data in a different table: three clause orders and a subquery fallback.","intro":"This is where the dialects visibly diverge. SQL Server puts a FROM … JOIN after SET, MySQL puts the JOIN before SET, and PostgreSQL, SQLite 3.33+ and Oracle 23ai take a FROM clause with the join condition in WHERE. Older Oracle and SQLite need a correlated subquery, which runs everywhere.","rows":[{"engine_slug":"sql-server","sql":"UPDATE o\nSET o.status = 'shipped'\nFROM orders o\nJOIN shipments s ON s.order_id = o.id\nWHERE s.tracking IS NOT NULL;","note":"The target appears twice: after UPDATE and again in FROM with its alias. Rows matched by several joined rows are updated once, non-deterministically."},{"engine_slug":"postgresql","sql":"UPDATE orders o\nSET status = 'shipped'\nFROM shipments s\nWHERE s.order_id = o.id\n  AND s.tracking IS NOT NULL;","note":"FROM lists only the other tables; the join condition lives in WHERE. Like SQL Server, a many-match join updates once per target row, not per match."},{"engine_slug":"mysql","sql":"UPDATE orders o\nJOIN shipments s ON s.order_id = o.id\nSET o.status = 'shipped'\nWHERE s.tracking IS NOT NULL;","note":"The JOIN sits between UPDATE and SET, the reverse of SQL Server's order. A multi-table UPDATE can also set columns in both tables at once."},{"engine_slug":"sqlite","sql":"UPDATE orders\nSET status = 'shipped'\nWHERE id IN (SELECT order_id FROM shipments\n             WHERE tracking IS NOT NULL);","note":"An IN subquery runs on every version. UPDATE ... FROM exists since 3.33 if you prefer join-shaped code."},{"engine_slug":"oracle","sql":"UPDATE orders o\nSET o.status = 'shipped'\nWHERE EXISTS (SELECT 1 FROM shipments s\n              WHERE s.order_id = o.id\n                AND s.tracking IS NOT NULL);","note":"Runs on every version. 23ai adds join updates: UPDATE orders o SET o.status = 'shipped' FROM shipments s WHERE s.order_id = o.id AND s.tracking IS NOT NULL. MERGE or an updatable join view also work."}],"verdict":"PostgreSQL's UPDATE … FROM is the cleanest design, and SQLite 3.33+ and Oracle 23ai copied it. SQL Server and MySQL support join updates too but disagree on clause order. The EXISTS or IN subquery is the only form that runs on all five.","faqs":[{"question":"What if the join matches several rows?","answer":"Each target row is still updated once, with whichever matching row the engine meets first, in SQL Server, PostgreSQL, MySQL and SQLite; none of them raises an error. Oracle refuses with ORA-30926, in MERGE and in 23ai's UPDATE … FROM alike. Aggregate or deduplicate the source first if it can fan out."},{"question":"Does Oracle have UPDATE … FROM?","answer":"Since 23ai, yes. Before that, use a correlated subquery, a MERGE with only a WHEN MATCHED branch, or an update through a key-preserved inline view."},{"question":"Can I update the same table I join?","answer":"Yes, with a self-join under two aliases in SQL Server, PostgreSQL and SQLite 3.33+. MySQL rejects a plain subquery on the target table (error 1093) but accepts a join to a derived table. Older Oracle needs the correlated form."}],"related":["update-same-table-subquery","delete-with-join","merge-statement"]},"source_url":"https://sqlly.app/sql-dialects/update-with-join","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/upsert-syntax","corpus":"sql-dialects","engine":null,"language":"en","title":"Upsert: insert or update in one statement","description":"INSERT ON CONFLICT, ON DUPLICATE KEY UPDATE, MERGE and INSERT OR REPLACE side by side in SQL Server, PostgreSQL, MySQL, SQLite and Oracle.","body":{"slug":"upsert-syntax","name":"Upsert (insert or update)","h1":"Upsert: insert or update in one statement","category":"dml","lede":"Change the row if it is already there, insert it if it is not: the statement every engine spells differently.","intro":"PostgreSQL and SQLite share the ON CONFLICT clause (an extension, not standard SQL), MySQL has ON DUPLICATE KEY UPDATE, and SQL Server and Oracle use the standard MERGE. SQLite's INSERT OR REPLACE and MySQL's REPLACE look similar but delete the old row and insert a new one, which resets columns you didn't list and, in MySQL, fires delete triggers.","rows":[{"engine_slug":"sql-server","sql":"MERGE INTO customers WITH (HOLDLOCK) AS c\nUSING (VALUES (7, 'ann@example.com')) AS s(id, email)\nON c.id = s.id\nWHEN MATCHED THEN UPDATE SET c.email = s.email\nWHEN NOT MATCHED THEN INSERT (id, email) VALUES (s.id, s.email);","note":"No ON CONFLICT. Without HOLDLOCK, two sessions can both see no match and both insert, and one fails with a duplicate key error."},{"engine_slug":"postgresql","sql":"INSERT INTO customers (id, email) VALUES (7, 'ann@example.com')\nON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;","note":"The conflict target must match a unique index or constraint. EXCLUDED is the row you tried to insert; DO NOTHING skips duplicates. MERGE also exists since PostgreSQL 15."},{"engine_slug":"mysql","sql":"INSERT INTO customers (id, email) VALUES (7, 'ann@example.com') AS new\nON DUPLICATE KEY UPDATE email = new.email;","note":"Fires on a collision with any unique key, not a chosen one. The row alias (AS new) needs 8.0.19+; it replaces VALUES(email), which is deprecated."},{"engine_slug":"sqlite","sql":"INSERT INTO customers (id, email) VALUES (7, 'ann@example.com')\nON CONFLICT (id) DO UPDATE SET email = excluded.email;","note":"3.24+. INSERT OR REPLACE also works but deletes the old row first, resetting columns you didn't list; its delete triggers fire only with PRAGMA recursive_triggers = ON."},{"engine_slug":"oracle","sql":"MERGE INTO customers c\nUSING (SELECT 7 AS id, 'ann@example.com' AS email FROM dual) s\nON (c.id = s.id)\nWHEN MATCHED THEN UPDATE SET c.email = s.email\nWHEN NOT MATCHED THEN INSERT (id, email) VALUES (s.id, s.email);","note":"MERGE is the only upsert. It fails with ORA-30926 when one target row matches several source rows. 23ai lets you drop FROM dual."}],"verdict":"PostgreSQL and SQLite have the shortest upsert with ON CONFLICT, and MySQL's ON DUPLICATE KEY UPDATE is close behind for tables with one unique key. SQL Server and Oracle need a full MERGE, and on SQL Server it needs HOLDLOCK to be safe under concurrency.","faqs":[{"question":"Why does INSERT OR REPLACE lose my other columns?","answer":"It deletes the conflicting row and inserts a new one, so every column you didn't list gets its default. Use ON CONFLICT … DO UPDATE to keep them."},{"question":"Can I upsert several rows at once?","answer":"Yes. Use a multi-row VALUES list or an INSERT … SELECT, and the conflict clause applies per row in PostgreSQL, SQLite and MySQL. PostgreSQL raises an error if the same key appears twice in one statement. With MERGE, put the batch in the USING source."},{"question":"How do I tell whether the row was inserted or updated?","answer":"PostgreSQL: RETURNING (xmax = 0) AS inserted on ON CONFLICT, or merge_action() in MERGE … RETURNING (17+). MySQL: affected rows is 1 for an insert, 2 for an update, 0 for an unchanged row. SQL Server: OUTPUT $action on the MERGE."}],"related":["merge-statement","generated-ids","multi-row-insert"]},"source_url":"https://sqlly.app/sql-dialects/upsert-syntax","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/uuid-generation","corpus":"sql-dialects","engine":null,"language":"en","title":"Generate a UUID in SQL in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","description":"NEWID, GEN_RANDOM_UUID, UUID and SYS_GUID compared, plus SQLite, where you build one from RANDOMBLOB yourself.","body":{"slug":"uuid-generation","name":"Generate a UUID in SQL","h1":"Generate a UUID in SQL in SQL Server, PostgreSQL, MySQL, SQLite and Oracle","category":"types","lede":"Four named functions with different versions and shapes, plus one engine that makes you roll your own.","intro":"Every engine can mint a unique id, but the versions differ (v1-style time-based vs v4 random), the shapes differ (dashes, case, RAW), and SQLite alone has no function at all.","rows":[{"engine_slug":"sql-server","sql":"SELECT NEWID();","note":"Random v4-style GUID as a UNIQUEIDENTIFIER. NEWSEQUENTIALID() gives index-friendly values but only works as a column default."},{"engine_slug":"postgresql","sql":"SELECT GEN_RANDOM_UUID();","note":"Built in since PostgreSQL 13 (pgcrypto before that) and returns v4. PostgreSQL 18 adds uuidv7() for time-ordered ids; uuid_generate_v1() and friends come from the uuid-ossp extension."},{"engine_slug":"mysql","sql":"SELECT UUID();","note":"Version 1: timestamp plus node id, so values reveal the host and creation time. The text form starts with the low time bits and does not sort by time; UUID_TO_BIN(UUID(), 1) swaps the time fields so the binary form does."},{"engine_slug":"sqlite","sql":"SELECT LOWER(HEX(RANDOMBLOB(16)));","note":"No uuid function: 32 random hex chars with no dashes and no version bits. Real UUID formatting needs an app-side value or a custom function."},{"engine_slug":"oracle","sql":"SELECT RAWTOHEX(SYS_GUID()) FROM dual;","note":"SYS_GUID() returns a 16-byte RAW that is not an RFC 4122 UUID; RAWTOHEX renders 32 uppercase hex chars with no dashes. Recent 23ai releases add UUID(), which returns a random v4 UUID as RAW(16)."}],"verdict":"All five mint something unique but none agree on shape or version: random v4 in SQL Server and PostgreSQL (plus v7 in PostgreSQL 18), time-based v1 in MySQL, a RAW GUID in Oracle, and hand-rolled hex in SQLite. For cross-engine code, generate UUIDs in the application.","faqs":[{"question":"Which UUID version do the built-ins produce?","answer":"SQL Server's NEWID, PostgreSQL's GEN_RANDOM_UUID and Oracle's newer UUID() are random v4, and PostgreSQL 18's uuidv7() is time-ordered. MySQL's UUID() is v1 (timestamp plus node id), which leaks the host. Oracle's SYS_GUID() follows no UUID version at all."},{"question":"Is the SQLite RANDOMBLOB trick a real UUID?","answer":"Not strictly: it is 16 random bytes formatted as hex, with no version/variant bits set. Uniqueness is fine at 128 bits; interop with strict UUID parsers is not."},{"question":"Should the database or the app generate UUIDs?","answer":"App-side generation keeps IDs available before insert (batching, offline clients) and is identical across engines; DB-side defaults guarantee no app can forget it."}],"related":["guid-column-type","autoincrement-column","add-column"]},"source_url":"https://sqlly.app/sql-dialects/uuid-generation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-dialects/vacuum-analyze","corpus":"sql-dialects","engine":null,"language":"en","title":"Maintenance commands: VACUUM, ANALYZE, OPTIMIZE in every dialect","description":"Reclaim space and refresh statistics with VACUUM, ANALYZE and OPTIMIZE TABLE in the five engines.","body":{"slug":"vacuum-analyze","name":"VACUUM / ANALYZE / OPTIMIZE","h1":"Maintenance commands: VACUUM, ANALYZE, OPTIMIZE in every dialect","category":"admin","lede":"The periodic-housekeeping commands: reclaim dead space and refresh the statistics the optimizer plans with.","intro":"No shared syntax or even shared concepts: PostgreSQL's VACUUM reclaims dead tuples, SQL Server never needs vacuuming, and everyone wants fresh statistics.","rows":[{"engine_slug":"sql-server","sql":"UPDATE STATISTICS orders;\n-- space reclamation is automatic; index bloat is handled by ALTER INDEX ... REORGANIZE","note":"No VACUUM: deleted space is reused. The maintenance is statistics (UPDATE STATISTICS or Ola Hallengren's scripts) and index reorganize/rebuild."},{"engine_slug":"postgresql","sql":"VACUUM ANALYZE orders;\n-- autovacuum normally covers this; VACUUM FULL reclaims all space but locks","note":"VACUUM removes dead tuples without blocking reads/writes; ANALYZE refreshes planner stats. VACUUM FULL rewrites the table with an exclusive lock; pg_repack avoids the lock."},{"engine_slug":"mysql","sql":"ANALYZE TABLE orders;\nOPTIMIZE TABLE orders;","note":"ANALYZE refreshes InnoDB statistics under a read lock; OPTIMIZE TABLE maps to a table rebuild on InnoDB, done as online DDL that blocks writes only briefly at the start and end."},{"engine_slug":"sqlite","sql":"VACUUM;\nANALYZE;","note":"VACUUM rebuilds the whole database file, reclaiming free pages; it needs enough free space for a copy and an exclusive lock. ANALYZE populates sqlite_stat1 for the query planner."},{"engine_slug":"oracle","sql":"EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');","note":"No vacuum: undo + segment reuse. DBMS_STATS is the statistics API (never ANALYZE ... COMPUTE for real systems); segment shrink via ALTER TABLE ... SHRINK SPACE."}],"verdict":"Four different worlds. PostgreSQL needs vacuuming enough that autovacuum runs by default; SQL Server and Oracle reuse space internally; MySQL and SQLite each get one rebuild command. Statistics refresh is the common denominator, with five different spellings.","faqs":[{"question":"Why is PostgreSQL's autovacuum falling behind?","answer":"Long-running transactions hold back dead-tuple cleanup: one open idle transaction blocks vacuum progress everywhere. Monitor pg_stat_user_tables dead tuples and long transactions."},{"question":"Does ANALYZE block anything?","answer":"Engine-dependent. PostgreSQL's ANALYZE, SQL Server's UPDATE STATISTICS and Oracle's DBMS_STATS do not block reads or writes. MySQL's ANALYZE TABLE holds a read lock, so writes wait, and SQLite's ANALYZE is a write transaction that blocks other writers."},{"question":"How often should I run these?","answer":"Lean on automatics first: autovacuum/autovacuum-analyze in PostgreSQL, auto-updated stats in SQL Server and Oracle, InnoDB auto-recalc. Manually after bulk loads and large deletes."}],"related":["rebuild-index","create-index","isolation-levels"]},"source_url":"https://sqlly.app/sql-dialects/vacuum-analyze","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
