{"id":"sql-ddl/add-check-constraint","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ADD CHECK","description":"Add a CHECK constraint on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: per-row validation, MySQL's 8.0.16 enforcement switch, NOT VALID, SQLite's 3.53.0 ALTER form.","body":{"slug":"add-check-constraint","name":"ADD CHECK","h1":"ALTER TABLE ADD CHECK","category":"tables","lede":"Attaches a rule that every row must satisfy, old and new. All five engines now take the same clause; the differences are which MySQL and SQLite versions mean it and how to skip the big scan.","syntax":"ALTER TABLE t ADD CONSTRAINT ck_name CHECK (condition)  -- SQL Server, PostgreSQL, MySQL 8.0.16+, SQLite 3.53.0+, Oracle  |  ALTER TABLE t ADD CONSTRAINT ck_name CHECK (condition) NOT VALID  -- PostgreSQL: scan old rows later  |  -- SQLite before 3.53.0: rebuild the table to add one","support":[{"engine_slug":"sql-server","status":"yes","note":"validates existing rows unless you add WITH NOCHECK, which stores the constraint untrusted"},{"engine_slug":"postgresql","status":"yes","note":"the plain form scans under a strong lock; NOT VALID plus VALIDATE CONSTRAINT keeps writes running"},{"engine_slug":"mysql","status":"partial","note":"enforced from 8.0.16; older servers accepted the clause and ignored it"},{"engine_slug":"sqlite","status":"partial","note":"ALTER TABLE ADD CONSTRAINT ... CHECK arrived in 3.53.0 and checks existing rows; older versions rebuild the table"},{"engine_slug":"oracle","status":"yes","note":"ENABLE NOVALIDATE skips existing rows; every future write is checked"}],"gotchas":["A CHECK sees one row and nothing else: every engine rejects subqueries and references to other rows inside the condition. A rule that needs another table is a foreign key's job.","MySQL's history bites quietly: before 8.0.16 the parser accepted CHECK and the server never enforced it, so parsed and enforced are different claims there. Run SELECT VERSION() before trusting one.","The row scan is the expensive part. PostgreSQL's VALIDATE CONSTRAINT step re-scans but takes only SHARE UPDATE EXCLUSIVE, so reads and writes continue. SQL Server's WITH NOCHECK and Oracle's NOVALIDATE skip old rows entirely and enforce the rule only on new writes.","The condition passes NULLs: in SQL's three-valued logic a condition over NULL comes out unknown, and CHECK accepts unknown. CHECK (price > 0) lets NULL prices through; add NOT NULL to the column to close that door."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped'));"},{"engine_slug":"postgresql","sql":"-- add without the scan, validate later while writes continue\nALTER TABLE orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped')) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT ck_orders_status;"},{"engine_slug":"sql-server","sql":"ALTER TABLE dbo.orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped'));"},{"engine_slug":"mysql","sql":"-- requires 8.0.16 or newer; older servers ignore CHECK\nALTER TABLE orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped'));"},{"engine_slug":"oracle","sql":"-- skip the scan of old rows\nALTER TABLE orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped')) ENABLE NOVALIDATE;"},{"engine_slug":"sqlite","sql":"-- requires 3.53.0 or newer; older versions rebuild the table\nALTER TABLE orders ADD CONSTRAINT ck_orders_status\n  CHECK (status IN ('new', 'paid', 'shipped'));"}],"faqs":[{"question":"Why is my CHECK constraint ignored on MySQL?","answer":"Servers older than 8.0.16 parse CHECK constraints and never enforce them, a leftover from the old parser. The clause returns success either way, so verify with SELECT VERSION() and test one deliberately bad insert."},{"question":"Can a CHECK query another table?","answer":"No, on every engine. The condition may only read the current row, and subqueries are rejected outright. For cross-table rules use a foreign key, a trigger, or validation in the application."},{"question":"Does the CHECK apply to NULLs?","answer":"It passes them: unknown satisfies a CHECK. CHECK (price > 0) therefore allows a NULL price on every engine, which surprises people who wrote the rule as a range check. Declare the column NOT NULL when NULL is not a legal value."}],"related":["add-foreign-key","add-unique-constraint","alter-table-add-column","create-table"]},"source_url":"https://sqlly.app/sql-ddl/add-check-constraint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/add-foreign-key","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ADD FOREIGN KEY","description":"Add a foreign key to an existing table on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: who validates existing rows, NOT VALID, MySQL's index rules, SQLite's limits.","body":{"slug":"add-foreign-key","name":"ADD FOREIGN KEY","h1":"ALTER TABLE ADD FOREIGN KEY","category":"tables","lede":"Points a column at another table's key and starts checking every write. The clause reads the same on four engines; validation and indexing are where they diverge.","syntax":"ALTER TABLE t ADD CONSTRAINT fk_name FOREIGN KEY (col) REFERENCES other (id)  -- SQL Server, PostgreSQL, MySQL, Oracle  |  ALTER TABLE t ADD CONSTRAINT fk_name FOREIGN KEY (col) REFERENCES other (id) NOT VALID  -- PostgreSQL: check old rows in a second step  |  -- SQLite: no ADD CONSTRAINT form; rebuild, or ADD COLUMN ... REFERENCES for a new column","support":[{"engine_slug":"sql-server","status":"yes","note":"validates existing rows by default; WITH NOCHECK skips the scan but leaves the constraint not trusted"},{"engine_slug":"postgresql","status":"yes","note":"the plain form scans and locks; NOT VALID plus VALIDATE CONSTRAINT splits the work"},{"engine_slug":"mysql","status":"yes","note":"InnoDB only; both tables InnoDB, the referenced columns a primary or unique key, and an index on the referencing columns gets built for you if missing"},{"engine_slug":"sqlite","status":"no","note":"no ALTER form for an existing column (ADD COLUMN ... REFERENCES works for a new one); even then it is inert until PRAGMA foreign_keys = ON"},{"engine_slug":"oracle","status":"yes","note":"ENABLE NOVALIDATE enforces new rows without scanning old ones"}],"gotchas":["The plain ADD CONSTRAINT walks the whole table to validate existing rows, on all four engines that support it. On a large table that is minutes of scanning; PostgreSQL's NOT VALID and Oracle's NOVALIDATE exist for exactly this.","MySQL's InnoDB quietly creates an index on the referencing columns if none exists, and that index stays when you drop the constraint later. Create your own index with the name you want before adding the key.","SQL Server's WITH NOCHECK has a trap: the constraint is stored untrusted, and the optimizer skips untrusted constraints in its plans. Re-trust it with ALTER TABLE t WITH CHECK CHECK CONSTRAINT fk_name.","SQLite has no ALTER TABLE ADD FOREIGN KEY: an existing column only gains a reference through the full table rebuild. ALTER TABLE ADD COLUMN ... REFERENCES does work for a brand-new column with a NULL default, and enforcement still needs PRAGMA foreign_keys = ON per connection."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id);"},{"engine_slug":"postgresql","sql":"-- scan-free add, then validate while writes continue\nALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;"},{"engine_slug":"sql-server","sql":"-- fast add that skips the row scan\nALTER TABLE dbo.orders WITH NOCHECK\n  ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES dbo.customers (id);\n-- later, make it trusted again:\nALTER TABLE dbo.orders WITH CHECK CHECK CONSTRAINT fk_orders_customer;"},{"engine_slug":"mysql","sql":"ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id);"},{"engine_slug":"oracle","sql":"-- enforce new rows, skip the scan of old ones\nALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id)\n  ENABLE NOVALIDATE;"},{"engine_slug":"sqlite","sql":"-- no ALTER form for an existing column; declare it at creation or rebuild:\n-- CREATE TABLE orders (..., FOREIGN KEY (customer_id) REFERENCES customers (id))\n-- and per connection:\nPRAGMA foreign_keys = ON;"}],"faqs":[{"question":"Can I add a foreign key without checking existing rows?","answer":"Yes. PostgreSQL: NOT VALID, then VALIDATE CONSTRAINT later. Oracle: ENABLE NOVALIDATE. SQL Server: WITH NOCHECK (and remember the untrusted flag). MySQL: SET FOREIGN_KEY_CHECKS = 0 around the ALTER skips the scan, so turn checks back on and reconcile any bad rows the scan would have caught."},{"question":"Does the referenced column need to be a primary key?","answer":"No. A unique constraint works on every engine, and a plain unique index also works on SQL Server, PostgreSQL, MySQL and SQLite; Oracle needs an actual primary key or unique constraint. The referenced columns need uniqueness, not the primary key specifically."},{"question":"Why did MySQL create an index I did not ask for?","answer":"InnoDB must be able to find the child rows to police updates and deletes, so it builds an index on the referencing columns when none exists, naming it after the constraint if you gave one, otherwise after the column. Define your own index first if the name matters."}],"related":["drop-foreign-key","add-primary-key","add-check-constraint","create-table"]},"source_url":"https://sqlly.app/sql-ddl/add-foreign-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/add-primary-key","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ADD PRIMARY KEY","description":"Add a primary key to an existing table on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: NOT NULL prerequisites, index promotion, clustered index cost, rebuilds.","body":{"slug":"add-primary-key","name":"ADD PRIMARY KEY","h1":"ALTER TABLE ADD PRIMARY KEY","category":"tables","lede":"Turns an existing column or column list into the table's key. Four engines share one clause; the differences are the prerequisites, the lock you take and where the index lands.","syntax":"ALTER TABLE t ADD CONSTRAINT pk_name PRIMARY KEY (col [, ...])  -- SQL Server, PostgreSQL, MySQL, Oracle  |  ALTER TABLE t ADD CONSTRAINT pk_name PRIMARY KEY USING INDEX idx_name  -- PostgreSQL: promote an existing unique index  |  -- SQLite: no ALTER form; the key belongs in CREATE TABLE","support":[{"engine_slug":"sql-server","status":"yes","note":"the column must already be NOT NULL; the key becomes the clustered index unless you write NONCLUSTERED or the table already has a clustered index"},{"engine_slug":"postgresql","status":"yes","note":"also accepts ADD PRIMARY KEY without a name; USING INDEX promotes a unique index you built CONCURRENTLY"},{"engine_slug":"mysql","status":"yes","note":"InnoDB stores rows in primary key order, so ADD PRIMARY KEY rebuilds the table; a CONSTRAINT name is accepted but the index is always named PRIMARY"},{"engine_slug":"sqlite","status":"no","note":"no ADD CONSTRAINT: declare the key in CREATE TABLE or rebuild the table"},{"engine_slug":"oracle","status":"yes","note":"creates the backing unique index unless you hand it one with USING INDEX"}],"gotchas":["The ALTER fails on data before it fails on syntax: existing NULLs or duplicates stop the constraint in every engine. SQL Server adds a harder rule in front, refusing a nullable column until you ALTER COLUMN it to NOT NULL.","On MySQL, and on SQL Server by default, the primary key is the clustered index, so adding one to a large table rewrites the whole table. SQL Server builds it offline, blocking the table, unless you add WITH (ONLINE = ON) (Enterprise and Developer editions); MySQL rebuilds in place and allows concurrent DML, but still copies every row. PostgreSQL takes ACCESS EXCLUSIVE and scans the table to build the index. Schedule all three.","PostgreSQL's promotion path avoids the long scan under lock: CREATE UNIQUE INDEX CONCURRENTLY first (it cannot run inside a transaction and must not be partial or expression-based), then ADD CONSTRAINT ... PRIMARY KEY USING INDEX. The final ALTER is brief only when the key columns are already NOT NULL; otherwise it scans the whole table to set NOT NULL while holding ACCESS EXCLUSIVE. A DESC index is rejected too.","Oracle drops the unique index it created with the constraint when you drop the constraint later, but an index you supplied with USING INDEX survives. MySQL's PRIMARY index and SQL Server's key index go with the drop too, and so does a PostgreSQL index, even one you promoted with USING INDEX."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD CONSTRAINT pk_orders PRIMARY KEY (id);"},{"engine_slug":"postgresql","sql":"-- build the index without blocking writes, then promote it\nCREATE UNIQUE INDEX CONCURRENTLY idx_orders_id ON orders (id);\nALTER TABLE orders ADD CONSTRAINT pk_orders PRIMARY KEY USING INDEX idx_orders_id;"},{"engine_slug":"sql-server","sql":"-- nullable columns are rejected: tighten the column first\nALTER TABLE dbo.orders ALTER COLUMN id BIGINT NOT NULL;\nALTER TABLE dbo.orders ADD CONSTRAINT pk_orders PRIMARY KEY (id);"},{"engine_slug":"mysql","sql":"ALTER TABLE orders ADD PRIMARY KEY (id);"},{"engine_slug":"oracle","sql":"-- reuse an index you already built instead of growing a new one\nCREATE UNIQUE INDEX idx_orders_id ON orders (id);\nALTER TABLE orders ADD CONSTRAINT pk_orders PRIMARY KEY (id) USING INDEX idx_orders_id;"},{"engine_slug":"sqlite","sql":"-- the key must be in the table definition: rebuild\nCREATE TABLE orders_new (\n  id INTEGER PRIMARY KEY,\n  customer_id INTEGER NOT NULL,\n  status TEXT NOT NULL\n);\nINSERT INTO orders_new SELECT id, customer_id, status FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;"}],"faqs":[{"question":"Can I add a primary key without a long lock?","answer":"On PostgreSQL, yes: build a unique index with CONCURRENTLY, then promote it with PRIMARY KEY USING INDEX; the last ALTER still takes an exclusive lock, which stays brief only if the key columns are already NOT NULL. MySQL and SQL Server have online DDL options that depend on version and edition, so check your release's docs before the maintenance window. SQLite always copies the table."},{"question":"Why does SQL Server reject my ADD PRIMARY KEY?","answer":"The column is still nullable, and SQL Server demands NOT NULL before it will build the key. If no NULLs are present, ALTER COLUMN ... NOT NULL goes through; otherwise backfill them first, often with a DEFAULT or an UPDATE."},{"question":"What is the difference between a primary key and a unique constraint?","answer":"A table gets at most one primary key and it allows no NULLs. A table can carry several unique constraints, and they accept NULLs: PostgreSQL, MySQL, SQLite and Oracle allow any number of NULL rows, while SQL Server and PostgreSQL 15+ with NULLS NOT DISTINCT allow just one. On MySQL, and on SQL Server by default, the primary key is also where the rows physically cluster."}],"related":["drop-primary-key","add-unique-constraint","add-foreign-key","create-table"]},"source_url":"https://sqlly.app/sql-ddl/add-primary-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/add-unique-constraint","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ADD UNIQUE","description":"Add a unique constraint on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: index-backed enforcement, SQL Server's one-NULL rule, MySQL's constraint-is-an-index reality.","body":{"slug":"add-unique-constraint","name":"ADD UNIQUE","h1":"ALTER TABLE ADD UNIQUE","category":"tables","lede":"Forbids duplicate values in a column or column list. Four engines take one clause and back it with a unique index; SQLite goes straight to the index or rebuilds.","syntax":"ALTER TABLE t ADD CONSTRAINT uq_name UNIQUE (col [, ...])  -- SQL Server, PostgreSQL, Oracle  |  ALTER TABLE t ADD UNIQUE [KEY] (col)  -- MySQL: a unique constraint is a unique index  |  CREATE UNIQUE INDEX uq_name ON t (col)  -- SQLite: the practical equivalent, no table rebuild  |  ALTER TABLE t ADD CONSTRAINT uq_name UNIQUE USING INDEX idx_name  -- PostgreSQL: promote an existing unique index","support":[{"engine_slug":"sql-server","status":"yes","note":"creates a unique index to enforce it; the constraint and its index drop as a unit; NULL counts as a value, so only one NULL fits (a filtered unique index WHERE col IS NOT NULL allows many)"},{"engine_slug":"postgresql","status":"yes","note":"also UNIQUE USING INDEX over an index built CONCURRENTLY; NULLS NOT DISTINCT from 15"},{"engine_slug":"mysql","status":"yes","note":"the constraint is literally a unique index: same name, same SHOW INDEX row, dropped with DROP INDEX"},{"engine_slug":"sqlite","status":"partial","note":"no ADD CONSTRAINT: a unique index enforces the same rule without a rebuild"},{"engine_slug":"oracle","status":"yes","note":"backs the constraint with a unique index; USING INDEX reuses one you built"}],"gotchas":["NULL handling splits the engines. PostgreSQL, MySQL, SQLite and Oracle treat NULLs as distinct, so a nullable column holds any number of NULLs under a unique constraint; PostgreSQL 15+ can close that with UNIQUE NULLS NOT DISTINCT, and elsewhere you add NOT NULL to the column. SQL Server goes the other way: NULL counts as a value, so a second NULL is a duplicate (error 2627); a filtered unique index (CREATE UNIQUE INDEX ... WHERE col IS NOT NULL) gives you many NULLs.","On MySQL the constraint is an index by another name: it appears in SHOW INDEX and DROP INDEX removes it (DROP CONSTRAINT works too from 8.0.19). information_schema.TABLE_CONSTRAINTS lists it as UNIQUE, but a plain CREATE UNIQUE INDEX shows up there the same way, because there is no separate constraint object.","Adding the constraint checks the whole table for duplicates, a full scan on a big table. PostgreSQL's UNIQUE USING INDEX promotes an index you built with CONCURRENTLY, and Oracle's USING INDEX reuses one you already built, so the scan happens once, when you choose.","For a composite list the whole tuple is the unit: (7, 3) twice collides, (7, 3) next to (7, 4) does not, and rows where every listed column is NULL stay allowed everywhere except SQL Server, which rejects a second (NULL, NULL), and PostgreSQL with NULLS NOT DISTINCT."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD CONSTRAINT uq_orders_ref UNIQUE (order_ref);"},{"engine_slug":"postgresql","sql":"-- index built without blocking writes, promoted without a re-scan\nCREATE UNIQUE INDEX CONCURRENTLY idx_orders_ref ON orders (order_ref);\nALTER TABLE orders ADD CONSTRAINT uq_orders_ref UNIQUE USING INDEX idx_orders_ref;"},{"engine_slug":"sql-server","sql":"ALTER TABLE dbo.orders ADD CONSTRAINT uq_orders_ref UNIQUE (order_ref);"},{"engine_slug":"mysql","sql":"-- the constraint and the index are the same object\nALTER TABLE orders ADD UNIQUE KEY uq_orders_ref (order_ref);"},{"engine_slug":"sqlite","sql":"-- no ALTER form, no rebuild needed:\nCREATE UNIQUE INDEX uq_orders_ref ON orders (order_ref);"},{"engine_slug":"oracle","sql":"CREATE UNIQUE INDEX idx_orders_ref ON orders (order_ref);\nALTER TABLE orders ADD CONSTRAINT uq_orders_ref UNIQUE (order_ref) USING INDEX idx_orders_ref;"}],"faqs":[{"question":"Does a unique constraint allow NULLs?","answer":"On PostgreSQL, MySQL, SQLite and Oracle, yes, and any number of them: NULL never equals NULL in SQL comparisons. PostgreSQL 15+ offers NULLS NOT DISTINCT to treat them as duplicates; on the others, declare the column NOT NULL alongside the constraint. SQL Server is the exception: it allows exactly one NULL, and a filtered unique index (WHERE col IS NOT NULL) is how you allow more."},{"question":"Unique constraint or unique index?","answer":"They enforce the same rule at the same cost. The named constraint is the portable form and reads well in catalogs (MySQL excepted, where they are one object). The bare index is what you use on SQLite, and what you build CONCURRENTLY on PostgreSQL before promoting it."},{"question":"Why did my ADD UNIQUE fail?","answer":"Existing duplicates. Find them with SELECT order_ref, COUNT(*) FROM orders GROUP BY order_ref HAVING COUNT(*) > 1, merge or archive the extras, then run the ALTER again. The duplicate check runs before the change commits, so the table is untouched after a failure."}],"related":["add-primary-key","create-index","drop-index","drop-primary-key"]},"source_url":"https://sqlly.app/sql-ddl/add-unique-constraint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-sequence","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL ALTER SEQUENCE","description":"Alter a sequence on SQL Server, PostgreSQL and Oracle: RESTART WITH, new increments and bounds, OWNED BY lifecycle, Oracle's pre-18c workarounds, engines without any.","body":{"slug":"alter-sequence","name":"ALTER SEQUENCE","h1":"SQL ALTER SEQUENCE","category":"tables","lede":"Retunes a running counter: new step size, new bounds, or a rewind behind the current value. MySQL and SQLite have no sequences, so their reset paths are table-level.","syntax":"ALTER SEQUENCE [IF EXISTS] name [AS type] [INCREMENT BY n] [RESTART [WITH n]]  -- PostgreSQL: plus MINVALUE, MAXVALUE, CYCLE, CACHE, OWNED BY  |  ALTER SEQUENCE name RESTART WITH 1  -- SQL Server: parameters only, the datatype never changes  |  ALTER SEQUENCE name RESTART START WITH 500  -- Oracle 18c+: RESTART alone rewinds to MINVALUE  |  -- MySQL: no sequence to alter; ALTER TABLE t AUTO_INCREMENT = 500 sets the counter  |  -- SQLite: no sequence; AUTOINCREMENT counters sit in the sqlite_sequence table","support":[{"engine_slug":"sql-server","status":"yes","note":"RESTART [WITH n], INCREMENT BY, MINVALUE, MAXVALUE, CYCLE, CACHE; the datatype is not alterable"},{"engine_slug":"postgresql","status":"yes","note":"the full set including AS type and OWNED BY table.column or OWNED BY NONE"},{"engine_slug":"mysql","status":"no","note":"nothing to alter: the table option AUTO_INCREMENT = n sets the next value"},{"engine_slug":"sqlite","status":"no","note":"no sequences; the AUTOINCREMENT counter is one row in the sqlite_sequence table, holding the last id used and written on the table's first insert"},{"engine_slug":"oracle","status":"partial","note":"INCREMENT BY and bounds always worked; RESTART needs 18c or newer"}],"gotchas":["RESTART changes the future, not the past: rows already written keep their ids. Set the restart point past MAX(id) or an insert collides with an existing row as soon as the counter reaches it, and a unique or primary key rejects it.","Oracle before 18c had no RESTART at all: the moves were drop-and-recreate, which invalidates every stored object using the sequence, or the increment-swing trick (set INCREMENT BY negative, pull one NEXTVAL, set it back). 18c's RESTART START WITH ends both rituals.","PostgreSQL's OWNED BY table.column makes the sequence drop with its column, which is the linkage serial builds for you; OWNED BY NONE cuts it loose. A bare CREATE SEQUENCE leaves an orphan behind whenever the table goes.","SQL Server fixes the datatype at creation: ALTER SEQUENCE retunes the running behaviour but never the AS type, so an INT sequence heading past 2.1 billion is a drop-and-recreate job with dependency juggling."],"examples":[{"engine_slug":"postgresql","sql":"ALTER SEQUENCE order_id_seq RESTART WITH 5000;\n-- detach a serial's sequence so the table drop leaves it alone:\nALTER SEQUENCE order_id_seq OWNED BY NONE;"},{"engine_slug":"sql-server","sql":"ALTER SEQUENCE dbo.invoice_number RESTART WITH 1000 INCREMENT BY 10;"},{"engine_slug":"oracle","sql":"-- 18c+: rewind to MINVALUE, or to a chosen value\nALTER SEQUENCE invoice_number RESTART;\nALTER SEQUENCE invoice_number RESTART START WITH 5000;"},{"engine_slug":"mysql","sql":"-- no sequences: the table option is the reset\nALTER TABLE invoices AUTO_INCREMENT = 5000;"},{"engine_slug":"sqlite","sql":"-- counter rows live in sqlite_sequence, one per AUTOINCREMENT table; seq is the last id used, so the next insert gets 5000\nUPDATE sqlite_sequence SET seq = 4999 WHERE name = 'invoices';"}],"faqs":[{"question":"How do I reset a sequence to match the table's max id?","answer":"PostgreSQL: SELECT setval('order_id_seq', COALESCE((SELECT MAX(id) FROM orders), 0) + 1, false), or ALTER SEQUENCE ... RESTART WITH n. Oracle 18c: RESTART START WITH n. MySQL: ALTER TABLE invoices AUTO_INCREMENT = n, which InnoDB quietly raises to MAX(id) + 1 if n is lower. On PostgreSQL, SQL Server and Oracle, check MAX(id) again afterwards: a restart at or below an existing id makes inserts collide once the counter reaches it."},{"question":"What does OWNED BY actually change?","answer":"Lifecycle, not values: an owned sequence drops automatically when its column or table drops, while a bare sequence survives as an orphan. serial and GENERATED AS IDENTITY set the ownership up for you; the number stream is identical either way."},{"question":"Can I change a sequence's datatype?","answer":"PostgreSQL yes: ALTER SEQUENCE ... AS bigint (10+) revalidates the bounds. SQL Server no: the type is fixed at creation, so a cramped INT sequence means recreate-and-repoint. Oracle sequences have no type clause at all; values are NUMBER."}],"related":["create-sequence","truncate-table","add-primary-key","alter-table-set-default"]},"source_url":"https://sqlly.app/sql-ddl/alter-sequence","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-table-add-column","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ADD COLUMN","description":"Add a column on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the COLUMN keyword, defaults, NOT NULL, column position on MySQL, and SQLite's restrictions.","body":{"slug":"alter-table-add-column","name":"ADD COLUMN","h1":"ALTER TABLE ADD COLUMN","category":"columns","lede":"Extends a table with a new column. The basic clause is near-identical everywhere; the interesting parts are which engines drop the COLUMN keyword, and the rules a new column's default and NOT NULL must follow.","syntax":"ALTER TABLE t ADD COLUMN col type [constraints]  -- PostgreSQL, MySQL, SQLite  |  ALTER TABLE t ADD col type [constraints] [, ...]  -- SQL Server, Oracle: no COLUMN keyword  |  ALTER TABLE t ADD COLUMN col type AFTER other_col  -- MySQL: position","support":[{"engine_slug":"sql-server","status":"yes","note":"ADD without COLUMN; several columns comma-separated"},{"engine_slug":"postgresql","status":"yes","note":"a constant default skips the table rewrite (fast default, 11+)"},{"engine_slug":"mysql","status":"yes","note":"ADD COLUMN, with AFTER or FIRST to place it; instant adds from 8.0.12"},{"engine_slug":"sqlite","status":"partial","note":"the new column cannot be PRIMARY KEY or UNIQUE; NOT NULL needs a constant default"},{"engine_slug":"oracle","status":"yes","note":"ADD without COLUMN; several columns in parentheses"}],"gotchas":["SQL Server and Oracle drop the COLUMN keyword: ALTER TABLE t ADD created_at DATETIME2. MySQL, PostgreSQL and SQLite accept ADD COLUMN, where COLUMN is optional. Pasting ADD COLUMN into SQL Server is the classic cross-dialect error: it fails with Incorrect syntax near the keyword 'COLUMN'.","Adding a NOT NULL column without a default fails on a non-empty table in SQL Server, PostgreSQL, SQLite and Oracle: the existing rows would have nothing to put in the column. Give it a DEFAULT and the backfill is automatic. MySQL is the exception: it accepts the statement, even in strict mode, and quietly fills existing rows with the type's implicit default, such as 0 or an empty string.","SQLite keeps ADD COLUMN conservative: the new column cannot be PRIMARY KEY or UNIQUE, a NOT NULL column needs a non-NULL constant default, and defaults must be constants rather than expressions.","PostgreSQL 11+ stores a constant default as metadata and skips the rewrite, so ADD COLUMN ... DEFAULT 0 on a billion-row table is instant. A volatile default such as DEFAULT clock_timestamp() or random() still rewrites every row; now() is only stable, so it is evaluated once and stays a fast default."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ADD COLUMN shipped_at TIMESTAMPTZ;"},{"engine_slug":"postgresql","sql":"-- instant on 11+, no rewrite despite the default\nALTER TABLE orders ADD COLUMN priority SMALLINT NOT NULL DEFAULT 0;"},{"engine_slug":"sql-server","sql":"ALTER TABLE dbo.orders ADD shipped_at DATETIME2 NULL, priority SMALLINT NOT NULL DEFAULT 0;"},{"engine_slug":"mysql","sql":"ALTER TABLE orders ADD COLUMN shipped_at DATETIME NULL AFTER placed_at;"},{"engine_slug":"sqlite","sql":"-- constant default only, no PRIMARY KEY or UNIQUE\nALTER TABLE orders ADD COLUMN priority INTEGER NOT NULL DEFAULT 0;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders ADD (shipped_at DATE, priority NUMBER(3) DEFAULT 0 NOT NULL);"}],"faqs":[{"question":"Why does my NOT NULL ADD COLUMN fail?","answer":"Existing rows have no value for the new column. SQL Server, PostgreSQL, SQLite and Oracle demand a DEFAULT for a NOT NULL column on a non-empty table; add the default and the backfill happens as part of the statement. MySQL lets it through and fills existing rows with the type's implicit default, such as 0 or an empty string."},{"question":"Does adding a column lock or rewrite the table?","answer":"Depends on the engine and the form. PostgreSQL 11+ with a constant default is metadata-only, and SQLite never rewrites because the default lives in the schema. MySQL 8.0.12+ can add a plain trailing column with the INSTANT algorithm. For anything else on a large table, check the engine's docs before running the statement."},{"question":"Can I add a column in a specific position?","answer":"MySQL: ADD COLUMN x INT AFTER other_col, or FIRST. SQL Server, PostgreSQL and SQLite append at the end. Column order is cosmetic anyway; queries that name columns do not care where the column sits."}],"related":["alter-table-alter-column","alter-table-drop-column","create-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-table-add-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-table-alter-column","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE ALTER COLUMN","description":"Change a column's type on all five engines: ALTER COLUMN on SQL Server, TYPE USING on PostgreSQL, MODIFY COLUMN on MySQL, and SQLite's table rebuild.","body":{"slug":"alter-table-alter-column","name":"ALTER COLUMN","h1":"ALTER TABLE ALTER COLUMN","category":"columns","lede":"Changes an existing column's data type or size. Five engines, five spellings, and one engine with no statement at all: SQLite rebuilds the table instead.","syntax":"ALTER TABLE t ALTER COLUMN col new_type [NULL | NOT NULL]  -- SQL Server  |  ALTER TABLE t ALTER COLUMN col TYPE new_type [USING expression]  -- PostgreSQL  |  ALTER TABLE t MODIFY COLUMN col new_type  -- MySQL  |  ALTER TABLE t MODIFY (col new_type)  -- Oracle","support":[{"engine_slug":"sql-server","status":"partial","note":"ALTER COLUMN; dependent constraints and indexes usually must be dropped first"},{"engine_slug":"postgresql","status":"yes","note":"TYPE with an optional USING expression; indexes rebuild automatically"},{"engine_slug":"mysql","status":"partial","note":"MODIFY or CHANGE COLUMN; plain ALTER COLUMN only sets the default or visibility"},{"engine_slug":"sqlite","status":"no","note":"no statement: create the new table, INSERT SELECT, DROP, RENAME"},{"engine_slug":"oracle","status":"partial","note":"MODIFY; shrinking requires the stored data to fit the new size"}],"gotchas":["MySQL is the trap: ALTER TABLE t ALTER COLUMN c ... sets or drops the column's DEFAULT, it does not change the type. Type changes go through MODIFY COLUMN, or CHANGE COLUMN when you also rename.","On SQL Server, ALTER COLUMN usually fails while the column appears in an index, a primary key or UNIQUE constraint, or a CHECK, FOREIGN KEY or DEFAULT constraint: drop them, alter, recreate. Widening a varchar is the common case that still goes through. It also resets the column to nullable when you omit NULL or NOT NULL, so restate NOT NULL every time.","PostgreSQL needs USING when the old and new types have no assignment cast: ALTER TABLE t ALTER COLUMN c TYPE int USING c::int. With no such cast it fails rather than guess, unless USING says how; a cast that does exist still runs, so numeric to int quietly rounds 3.7 to 4.","SQLite cannot change a column's type in place. The supported recipe: create a new table with the wanted types, INSERT INTO new SELECT ... FROM old, DROP the old table, RENAME the new one, with foreign keys off and everything in one transaction."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ALTER COLUMN priority TYPE smallint USING priority::smallint;"},{"engine_slug":"sql-server","sql":"ALTER TABLE dbo.orders ALTER COLUMN priority SMALLINT NOT NULL;"},{"engine_slug":"mysql","sql":"ALTER TABLE orders MODIFY COLUMN priority SMALLINT NOT NULL DEFAULT 0;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders MODIFY (priority NUMBER(5));"},{"engine_slug":"sqlite","sql":"-- the rebuild is the only way; see SQLite's ALTER TABLE docs\nPRAGMA foreign_keys = OFF;\nBEGIN;\nCREATE TABLE orders_new (id INTEGER PRIMARY KEY, priority SMALLINT NOT NULL);\nINSERT INTO orders_new SELECT id, priority FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;\nCOMMIT;\nPRAGMA foreign_keys = ON;"}],"faqs":[{"question":"Why does MySQL ALTER COLUMN not change my column type?","answer":"On MySQL, ALTER COLUMN sets or drops the DEFAULT. The type-changing statement is ALTER TABLE t MODIFY COLUMN c new_type, or CHANGE COLUMN when you also rename. PostgreSQL and SQL Server spell type changes ALTER COLUMN."},{"question":"How do I change a column type in SQLite?","answer":"You rebuild the table: create the replacement with the right types, copy the rows in, drop the original, rename the copy, and recreate indexes. SQLite's ALTER TABLE documentation lists the full procedure, including turning foreign keys off for the duration."},{"question":"Will changing a column type lose my indexes?","answer":"PostgreSQL rebuilds and restores them as part of the statement (though it refuses while a view uses the column), and MySQL keeps them while it rebuilds the table. SQL Server typically makes you drop indexes and constraints first and recreate them yourself, and SQLite's rebuild recreates them by hand anyway."}],"related":["alter-table-add-column","alter-table-drop-column","create-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-table-alter-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-table-drop-column","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE DROP COLUMN","description":"Remove a column on SQL Server, PostgreSQL, MySQL, SQLite (3.35+) and Oracle: CASCADE rules, index refusals, and Oracle's SET UNUSED two-step for big tables.","body":{"slug":"alter-table-drop-column","name":"DROP COLUMN","h1":"ALTER TABLE DROP COLUMN","category":"columns","lede":"Removes a column and the data in it. All five engines can do it in one statement today; what differs is how hard they fight you when other objects still use the column.","syntax":"ALTER TABLE t DROP COLUMN col  -- SQL Server, PostgreSQL, MySQL, SQLite  |  ALTER TABLE t DROP COLUMN col CASCADE  -- PostgreSQL: drops dependent objects too  |  ALTER TABLE t DROP (col)  -- Oracle  |  ALTER TABLE t SET UNUSED (col)  -- Oracle: hide now, drop later","support":[{"engine_slug":"sql-server","status":"yes","note":"DROP COLUMN c1, c2; refuses columns used by indexes, constraints or computed columns"},{"engine_slug":"postgresql","status":"yes","note":"IF EXISTS, and RESTRICT (default) or CASCADE"},{"engine_slug":"mysql","status":"yes","note":"DROP COLUMN, several in one ALTER TABLE"},{"engine_slug":"sqlite","status":"partial","note":"3.35+; refuses PRIMARY KEY, UNIQUE and indexed columns"},{"engine_slug":"oracle","status":"partial","note":"DROP (col), or SET UNUSED and DROP UNUSED COLUMNS later"}],"gotchas":["PostgreSQL's default is RESTRICT: the drop fails while a view, or a foreign key in another table, depends on the column. Indexes and constraints on the table itself are dropped along with the column without asking. CASCADE removes the outside dependents silently too, so read the dependency list (or drop them yourself) before reaching for it.","SQLite allows DROP COLUMN only from 3.35, and refuses columns that are PRIMARY KEY or UNIQUE, appear in an index, or are referenced by a trigger or view. Anything older rebuilds the table.","Oracle's SET UNUSED marks columns invisible immediately without paying to remove them; DROP UNUSED COLUMNS reclaims the space later, in a quiet window. A SET UNUSED column cannot be read again, it is only hidden.","SQL Server refuses when the column is in an index or constraint: drop those first. Views and procedures that selected the column are not updated, and they fail the next time they run."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders DROP COLUMN legacy_ref;"},{"engine_slug":"postgresql","sql":"ALTER TABLE orders DROP COLUMN IF EXISTS legacy_ref CASCADE;"},{"engine_slug":"sql-server","sql":"ALTER TABLE dbo.orders DROP COLUMN legacy_ref;"},{"engine_slug":"mysql","sql":"ALTER TABLE orders DROP COLUMN legacy_ref, DROP COLUMN temp_flag;"},{"engine_slug":"sqlite","sql":"-- needs SQLite 3.35+, and no index on the column\nALTER TABLE orders DROP COLUMN legacy_ref;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders SET UNUSED (legacy_ref);\nALTER TABLE orders DROP UNUSED COLUMNS;"}],"faqs":[{"question":"Does DROP COLUMN reclaim the disk space right away?","answer":"Not always. PostgreSQL and SQL Server drop the column as metadata and leave the values in place until rows are rewritten (SQL Server ships DBCC CLEANTABLE for exactly that). Oracle's SET UNUSED plus DROP UNUSED COLUMNS is the scheduled version of the same idea."},{"question":"Why can I not drop this column?","answer":"Something depends on it: an index, a primary or unique key, a check or foreign key constraint, a view or a trigger. SQL Server and SQLite refuse and name the offender in the error, so remove it first (SQLite lets a column's own CHECK go with it). PostgreSQL drops the table's own indexes and constraints along with the column and refuses only for views and other tables' foreign keys, which CASCADE removes for you. MySQL trims indexes and refuses only when a foreign key needs the column."},{"question":"How do I drop several columns at once?","answer":"SQL Server: DROP COLUMN a, b. MySQL: DROP COLUMN a, DROP COLUMN b in one ALTER TABLE. PostgreSQL: DROP COLUMN a, DROP COLUMN b in one statement. Oracle: DROP (a, b). SQLite: one column per statement."}],"related":["alter-table-add-column","alter-table-alter-column","drop-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-table-drop-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-table-drop-default","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE DROP DEFAULT","description":"Remove a column default on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: DROP DEFAULT where it exists, SQL Server's constraint-name hunt, Oracle's DEFAULT NULL.","body":{"slug":"alter-table-drop-default","name":"DROP DEFAULT","h1":"ALTER TABLE DROP DEFAULT","category":"columns","lede":"Stops new inserts from picking up the old fallback. PostgreSQL and MySQL share one clause; SQL Server drops a named constraint; Oracle has no DROP at all; SQLite rebuilds.","syntax":"ALTER TABLE t ALTER COLUMN c DROP DEFAULT  -- PostgreSQL, MySQL  |  ALTER TABLE t DROP CONSTRAINT df_name  -- SQL Server: the default is a constraint  |  ALTER TABLE t MODIFY c DEFAULT NULL  -- Oracle: the way to remove a default  |  -- SQLite: no clause; rebuild the table without the default","support":[{"engine_slug":"sql-server","status":"partial","note":"drop the constraint by name; unnamed defaults got machine-generated names you must look up in sys.default_constraints"},{"engine_slug":"postgresql","status":"yes","note":"one clause, metadata only; afterwards an omitted nullable column inserts NULL"},{"engine_slug":"mysql","status":"yes","note":"one clause, metadata only (ALGORITHM=INSTANT); afterwards the column has no default at all, so strict mode rejects inserts that omit it even when it is nullable (SET DEFAULT NULL keeps a NULL fallback)"},{"engine_slug":"sqlite","status":"no","note":"no clause; rebuild the table, or use the writable_schema edit SQLite documents for default changes, which corrupts the database if the new CREATE TABLE text is wrong"},{"engine_slug":"oracle","status":"no","note":"MODIFY c DEFAULT NULL is how Oracle drops a default; there is no DROP DEFAULT clause"}],"gotchas":["Removing a default changes no stored value: existing rows keep what they have, and inserts that spell the column out keep working. Only inserts that omit the column notice the difference.","On SQL Server the generated name is the obstacle: query sys.default_constraints for parent_object_id = OBJECT_ID(N'dbo.orders') to get it. DROP CONSTRAINT takes IF EXISTS from SQL Server 2016 on, but you still need the name.","After the drop, a nullable column falls back to NULL on SQL Server, PostgreSQL and Oracle, and a NOT NULL column fails any insert that omits it. MySQL differs: DROP DEFAULT leaves the column with no default at all, so strict mode rejects an insert that omits it even on a nullable column (error 1364), and non-strict mode stores NULL or the type's implicit default ('' or 0) with a warning. On MySQL, use SET DEFAULT NULL when you want the NULL fallback.","PostgreSQL and MySQL do this as a catalog change, so it is instant at any table size. Oracle's DEFAULT NULL is also metadata-only. SQLite's rebuild copies the whole table, indexes and triggers included."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;"},{"engine_slug":"sql-server","sql":"-- find the generated name first\nSELECT dc.name\nFROM sys.default_constraints AS dc\nWHERE dc.parent_object_id = OBJECT_ID(N'dbo.orders');\nALTER TABLE dbo.orders DROP CONSTRAINT DF__orders__status__5AEE82B9;"},{"engine_slug":"mysql","sql":"ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;"},{"engine_slug":"sqlite","sql":"-- no DROP DEFAULT: rebuild without the clause (shortened;\n-- the full procedure also re-creates indexes and triggers)\nCREATE TABLE orders_new (\n  id INTEGER PRIMARY KEY,\n  customer_id INTEGER NOT NULL,\n  status TEXT NOT NULL\n);\nINSERT INTO orders_new SELECT id, customer_id, status FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;"},{"engine_slug":"oracle","sql":"-- DEFAULT NULL means no default\nALTER TABLE orders MODIFY status DEFAULT NULL;"}],"faqs":[{"question":"How do I find the default constraint's name on SQL Server?","answer":"Query sys.default_constraints: SELECT name FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'dbo.orders') AND parent_column_id = COLUMNPROPERTY(OBJECT_ID(N'dbo.orders'), 'status', 'ColumnId'). Generated names look like DF__orders__status__5AEE82B9, which is why naming defaults at creation pays off."},{"question":"What do inserts do once the default is gone?","answer":"A nullable column gets NULL where the column is omitted, except on MySQL: there DROP DEFAULT leaves no default at all, and strict mode fails the insert with error 1364 (SET DEFAULT NULL keeps the NULL fallback). A NOT NULL column makes the insert fail since there is no value to use; only non-strict MySQL lets it through, storing the type's implicit default with a warning. Inserts that name the column explicitly never notice the drop."},{"question":"Why does Oracle use DEFAULT NULL to drop a default?","answer":"In Oracle a default is the value after the DEFAULT keyword, nothing more. Setting it to NULL is identical to having no default, so the engine never needed a DROP DEFAULT clause; MODIFY c DEFAULT NULL is the idiom."}],"related":["alter-table-set-default","alter-table-alter-column","alter-table-add-column","create-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-table-drop-default","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-table-set-default","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE SET DEFAULT","description":"Set a column default on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the one-line clause, SQL Server's named constraint, MySQL's expression rules, SQLite's rebuild.","body":{"slug":"alter-table-set-default","name":"SET DEFAULT","h1":"ALTER TABLE SET DEFAULT","category":"columns","lede":"Gives future inserts a fallback value for a column. Three engines change a default in one clause; SQL Server adds a named constraint and SQLite rebuilds the table.","syntax":"ALTER TABLE t ALTER COLUMN c SET DEFAULT value  -- PostgreSQL, MySQL  |  ALTER TABLE t ADD CONSTRAINT df_name DEFAULT value FOR c  -- SQL Server: the default is a constraint  |  ALTER TABLE t MODIFY c DEFAULT value  -- Oracle  |  -- SQLite: no clause; rebuild the table with the new default in CREATE TABLE","support":[{"engine_slug":"sql-server","status":"partial","note":"no SET DEFAULT clause: a default is a constraint, added as ADD CONSTRAINT df_name DEFAULT value FOR c; to change an existing default, DROP CONSTRAINT the old one first (a second default fails with Msg 1781)"},{"engine_slug":"postgresql","status":"yes","note":"one line, metadata only; the value can be any expression, including volatile ones like clock_timestamp() or random()"},{"engine_slug":"mysql","status":"yes","note":"one line, metadata only (ALGORITHM=INSTANT); expressions must be wrapped in parentheses"},{"engine_slug":"sqlite","status":"no","note":"the default lives in the table definition; changing it means the create-new-table-and-copy rebuild"},{"engine_slug":"oracle","status":"no","note":"different clause: MODIFY c DEFAULT value; DEFAULT NULL removes the default"}],"gotchas":["Changing a default never touches existing rows on any engine. Defaults fill in when an INSERT omits the column, so a new default is invisible until the next insert that needs it.","SQL Server wraps every default in a constraint, and an unnamed one gets a machine name such as DF__orders__status__5AEE82B9. You need that exact name to drop it later, so name defaults when you create them.","MySQL takes a literal bare; an expression must be in parentheses and needs 8.0.13 or newer, as in SET DEFAULT (UPPER('new')). PostgreSQL accepts either shape, bare or parenthesized.","Oracle's MODIFY c DEFAULT value rewrites nothing either, but from 12c you can add ON NULL: DEFAULT ON NULL value feeds the default to inserts that explicitly send NULL instead of erroring."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'new';"},{"engine_slug":"sql-server","sql":"-- the name is yours to keep: DROP CONSTRAINT wants it later\nALTER TABLE dbo.orders\n  ADD CONSTRAINT df_orders_status DEFAULT 'new' FOR status;"},{"engine_slug":"mysql","sql":"-- literals need no parentheses on any version:\nALTER TABLE orders ALTER COLUMN status SET DEFAULT 'new';\n-- expressions do, from 8.0.13:\nALTER TABLE orders ALTER COLUMN placed_at SET DEFAULT (CURRENT_DATE);"},{"engine_slug":"sqlite","sql":"-- no SET DEFAULT: rebuild (shortened; the full procedure\n-- also re-creates indexes and triggers)\nCREATE TABLE orders_new (\n  id INTEGER PRIMARY KEY,\n  customer_id INTEGER NOT NULL,\n  status TEXT NOT NULL DEFAULT 'new'\n);\nINSERT INTO orders_new (id, customer_id, status) SELECT id, customer_id, status FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders MODIFY status DEFAULT 'new';\n-- DEFAULT ON NULL also covers inserts that send NULL (12c+)\nALTER TABLE orders MODIFY status DEFAULT ON NULL 'new';"}],"faqs":[{"question":"Why does SQL Server have no SET DEFAULT clause?","answer":"Defaults are constraints on SQL Server, so they get names and live in the catalog alongside primary keys and foreign keys. Adding one without a name makes SQL Server generate one, and the generated name is what DROP CONSTRAINT wants later. ADD CONSTRAINT ... DEFAULT ... FOR lets you pick the name."},{"question":"Does setting a new default update existing rows?","answer":"No, on every engine. A default is consulted only when an INSERT leaves the column out; rows already in the table keep their values. Run an UPDATE afterwards for the rows you want changed."},{"question":"Can a default be an expression like now()?","answer":"PostgreSQL yes, bare or parenthesized. MySQL accepts expressions in parentheses from 8.0.13, and through SET DEFAULT even CURRENT_TIMESTAMP must be parenthesized, as in SET DEFAULT (CURRENT_TIMESTAMP); it goes bare only in a full column definition such as MODIFY c DATETIME DEFAULT CURRENT_TIMESTAMP. Subqueries, variables and stored functions are never allowed. SQL Server and Oracle accept functions such as SYSDATETIME() and SYSDATE. SQLite allows parenthesized constant expressions in CREATE TABLE, non-deterministic ones like (datetime('now')) and (random()) included, and nothing at all after creation."}],"related":["alter-table-drop-default","alter-table-add-column","alter-table-alter-column","create-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-table-set-default","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/alter-view","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL ALTER VIEW","description":"Redefine or adjust a view on all five engines: ALTER VIEW AS on SQL Server and MySQL, CREATE OR REPLACE on PostgreSQL and Oracle, and SQLite's drop-and-recreate.","body":{"slug":"alter-view","name":"ALTER VIEW","h1":"SQL ALTER VIEW","category":"views","lede":"Changes an existing view: its query on SQL Server and MySQL, its name, schema or options on PostgreSQL and Oracle. SQLite has no ALTER VIEW at all.","syntax":"ALTER VIEW view_name AS SELECT ...  -- SQL Server, MySQL: new definition  |  CREATE OR REPLACE VIEW view_name AS SELECT ...  -- PostgreSQL, Oracle  |  ALTER VIEW view_name RENAME TO new_name  -- PostgreSQL  |  DROP VIEW view_name; CREATE VIEW view_name AS SELECT ...  -- SQLite","support":[{"engine_slug":"sql-server","status":"yes","note":"ALTER VIEW ... AS redefines; permissions survive"},{"engine_slug":"postgresql","status":"partial","note":"ALTER VIEW renames or moves it; the query changes with CREATE OR REPLACE"},{"engine_slug":"mysql","status":"yes","note":"ALTER VIEW ... AS redefines, the same as CREATE OR REPLACE"},{"engine_slug":"sqlite","status":"no","note":"no ALTER VIEW: drop and recreate"},{"engine_slug":"oracle","status":"partial","note":"CREATE OR REPLACE redefines; ALTER VIEW COMPILE revalidates"}],"gotchas":["PostgreSQL splits the job: ALTER VIEW handles RENAME TO, SET SCHEMA, owners and options such as security_invoker, while the query itself only changes through CREATE OR REPLACE VIEW, with the frozen-column-list rules that come with it.","SQL Server's ALTER VIEW replaces the definition and keeps the view's permissions, which is why it beats drop-and-create for anything with grants attached.","SQLite has neither ALTER VIEW nor OR REPLACE. DROP VIEW then CREATE VIEW inside one transaction is the standard move; readers see the old definition until the commit lands.","Oracle's ALTER VIEW does not change the query: it recompiles (ALTER VIEW v COMPILE) and manages view constraints. Redefinition is CREATE OR REPLACE VIEW."],"examples":[{"engine_slug":"sql-server","sql":"ALTER VIEW dbo.open_orders\nAS\nSELECT id, customer_id, placed_at, total\nFROM dbo.orders\nWHERE status IN ('open', 'processing');"},{"engine_slug":"mysql","sql":"ALTER VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders WHERE status IN ('open', 'processing');"},{"engine_slug":"postgresql","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders WHERE status IN ('open', 'processing');"},{"engine_slug":"postgresql","sql":"ALTER VIEW open_orders RENAME TO active_orders;"},{"engine_slug":"sqlite","sql":"BEGIN;\nDROP VIEW open_orders;\nCREATE VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders WHERE status IN ('open', 'processing');\nCOMMIT;"},{"engine_slug":"oracle","sql":"ALTER VIEW open_orders COMPILE;"}],"faqs":[{"question":"Why is there no ALTER VIEW AS on PostgreSQL?","answer":"PostgreSQL reserves ALTER VIEW for metadata: RENAME TO, SET SCHEMA, owner and options. The query changes through CREATE OR REPLACE VIEW, which keeps permissions and dependencies while swapping the definition under the column-freeze rules."},{"question":"How do I rename a view?","answer":"PostgreSQL: ALTER VIEW v RENAME TO v2. MySQL: RENAME TABLE v TO v2, which works for views too. SQL Server's sp_rename renames the object but leaves stored definitions stale, so drop-and-recreate is the recommended path there. SQLite and Oracle: drop and recreate."},{"question":"Do permissions survive a view change?","answer":"On SQL Server's ALTER VIEW and PostgreSQL's CREATE OR REPLACE VIEW, yes: the object keeps its identity and its grants. Drop-and-recreate loses grants on SQL Server, PostgreSQL and Oracle, so re-apply them, which is the main reason engines grew replace forms. MySQL is the exception: its grants are stored by name in mysql.tables_priv, so they survive DROP VIEW and apply to the recreated view."}],"related":["create-view","drop-view","rename-table"]},"source_url":"https://sqlly.app/sql-ddl/alter-view","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-index","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL CREATE INDEX","description":"CREATE INDEX on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: unique and partial indexes, INCLUDE and covering columns, CONCURRENTLY, and expression indexes.","body":{"slug":"create-index","name":"CREATE INDEX","h1":"SQL CREATE INDEX","category":"indexes","lede":"Builds the structure that makes lookups and sorts fast, at the cost of write overhead. The core clause is shared; everything interesting (covering columns, partial filters, online builds) is spelled differently.","syntax":"CREATE [UNIQUE] INDEX index_name ON table_name (column [ASC | DESC] [, ...])  |  CREATE INDEX i ON t (col) INCLUDE (other_col) [WHERE predicate]  -- SQL Server  |  CREATE [UNIQUE] INDEX [CONCURRENTLY] i ON t (expression) [WHERE predicate]  -- PostgreSQL  |  CREATE INDEX i ON t (LOWER(email))  -- expression index: PostgreSQL, SQLite, Oracle; MySQL 8.0.13+ needs double parentheses: ((LOWER(email)))","support":[{"engine_slug":"sql-server","status":"yes","note":"INCLUDE columns, filtered WHERE, ONLINE = ON on supported editions"},{"engine_slug":"postgresql","status":"yes","note":"CONCURRENTLY builds without blocking writes; partial, expression and USING method"},{"engine_slug":"mysql","status":"yes","note":"prefix indexes col(n); functional key parts from 8.0.13; no IF NOT EXISTS"},{"engine_slug":"sqlite","status":"yes","note":"IF NOT EXISTS; partial WHERE; expression indexes from 3.9"},{"engine_slug":"oracle","status":"yes","note":"function-based, bitmap, INVISIBLE and ONLINE builds"}],"gotchas":["Index-name scope differs: SQL Server and MySQL keep names per table, so two tables can each have idx_email. PostgreSQL, Oracle and SQLite share one namespace per schema or database, where the same name cannot be reused anywhere else.","PostgreSQL's CONCURRENTLY, Oracle's ONLINE and SQL Server's ONLINE = ON (where licensed) let reads and writes continue while the index builds. A plain build holds a lock that blocks writes for the duration, which is minutes on a big table.","MySQL has no IF NOT EXISTS for CREATE INDEX and no partial indexes: WHERE is not part of its grammar. Filtered or partial indexes are PostgreSQL, SQLite and SQL Server territory.","Expression indexes index a function's result: CREATE INDEX idx_users_email_lc ON users (LOWER(email)) makes LOWER(email) = ? fast on PostgreSQL, SQLite and Oracle, and on MySQL 8.0.13+ with double parentheses: ((LOWER(email)))."],"examples":[{"engine_slug":"all","sql":"CREATE INDEX idx_orders_customer ON orders (customer_id);"},{"engine_slug":"postgresql","sql":"CREATE INDEX CONCURRENTLY idx_orders_placed\nON orders (placed_at DESC)\nWHERE status <> 'cancelled';"},{"engine_slug":"sql-server","sql":"CREATE NONCLUSTERED INDEX idx_orders_customer\nON dbo.orders (customer_id)\nINCLUDE (placed_at, total)\nWHERE status = 'open';"},{"engine_slug":"mysql","sql":"-- 8.0.13+: note the double parentheses\nCREATE INDEX idx_users_email_lc ON users ((LOWER(email)));"},{"engine_slug":"sqlite","sql":"CREATE INDEX IF NOT EXISTS idx_orders_placed\nON orders (placed_at DESC)\nWHERE status <> 'cancelled';"},{"engine_slug":"oracle","sql":"CREATE INDEX idx_customers_email_lc ON customers (LOWER(email)) ONLINE;"}],"faqs":[{"question":"How do I create an index without blocking writes?","answer":"PostgreSQL: CREATE INDEX CONCURRENTLY. Oracle: CREATE INDEX ... ONLINE. SQL Server: ONLINE = ON on editions that support it. MySQL's InnoDB builds secondary indexes online by default. SQLite has no such option, so build on a quiet database."},{"question":"What is the difference between INCLUDE and an indexed column?","answer":"INCLUDE columns (SQL Server; PostgreSQL 11+ has the same clause) are stored in the index but are not part of the search key. The index can then cover a query, with no table lookup, without bloating the key or hitting key-size limits."},{"question":"Why is my function index not used?","answer":"The query must spell the expression the same way the index does. An index on LOWER(email) does not help WHERE email = 'x', only WHERE LOWER(email) = 'x'. MySQL additionally needs the double parentheses and 8.0.13+."}],"related":["drop-index","create-table","alter-table-add-column"]},"source_url":"https://sqlly.app/sql-ddl/create-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-schema","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL CREATE SCHEMA","description":"Create a schema on SQL Server, PostgreSQL, MySQL and Oracle: a namespace, MySQL's database synonym, Oracle's user-schema pairing, and SQLite's ATTACH alternative.","body":{"slug":"create-schema","name":"CREATE SCHEMA","h1":"SQL CREATE SCHEMA","category":"tables","lede":"Makes a named container for tables, views and the rest of a database. PostgreSQL and SQL Server scope it inside one database; MySQL's schema is the database; Oracle's is a user.","syntax":"CREATE SCHEMA [IF NOT EXISTS] name [AUTHORIZATION role]  -- PostgreSQL: a namespace inside the current database  |  CREATE SCHEMA name  -- SQL Server: must be the only statement in its batch  |  CREATE {DATABASE | SCHEMA} name  -- MySQL: two spellings of one statement  |  CREATE USER name IDENTIFIED BY password  -- Oracle: creating the user creates the schema  |  ATTACH DATABASE 'file.db' AS name  -- SQLite: named attached files instead of schemas","support":[{"engine_slug":"sql-server","status":"yes","note":"can also create tables, views and grants in the same statement, but only as a standalone batch"},{"engine_slug":"postgresql","status":"yes","note":"IF NOT EXISTS and AUTHORIZATION role; search_path decides which schema receives unqualified CREATE TABLE"},{"engine_slug":"mysql","status":"yes","note":"CREATE SCHEMA is a synonym for CREATE DATABASE, so the smallest container is the database"},{"engine_slug":"sqlite","status":"partial","note":"no schemas: ATTACH DATABASE names extra files on one connection, alongside the defaults main and temp"},{"engine_slug":"oracle","status":"partial","note":"a schema never exists without its user; the CREATE SCHEMA statement only creates objects inside your own schema"}],"gotchas":["SQL Server runs CREATE SCHEMA only as the first statement of a batch: put GO on the line before it in SSMS, and give it its own batch inside stored procedures. Anything earlier in the same batch fails at parse time.","MySQL has no namespace below the database: what the other engines call a schema is MySQL's whole database. Migration scripts that create one schema per tenant end up creating one database per tenant, with all the connection-string changes that follow.","Oracle's schema needs a user with a password and, to hold objects, a quota on a tablespace. There is no statement that conjures an empty container first; users are containers there, and dropping the user drops everything in it.","PostgreSQL's default search_path ($user, public) decides where an unqualified CREATE TABLE lands: a fresh schema is invisible to unqualified queries until you add it to search_path or write schema.table explicitly."],"examples":[{"engine_slug":"postgresql","sql":"CREATE SCHEMA IF NOT EXISTS billing;\nCREATE TABLE billing.invoices (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY);"},{"engine_slug":"sql-server","sql":"-- own batch, or the parse fails\nGO\nCREATE SCHEMA billing;\nGO"},{"engine_slug":"mysql","sql":"-- synonym for CREATE DATABASE\nCREATE DATABASE billing CHARACTER SET utf8mb4;"},{"engine_slug":"oracle","sql":"-- the user is the schema\nCREATE USER billing IDENTIFIED BY Str0ngPass QUOTA 1G ON users;"},{"engine_slug":"sqlite","sql":"-- named databases per connection, not schemas\nATTACH DATABASE 'billing.db' AS billing;\nCREATE TABLE billing.invoices (id INTEGER PRIMARY KEY, total_cents INTEGER NOT NULL);"}],"faqs":[{"question":"What is the difference between a schema and a database?","answer":"PostgreSQL and SQL Server: schemas are namespaces inside one database, many per database. MySQL: schema is a documented synonym for database, one and the same. Oracle: a schema is what a user owns, created and destroyed with the user. SQLite: neither, you attach files and prefix table names with the attach name."},{"question":"Why does SQL Server reject CREATE SCHEMA in my script?","answer":"It must open its batch. Any statement before it in the same batch makes the parser reject the whole thing; separate with GO or run it alone. Inside a stored procedure, run it through its own dynamic batch (EXEC)."},{"question":"How does SQLite cope without schemas?","answer":"Each connection gets main and temp plus attached files: ATTACH DATABASE 'billing.db' AS billing, with the name then working as a prefix (billing.invoices). The default limit is 10 attached databases, set by SQLITE_MAX_ATTACHED and raiseable to 125 at build time."}],"related":["drop-schema","create-table","create-sequence","temp-tables"]},"source_url":"https://sqlly.app/sql-ddl/create-schema","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-sequence","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL CREATE SEQUENCE","description":"Create a sequence on SQL Server, PostgreSQL and Oracle: standalone counters, NEXT VALUE FOR versus nextval() and .NEXTVAL, OWNED BY, and why MySQL and SQLite have none.","body":{"slug":"create-sequence","name":"CREATE SEQUENCE","h1":"SQL CREATE SEQUENCE","category":"tables","lede":"Makes a number generator that lives outside any table and hands out increasing values on demand. Three engines ship one; MySQL and SQLite build the counter into the table instead.","syntax":"CREATE SEQUENCE [IF NOT EXISTS] name [AS type] [START WITH n] [INCREMENT BY n]  -- PostgreSQL: plus MINVALUE, MAXVALUE, CYCLE, CACHE, OWNED BY  |  CREATE SEQUENCE name START WITH 1 INCREMENT BY 1  -- SQL Server, Oracle: pulled with NEXT VALUE FOR name or name.NEXTVAL  |  -- MySQL: no sequences; AUTO_INCREMENT on a key column is the counter  |  -- SQLite: no sequences; an INTEGER PRIMARY KEY column counts by itself","support":[{"engine_slug":"sql-server","status":"yes","note":"since 2012; not tied to any column, values come from NEXT VALUE FOR name"},{"engine_slug":"postgresql","status":"yes","note":"OWNED BY table.column ties the sequence's life to a column, which is what serial sets up"},{"engine_slug":"mysql","status":"no","note":"no CREATE SEQUENCE; AUTO_INCREMENT columns are the counter (MariaDB, a fork, has its own)"},{"engine_slug":"sqlite","status":"no","note":"no sequences at all; the rowid behind INTEGER PRIMARY KEY is the counter"},{"engine_slug":"oracle","status":"yes","note":"values via name.NEXTVAL, current via name.CURRVAL; from 12.1 a column DEFAULT can call it"}],"gotchas":["Sequences are transaction-proof on purpose: a rolled-back insert still burns the number, and no two sessions get the same one unless the sequence was declared CYCLE and has wrapped around. Gaps in a sequence-fed id are normal operation, not a sign of trouble.","SQL Server's sequence belongs to no column: the link is a DEFAULT expression calling NEXT VALUE FOR, and that dependency blocks dropping the sequence until you remove or alter the default. There is no OWNED BY clause.","Scripts ported between MySQL and MariaDB break quietly: MariaDB 10.3+ has CREATE SEQUENCE, real MySQL does not, so a script that runs green on one fails at parse on the other.","Oracle dispenses values in cached batches, 20 by default; an instance restart discards the unused tail of the batch and widens the gap. NOCACHE narrows the gaps at the cost of every session serializing on one counter."],"examples":[{"engine_slug":"postgresql","sql":"CREATE SEQUENCE invoice_number START WITH 1000 INCREMENT BY 1;\nSELECT nextval('invoice_number');"},{"engine_slug":"postgresql","sql":"-- serial does this wiring for you: the sequence dies with the column\nCREATE SEQUENCE order_id_seq OWNED BY orders.id;\nALTER TABLE orders ALTER COLUMN id SET DEFAULT nextval('order_id_seq');"},{"engine_slug":"sql-server","sql":"CREATE SEQUENCE dbo.invoice_number AS BIGINT START WITH 1000 INCREMENT BY 1;\n-- pull values:\nSELECT NEXT VALUE FOR dbo.invoice_number;"},{"engine_slug":"oracle","sql":"CREATE SEQUENCE invoice_number START WITH 1000 INCREMENT BY 1 NOCACHE;\nSELECT invoice_number.NEXTVAL FROM dual;"},{"engine_slug":"mysql","sql":"-- the MySQL way: the counter lives in the table\nCREATE TABLE invoices (\n  id BIGINT AUTO_INCREMENT PRIMARY KEY,\n  total_cents INT NOT NULL\n);"},{"engine_slug":"sqlite","sql":"-- the SQLite way: rowid doubles as the counter\nCREATE TABLE invoices (\n  id INTEGER PRIMARY KEY,\n  total_cents INTEGER NOT NULL\n);"}],"faqs":[{"question":"Will a sequence give me gap-free invoice numbers?","answer":"No. nextval(), NEXT VALUE FOR and .NEXTVAL all burn numbers on rollback and restarts, by design. If the business needs consecutive numbers, generate them inside the transaction that writes the row, or use a dedicated counter table with row locking."},{"question":"Sequence or identity column?","answer":"For one table's surrogate key, the built-in forms win: IDENTITY on SQL Server, GENERATED AS IDENTITY on PostgreSQL and Oracle, AUTO_INCREMENT on MySQL, INTEGER PRIMARY KEY on SQLite. A standalone sequence earns its keep when several tables share one numbering space, or when you need to reserve ranges at once (SQL Server's sp_sequence_get_range)."},{"question":"How does MySQL fill a sequence's role?","answer":"AUTO_INCREMENT: one column per table, and it must be a key (the primary key in practice). The counter lives in the table's metadata; TRUNCATE TABLE resets it, DELETE does not."}],"related":["alter-sequence","create-table","alter-table-set-default","truncate-table"]},"source_url":"https://sqlly.app/sql-ddl/create-sequence","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-table","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL CREATE TABLE","description":"CREATE TABLE across SQL Server, PostgreSQL, MySQL, SQLite and Oracle: identity columns, types, IF NOT EXISTS, and the quirks that bite in each dialect.","body":{"slug":"create-table","name":"CREATE TABLE","h1":"SQL CREATE TABLE","category":"tables","lede":"Creates a new table from a column list. Every engine writes the basic form the same way; the differences are in the types, the auto-increment clause and whether an IF NOT EXISTS guard exists.","syntax":"CREATE TABLE table_name (\n  column_name type [constraints] [, ...]\n)  |  CREATE TABLE [IF NOT EXISTS] table_name (...)  -- PostgreSQL, MySQL, SQLite","support":[{"engine_slug":"sql-server","status":"yes","note":"no IF NOT EXISTS; guard with IF OBJECT_ID(...) IS NULL, or DROP TABLE IF EXISTS (2016+) first"},{"engine_slug":"postgresql","status":"yes","note":"IF NOT EXISTS, LIKE other_table, PARTITION OF, UNLOGGED and TEMPORARY forms"},{"engine_slug":"mysql","status":"yes","note":"IF NOT EXISTS, plus ENGINE and CHARSET table options"},{"engine_slug":"sqlite","status":"yes","note":"column types are affinities, not enforced types; STRICT tables from 3.37"},{"engine_slug":"oracle","status":"yes","note":"VARCHAR2 and NUMBER; no IF NOT EXISTS clause"}],"gotchas":["Auto-increment is spelled four ways: IDENTITY(1,1) on SQL Server, GENERATED ALWAYS AS IDENTITY on PostgreSQL 10+ and Oracle 12.1+, AUTO_INCREMENT on MySQL. On SQLite, an INTEGER PRIMARY KEY column is the rowid and fills itself in.","SQLite column types are affinities rather than enforced types: an INTEGER column happily stores the string 'abc'. Declare the table STRICT (3.37+) for real type checking, at the cost of a shorter list of allowed types.","SQLite parses foreign keys but does not enforce them until the connection runs PRAGMA foreign_keys = ON. Every new connection starts with them off.","MySQL parsed CHECK constraints for years without enforcing them; real enforcement arrived in MySQL 8.0.16, so a CHECK that must hold needs a current server, not just current syntax."],"examples":[{"engine_slug":"all","sql":"CREATE TABLE customers (\n  id INTEGER PRIMARY KEY,\n  email VARCHAR(320) NOT NULL UNIQUE\n);"},{"engine_slug":"postgresql","sql":"CREATE TABLE orders (\n  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  customer_id INT NOT NULL REFERENCES customers (id),\n  placed_at TIMESTAMPTZ NOT NULL DEFAULT now()\n);"},{"engine_slug":"sql-server","sql":"-- no IF NOT EXISTS on CREATE TABLE\nIF OBJECT_ID(N'dbo.orders', N'U') IS NULL\nBEGIN\n  CREATE TABLE dbo.orders (\n    id BIGINT IDENTITY(1,1) PRIMARY KEY,\n    customer_id INT NOT NULL REFERENCES dbo.customers (id),\n    placed_at DATETIME2 NOT NULL DEFAULT SYSDATETIME()\n  );\nEND;"},{"engine_slug":"mysql","sql":"CREATE TABLE orders (\n  id BIGINT AUTO_INCREMENT PRIMARY KEY,\n  customer_id INT NOT NULL,\n  placed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)\n) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;"},{"engine_slug":"sqlite","sql":"-- INTEGER PRIMARY KEY is the rowid: it assigns values itself\nCREATE TABLE orders (\n  id INTEGER PRIMARY KEY,\n  customer_id INTEGER NOT NULL REFERENCES customers (id),\n  placed_at TEXT NOT NULL DEFAULT (datetime('now'))\n);"},{"engine_slug":"oracle","sql":"CREATE TABLE orders (\n  id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  customer_id NUMBER NOT NULL REFERENCES customers (id),\n  placed_at DATE DEFAULT SYSDATE NOT NULL\n);"}],"faqs":[{"question":"How do I create a table only if it does not exist?","answer":"PostgreSQL, MySQL and SQLite take CREATE TABLE IF NOT EXISTS directly. SQL Server has no such clause: drop first with DROP TABLE IF EXISTS (2016+), or guard the CREATE with IF OBJECT_ID(N'dbo.orders', N'U') IS NULL. Oracle has neither; wrap the CREATE in a PL/SQL block and handle the name-is-already-used exception."},{"question":"Which type do I use for auto-incrementing ids?","answer":"IDENTITY(1,1) on SQL Server, GENERATED ALWAYS AS IDENTITY on PostgreSQL 10+ and Oracle 12.1+, AUTO_INCREMENT on MySQL. On SQLite an INTEGER PRIMARY KEY column is an alias for the rowid and assigns values by itself; the AUTOINCREMENT keyword exists but is rarely needed and slightly slower."},{"question":"Does SQLite enforce the types I declare?","answer":"Not by default. Each column gets a type affinity that guides storage but does not reject other values. Declare the table STRICT (SQLite 3.37+) to have types enforced, using the small set of STRICT types."}],"related":["temp-tables","create-table-as","drop-table","alter-table-add-column","truncate-table"]},"source_url":"https://sqlly.app/sql-ddl/create-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-table-as","corpus":"sql-ddl","engine":null,"language":"en","title":"CREATE TABLE AS SELECT (CTAS)","description":"Copy a query's result into a new table: CREATE TABLE AS on PostgreSQL, MySQL, SQLite and Oracle, SELECT INTO on SQL Server, and what is never copied.","body":{"slug":"create-table-as","name":"CREATE TABLE AS","h1":"CREATE TABLE AS SELECT (CTAS)","category":"tables","lede":"Builds a new table from the rows of a SELECT. It copies data and, in most engines, almost nothing else: not primary keys, not indexes, not defaults. SQL Server spells the same move SELECT INTO.","syntax":"CREATE TABLE new_table AS SELECT ...  -- PostgreSQL, MySQL, SQLite, Oracle  |  SELECT ... INTO new_table FROM ...  -- SQL Server  |  CREATE TABLE new_table (LIKE old_table [INCLUDING ALL])  -- PostgreSQL: structure from another table","support":[{"engine_slug":"sql-server","status":"partial","note":"spelled SELECT ... INTO new_table FROM ...; there is no CREATE TABLE AS SELECT"},{"engine_slug":"postgresql","status":"yes","note":"also CREATE TEMP TABLE ... AS; (LIKE old INCLUDING ALL) copies structure more fully"},{"engine_slug":"mysql","status":"yes","note":"CREATE TABLE ... AS SELECT copies data plus NOT NULL and DEFAULT; CREATE TABLE ... LIKE copies structure only"},{"engine_slug":"sqlite","status":"yes","note":"the new table has no constraints, and column types are cut down to their affinity (INT, TEXT, NUM, REAL, or none)"},{"engine_slug":"oracle","status":"yes","note":"column types come from the query; NOT NULL is the only constraint carried over"}],"gotchas":["None of the five copies primary keys, unique keys, checks or indexes: the new table is just the data. Add the constraints and indexes afterwards with ALTER TABLE and CREATE INDEX.","On SQL Server, SELECT INTO inherits column nullability from the source and carries an identity column through only when the SELECT passes it unchanged. Defaults, keys and checks never come along.","MySQL has two copy statements people mix up: CREATE TABLE new AS SELECT copies rows with no keys or indexes, while CREATE TABLE new LIKE old copies the structure (indexes and checks included, foreign keys not) with no rows.","SQLite's CREATE TABLE AS keeps only each column's affinity as its declared type (INT, TEXT, NUM, REAL, or nothing for expressions and BLOBs) and drops every constraint, so an INTEGER PRIMARY KEY comes out as a plain INT column. When the types matter, declare the table yourself and fill it with INSERT ... SELECT."],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE orders_2026 AS\nSELECT * FROM orders WHERE placed_at >= DATE '2026-01-01';"},{"engine_slug":"sql-server","sql":"SELECT * INTO orders_2026\nFROM orders\nWHERE placed_at >= '2026-01-01';"},{"engine_slug":"mysql","sql":"-- structure and indexes, no rows:\nCREATE TABLE orders_copy LIKE orders;"},{"engine_slug":"sqlite","sql":"CREATE TABLE orders_2026 AS\nSELECT * FROM orders WHERE placed_at >= '2026-01-01';"},{"engine_slug":"oracle","sql":"CREATE TABLE orders_2026 AS\nSELECT * FROM orders WHERE placed_at >= DATE '2026-01-01';"}],"faqs":[{"question":"Does CREATE TABLE AS copy indexes and keys?","answer":"No, on all five engines. Only data carries over, plus NOT NULL flags on Oracle, SQL Server and MySQL (MySQL also keeps column defaults, and SQL Server keeps an unchanged IDENTITY column). Recreate the keys and indexes afterwards, which is also your chance to build them in bulk after the load instead of maintaining them row by row."},{"question":"How do I copy a table's structure without its data?","answer":"MySQL: CREATE TABLE new LIKE old. PostgreSQL: CREATE TABLE new (LIKE old INCLUDING ALL). SQL Server: SELECT * INTO new FROM old WHERE 1 = 0. SQLite: declare the table yourself, because CREATE TABLE AS keeps only type affinities and no constraints."},{"question":"Can CREATE TABLE AS be rolled back?","answer":"On SQL Server, PostgreSQL and SQLite, yes: the statement runs inside the transaction like any other. MySQL and Oracle commit implicitly around DDL, so once the statement succeeds the new table stays even if the surrounding transaction rolls back."}],"related":["create-table","truncate-table","temp-tables"]},"source_url":"https://sqlly.app/sql-ddl/create-table-as","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/create-view","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL CREATE VIEW","description":"CREATE VIEW on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: OR REPLACE support, frozen column lists, WITH CHECK OPTION, and how each engine redefines a view.","body":{"slug":"create-view","name":"CREATE VIEW","h1":"SQL CREATE VIEW","category":"views","lede":"Stores a named query that you can select from like a table. Most engines take CREATE OR REPLACE VIEW; SQL Server instead has CREATE OR ALTER VIEW, and SQLite has neither.","syntax":"CREATE VIEW view_name [(column_aliases)] AS SELECT ...  |  CREATE OR REPLACE VIEW view_name AS SELECT ...  -- PostgreSQL, MySQL, Oracle  |  CREATE OR ALTER VIEW view_name AS SELECT ...  -- SQL Server 2016 SP1+","support":[{"engine_slug":"sql-server","status":"partial","note":"no OR REPLACE; CREATE OR ALTER VIEW from 2016 SP1"},{"engine_slug":"postgresql","status":"yes","note":"OR REPLACE keeps permissions; existing output columns are frozen"},{"engine_slug":"mysql","status":"yes","note":"OR REPLACE, plus ALGORITHM, DEFINER and WITH CHECK OPTION"},{"engine_slug":"sqlite","status":"partial","note":"read-only; no OR REPLACE and no ALTER VIEW"},{"engine_slug":"oracle","status":"yes","note":"OR REPLACE; FORCE creates the view even while base objects are missing"}],"gotchas":["SQL Server has no CREATE OR REPLACE VIEW. Use CREATE OR ALTER VIEW (2016 SP1+) or drop-and-create; a plain CREATE fails once the view exists, which breaks re-runnable migration scripts.","PostgreSQL's OR REPLACE cannot change existing output columns: the names, order and types of the original column list are frozen, and you may only append new ones. Changing a column's type means DROP VIEW and CREATE again.","SQLite views are read-only stored queries with no OR REPLACE and no ALTER VIEW: redefine by DROP VIEW then CREATE VIEW, ideally in one transaction so no reader sees the view missing.","MySQL's WITH CHECK OPTION makes writes through the view reject rows the view would not show; without it an UPDATE through a filtered view can move a row out of its own view. PostgreSQL accepts WITH CHECK OPTION on updatable views too."],"examples":[{"engine_slug":"all","sql":"CREATE VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders\nWHERE status = 'open';"},{"engine_slug":"postgresql","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders\nWHERE status = 'open';"},{"engine_slug":"sql-server","sql":"CREATE OR ALTER VIEW dbo.open_orders\nAS\nSELECT id, customer_id, placed_at, total\nFROM dbo.orders\nWHERE status = 'open';"},{"engine_slug":"mysql","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open'\nWITH CHECK OPTION;"},{"engine_slug":"oracle","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, total FROM orders WHERE status = 'open';"}],"faqs":[{"question":"How do I change a view's definition?","answer":"CREATE OR REPLACE VIEW on PostgreSQL, MySQL and Oracle; CREATE OR ALTER VIEW on SQL Server 2016 SP1+; DROP VIEW then CREATE VIEW on SQLite (and anywhere else, if you prefer one portable habit)."},{"question":"Can I insert or update rows through a view?","answer":"On simple single-table views, yes: MySQL, PostgreSQL, SQL Server and Oracle accept writes through views that stay within the base table's rules, subject to WITH CHECK OPTION when declared. SQLite views are read-only unless an INSTEAD OF trigger handles the write. Views over aggregates reject writes everywhere. Join views differ: PostgreSQL rejects them, while MySQL and SQL Server accept a write that changes only one base table. INSTEAD OF triggers on PostgreSQL, SQL Server, Oracle and SQLite can translate the rest; MySQL has none."},{"question":"Do views make queries faster?","answer":"No: a plain view is a stored query, and every use re-runs it. PostgreSQL and Oracle have materialized views that store the result, and SQL Server has indexed views. On MySQL and SQLite, build and refresh a summary table yourself."}],"related":["alter-view","drop-view","create-table"]},"source_url":"https://sqlly.app/sql-ddl/create-view","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-foreign-key","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE DROP FOREIGN KEY","description":"Drop a foreign key on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: always by constraint name, MySQL's separate clause, the index MySQL leaves behind, rebuilds.","body":{"slug":"drop-foreign-key","name":"DROP FOREIGN KEY","h1":"ALTER TABLE DROP FOREIGN KEY","category":"tables","lede":"Removes the reference check and nothing else: the data stays, the columns stay. Every engine drops by name; MySQL has its own clause (8.0.19+ also takes DROP CONSTRAINT) and leaves a souvenir index.","syntax":"ALTER TABLE t DROP CONSTRAINT fk_name  -- SQL Server, PostgreSQL, Oracle, MySQL 8.0.19+; SQL Server takes IF EXISTS from 2016  |  ALTER TABLE t DROP FOREIGN KEY fk_name  -- MySQL's own clause, the only form before 8.0.19; no IF EXISTS  |  -- SQLite: no DROP CONSTRAINT; rebuild the table without the reference","support":[{"engine_slug":"sql-server","status":"yes","note":"DROP CONSTRAINT fk_name; find generated names in sys.foreign_keys"},{"engine_slug":"postgresql","status":"yes","note":"DROP CONSTRAINT fk_name; no dependants to worry about, a foreign key is a leaf"},{"engine_slug":"mysql","status":"yes","note":"DROP FOREIGN KEY fk_name; the index InnoDB built for it stays"},{"engine_slug":"sqlite","status":"no","note":"the reference is part of the table definition; rebuild to remove it"},{"engine_slug":"oracle","status":"yes","note":"DROP CONSTRAINT fk_name, by name"}],"gotchas":["MySQL's DROP FOREIGN KEY leaves the index InnoDB created for the constraint in place; it is retired only if you later build another index that can serve a foreign key on those columns. The reverse fails while the constraint lives: MySQL refuses to drop an index the constraint still needs.","The name is the whole game: four of five engines generate names for unnamed constraints (MySQL's look like orders_ibfk_1, SQL Server's like FK__orders__customer__7). Find them before scripting the drop; sys.foreign_keys, information_schema and user_constraints all list them.","Dropping the constraint changes no data: rows that already point at missing parents keep pointing. If the goal was to delete parents the constraint was blocking, the orphan cleanup is on you afterwards.","The drop itself is catalog-only, but re-adding the constraint later validates every existing row (PostgreSQL reads the referencing and the referenced table in full to do it), so a drop-then-re-add cycle on a large table is not free. On PostgreSQL, re-add with NOT VALID and run VALIDATE CONSTRAINT later: the scan is the same size, but it holds only a SHARE UPDATE EXCLUSIVE lock, so writes keep running during the check."],"examples":[{"engine_slug":"sql-server","sql":"-- find the name, then drop\nSELECT fk.name\nFROM sys.foreign_keys AS fk\nWHERE fk.parent_object_id = OBJECT_ID(N'dbo.orders');\nALTER TABLE dbo.orders DROP CONSTRAINT fk_orders_customer;"},{"engine_slug":"postgresql","sql":"ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;"},{"engine_slug":"mysql","sql":"-- drop the constraint, then the index if you do not want it\nALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;\nALTER TABLE orders DROP INDEX fk_orders_customer;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;"},{"engine_slug":"sqlite","sql":"-- rebuild without the FOREIGN KEY clause; run PRAGMA foreign_keys = OFF\n-- before BEGIN (it is a no-op inside a transaction), then wrap the copy in one"}],"faqs":[{"question":"How do I find a foreign key's name?","answer":"SQL Server: sys.foreign_keys filtered by parent_object_id. MySQL: SHOW CREATE TABLE orders, or information_schema.referential_constraints. PostgreSQL: information_schema or pg_constraint WHERE contype = 'f'. Oracle: user_constraints WHERE constraint_type = 'R'."},{"question":"Why can I not drop the index on my MySQL foreign key column?","answer":"InnoDB needs an index on the referencing columns to enforce the constraint, so it blocks the DROP INDEX while the constraint exists. Drop the foreign key first, then the index, or keep the index: it still speeds joins and lookups on that column."},{"question":"Will dropping a foreign key delete or fix orphaned rows?","answer":"No. The statement is catalog-only: no rows are checked, changed or deleted. Rows referencing missing parents stay as they are, so run your own anti-join cleanup if that is why the constraint is going."}],"related":["add-foreign-key","drop-primary-key","drop-index","create-table"]},"source_url":"https://sqlly.app/sql-ddl/drop-foreign-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-index","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL DROP INDEX","description":"Drop an index on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the ON table clauses, DROP INDEX CONCURRENTLY, IF EXISTS, and constraint-backed indexes.","body":{"slug":"drop-index","name":"DROP INDEX","h1":"SQL DROP INDEX","category":"indexes","lede":"Removes an index and its space. The syntax split is real: two engines say which table the index is on, three do not, and every engine but MySQL refuses to drop the index that backs a key constraint.","syntax":"DROP INDEX index_name ON table_name  -- SQL Server, MySQL  |  DROP INDEX [IF EXISTS] index_name  -- SQLite, Oracle 23c+  |  DROP INDEX [CONCURRENTLY] [IF EXISTS] index_name  -- PostgreSQL","support":[{"engine_slug":"sql-server","status":"yes","note":"DROP INDEX name ON table; IF EXISTS from 2016"},{"engine_slug":"postgresql","status":"yes","note":"CONCURRENTLY drops without blocking writes; schema-wide names"},{"engine_slug":"mysql","status":"yes","note":"DROP INDEX name ON table, or ALTER TABLE t DROP INDEX name"},{"engine_slug":"sqlite","status":"yes","note":"IF EXISTS; index names are database-wide"},{"engine_slug":"oracle","status":"partial","note":"constraint-backed indexes refuse: drop or disable the constraint instead"}],"gotchas":["MySQL and SQL Server need the table name in the statement (DROP INDEX idx ON t); PostgreSQL, SQLite and Oracle do not, because their index names are already unique in the schema or database.","The index behind a PRIMARY KEY or UNIQUE constraint belongs to the constraint on SQL Server (error 3723), PostgreSQL (\"constraint ... requires it\"), SQLite (\"index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped\") and Oracle. DROP INDEX fails; drop the constraint (Oracle also lets you disable it) and the index goes with it. MySQL is the exception: DROP INDEX on a UNIQUE key, or on PRIMARY, removes the constraint too.","PostgreSQL's DROP INDEX CONCURRENTLY, like CREATE INDEX CONCURRENTLY, keeps reads and writes flowing while the index is removed, at the cost of taking longer, being unusable inside a transaction block, and dropping only one index per statement with no CASCADE.","IF EXISTS arrived in SQL Server 2016 and Oracle 23c; PostgreSQL and SQLite have had it for years. MySQL still has none, so MySQL scripts either catch the error or check information_schema.statistics first."],"examples":[{"engine_slug":"postgresql","sql":"DROP INDEX CONCURRENTLY IF EXISTS idx_orders_placed;"},{"engine_slug":"sql-server","sql":"DROP INDEX IF EXISTS idx_orders_placed ON dbo.orders;"},{"engine_slug":"mysql","sql":"DROP INDEX idx_orders_placed ON orders;"},{"engine_slug":"sqlite","sql":"DROP INDEX IF EXISTS idx_orders_placed;"},{"engine_slug":"oracle","sql":"DROP INDEX idx_orders_placed;"}],"faqs":[{"question":"How do I drop an index without blocking queries?","answer":"PostgreSQL's DROP INDEX CONCURRENTLY is the clean option. MySQL's InnoDB drops secondary indexes online. Oracle's and SQL Server's drops of a nonclustered index are quick; dropping a SQL Server clustered index turns the table into a heap and rebuilds its nonclustered indexes, so use WITH (ONLINE = ON) there. SQLite blocks, so drop in a quiet window."},{"question":"What happens to queries that used the index?","answer":"They keep running, just slower: the planner falls back to another index or a table scan. Nothing breaks; the cost shows up in the slow-query log days later, which is why it pays to confirm an index is unused before dropping it."},{"question":"Why can I not drop this index?","answer":"It enforces a PRIMARY KEY or UNIQUE constraint. On SQL Server, PostgreSQL, SQLite and Oracle the index belongs to the constraint, so drop the constraint (on Oracle, or disable it) and the index disappears with it. MySQL lets DROP INDEX remove the constraint directly."}],"related":["create-index","create-table","truncate-table"]},"source_url":"https://sqlly.app/sql-ddl/drop-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-primary-key","corpus":"sql-ddl","engine":null,"language":"en","title":"ALTER TABLE DROP PRIMARY KEY","description":"Drop a primary key on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: constraint names, MySQL's AUTO_INCREMENT rule, foreign keys pointing at the key, rebuilds.","body":{"slug":"drop-primary-key","name":"DROP PRIMARY KEY","h1":"ALTER TABLE DROP PRIMARY KEY","category":"tables","lede":"Removes the table's key. MySQL has a nameless clause, PostgreSQL and Oracle offer CASCADE, and SQL Server wants the constraint name plus an empty dependency list.","syntax":"ALTER TABLE t DROP CONSTRAINT pk_name  -- SQL Server, PostgreSQL; SQL Server takes IF EXISTS from 2016  |  ALTER TABLE t DROP PRIMARY KEY  -- MySQL: nameless, the key is literally called PRIMARY  |  ALTER TABLE t DROP PRIMARY KEY CASCADE  -- Oracle: add KEEP INDEX to spare the backing index  |  -- SQLite: no DROP CONSTRAINT; rebuild the table without the key","support":[{"engine_slug":"sql-server","status":"yes","note":"drop by constraint name; if the key was clustered the table reverts to a heap"},{"engine_slug":"postgresql","status":"yes","note":"RESTRICT is the default: the drop refuses while foreign keys reference the key, CASCADE removes them"},{"engine_slug":"mysql","status":"yes","note":"DROP PRIMARY KEY; an AUTO_INCREMENT column with no other index must lose that attribute in the same statement"},{"engine_slug":"sqlite","status":"no","note":"no DROP CONSTRAINT; rebuild the table"},{"engine_slug":"oracle","status":"yes","note":"DROP CONSTRAINT name or DROP PRIMARY KEY; the backing index goes too unless you add KEEP INDEX"}],"gotchas":["MySQL refuses to drop the primary key when it is the only index on the AUTO_INCREMENT column, because every auto-increment column must sit in a key (error 1075). Remove the attribute and the key in one statement: ALTER TABLE t MODIFY id BIGINT NOT NULL, DROP PRIMARY KEY.","PostgreSQL's CASCADE drops every foreign key that references the key, here and on other tables, and reports them in a single NOTICE (drop cascades to N other objects) with one DETAIL line per constraint. Without it, the default RESTRICT behaviour fails the statement while references exist.","SQL Server checks references too: every foreign key pointing at the key must be dropped first, and disabling it with NOCHECK does not help (error 3725 either way). And when the key was the clustered index, dropping it turns the table back into a heap, which changes storage and can hurt range scans.","Oracle's KEEP INDEX keeps the backing index and its statistics while dropping the constraint, which is the cheap path when you plan to re-add a key over the same columns."],"examples":[{"engine_slug":"sql-server","sql":"-- find the name, then drop it\nSELECT kc.name\nFROM sys.key_constraints AS kc\nWHERE kc.parent_object_id = OBJECT_ID(N'dbo.orders') AND kc.type = 'PK';\nALTER TABLE dbo.orders DROP CONSTRAINT pk_orders;"},{"engine_slug":"postgresql","sql":"ALTER TABLE orders DROP CONSTRAINT pk_orders;\n-- or take the referencing foreign keys down with it:\nALTER TABLE orders DROP CONSTRAINT pk_orders CASCADE;"},{"engine_slug":"mysql","sql":"-- AUTO_INCREMENT blocks the drop; remove it in the same ALTER\nALTER TABLE orders MODIFY id BIGINT NOT NULL, DROP PRIMARY KEY;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders DROP PRIMARY KEY;\n-- keep the index for a quick re-add later:\nALTER TABLE orders DROP PRIMARY KEY KEEP INDEX;"},{"engine_slug":"sqlite","sql":"-- rebuild without the key; PRAGMA foreign_keys is ignored inside\n-- a transaction, so turn it off before BEGIN\nPRAGMA foreign_keys = OFF;\nBEGIN;\nCREATE TABLE orders_new (id INTEGER NOT NULL, total NUMERIC);\nINSERT INTO orders_new (id, total) SELECT id, total FROM orders;\nDROP TABLE orders;\nALTER TABLE orders_new RENAME TO orders;\nCOMMIT;\nPRAGMA foreign_keys = ON;"}],"faqs":[{"question":"How do I find my primary key's constraint name?","answer":"SQL Server: sys.key_constraints WHERE type = 'PK' and parent_object_id = OBJECT_ID(N'dbo.orders'). PostgreSQL: psql's \\d orders, or pg_constraint WHERE contype = 'p'. Oracle: user_constraints WHERE constraint_type = 'P'. MySQL: no name to find, the clause is DROP PRIMARY KEY."},{"question":"Why can I not drop the primary key on my MySQL auto-increment column?","answer":"MySQL allows one AUTO_INCREMENT column per table and it must be part of a key. Dropping the key would leave the column unkeyed, so the server refuses. Strip the attribute with MODIFY in the same ALTER TABLE and the drop goes through."},{"question":"What happens to foreign keys that point at the key?","answer":"PostgreSQL and Oracle drop them with CASCADE, or refuse without it. SQL Server and MySQL refuse until you drop the referencing foreign keys yourself. The child rows are untouched either way; only the checks disappear."}],"related":["add-primary-key","drop-foreign-key","add-unique-constraint","alter-table-drop-column"]},"source_url":"https://sqlly.app/sql-ddl/drop-primary-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-schema","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL DROP SCHEMA","description":"Drop a schema on SQL Server, PostgreSQL, MySQL and Oracle: empty-first rules, PostgreSQL's CASCADE, MySQL's whole-database drop, Oracle's user, SQLite's DETACH.","body":{"slug":"drop-schema","name":"DROP SCHEMA","h1":"SQL DROP SCHEMA","category":"tables","lede":"Removes a named container. PostgreSQL guards its contents behind CASCADE, SQL Server refuses until you empty it, and MySQL removes the database and everything in it.","syntax":"DROP SCHEMA [IF EXISTS] name [CASCADE | RESTRICT]  -- PostgreSQL: CASCADE takes the contents with it  |  DROP SCHEMA [IF EXISTS] name  -- SQL Server: only drops an empty schema; IF EXISTS from 2016  |  DROP {DATABASE | SCHEMA} [IF EXISTS] name  -- MySQL: drops the database and every table in it  |  DROP USER name CASCADE  -- Oracle: the schema goes with the user  |  DETACH DATABASE name  -- SQLite: forgets an attached file, the file stays","support":[{"engine_slug":"sql-server","status":"yes","note":"fails while the schema contains any object; drop them or move them out first"},{"engine_slug":"postgresql","status":"yes","note":"RESTRICT (the default) refuses a non-empty schema; CASCADE drops everything inside, following dependencies"},{"engine_slug":"mysql","status":"yes","note":"DROP DATABASE by another name: every table and the data with them, no confirmation"},{"engine_slug":"sqlite","status":"partial","note":"nothing to drop; DETACH DATABASE removes the alias from the connection, the file survives"},{"engine_slug":"oracle","status":"partial","note":"DROP USER name; CASCADE is required once the user owns any object"}],"gotchas":["MySQL's DROP SCHEMA has no empty-check: the statement deletes every table and its data in one shot. IF EXISTS only spares you a missing-name error; it never asks about contents.","PostgreSQL's CASCADE reaches further than the schema's own listing: it also drops objects in other schemas that depend on the doomed ones, such as views and foreign key constraints. One NOTICE reports the count and its DETAIL lists each object, but only the first 100; past that the rest are only in the server log. Read the DETAIL, or run plain DROP SCHEMA first, which fails and prints the same list without dropping anything.","SQL Server is the opposite temperament: it refuses while any object remains. The escape hatch is ALTER SCHEMA dbo TRANSFER billing.invoices, which moves an object between schemas without dropping it.","Oracle's DROP USER CASCADE is one statement with no checkpoint: every table, index, view and grant in the schema is gone when it returns, so export anything worth keeping first."],"examples":[{"engine_slug":"postgresql","sql":"DROP SCHEMA IF EXISTS staging CASCADE;"},{"engine_slug":"sql-server","sql":"-- empty first, then drop\nDROP TABLE billing.invoices;\nDROP SCHEMA billing;"},{"engine_slug":"mysql","sql":"-- drops the database and all its tables\nDROP DATABASE IF EXISTS staging;"},{"engine_slug":"oracle","sql":"DROP USER staging CASCADE;"},{"engine_slug":"sqlite","sql":"-- the alias goes, billing.db stays on disk\nDETACH DATABASE billing;"}],"faqs":[{"question":"How do I empty a SQL Server schema before dropping it?","answer":"List what is in it with SELECT name, type_desc FROM sys.objects WHERE schema_id = SCHEMA_ID(N'billing'), then check sys.types and sys.xml_schema_collections with the same schema_id filter, because user types and XML schema collections also block the drop and sys.objects does not show them. Drop each object, or move it with ALTER SCHEMA dbo TRANSFER billing.invoices (TRANSFER TYPE::billing.name for a type). Only then does DROP SCHEMA run."},{"question":"Does DROP SCHEMA delete the data files?","answer":"Only in MySQL, where the schema is the database and the drop removes its storage. PostgreSQL and SQL Server drop objects inside one database and keep the database itself. Oracle drops the user's objects with CASCADE. SQLite's DETACH deletes nothing: the file stays on disk."},{"question":"What is the difference between RESTRICT and CASCADE?","answer":"PostgreSQL's choice: RESTRICT (the default) fails while anything still lives in the schema or depends on it; CASCADE removes the contents and dependent objects too. SQL Server always behaves like RESTRICT, MySQL always like CASCADE."}],"related":["create-schema","drop-table","drop-view","create-sequence"]},"source_url":"https://sqlly.app/sql-ddl/drop-schema","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-table","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL DROP TABLE","description":"Drop a table on all five engines: IF EXISTS support per engine, foreign key refusals, CASCADE on PostgreSQL, and Oracle's recycle bin before the space is freed.","body":{"slug":"drop-table","name":"DROP TABLE","h1":"SQL DROP TABLE","category":"tables","lede":"Deletes a table together with its data, indexes and triggers. The differences worth knowing: which engines take IF EXISTS, what happens to foreign keys and views, and where Oracle parks the table first.","syntax":"DROP TABLE [IF EXISTS] table_name  |  DROP TABLE table_name CASCADE  -- PostgreSQL: drops dependent views and constraints too  |  DROP TABLE table_name PURGE  -- Oracle: skip the recycle bin","support":[{"engine_slug":"sql-server","status":"yes","note":"IF EXISTS from SQL Server 2016"},{"engine_slug":"postgresql","status":"yes","note":"RESTRICT is the default; CASCADE takes dependent objects with it"},{"engine_slug":"mysql","status":"yes","note":"several tables in one statement; FOREIGN_KEY_CHECKS = 0 overrides refusals"},{"engine_slug":"sqlite","status":"yes","note":"IF EXISTS; dropping a table drops its indexes and triggers with it"},{"engine_slug":"oracle","status":"yes","note":"lands in the recycle bin first; PURGE drops for real; IF EXISTS from 23c"}],"gotchas":["SQL Server refuses to drop a table that a foreign key references: drop the constraint or the referencing table first. PostgreSQL's CASCADE does it for you, dropping dependent views and the referencing foreign key constraints (the referencing tables stay) with nothing more than a NOTICE listing them, which is exactly why it should be typed deliberately.","Oracle does not free the space immediately: a dropped table sits in the recycle bin as a BIN$ name, still counting against your quota, until PURGE or space pressure removes it. FLASHBACK TABLE ... TO BEFORE DROP can bring it back; DROP TABLE ... PURGE skips the bin.","IF EXISTS arrived in SQL Server 2016 and Oracle 23c; PostgreSQL, MySQL and SQLite have had it for years. On anything older, query the catalog first or catch the error.","MySQL's DROP TABLE takes a list and, with IF EXISTS, reports a warning rather than an error for names that do not exist, which makes cleanup scripts simple: DROP TABLE IF EXISTS a, b, c."],"examples":[{"engine_slug":"all","sql":"DROP TABLE IF EXISTS stage_orders;"},{"engine_slug":"postgresql","sql":"DROP TABLE orders_archive CASCADE; -- dependent views go too"},{"engine_slug":"oracle","sql":"DROP TABLE orders_archive PURGE; -- do not park it in the recycle bin"},{"engine_slug":"mysql","sql":"DROP TABLE IF EXISTS tmp_a, tmp_b, tmp_c;"}],"faqs":[{"question":"What is the difference between DROP TABLE and TRUNCATE TABLE?","answer":"TRUNCATE empties the table and keeps the definition, indexes and permissions. DROP removes the whole object; you get it back only by recreating it, or on Oracle with flashback drop while the recycle bin still holds it. Truncate to reload, drop to remove."},{"question":"Can I undo a DROP TABLE?","answer":"Inside an open transaction on SQL Server, PostgreSQL or SQLite, ROLLBACK undoes it, because DDL is transactional there. MySQL and Oracle commit DDL implicitly, so the recovery paths are backups or, on Oracle, FLASHBACK TABLE ... TO BEFORE DROP while the recycle bin still holds the table."},{"question":"Why does DROP TABLE fail with a foreign key error?","answer":"Another table's foreign key points at this one. Drop the constraint or the referencing table first; on PostgreSQL, DROP TABLE ... CASCADE does it in one statement, and on MySQL, FOREIGN_KEY_CHECKS = 0 for the session is the blunt-instrument version."}],"related":["truncate-table","rename-table","create-table"]},"source_url":"https://sqlly.app/sql-ddl/drop-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/drop-view","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL DROP VIEW","description":"Drop a view on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: IF EXISTS everywhere but old Oracle, CASCADE on PostgreSQL, and multiple views per statement.","body":{"slug":"drop-view","name":"DROP VIEW","h1":"SQL DROP VIEW","category":"views","lede":"Removes a saved query. Nothing that reads the base tables is touched; the only casualties are things that read the view itself, and engines disagree about how loudly they complain.","syntax":"DROP VIEW [IF EXISTS] view_name [, ...]  |  DROP VIEW view_name [RESTRICT | CASCADE]  -- PostgreSQL","support":[{"engine_slug":"sql-server","status":"yes","note":"IF EXISTS from 2016; several views comma-separated"},{"engine_slug":"postgresql","status":"yes","note":"RESTRICT by default; CASCADE removes dependent views"},{"engine_slug":"mysql","status":"yes","note":"several views per statement; IF EXISTS logs a note instead of failing"},{"engine_slug":"sqlite","status":"yes","note":"IF EXISTS; one view per statement"},{"engine_slug":"oracle","status":"yes","note":"IF EXISTS from 23c"}],"gotchas":["PostgreSQL is the one that checks dependencies by default: RESTRICT (the default) fails the drop when another view depends on it, and CASCADE removes the dependents too. SQL Server, MySQL, SQLite and Oracle let the drop through and leave dependent views broken until someone recreates what they needed; SQL Server refuses the drop only when a dependent view was created WITH SCHEMABINDING.","Oracle's recycle bin holds dropped tables, not views, so a dropped view is gone unless you kept the definition scripted somewhere.","MySQL's DROP VIEW IF EXISTS v1, v2, v3 reports a warning for each missing name instead of failing, which makes it a tidy closer for migration scripts.","Dropping a view never drops its base tables; the risk runs the other way (drop the table and the view breaks). Keep view definitions in source control, since no engine offers an undo once the drop is committed (PostgreSQL, SQL Server and SQLite can still roll it back inside an open transaction)."],"examples":[{"engine_slug":"all","sql":"DROP VIEW IF EXISTS open_orders;"},{"engine_slug":"postgresql","sql":"DROP VIEW open_orders CASCADE; -- dependent views go too"},{"engine_slug":"mysql","sql":"DROP VIEW IF EXISTS v_tmp1, v_tmp2;"},{"engine_slug":"sql-server","sql":"DROP VIEW IF EXISTS dbo.open_orders;"}],"faqs":[{"question":"Does DROP VIEW delete any data?","answer":"No. A view stores a query, not rows, so dropping it removes only the definition. The base tables and their data stay exactly as they were."},{"question":"How do I drop a view only if it exists?","answer":"DROP VIEW IF EXISTS works on SQL Server 2016+, PostgreSQL, MySQL, SQLite and Oracle 23c+. Older engines need a catalog check first or a caught error."},{"question":"What happens to views built on a dropped view?","answer":"On PostgreSQL the drop fails unless you add CASCADE, which removes the dependents deliberately. On SQL Server, MySQL, SQLite and Oracle the drop succeeds, and the dependent views fail with an error the next time they are used (SQL Server: invalid object name; MySQL: error 1356, invalid table or column). The exception is a SQL Server view created WITH SCHEMABINDING, which blocks the drop outright."}],"related":["create-view","alter-view","drop-table"]},"source_url":"https://sqlly.app/sql-ddl/drop-view","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/rename-table","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL RENAME TABLE","description":"Rename a table on SQL Server (sp_rename), PostgreSQL, MySQL, SQLite and Oracle, and what each engine does to views, procedures and foreign keys that point at it.","body":{"slug":"rename-table","name":"RENAME TABLE","h1":"SQL RENAME TABLE","category":"tables","lede":"Changes a table's name in place. The statement is easy; the interesting part is what happens to the objects that referenced the old name, and that answer differs more than you would expect.","syntax":"ALTER TABLE old_name RENAME TO new_name  -- PostgreSQL, SQLite, Oracle, MySQL  |  RENAME TABLE old_name TO new_name  -- MySQL, several tables in one statement  |  EXEC sp_rename 'dbo.old_name', 'new_name'  -- SQL Server","support":[{"engine_slug":"sql-server","status":"yes","note":"EXEC sp_rename 'old', 'new'; there is no ALTER TABLE RENAME"},{"engine_slug":"postgresql","status":"yes","note":"views and foreign keys follow the rename automatically"},{"engine_slug":"mysql","status":"yes","note":"RENAME TABLE a TO b, c TO d renames several tables in one atomic statement"},{"engine_slug":"sqlite","status":"yes","note":"since 3.25, references inside views and triggers are updated too"},{"engine_slug":"oracle","status":"yes","note":"ALTER TABLE old RENAME TO new, or the RENAME old TO new statement"}],"gotchas":["SQL Server's sp_rename changes the name but not the text of views, procedures or functions that mention it. Those modules bind by name, so after the rename they fail with Msg 208 (Invalid object name) until you edit them; only foreign keys, which bind by object id, follow the rename. Renaming a column breaks them the same way (Msg 207), a schema-bound view blocks the rename outright (Msg 15336), and every sp_rename prints a warning to this effect.","PostgreSQL views and foreign keys follow the rename on their own, because they reference the table's internal id rather than its name. Functions are the exception: SQL and PL/pgSQL bodies written as strings keep the old name and fail with relation does not exist; only BEGIN ATOMIC function bodies are rewritten.","SQLite 3.25+ updates references to the table inside views and triggers as part of the rename; older builds left them stale, and the legacy_alter_table pragma recreates that old behaviour. Apple's macOS build of sqlite3 turns that pragma on by default, so run PRAGMA legacy_alter_table = OFF there first.","Oracle views and PL/SQL units that spell the old name go invalid on the rename and stay broken until you recreate or recompile them against the new name."],"examples":[{"engine_slug":"postgresql","sql":"ALTER TABLE orders RENAME TO orders_archive;"},{"engine_slug":"mysql","sql":"RENAME TABLE orders TO orders_archive, orders_new TO orders;"},{"engine_slug":"sql-server","sql":"EXEC sp_rename 'dbo.orders', 'orders_archive';"},{"engine_slug":"sqlite","sql":"ALTER TABLE orders RENAME TO orders_archive;"},{"engine_slug":"oracle","sql":"ALTER TABLE orders RENAME TO orders_archive;"}],"faqs":[{"question":"Does renaming a table break views and stored procedures?","answer":"On SQL Server, MySQL and Oracle, yes: their definitions still spell the old name, so SQL Server views, procedures and functions fail with Invalid object name, MySQL views fail with error 1356 and procedures with 1146, and Oracle marks dependents invalid. PostgreSQL rewrites views and foreign keys (but not functions whose body is a string), and SQLite 3.25+ rewrites views and triggers."},{"question":"How do I swap two table names?","answer":"MySQL takes it in one atomic statement: RENAME TABLE orders TO tmp, orders_new TO orders, tmp TO orders_new. SQL Server, PostgreSQL and SQLite run the same three renames inside one transaction, so other sessions never see a missing name. Oracle commits each DDL statement, so there you accept a brief window where one name is missing."},{"question":"Why does sp_rename warn me?","answer":"Because it only changes the name. Foreign keys and other objects that bind by id keep working, but every view, procedure and function that stored the old name as text now fails with Invalid object name until you edit it. Search sys.sql_modules for the old name after renaming."}],"related":["drop-table","create-table","alter-view"]},"source_url":"https://sqlly.app/sql-ddl/rename-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/temp-tables","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL temporary tables","description":"Temporary tables on SQL Server (#temp), PostgreSQL, MySQL, SQLite and Oracle: scope, cleanup, ON COMMIT behaviour and how Oracle's version differs.","body":{"slug":"temp-tables","name":"Temporary tables","h1":"SQL temporary tables","category":"tables","lede":"A table that lives only for your session or transaction. Four engines create ad-hoc temp tables with one statement; Oracle instead pre-creates a table whose data is private to each session.","syntax":"CREATE TEMPORARY TABLE table_name (...)  -- PostgreSQL, MySQL, SQLite  |  CREATE TEMP TABLE table_name (...)  -- PostgreSQL, SQLite  |  #table_name  -- SQL Server: the # prefix makes it session-local  |  CREATE GLOBAL TEMPORARY TABLE table_name (...) ON COMMIT {PRESERVE | DELETE} ROWS  -- Oracle","support":[{"engine_slug":"sql-server","status":"yes","note":"#name is session-local, ##name is global; both live in tempdb"},{"engine_slug":"postgresql","status":"yes","note":"ON COMMIT DROP, DELETE ROWS or PRESERVE ROWS; temp tables live in the pg_temp schema"},{"engine_slug":"mysql","status":"yes","note":"CREATE TEMPORARY TABLE; dropped when the session ends; no foreign keys"},{"engine_slug":"sqlite","status":"yes","note":"CREATE TEMP TABLE; one temp database per connection"},{"engine_slug":"oracle","status":"partial","note":"no ad-hoc temp tables: GLOBAL TEMPORARY (pre-created, session-private data) or PRIVATE TEMPORARY (18c+)"}],"gotchas":["SQL Server names temp tables with a leading #: #orders is visible only to your session, ##orders to everyone. Two sessions can each create their own #orders; two sessions cannot both own ##orders.","PostgreSQL temp tables are dropped at the end of the session. ON COMMIT DROP drops one at the end of the transaction instead, and ON COMMIT DELETE ROWS empties it at every commit while keeping the table. Outside an explicit transaction each statement commits on its own, so an ON COMMIT DROP table is gone before the next statement can read it.","Oracle's GLOBAL TEMPORARY TABLE is created once, like a permanent table: the definition is shared and the rows are private per session. The row lifecycle is fixed at creation with ON COMMIT DELETE ROWS or PRESERVE ROWS.","MySQL temporary tables do not support foreign keys, and they are visible only to the session that made them, so two connections can use the same name without colliding."],"examples":[{"engine_slug":"sql-server","sql":"SELECT customer_id, COUNT(*) AS orders\nINTO #big_customers\nFROM orders\nGROUP BY customer_id\nHAVING COUNT(*) > 100;\n\nSELECT * FROM #big_customers; -- gone when the session ends"},{"engine_slug":"postgresql","sql":"BEGIN;\nCREATE TEMP TABLE big_customers ON COMMIT DROP AS\nSELECT customer_id FROM orders\nGROUP BY customer_id HAVING COUNT(*) > 100;\n\nSELECT * FROM big_customers;\nCOMMIT; -- big_customers is dropped here"},{"engine_slug":"mysql","sql":"CREATE TEMPORARY TABLE tmp_stage (\n  id BIGINT PRIMARY KEY,\n  email VARCHAR(320)\n);\n\nDROP TEMPORARY TABLE tmp_stage; -- or let the session end do it"},{"engine_slug":"sqlite","sql":"CREATE TEMP TABLE candidates AS\nSELECT id, email FROM users WHERE last_login IS NULL;"},{"engine_slug":"oracle","sql":"CREATE GLOBAL TEMPORARY TABLE session_scratch (\n  id NUMBER PRIMARY KEY\n) ON COMMIT DELETE ROWS;"}],"faqs":[{"question":"How long does a temporary table live?","answer":"Until the session ends on SQL Server, PostgreSQL, MySQL and SQLite (a #temp table created inside a SQL Server stored procedure is dropped when the procedure returns), or until the transaction ends if you declared ON COMMIT DROP on PostgreSQL. Oracle's global temporary tables are permanent objects: only their rows are temporary."},{"question":"Are temp tables the same as table variables on SQL Server?","answer":"No. A @table variable is a lightweight declaration scoped to the batch; a #temp table is a real table in tempdb with its own statistics. Tiny row counts suit variables; larger sets usually plan better as #temp."},{"question":"Can two sessions use the same temp table name?","answer":"Yes on SQL Server (#orders is per session), PostgreSQL (temp tables live in a per-session pg_temp schema), MySQL and SQLite. One catch on SQL Server: constraint names on a #temp table are global in tempdb, so if two sessions each create #orders with CONSTRAINT pk_orders, the second fails with error 2714. Leave temp-table constraints unnamed. On PostgreSQL, MySQL and SQLite a temp table also hides a permanent table of the same name from unqualified references."}],"related":["create-table","create-table-as","drop-table"]},"source_url":"https://sqlly.app/sql-ddl/temp-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-ddl/truncate-table","corpus":"sql-ddl","engine":null,"language":"en","title":"SQL TRUNCATE TABLE","description":"Empty a table fast with TRUNCATE on SQL Server, PostgreSQL, MySQL and Oracle: identity resets, foreign key limits, rollback rules, and what SQLite uses instead.","body":{"slug":"truncate-table","name":"TRUNCATE TABLE","h1":"SQL TRUNCATE TABLE","category":"tables","lede":"Removes every row without visiting them one by one, usually by dropping and recreating the storage. It is DDL in most engines: faster than DELETE, harder to undo, and stricter about foreign keys.","syntax":"TRUNCATE TABLE table_name  |  TRUNCATE TABLE t1, t2 [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE]  -- PostgreSQL  |  DELETE FROM table_name  -- SQLite has no TRUNCATE","support":[{"engine_slug":"sql-server","status":"yes","note":"resets IDENTITY to the seed; refuses while any foreign key references the table"},{"engine_slug":"postgresql","status":"yes","note":"several tables at once; RESTART IDENTITY; CASCADE empties referencing tables too"},{"engine_slug":"mysql","status":"yes","note":"implicit commit; resets AUTO_INCREMENT; refuses on InnoDB tables a foreign key points at"},{"engine_slug":"sqlite","status":"no","note":"no TRUNCATE; DELETE FROM t does the same job"},{"engine_slug":"oracle","status":"yes","note":"DDL with implicit commit; no flashback query afterwards; CASCADE empties referencing tables"}],"gotchas":["Foreign keys gate the statement: SQL Server and MySQL refuse to truncate any table another table's foreign key points at, even when the referencing table is empty (a foreign key from the table to itself is allowed). PostgreSQL refuses too, empty or not, unless you list the referencing tables in the same TRUNCATE or add CASCADE, which truncates them too.","Rollback rules differ by engine. SQL Server, PostgreSQL and SQLite run inside a transaction and roll back cleanly. MySQL and Oracle commit implicitly around TRUNCATE, so there is no undo once it runs (and no flashback query on Oracle afterwards).","TRUNCATE resets the auto-increment counter on SQL Server and MySQL. PostgreSQL keeps counting unless you add RESTART IDENTITY. If ids must keep climbing after an empty-and-reload, use DELETE, or RESTART IDENTITY deliberately.","SQLite has no TRUNCATE. DELETE FROM t with no WHERE removes every row and gets SQLite's truncate optimization, which skips the row-by-row walk. A table using AUTOINCREMENT keeps its counter in sqlite_sequence, so ids continue unless you delete the row there too."],"examples":[{"engine_slug":"postgresql","sql":"TRUNCATE TABLE stage_orders RESTART IDENTITY;"},{"engine_slug":"sql-server","sql":"TRUNCATE TABLE dbo.stage_orders;"},{"engine_slug":"mysql","sql":"TRUNCATE TABLE stage_orders; -- implicit commit: no rollback"},{"engine_slug":"sqlite","sql":"-- no TRUNCATE in SQLite\nDELETE FROM stage_orders;"},{"engine_slug":"oracle","sql":"TRUNCATE TABLE stage_orders;"}],"faqs":[{"question":"Is TRUNCATE faster than DELETE?","answer":"Usually, yes: it releases the storage without visiting each row and logs far less. DELETE also fires delete triggers and never resets the identity counter; TRUNCATE skips the triggers and, on SQL Server and MySQL, resets the counter. For a few hundred rows the difference is noise; for millions it is seconds versus minutes."},{"question":"Why can I not truncate my table?","answer":"A foreign key somewhere references it. SQL Server and MySQL refuse while the constraint exists, even against an empty child table; PostgreSQL and Oracle offer CASCADE, which empties the referencing tables as well."},{"question":"Does TRUNCATE reset the identity counter?","answer":"Yes on SQL Server and MySQL. PostgreSQL needs RESTART IDENTITY; without it the counter continues. SQLite has no counter to reset unless the table used AUTOINCREMENT, whose value lives in sqlite_sequence."}],"related":["drop-table","create-table-as","create-table"]},"source_url":"https://sqlly.app/sql-ddl/truncate-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
