{"id":"errors/clickhouse/authentication-failed","corpus":"errors","engine":"clickhouse","language":"en","title":"AUTHENTICATION_FAILED (code 516)","description":"The user name, password, certificate or Kerberos identity did not check out at login.","body":{"code":"516","slug":"authentication-failed","name":"AUTHENTICATION_FAILED","message":"{user}: Authentication failed: password is incorrect, or there is no user with such name","group":"auth-access","severity":null,"sql_state":null,"summary":"The user name, password, certificate or Kerberos identity did not check out at login.","meaning":"`AUTHENTICATION_FAILED` (516) is the modern ClickHouse login failure. It covers a wrong password and an unknown user with one message by design, so the error does not leak which of the two failed. Older or other errors you may see alongside are `UNKNOWN_USER` (192) and `WRONG_PASSWORD` (193).","causes":["The password is wrong, was rotated, or the app config still holds an old value.","The user does not exist on that server, for example a replica without replicated access control synced.","The user exists but its auth type (no_password, certificate, Kerberos) does not match how the client connected."],"fix":[{"text":"Confirm the user and its auth type on the server you reached.","sql":"SELECT name, auth_type FROM system.users;"},{"text":"Reset the password if rotation broke it.","sql":"ALTER USER app_user IDENTIFIED BY 'new_password';"},{"text":"Test the credentials from the client host to rule out the wrong server.","sql":"clickhouse-client --host my_host --user app_user --password"}],"diagnostic":"`system.users` for existence and auth type, `system.query_log` has no rows for failed logins so use the server log, which records each failure with the user name and code 516. The failure line does not include the source address on this build, so take the IP from connection or proxy logs.","alternatives":"`SHOW USERS` lists names fast. For access control stored in ZooKeeper, verify all replicas run the same `access_management` settings.","details":[],"details_title":null,"repro":"CREATE USER scratch_u IDENTIFIED BY 'pw'; then clickhouse-client --user scratch_u --password wrong returns 516.","repro_note":null,"related":["clickhouse/readonly","clickhouse/too-many-simultaneous-queries"],"sqlly":"SQLly's connection test tells a server that answered and rejected the login from one that was never reached, before you retest by hand.","faqs":[{"question":"Why does the message not say whether the user exists?","answer":"On purpose. A single message stops attackers from enumerating user names."},{"question":"Users vanish after restart?","answer":"They were defined in a local access control file while other replicas use replicated access control; align the user_directories configuration across the replicas so each node reads the same store. The access_management setting does not select storage; it grants SQL-driven access control and account management to a user."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/authentication-failed","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/memory-limit-exceeded","corpus":"errors","engine":"clickhouse","language":"en","title":"MEMORY_LIMIT_EXCEEDED (code 241)","description":"The query would exceed the memory limit set by max_memory_usage or max_server_memory_usage.","body":{"code":"241","slug":"memory-limit-exceeded","name":"MEMORY_LIMIT_EXCEEDED","message":"Memory limit (for query) exceeded: would use {bytes}","group":"resources-limits","severity":null,"sql_state":null,"summary":"The query would exceed the memory limit set by max_memory_usage or max_server_memory_usage.","meaning":"`MEMORY_LIMIT_EXCEEDED` (241) fires when a query would push past `max_memory_usage` per query or the server total limit. The message shows the bytes it would have used. GROUP BY over wide data, ORDER BY without limits, and huge joins are the usual offenders.","causes":["A large GROUP BY or DISTINCT that does not fit the per-query limit.","ORDER BY over a big result without `max_bytes_before_external_sort` configured.","Many heavy queries at once exhausting the server total, not one query alone."],"fix":[{"text":"Let GROUP BY spill to disk instead of aborting.","sql":"SET max_bytes_before_external_group_by = 20000000000; SET max_memory_usage = 40000000000;"},{"text":"Sort externally the same way.","sql":"SET max_bytes_before_external_sort = 20000000000, max_bytes_ratio_before_external_sort = 0;"},{"text":"Cap the result with LIMIT so ORDER BY keeps only the top rows in memory.","sql":"SELECT * FROM big ORDER BY ts DESC LIMIT 100;"},{"text":"Raise the per-query limit for a heavy session without touching the server default.","sql":"SET max_memory_usage = 50000000000;"}],"diagnostic":"`system.query_log` column `memory_usage` per finished query, `system.metrics` and `system.processes` (or `SHOW PROCESSLIST`) to see live memory per query, `system.events` for `QueryMemoryLimitExceeded` count.","alternatives":"`SETTINGS max_memory_usage = ...` per query is safer than editing user profiles. `max_execution_time` complements memory limits for runaway queries.","details":[],"details_title":null,"repro":"SELECT groupArray(number) FROM numbers(10000000) SETTINGS max_memory_usage = 10000000; raises code 241.","repro_note":"groupArray materializes every value; the final array is about 80 MB for 10 million numbers and the query peaks near 257 MiB, so the 10 MB limit fires deterministically; a count() grouped by number % 1000 holds only a few thousand tiny states and never gets close.","related":["clickhouse/too-many-simultaneous-queries","clickhouse/timeout-exceeded"],"sqlly":"SQLly's activity monitor lists running queries with elapsed time and rows, and you can kill the heavy one without opening clickhouse-client.","faqs":[{"question":"Should I just raise max_memory_usage?","answer":"Only if the server has the RAM. Prefer spilling to disk and LIMIT-first patterns; raising the limit moves the failure to the OS OOM killer."},{"question":"Where do I see which query used the most memory?","answer":"SELECT query_id, memory_usage, query FROM system.query_log ORDER BY memory_usage DESC."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/memory-limit-exceeded","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/no-such-column-in-table","corpus":"errors","engine":"clickhouse","language":"en","title":"NO_SUCH_COLUMN_IN_TABLE (code 16)","description":"A write path such as ALTER, a mutation or an INSERT column list names a column the table does not have.","body":{"code":"16","slug":"no-such-column-in-table","name":"NO_SUCH_COLUMN_IN_TABLE","message":"There is no column {column} in table {database}.{table}","group":"table-metadata","severity":null,"sql_state":null,"summary":"A write path such as ALTER, a mutation or an INSERT column list names a column the table does not have.","meaning":"`NO_SUCH_COLUMN_IN_TABLE` (16) checks statements against the stored table schema and fails when a named column does not exist, most often in `ALTER TABLE`, `ALTER UPDATE`/`DELETE` mutations, `INSERT INTO t (col_list) ...` and materialized view definitions. A bad column in a plain SELECT is `UNKNOWN_IDENTIFIER` (47) instead.","causes":["A typo or a renamed column in an ALTER or mutation command.","INSERT lists a column the target table does not have, or a view's target list drifted from its source.","Generated SQL was written for an older schema."],"fix":[{"text":"List the columns the table actually has.","sql":"SELECT name, type FROM system.columns WHERE database = 'my_db' AND table = 'my_table' ORDER BY position;"},{"text":"Rewrite the mutation against the real name, or add the column first.","sql":"ALTER TABLE my_table ADD COLUMN IF NOT EXISTS new_col String;"},{"text":"Fix a materialized view whose target list drifted by rewriting its SELECT.","sql":"ALTER TABLE my_mv MODIFY QUERY SELECT id, new_name FROM my_table;"}],"diagnostic":"`system.columns` for the true schema, `SHOW CREATE TABLE` for view definitions, `system.query_log` for the failed statement, and `system.mutations` shows stuck mutations with `latest_fail_reason`.","alternatives":"`DESCRIBE TABLE my_table` answers existence fast. `EXISTS` checks a table, never a column; generated code should query `system.columns`.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_g (id UInt32) ENGINE = MergeTree ORDER BY id; then ALTER TABLE scratch_g DELETE WHERE missing_col = 1 gets code 16.","repro_note":"Mutations resolve against the stored schema, so the failure comes back from the ALTER itself, not from a SELECT.","related":["clickhouse/unknown-identifier","clickhouse/type-mismatch","clickhouse/table-not-exists"],"sqlly":"SQLly's Validate SQL marks the missing column in the editor before the mutation runs, using the schema it loaded from your ClickHouse connection.","faqs":[{"question":"Why 16 in mutations but 47 in SELECT?","answer":"SELECT column resolution reports UNKNOWN_IDENTIFIER (47) through the analyzer. DDL and mutation commands resolve against the stored schema and report 16."},{"question":"The column exists on another replica?","answer":"Then the schema drifted between nodes. Compare system.columns on every replica and keep them aligned with ALTER ... ON CLUSTER."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/no-such-column-in-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/not-enough-space","corpus":"errors","engine":"clickhouse","language":"en","title":"NOT_ENOUGH_SPACE (code 243)","description":"The server could not reserve disk space for a new part, merge or mutation; the disk under the data path is out of room.","body":{"code":"243","slug":"not-enough-space","name":"NOT_ENOUGH_SPACE","message":"Cannot reserve {size}, not enough space","group":"resources-limits","severity":null,"sql_state":null,"summary":"The server could not reserve disk space for a new part, merge or mutation; the disk under the data path is out of room.","meaning":"`NOT_ENOUGH_SPACE` (243) is raised before any bytes are written: ClickHouse reserves space for each new part, merge and mutation on the target disk, and the reservation failed. `df` can still show free space, because parallel reservations, `keep_free_space_bytes` and the merge rule of keeping free space for the merge's input parts all shrink what the server may use.","causes":["The disk or volume under the data path is genuinely full, often by ClickHouse's own log tables.","Free space exists but is reserved by concurrent merges, mutations and inserts.","The filesystem ran out of inodes, which looks exactly like a full disk."],"fix":[{"text":"Compare what the OS sees with what the server sees.","sql":"SELECT name, path, free_space, total_space, unreserved_space, keep_free_space FROM system.disks;"},{"text":"Find the biggest consumers and drop or add TTL to what you can.","sql":"SELECT database, table, formatReadableSize(sum(bytes_on_disk)) AS size FROM system.parts WHERE active GROUP BY database, table ORDER BY sum(bytes_on_disk) DESC LIMIT 10;"},{"text":"On a full disk, DROP TABLE ... SYNC returns space at once; a plain DROP waits out the cleanup delay.","sql":"DROP TABLE old_log_table SYNC;"}],"diagnostic":"`system.disks` for free and unreserved space, `system.parts` for the biggest tables, `df -i` for inodes, and the server log names the task whose reservation failed: insert, merge or mutation.","alternatives":"`SYSTEM STOP MERGES` pauses merge reservations while you free space, but new inserts still need room. A `TTL ... DELETE` policy shrinks log tables without manual drops.","details":[],"details_title":null,"repro":"Point a test container's data path at a tiny loopback filesystem, fill it, and any INSERT raises 243. Never test this on a data disk that matters.","repro_note":"Use a throwaway container or a loopback filesystem sized in megabytes; never a disk holding real data.","related":["clickhouse/table-is-read-only","clickhouse/memory-limit-exceeded"],"sqlly":"Run the biggest-tables query from this page in SQLly and the sizes land in a sortable grid, which makes the space hog obvious.","faqs":[{"question":"df shows free space. Why 243?","answer":"Merges reserve free space for their source parts before writing, and other queries hold reservations too. Check unreserved_space in system.disks, not just free_space."},{"question":"What does the size in the message mean?","answer":"The size is the number of bytes the server tried to reserve for the insert, merge or mutation, formatted for humans, for example Cannot reserve 1.00 MiB, not enough space."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/not-enough-space","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/number-of-columns-doesnt-match","corpus":"errors","engine":"clickhouse","language":"en","title":"NUMBER_OF_COLUMNS_DOESNT_MATCH (code 20)","description":"The rows being inserted have a different column count than the statement or the target table expects.","body":{"code":"20","slug":"number-of-columns-doesnt-match","name":"NUMBER_OF_COLUMNS_DOESNT_MATCH","message":"Number of columns doesn't match","group":"format-input","severity":null,"sql_state":null,"summary":"The rows being inserted have a different column count than the statement or the target table expects.","meaning":"`NUMBER_OF_COLUMNS_DOESNT_MATCH` (20) fires while INSERT data is parsed, when a row's value count disagrees with the column list or the table: a VALUES tuple with the wrong arity, a CSV or JSONEachRow row with missing or extra fields, or an INSERT ... SELECT projection that differs from the target list.","causes":["A hand written INSERT has a different number of values per tuple.","A CSV or JSONEachRow row gained or lost fields, often after a schema edit on either side.","INSERT INTO t (a, b) SELECT ... selects a different number of columns."],"fix":[{"text":"Compare the target schema against the file header before importing.","sql":"DESCRIBE TABLE my_table;"},{"text":"Name every column explicitly so positional drift becomes an error you can read.","sql":"INSERT INTO my_table (id, name) VALUES (1, 'a');"},{"text":"Eyeball the first rows of a suspect file with the same format the import uses.","sql":"SELECT * FROM file('data.csv', CSVWithNames) LIMIT 5;"}],"diagnostic":"`DESCRIBE TABLE` for the target arity, `system.query_log` for the failed statement, and for file formats the exception names the first bad row, which is usually enough.","alternatives":"Reading a file through `file()` with an explicit format isolates parse errors from schema errors. INSERT with an explicit column list beats INSERT without one.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_h (a UInt32, b String) ENGINE = MergeTree ORDER BY a; then INSERT INTO scratch_h VALUES (1) returns code 20.","repro_note":"VALUES binds positionally, so a single missing value is enough; file formats report the first bad row instead.","related":["clickhouse/type-mismatch","clickhouse/no-such-column-in-table"],"sqlly":"SQLly's CSV import previews parsed rows with their row and column numbers and rejects the file before it inserts anything.","faqs":[{"question":"A CSV row has too many fields?","answer":"An extra CSV field raises 117 INCORRECT_DATA (Expected end of line). A short row raises 27 CANNOT_PARSE_INPUT_ASSERTION_FAILED. Neither is code 20. A trailing comma on a two-column row was accepted silently in 26.9, so check the loaded rows."},{"question":"Why did this break after we added a column?","answer":"INSERT without a column list binds values positionally to every table column. Appending a column with ADD COLUMN makes an old-width VALUES tuple fail with code 62. A column added AFTER a position can shift values silently when the tuple width still matches. Always list columns explicitly."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/number-of-columns-doesnt-match","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/readonly","corpus":"errors","engine":"clickhouse","language":"en","title":"READONLY (code 164)","description":"The session runs under the readonly setting, so INSERT, CREATE, ALTER and other writes are refused at the server.","body":{"code":"164","slug":"readonly","name":"READONLY","message":"Cannot execute query in readonly mode. (READONLY)","group":"auth-access","severity":null,"sql_state":null,"summary":"The session runs under the readonly setting, so INSERT, CREATE, ALTER and other writes are refused at the server.","meaning":"`READONLY` (164) means the session's `readonly` setting blocks data changes: `readonly = 1` allows reads only, so SET is blocked too; `readonly = 2` allows reads and SET but still blocks data changes. The value comes from the user's profile or the connection string, not from the table; a table refusing writes is `TABLE_IS_READ_ONLY` (242).","causes":["The user's profile sets readonly = 1 or 2, common for dashboards and the HTTP interface.","The connection string or driver appends readonly=1 and the application then sends writes.","A proxy or managed service hands out a readonly profile the user never asked for."],"fix":[{"text":"See what the session enforces and whether it was changed on the fly.","sql":"SELECT name, value, changed FROM system.settings WHERE name = 'readonly';"},{"text":"Ask an administrator to move the user into a writable profile; do not try to escape the restriction.","sql":"ALTER USER app_user SETTINGS PROFILE default;"},{"text":"Split workloads: keep dashboards on their readonly user and run writes as a separate read-write user.","sql":"GRANT SELECT ON my_db.* TO dashboard_ro;"}],"diagnostic":"`system.settings` for the session value, `SHOW GRANTS FOR app_user` and `system.users` for the profile, and the server's users.xml or access-control storage for where readonly is set.","alternatives":"`ACCESS_DENIED` (497) fails one statement for missing grants; 164 blocks all writes for the session. A readonly = 1 session that tries SET gets 164 (`Cannot modify 'max_threads' setting in readonly mode`); a readonly = 2 session may SET other settings, but changing `readonly` itself also returns 164.","details":[],"details_title":null,"repro":"clickhouse-client --setting readonly=1, then INSERT INTO scratch_f VALUES (1) returns 164; the same INSERT as an unrestricted user succeeds.","repro_note":"The same INSERT succeeds for an unrestricted user, which proves the block is the session profile, not the table.","related":["clickhouse/table-is-read-only"],"sqlly":"SQLly shows the connection name on every tab, so you can check you are editing the right user's profile when one server holds both readonly and read-write logins.","faqs":[{"question":"What is the difference between readonly 1 and 2?","answer":"readonly = 1 blocks data changes and SET; readonly = 2 allows SET but still blocks data changes. Remove the managed-service sentence unless it is sourced."},{"question":"Is this the same as a table in read-only mode?","answer":"No. 164 is the session setting, 242 TABLE_IS_READ_ONLY is a per-table state. The message and code tell you which one you hit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/readonly","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/syntax-error","corpus":"errors","engine":"clickhouse","language":"en","title":"SYNTAX_ERROR (code 62)","description":"The parser could not turn the statement text into a query tree; the message names the position and token.","body":{"code":"62","slug":"syntax-error","name":"SYNTAX_ERROR","message":"Syntax error: failed at position {position}: {token}","group":"syntax-parsing","severity":null,"sql_state":null,"summary":"The parser could not turn the statement text into a query tree; the message names the position and token.","meaning":"`SYNTAX_ERROR` (62) means the statement text is not valid ClickHouse SQL. The message gives the byte position and shows a fragment starting where parsing failed, so read that fragment first. Dialect differences from MySQL or Postgres are the most common cause.","causes":["Dialect SQL sent unmodified: `ON DUPLICATE KEY` or `ON CONFLICT` clauses ClickHouse does not have. With `INSERT ... VALUES` these fail with code 27 CANNOT_PARSE_INPUT_ASSERTION_FAILED; with `INSERT ... SELECT` they fail with 62.","A missing comma, quote or parenthesis before the fragment shown.","A clause keyword with nothing valid before it, for example `SELECT * FROM WHERE id = 1;`, which fails at the `=` with code 62."],"fix":[{"text":"Fix the fragment at the reported position; here the unfinished IN list just needs its list or subquery.","sql":"SELECT * FROM my_table WHERE id IN (1, 2);"},{"text":"Identifiers can keep their backticks or use double quotes; strings take single quotes, so only the dialect clauses need rewriting.","sql":"SELECT `id`, \"name\" FROM my_table LIMIT 10;"},{"text":"Quote identifiers that collide with keywords.","sql":"SELECT \"partition\", \"key\" FROM my_table;"}],"diagnostic":"`system.query_log` keeps the full failed statement; `clickhouse-client` reports the position immediately; `EXPLAIN AST SELECT ...` prints the parse tree when the statement parses, and returns the same SYNTAX_ERROR with its position when it does not.","alternatives":"`EXPLAIN AST` parses without running the query, which isolates syntax problems from execution ones.","details":[],"details_title":null,"repro":"SELECT * FROM scratch_d WHERE id IN; in clickhouse-client returns Code: 62 SYNTAX_ERROR at position 36 (end of query): ;, the semicolon just after IN.","repro_note":null,"related":["clickhouse/unknown-identifier","clickhouse/type-mismatch"],"sqlly":"When the server names the failing position, SQLly highlights that token in the editor, which is where MySQL-only dialect usually trips.","faqs":[{"question":"Why does my MySQL query fail?","answer":"ClickHouse is its own dialect. Rewrites are usually small: no ON DUPLICATE KEY, use a ReplacingMergeTree table and read with FINAL for upsert-like behavior; duplicate keys can stay visible until a background merge runs."},{"question":"The position points at the wrong token?","answer":"The position is where the parser gave up, which can trail the actual typo by a few tokens."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/syntax-error","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/table-already-exists","corpus":"errors","engine":"clickhouse","language":"en","title":"TABLE_ALREADY_EXISTS (code 57)","description":"You ran CREATE TABLE, CREATE MATERIALIZED VIEW or CREATE DICTIONARY for a name that a table or view in the current database already uses.","body":{"code":"57","slug":"table-already-exists","name":"TABLE_ALREADY_EXISTS","message":"Table {database}.{table} already exists","group":"table-metadata","severity":null,"sql_state":null,"summary":"You ran CREATE TABLE, CREATE MATERIALIZED VIEW or CREATE DICTIONARY for a name that a table or view in the current database already uses.","meaning":"`TABLE_ALREADY_EXISTS` (57) means the server already has a table or materialized view with the name you tried to create in that database. A dictionary name clash reports DICTIONARY_ALREADY_EXISTS (code 387) instead, and CREATE DICTIONARY on a name that a table holds reports code 57. With `CREATE TABLE IF NOT EXISTS` the statement succeeds silently instead. ClickHouse keeps `create_query` on disk, so a crash mid-create does not usually leave a half-made table; if you see this after a failed migration, the earlier attempt really did commit.","causes":["The migration ran once already and is being re-run without `IF NOT EXISTS` on the statement.","Two nodes or two workers create the same table name at the same time in a race.","A Distributed or Replicated table creates an inner `.inner.` table and you picked the same name by hand."],"fix":[{"text":"Check what exists before creating, then choose: reuse it, or drop and recreate it.","sql":"SELECT name, engine FROM system.tables WHERE database = currentDatabase() AND name = 'my_table';"},{"text":"Make the migration idempotent so re-runs are harmless.","sql":"CREATE TABLE IF NOT EXISTS my_table (id UInt64) ENGINE = MergeTree ORDER BY id;"},{"text":"If the old table is truly unwanted, drop it and recreate with the intended schema. Send the two statements as separate requests: the HTTP interface rejects multi-statement queries with code 62.","sql":"DROP TABLE my_table; CREATE TABLE my_table (id UInt64) ENGINE = MergeTree ORDER BY id;"}],"diagnostic":"`SHOW CREATE TABLE my_table` to see the existing schema, `system.tables` for engine and `metadata_modification_time`, `system.query_log` filtered on `event_date` and `query_kind = 'Create'` to find who made it.","alternatives":"`EXISTS TABLE my_table` returns a Boolean you can branch on without catching an error. `CREATE TABLE ... AS SELECT` also takes `IF NOT EXISTS`, and the query does nothing when the table exists.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_a (id UInt32) ENGINE = MergeTree ORDER BY id; then run the same CREATE TABLE again without IF NOT EXISTS and you get code 57.","repro_note":null,"related":["clickhouse/table-not-exists","clickhouse/no-such-column-in-table"],"sqlly":"SQLly's schema tree and DDL view show the table that already exists, so a failed migration re-run is a two-second check instead of a mystery.","faqs":[{"question":"Does IF NOT EXISTS hide a real problem?","answer":"It hides the schema mismatch: the statement succeeds but the existing table keeps its old schema. Run ALTER on the existing table when the schema should change."},{"question":"I dropped the table but still get 57","answer":"A plain MergeTree drop frees the name at once. For a Replicated table the name can stay taken briefly after the drop, so retry after a short wait or check `system.dropped_tables`."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/table-already-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/table-is-read-only","corpus":"errors","engine":"clickhouse","language":"en","title":"TABLE_IS_READ_ONLY (code 242)","description":"The table refuses writes because the server flagged it read-only; most often a ReplicatedMergeTree replica lost its Keeper session.","body":{"code":"242","slug":"table-is-read-only","name":"TABLE_IS_READ_ONLY","message":"Table is in readonly mode","group":"resources-limits","severity":null,"sql_state":null,"summary":"The table refuses writes because the server flagged it read-only; most often a ReplicatedMergeTree replica lost its Keeper session.","meaning":"`TABLE_IS_READ_ONLY` (242) is raised on INSERT or ALTER when the table engine put the table in read-only mode. For `ReplicatedMergeTree` the common trigger is a lost or expired session with ZooKeeper or ClickHouse Keeper: without a live session the replica cannot safely write. Plain MergeTree tables do not raise 242: a table with table_readonly = 1 fails INSERT with TABLE_IS_PERMANENTLY_READ_ONLY (774), and an unwritable data directory fails with code 1001 (std::exception). It is a table state, not a permission issue; that is `ACCESS_DENIED` (497), and a session-level limit is `READONLY` (164).","causes":["A ReplicatedMergeTree replica lost its ZooKeeper or Keeper session, or cannot reinitialize it after a restart.","The filesystem holding the data path is mounted read-only or has no space left.","A data part failed the check at startup and the server marked the table read-only."],"fix":[{"text":"See which tables are read-only and why: is_session_expired and the exception columns separate a Keeper problem from a local one.","sql":"SELECT database, table, is_readonly, is_session_expired, total_replicas, active_replicas, zookeeper_exception, last_queue_update_exception FROM system.replicas WHERE is_readonly;"},{"text":"For an expired Keeper session, restore connectivity to the Keeper cluster, then reinitialize the replica; it compares its state with Keeper and rebuilds its queue.","sql":"SYSTEM RESTART REPLICA my_db.my_table;"},{"text":"For a local cause, fix the disk or the damaged part first; system.detached_parts shows what the server set aside and why.","sql":"SELECT name, reason FROM system.detached_parts WHERE database = 'my_db' AND table = 'my_table';"},{"text":"When the cause is fixed but the server still refuses the table, the documented recovery is the force_restore_data flag: touch the flag file in the server's flags/ directory (or create the node under the table's flags/ path in Keeper), restart, then confirm the table is writable again:","sql":"SELECT database, table, is_readonly, is_session_expired FROM system.replicas WHERE database = 'my_db' AND table = 'my_table';"}],"diagnostic":"`system.replicas` (`is_readonly`, `is_session_expired`, `zookeeper_exception`) for replicated tables, `system.disks` for space and mount state, `system.parts` and `system.detached_parts` for part health, and the server log for the message that set read-only.","alternatives":"No client-side workaround clears the flag. Route writes to another replica meanwhile, and use force_restore_data only when the flagged parts are safe to lose.","details":[],"details_title":null,"repro":"On a scratch server, run ALTER TABLE scratch_mt MODIFY SETTING table_readonly = 1 on a MergeTree table and INSERT fails with 774 (TABLE_IS_PERMANENTLY_READ_ONLY), not 242. Code 242 needs a ReplicatedMergeTree table, which needs a ClickHouse Keeper or ZooKeeper ensemble; the docs say replicated tables switch to read-only when Keeper is unavailable at startup.","repro_note":"The replicated read-only state clears when the Keeper session reinitializes; nothing has to be deleted.","related":["clickhouse/not-enough-space","clickhouse/readonly"],"sqlly":"Nothing client-side clears the flag; keep SQLly on the reads you still need and point a second connection at another replica to see whether only one node refuses writes.","faqs":[{"question":"Is this the same as read-only user mode?","answer":"No. `READONLY` (164) is a user session setting. 242 is the table itself refusing writes."},{"question":"Does the table recover by itself?","answer":"A replica leaves read-only mode on its own once the Keeper session is back and its queue drains; for disk and part causes, fix the cause and restart."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/table-is-read-only","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/table-not-exists","corpus":"errors","engine":"clickhouse","language":"en","title":"UNKNOWN_TABLE (code 60)","description":"The table you queried or referenced is missing from the database the query reached.","body":{"code":"60","slug":"table-not-exists","name":"UNKNOWN_TABLE","message":"Unknown table expression identifier '{table}'. In scope {query}.","group":"table-metadata","severity":null,"sql_state":null,"summary":"The table you queried or referenced is missing from the database the query reached.","meaning":"`UNKNOWN_TABLE` (60) means the server cannot resolve a table name in the current database or the one you qualified. It is the ClickHouse twin of `no such table` in other engines. The database is fine (that failure is `UNKNOWN_DATABASE`, 81); only the table name fails. When a table with that name exists in another database, the server adds `Maybe you meant {database}.{table}?` before the scope clause. DDL and INSERT against a missing table report `Table {database}.{table} does not exist.` with the same code 60.","causes":["A typo in the table name, or the wrong database in the connection string.","The query hit a different server or tenant where the table was never created.","A Distributed table points at a shard where the local table is missing, so the remote query fails with this code."],"fix":[{"text":"List what the server actually sees and compare against your query.","sql":"SELECT database, name FROM system.tables WHERE name ILIKE '%my_table%';"},{"text":"Qualify the table with its database so the default database of the session stops mattering.","sql":"SELECT count() FROM my_db.my_table;"},{"text":"If a shard is missing its local table, create it on that shard's host before querying the Distributed table.","sql":"CREATE TABLE my_table (id UInt64) ENGINE = MergeTree ORDER BY id;"}],"diagnostic":"`SELECT currentDatabase()` to see the session default, `system.tables` for existence, `system.query_log` for the exact failed query text, and `system.clusters` when a Distributed table is involved.","alternatives":"`EXISTS TABLE my_table` and `SELECT * FROM system.tables WHERE ...` let the application check first. `SHOW TABLES FROM my_db` lists a database quickly.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_b (id UInt32) ENGINE = MergeTree ORDER BY id; then run SELECT * FROM scratch_b_wrong and you get code 60.","repro_note":null,"related":["clickhouse/table-already-exists","clickhouse/no-such-column-in-table"],"sqlly":"SQLly's schema tree lists what the connected server actually has, so a typo or a wrong default database shows up before you run the query.","faqs":[{"question":"Can case sensitivity cause this?","answer":"Yes. ClickHouse table, database and column names are case sensitive, so MyTable and mytable are different names."},{"question":"Why does the error mention the wrong database?","answer":"Unqualified names resolve against the session default database, which may differ from the one you had in mind."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/table-not-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/timeout-exceeded","corpus":"errors","engine":"clickhouse","language":"en","title":"TIMEOUT_EXCEEDED (code 159)","description":"The query or a waiting operation ran past max_execution_time or an internal timeout and was cancelled.","body":{"code":"159","slug":"timeout-exceeded","name":"TIMEOUT_EXCEEDED","message":"Timeout exceeded: elapsed {seconds} seconds, maximum: {max_seconds}","group":"resources-limits","severity":null,"sql_state":null,"summary":"The query or a waiting operation ran past max_execution_time or an internal timeout and was cancelled.","meaning":"`TIMEOUT_EXCEEDED` (159) is raised when an operation exceeds a deadline. Most often the query went past `max_execution_time`. In replication contexts the same code appears when waiting on ZooKeeper or a quorum takes too long. The query is cancelled; over HTTP, rows already streamed to the client are not retracted and the exception follows them.","causes":["A scan-heavy query that genuinely needs more time than the limit allows.","A stuck distributed query waiting on an unresponsive shard.","Replication waits, quorum writes or ZooKeeper operations hitting their deadlines."],"fix":[{"text":"Raise the limit for the heavy session only.","sql":"SET max_execution_time = 300;"},{"text":"Make the query cheaper: narrow columns, add a partition filter, or add LIMIT for exploratory reads.","sql":"SELECT ts, value FROM events WHERE event_date >= today() - 1 LIMIT 1000;"},{"text":"Make disconnecting HTTP clients cancel their reads: turn on cancel_http_readonly_queries_on_client_close in the server config; it is a server setting, not a session SET. Cap single requests instead with:","sql":"SELECT uniq(number) FROM numbers(1000000) SETTINGS max_execution_time = 30;"}],"diagnostic":"`system.query_log` elapsed time versus the limit for the query_id, `system.processes` for live queries and their elapsed time, `KILL QUERY WHERE query_id = '...'` to cancel a stuck one.","alternatives":"`max_execution_time` can be set per user profile instead of per session. For HTTP, `max_execution_time` in the URL parameters applies per request.","details":[],"details_title":null,"repro":"SET max_block_size = 1000 and max_execution_time = 1, then SELECT uniq(number) FROM numbers(1000000000); raises code 159 once a block finishes past the deadline.","repro_note":"The limit is checked as the query runs. sleep(3) with max_execution_time = 1 raises 159 at about 1 s, and uniq over a billion numbers at default block size finishes in under a second, so use a small max_block_size to force the check.","related":["clickhouse/memory-limit-exceeded","clickhouse/too-many-simultaneous-queries"],"sqlly":"The failed statement stays in SQLly's editor tab, so re-running it with a raised max_execution_time for that session is one edit.","faqs":[{"question":"Does the query keep running server-side after the client times out?","answer":"For native clients with cancel on close and for 159 itself, the server cancels. An HTTP client disconnect alone may leave the query running unless cancel_http_readonly_queries_on_client_close is on."},{"question":"Why did I get 159 on a replicated INSERT?","answer":"Quorum or ZooKeeper waits use the same code path; check replica health before raising timeouts."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/timeout-exceeded","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/too-many-parts","corpus":"errors","engine":"clickhouse","language":"en","title":"TOO_MANY_PARTS (code 252)","description":"Each INSERT makes a data part and merges cannot keep up, so the table hit parts_to_throw_insert or max_parts_in_total.","body":{"code":"252","slug":"too-many-parts","name":"TOO_MANY_PARTS","message":"Too many parts ({parts}). Merges are processing significantly slower than inserts","group":"resources-limits","severity":null,"sql_state":null,"summary":"Each INSERT makes a data part and merges cannot keep up, so the table hit parts_to_throw_insert or max_parts_in_total.","meaning":"`TOO_MANY_PARTS` (252) is rejected at INSERT time when active parts in one partition pass `parts_to_throw_insert` (300 before 23.6, 3000 since) or the whole table passes `max_parts_in_total` (100,000). Inserts are outrunning background merges, and raising the limit only trades SELECT speed for delay.","causes":["Rows arrive as many small INSERTs, each writing its own part.","The partition key is high cardinality, so parts land in thousands of partitions that never merge together.","Merges fall behind because the disk is slow or full, or many materialized views feed off the table."],"fix":[{"text":"See which partition is over the limit and by how much.","sql":"SELECT partition, count() AS active_parts FROM system.parts WHERE active AND database = 'my_db' AND table = 'my_table' GROUP BY partition ORDER BY active_parts DESC;"},{"text":"Batch on the client, or use asynchronous inserts so the server merges concurrent single-row inserts into a few parts. On ClickHouse 26.9, async_insert already defaults to 1.","sql":"INSERT INTO my_table SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1, 'a');"},{"text":"For a one-off migration INSERT ... SELECT, form bigger blocks so fewer parts are created.","sql":"INSERT INTO my_table SELECT * FROM old_table SETTINGS min_insert_block_size_bytes = 500000000;"}],"diagnostic":"`system.parts` counts active parts per partition, `system.merges` shows merges in flight, `system.query_log` grouped by user shows who inserts tiny rows, and the server log records merge failures.","alternatives":"`SYSTEM STOP MERGES my_table` halts merge reservations while you re-plan, but it also freezes the table's maintenance. Raising `parts_to_throw_insert` delays the error and slows SELECTs.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_e (id UInt32) ENGINE = MergeTree ORDER BY id SETTINGS parts_to_throw_insert = 2; then run three single-row INSERTs back to back and one gets code 252.","repro_note":"parts_to_throw_insert counts per partition, so the scratch table trips on the third INSERT while the rest of the server is untouched.","related":["clickhouse/memory-limit-exceeded","clickhouse/table-is-read-only"],"sqlly":"SQLly's CSV import shows the row count it will insert in the preview, so you can see whether a run is one big INSERT or thousands of small ones.","faqs":[{"question":"Should I raise parts_to_throw_insert?","answer":"Only as a stopgap. The official guidance is fewer, larger inserts: around one INSERT query per second, with at least 1,000 rows per INSERT and ideally 10,000 to 100,000; a higher limit trades SELECT performance for delay."},{"question":"Do asynchronous inserts fix it?","answer":"They move batching to the server, so concurrent single-row inserts share a few parts instead of one part each. A high-cardinality partition key can still exceed the limit. A high-cardinality partition key can still exceed the limit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/too-many-parts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/too-many-simultaneous-queries","corpus":"errors","engine":"clickhouse","language":"en","title":"TOO_MANY_SIMULTANEOUS_QUERIES (code 202)","description":"The server already runs the max_concurrent_queries limit and rejected the new one.","body":{"code":"202","slug":"too-many-simultaneous-queries","name":"TOO_MANY_SIMULTANEOUS_QUERIES","message":"Too many simultaneous queries. Maximum: {max_queries}","group":"resources-limits","severity":null,"sql_state":null,"summary":"The server already runs the max_concurrent_queries limit and rejected the new one.","meaning":"`TOO_MANY_SIMULTANEOUS_QUERIES` (202) means a concurrency cap was hit: either the server-wide `max_concurrent_queries` is full, or one user has reached `max_concurrent_queries_for_user`. Backfills, dashboards polling in a loop, or one slow query type piling up are typical. The right fix is finding the pile-up, not just raising the limit.","causes":["A batch job fires more concurrent queries than the server can drain.","A few very slow queries block the pool and everything else queues.","The limit was set low for safety and real load outgrew it."],"fix":[{"text":"See what is running right now and who holds the slots.","sql":"SELECT query_id, user, elapsed, substring(query, 1, 80) AS q FROM system.processes ORDER BY elapsed DESC;"},{"text":"Cancel the pile-up of runaway queries.","sql":"KILL QUERY WHERE elapsed > 600 AND user = 'batch_user';"},{"text":"Raise the server limit in config once capacity is confirmed.","sql":"<max_concurrent_queries>200</max_concurrent_queries>"}],"diagnostic":"`system.processes` for live queries, `system.query_log` grouped by user and minute to find the source of bursts, `system.metrics` metric `Query` for current concurrency.","alternatives":"Throttle at the client or use a queue. `max_concurrent_queries_for_user` protects interactive users from one account monopolizing the server.","details":[],"details_title":null,"repro":"Start max_concurrent_queries+1 long SELECT sleep(10) sessions in parallel; the last one gets code 202 immediately.","repro_note":null,"related":["clickhouse/memory-limit-exceeded","clickhouse/timeout-exceeded","clickhouse/too-many-parts"],"sqlly":"SQLly's activity monitor lets you kill a query straight from the list, which is how you find what filled the server's slots without shelling into the host.","faqs":[{"question":"Is 202 per user?","answer":"Code 202 is returned for both limits. The server-wide limit (max_concurrent_queries) says \"Too many simultaneous queries. Maximum: {max}\". The per-user limit (max_concurrent_queries_for_user) also returns 202, with \"Too many simultaneous queries for user {user}. Current: N, maximum: M\"."},{"question":"Retry immediately?","answer":"Back off. The server is at capacity; retrying in a tight loop makes it worse. Use exponential backoff on 202."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/too-many-simultaneous-queries","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/type-mismatch","corpus":"errors","engine":"clickhouse","language":"en","title":"TYPE_MISMATCH (code 53)","description":"A value that cannot be converted to the other side's type met a comparison or an IN list.","body":{"code":"53","slug":"type-mismatch","name":"TYPE_MISMATCH","message":"Type mismatch in IN or VALUES section: {left_type} vs {right_type}","group":"table-metadata","severity":null,"sql_state":null,"summary":"A value that cannot be converted to the other side's type met a comparison or an IN list.","meaning":"`TYPE_MISMATCH` (53) is raised when comparison or assignment needs a common type and none exists, for example a string that cannot convert to UInt64. Array(Tuple) against String fails with CANNOT_READ_ARRAY_FROM_TEXT (130) instead. It differs from `ILLEGAL_TYPE_OF_ARGUMENT` (43), which complains about a function argument.","causes":["Comparing a numeric column to a quoted string literal from application code.","An IN list literal holding a value that cannot convert to the left side's type.","INSERT data whose columns do not match the declared schema; unparsable values raise 6 (CANNOT_PARSE_TEXT) instead."],"fix":[{"text":"Cast explicitly so the intent is on record.","sql":"SELECT * FROM events WHERE id = toUInt64('42');"},{"text":"Match the IN subquery type to the left column.","sql":"SELECT * FROM events WHERE user_id IN (SELECT toUInt64(external_id) FROM mapping);"},{"text":"Insert with explicit types rather than relying on inference.","sql":"INSERT INTO events (user_id) SELECT toUInt64(col) FROM staging;"}],"diagnostic":"`DESCRIBE TABLE` both sides, `system.query_log` for the failed statement, and `toTypeName(expr)` in a SELECT to print any expression's type.","alternatives":"`toTypeName()` is the fastest way to see a type. `SELECT ... WHERE toTypeName(col) = 'UInt64'` guards generated SQL.","details":[],"details_title":null,"repro":"SELECT 1 WHERE 1 IN ['a']; raises TYPE_MISMATCH between String and UInt64.","repro_note":null,"related":["clickhouse/syntax-error","clickhouse/number-of-columns-doesnt-match"],"sqlly":"SQLly's schema tree prints each column's ClickHouse type next to its name, so a String column compared to a bare number literal is visible before you run.","faqs":[{"question":"Does ClickHouse ever compare String and numbers implicitly?","answer":"It converts when the string parses, so WHERE id = '42' matches a UInt64 column. It raises 53 only when the string cannot be converted, such as 'abc'. Cast explicitly anyway so the intent is on record."},{"question":"Why does the message mention IN?","answer":"IN list literals raise it (1 IN ['a'] gives 53). An IN subquery with a mismatched type does not raise here, and a bad INSERT value raises 6 (CANNOT_PARSE_TEXT) instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/type-mismatch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/clickhouse/unknown-identifier","corpus":"errors","engine":"clickhouse","language":"en","title":"UNKNOWN_IDENTIFIER (code 47)","description":"A column or alias in SELECT, WHERE or ORDER BY does not exist in the tables the query sees.","body":{"code":"47","slug":"unknown-identifier","name":"UNKNOWN_IDENTIFIER","message":"Unknown expression identifier `{identifier}`. In scope {query}.","group":"syntax-parsing","severity":null,"sql_state":null,"summary":"A column or alias in SELECT, WHERE or ORDER BY does not exist in the tables the query sees.","meaning":"`UNKNOWN_IDENTIFIER` (47) is raised during analysis when a name cannot be resolved to any column, alias or CTE. The SQL parsed fine (that would be 62); the names do not line up. It is the ClickHouse twin of `no such column`.","causes":["A misspelled or differently cased column name.","The column exists on a different table than the one the query reads.","An alias is referenced outside the clause that defines it, or an upstream schema change renamed the column."],"fix":[{"text":"Check the real column names and their case.","sql":"SELECT name FROM system.columns WHERE database = 'my_db' AND table = 'my_table';"},{"text":"Qualify the column with the table name. An unqualified column that exists in both joined tables did not raise code 47 on 26.9.3.38; it resolved to the left table.","sql":"SELECT o.id FROM orders o JOIN users u ON o.user_id = u.id;"},{"text":"When a materialized view depends on a renamed column, add the new column to the view's target table first, then change its SELECT. MODIFY QUERY fails with code 16 (NO_SUCH_COLUMN_IN_TABLE) when the target lacks the column. A view with an implicit target was not tested here.","sql":"ALTER TABLE my_mv MODIFY QUERY SELECT id, new_name FROM my_table;"}],"diagnostic":"`system.columns` for what actually exists, `SHOW CREATE TABLE` for views that embed column lists, `system.query_log` for the failed query.","alternatives":"`EXISTS` and `system.columns` checks help generated SQL. `DESCRIBE TABLE` shows a table's columns fast.","details":[],"details_title":null,"repro":"CREATE TABLE scratch_c (id UInt32) ENGINE = MergeTree ORDER BY id; then run SELECT nope FROM scratch_c to get code 47.","repro_note":null,"related":["clickhouse/table-not-exists","clickhouse/syntax-error"],"sqlly":"SQLly's Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V on Windows and Linux) marks column names the connected ClickHouse schema does not have.","faqs":[{"question":"Is this the same as SYNTAX_ERROR?","answer":"No. 62 means the token stream could not parse. 47 means it parsed and a name did not resolve."},{"question":"Why do aliases in WHERE fail sometimes?","answer":"In ClickHouse 26.9 an alias from the same SELECT resolves in WHERE, in PREWHERE and inside aggregate arguments. Aggregate functions are still not allowed in WHERE; that fails with code 184 ILLEGAL_AGGREGATION."}],"aliases":[]},"source_url":"https://sqlly.app/errors/clickhouse/unknown-identifier","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/binder-error","corpus":"errors","engine":"duckdb","language":"en","title":"DuckDB could not plan the query","description":"DuckDB parsed the query but couldn't plan it: a missing column, an alias out of scope, or types that don't fit the function. A missing table raises Catalog Error instead.","body":{"code":"Binder Error","slug":"binder-error","name":null,"message":"Binder Error: Could not choose a best candidate function for the function call \"+(INTEGER_LITERAL, STRING_LITERAL)\". In order to select one, please add explicit type casts.","group":"binder","severity":null,"sql_state":null,"summary":"DuckDB parsed the query but couldn't plan it: a missing column, an alias out of scope, or types that don't fit the function. A missing table raises Catalog Error instead.","meaning":"`Binder Error` means the parser accepted the SQL but the binder could not resolve it against the catalog and the types. This is the class for the most common day-to-day mistakes: a column or table that does not exist, a function called with argument types that have no overload, or a struct key that is not there. DuckDB binds each statement before running it, so a bind error means that statement did not run. Statements earlier in the same script have already run.\n\nThe message says exactly which name, column or function signature failed. When the same SQL works elsewhere, compare the schema and the DuckDB version, because different builds ship different function overloads and extensions.","causes":["A column name that does not exist in the FROM clause, or a table alias used outside its scope.","A function called with argument types that match no overload, such as `1 + 'a'` or `avg(text_column)`.","A struct or union key that is not present, for example `{'a': 1}.b`.","A call to a function from an extension that is not loaded. DuckDB reports that as Catalog Error, not Binder Error."],"fix":[{"text":"Check the names the message mentions against the actual schema before changing the SQL:","sql":"DESCRIBE my_table;\nSELECT table_schema, table_name, column_name\nFROM information_schema.columns\nWHERE table_name = 'my_table';"},{"text":"Add explicit casts when the binder cannot pick an overload, so the operation is unambiguous:","sql":"SELECT int_col + CAST(text_col AS INTEGER) FROM my_table;"},{"text":"List the functions that do exist when a name fails. Some names are aliases with the same signatures, such as `group_concat` and `string_agg`:","sql":"SELECT function_name, parameter_types\nFROM duckdb_functions()\nWHERE function_name ILIKE '%agg%';"},{"text":"Load the extension a function belongs to when the name is unknown on this connection:","sql":"LOAD httpfs;"}],"diagnostic":"-- The message names the column, function or key that failed. Check what the connection can actually see:\nSELECT table_schema, table_name FROM information_schema.tables ORDER BY 1;\nDESCRIBE my_table;\n-- Which overloads exist for the function you called:\nSELECT function_name, parameter_types, return_type FROM duckdb_functions() WHERE function_name = 'substring';\nSELECT version();","alternatives":"If the column is genuinely missing, add it with ALTER TABLE rather than editing the query to fit the old schema. If the types are ambiguous, a cast in the query is better than relying on implicit conversion, which DuckDB keeps strict on purpose.","details":[],"details_title":null,"repro":"SELECT 1 + 'a';   -- Binder Error: Could not choose a best candidate function for the function call \"+(INTEGER_LITERAL, STRING_LITERAL)\". In order to select one, please add explicit type casts.","repro_note":null,"related":["duckdb/column-not-exist","duckdb/conversion-could-not-convert","duckdb/catalog-table-not-exist","duckdb/parser-syntax-error","sqlite/sqlite-error","postgresql/42703"],"sqlly":null,"faqs":[{"question":"Binder Error or Catalog Error: which one means a missing table?","answer":"A table that does not exist gives Catalog Error. A table that exists but lacks the column you named gives Binder Error."},{"question":"Why does the same query work in another tool?","answer":"The other tool may run a different DuckDB version or have extensions loaded. Check `version()` and `duckdb_extensions()` on both connections."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/binder-error","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/catalog-schema-not-exist","corpus":"errors","engine":"duckdb","language":"en","title":"The schema does not exist in this database","description":"A statement referenced a schema that is not in the connected database, so its objects cannot be reached.","body":{"code":"Catalog Error","slug":"catalog-schema-not-exist","name":null,"message":"Catalog Error: Schema with name no_such_schema does not exist!","group":"catalog","severity":null,"sql_state":null,"summary":"A statement referenced a schema that is not in the connected database, so its objects cannot be reached.","meaning":"DuckDB resolves qualified names as `database.schema.object`, and this error means the schema part is not one the connection can see. An unqualified name resolves against the search path, which points at the `main` schema of the connected database by default.\n\nAttached databases multiply the places a name can live: every attachment has its own `main` schema, and the same schema name can exist in two databases at once. The wording depends on the statement: `CREATE TABLE analytics.orders` and `DROP SCHEMA analytics` name the schema directly, while a query that reads through a missing schema reports the table instead, as `Table with name \"analytics.orders\" does not exist because schema \"analytics\" does not exist.`. In practice the name is misspelled, the object was created on another connection or another database, or a qualification points at the wrong attached alias.","causes":["A typo or wrong case in a qualified name such as analytics.orders.","The schema lives in an attached database, and the query used the wrong alias, or the ATTACH never ran on this connection.","The table was created in `main` while the query looks for it in another schema, or the search_path was changed.","A migration that creates the schema never ran on this connection."],"fix":[{"text":"List the schemas the connection can actually see:","sql":"SELECT database_name, schema_name\nFROM duckdb_schemas()\nORDER BY 1, 2;"},{"text":"Create the schema if it should exist, and qualify names while you populate it:","sql":"CREATE SCHEMA analytics;\nCREATE TABLE analytics.orders (id INTEGER, total DECIMAL(10,2));"},{"text":"Qualify with the attached database when the table lives there:","sql":"SELECT * FROM warehouse.main.orders LIMIT 5;"},{"text":"Point unqualified names at the right schema:","sql":"SET search_path = 'analytics,main';"}],"diagnostic":"-- Every schema in every attached database:\nSELECT database_name, schema_name FROM duckdb_schemas() ORDER BY 1, 2;\n-- Which databases are attached, and from which file:\nSELECT database_name, path FROM duckdb_databases();","alternatives":"Qualify every name in scripts that touch more than one database; unqualified names depend on the search path, which is invisible in the statement itself. Keep one migration per schema so creation and population cannot drift apart.","details":[],"details_title":null,"repro":"CREATE TABLE no_such_schema.t(a INTEGER);   -- Catalog Error: Schema with name no_such_schema does not exist!","repro_note":null,"related":["duckdb/catalog-table-not-exist","duckdb/catalog-table-exists","postgresql/3F000","mysql/1049"],"sqlly":null,"faqs":[{"question":"Where do temporary tables and views live?","answer":"In the temp database, under temp.main. Qualify them as temp.main.name when another schema is first in the search path."},{"question":"Why is my table invisible after ATTACHing a second database?","answer":"Each database has its own schemas. An unqualified name resolves inside the connected database, not the attachment, so qualify it as attached.main.table or change the search path."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/catalog-schema-not-exist","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/catalog-table-exists","corpus":"errors","engine":"duckdb","language":"en","title":"The table or object already exists","description":"A CREATE statement tried to add a table, view, schema or macro whose name is already taken in the same schema.","body":{"code":"Catalog Error","slug":"catalog-table-exists","name":null,"message":"Catalog Error: Table with name \"t\" already exists!","group":"catalog","severity":null,"sql_state":null,"summary":"A CREATE statement tried to add a table, view, schema or macro whose name is already taken in the same schema.","meaning":"DuckDB refuses to overwrite catalog objects, so `CREATE TABLE` without `IF NOT EXISTS` fails when the name is taken. The message quotes the name and names the kind of object when it is not a table, for example `Macro Function with name \"m\" already exists!`.\n\nIn scripts that run more than once, this error is the normal second run. The fix is usually to make the statement idempotent rather than to drop data.","causes":["A CREATE TABLE, CREATE VIEW, CREATE SCHEMA or CREATE MACRO without IF NOT EXISTS or OR REPLACE, run a second time.","A migration that already ran, applied again by a rerun or a second deployment target.","Two processes creating the same object concurrently.","The name collides with a different kind of object in the same schema, since DuckDB shares one namespace per schema for tables and views."],"fix":[{"text":"Make the statement idempotent so reruns are harmless:","sql":"CREATE TABLE IF NOT EXISTS metrics (id INTEGER, ts TIMESTAMP);\nCREATE OR REPLACE VIEW recent_metrics AS SELECT * FROM metrics WHERE ts > now() - INTERVAL 1 DAY;"},{"text":"Check what already owns the name before replacing it:","sql":"SELECT table_name, table_type FROM information_schema.tables WHERE table_name = 'metrics';"},{"text":"If the old object really must go, drop it explicitly rather than relying on CREATE to overwrite:","sql":"DROP TABLE IF EXISTS metrics;"}],"diagnostic":"-- See the object that holds the name, including its type:\nSELECT table_schema, table_name, table_type FROM information_schema.tables WHERE table_name = 'metrics';\nSELECT database_name, schema_name, table_name, temporary FROM duckdb_tables() WHERE table_name = 'metrics';\n-- A temp object of the same name does not collide: it lives in database 'temp' and, for unqualified names, DuckDB resolves to the temp one first:\nSELECT * FROM duckdb_databases();","alternatives":"In migration tooling, prefer a migrations ledger over IF NOT EXISTS everywhere: record which scripts ran and skip them, so a name change cannot silently leave an old table behind.","details":[],"details_title":null,"repro":"CREATE TABLE t(a INT);\nCREATE TABLE t(a INT);   -- Catalog Error: Table with name \"t\" already exists!","repro_note":null,"related":["duckdb/catalog-table-not-exist","duckdb/catalog-schema-not-exist","sqlite/sqlite-error","postgresql/42P07"],"sqlly":null,"faqs":[{"question":"Does CREATE OR REPLACE work for tables?","answer":"Yes. CREATE OR REPLACE TABLE drops the existing table and its data, then creates the new one, so use it only when losing the data is intended. Use CREATE TABLE IF NOT EXISTS to keep existing data."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/catalog-table-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/catalog-table-not-exist","corpus":"errors","engine":"duckdb","language":"en","title":"The table does not exist in this database","description":"DuckDB cannot find the named table, view or table function in the catalog of the database you are connected to.","body":{"code":"Catalog Error","slug":"catalog-table-not-exist","name":null,"message":"Catalog Error: Table with name no_such_table does not exist!","group":"catalog","severity":null,"sql_state":null,"summary":"DuckDB cannot find the named table, view or table function in the catalog of the database you are connected to.","meaning":"This is DuckDB's missing-object error. The binder looked up the name in the catalog and found nothing with it: no table, no view, no table function. For a missing table the message spells out `Table with name X does not exist!`. A missing table function reports `Table Function with name X does not exist!`.\n\nBecause DuckDB is often embedded, the usual cause is not a typo but the wrong database: the application opened a fresh in-memory database, the file path resolved relative to a different working directory, or the query ran on a connection that never created the schema. Lookups are case-insensitive even for names created in double quotes, so a table created as \"V07Mixed\" is found by SELECT * FROM v07mixed and SELECT * FROM \"v07mixed\".","causes":["A misspelled table name. Casing does not matter, even for names created with double quotes.","The query ran against a different database than you think, often a new in-memory one opened by default.","A table function from an extension that is not loaded, such as `iceberg_scan` with autoloading disabled, does not bind. Built-in functions such as `read_csv_auto` need no extension and fail with an IO error on a missing file, not a catalog error.","The migration that creates the table never ran on this connection."],"fix":[{"text":"List what actually exists in the connected database before rewriting the query:","sql":"SELECT table_schema, table_name, table_type\nFROM information_schema.tables\nORDER BY 1, 2;"},{"text":"Check which database file the connection opened. An empty catalog usually means the process opened a new or in-memory database:","sql":"SELECT current_database(), database_name, path FROM duckdb_databases();"},{"text":"Qualify the name if the table lives in another attached database:","sql":"SELECT * FROM backup.users LIMIT 5;"},{"text":"Create the table if it should exist, with IF NOT EXISTS so reruns are safe:","sql":"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email VARCHAR);"}],"diagnostic":"-- What tables does this connection see, and from which file?\nSELECT database_name, schema_name, table_name, estimated_size FROM duckdb_tables();\nSELECT database_name, path FROM duckdb_databases();\n-- Search every catalog position of the name, including views and table functions:\nSELECT * FROM duckdb_tables() WHERE table_name ILIKE '%users%';\nSELECT function_name FROM duckdb_functions() WHERE function_name ILIKE '%users%';","alternatives":"If the table should exist, run the migration on this connection instead of working around it. If it should not, point the connection at the right file with an absolute path; relative paths are resolved against the process working directory, which is rarely what you expect in a service.","details":[],"details_title":null,"repro":"SELECT * FROM no_such_table;   -- Catalog Error: Table with name no_such_table does not exist!","repro_note":null,"related":["duckdb/catalog-table-exists","duckdb/column-not-exist","duckdb/io-file-not-found","sqlite/sqlite-error","postgresql/42P01","mysql/1146"],"sqlly":null,"faqs":[{"question":"The table exists in my file. Why does DuckDB say it does not?","answer":"The connection is probably not on that file. Embedded apps often open an unnamed in-memory database by default, and a relative path may have resolved elsewhere. Run SELECT * FROM duckdb_databases() to see the path of what you are connected to."},{"question":"Does capitalization matter?","answer":"Names are matched case-insensitively, including names created inside double quotes. A name created as \"V07Mixed\" is found by any casing, quoted or not."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/catalog-table-not-exist","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/column-not-exist","corpus":"errors","engine":"duckdb","language":"en","title":"The column is not in the FROM clause","description":"The query names a column that no table or alias in its FROM clause provides, so DuckDB cannot bind it.","body":{"code":"Binder Error","slug":"column-not-exist","name":null,"message":"Binder Error: Referenced column \"nope\" not found in FROM clause!","group":"binder","severity":null,"sql_state":null,"summary":"The query names a column that no table or alias in its FROM clause provides, so DuckDB cannot bind it.","meaning":"The binder resolved the FROM clause first, then looked up every column reference in it. The name in quotes is the one it could not find anywhere in that scope. DuckDB will not guess: a missing column is an error even when another table in the database has it.\n\nTypical traps are the wrong alias (or no alias where a subquery needs one), a CTE referenced by a column it does not select, and a USING/JOIN that narrowed which columns remain visible. In INSERT or UPDATE the same class appears when the target table lacks a column you name.","causes":["A misspelled column name. Matching ignores case, quoted or not, so a wrong case alone does not cause this error.","The column belongs to a table that is not in the FROM clause, or a missing join to reach it.","A subquery or CTE that does not project the column, so the outer query cannot see it.","A GROUP BY or window context where the column is neither grouped nor aggregated, which DuckDB reports as a binder problem about the column."],"fix":[{"text":"Check the real columns of the table you query, not the ones you remember:","sql":"DESCRIBE my_table;\nSELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'my_table' ORDER BY ordinal_position;"},{"text":"When the name may exist in several tables, find which one has it:","sql":"SELECT table_schema, table_name FROM information_schema.columns WHERE column_name = 'email' ORDER BY 1, 2;"},{"text":"Qualify ambiguous references with the table or alias so the binder knows which one you mean:","sql":"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;"},{"text":"Project a column in a CTE if the outer query needs it:","sql":"WITH recent AS (SELECT id, email FROM users WHERE created_at > now() - INTERVAL 7 DAY)\nSELECT email FROM recent;"}],"diagnostic":"-- What does the query actually have to work with?\nDESCRIBE my_table;\n-- Every column named email anywhere in the catalog:\nSELECT table_schema, table_name, column_name FROM information_schema.columns WHERE column_name ILIKE '%email%';\n-- Which tables are in the statement's scope:\nSELECT * FROM duckdb_tables() WHERE table_name IN ('orders','customers');","alternatives":"If the column is genuinely missing, add it with ALTER TABLE ... ADD COLUMN rather than changing the query. If the name is ambiguous across joins, always qualify references; unqualified names fail with an ambiguous-reference Binder Error (for example: Ambiguous reference to column name \"id\" (use: 'o.id' or 'c.id')) when a new column with the same name appears in the other table.","details":[],"details_title":null,"repro":"SELECT nope FROM range(3);   -- Binder Error: Referenced column \"nope\" not found in FROM clause!","repro_note":null,"related":["duckdb/binder-error","duckdb/catalog-table-not-exist","duckdb/conversion-could-not-convert","postgresql/42703","mysql/1054","sqlite/sqlite-error"],"sqlly":null,"faqs":[{"question":"The column exists. Why is it not found?","answer":"Check the scope, not just the database. Inside a join, subquery or CTE, only the columns the clause projects are visible, and an alias may hide the table that has the column."},{"question":"Does quoting change how a column name is matched?","answer":"No. DuckDB matches column names case-insensitively whether or not they are quoted, so a column created as \"Email\" is found by email, \"EMAIL\" or \"Email\"."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/column-not-exist","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/constraint-check","corpus":"errors","engine":"duckdb","language":"en","title":"A CHECK constraint rejected the row","description":"An INSERT or UPDATE produced a row that failed a CHECK expression declared on the table.","body":{"code":"Constraint Error","slug":"constraint-check","name":null,"message":"Constraint Error: CHECK constraint failed on table \"t\" with expression CHECK((a > 0))","group":"constraint","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE produced a row that failed a CHECK expression declared on the table.","meaning":"A CHECK constraint is an expression evaluated per row on INSERT and UPDATE. When it comes out false, DuckDB rejects the row and the whole statement fails: in a multi-row insert nothing lands. NULL passes, as in standard SQL, because a CHECK only rejects rows where the expression evaluates false.\n\nThe message shows the table and the exact expression, which is usually enough to see what was refused. When the expression itself throws instead of returning false, for example a cast inside the CHECK, recent DuckDB versions append the inner error as `(Error: ...)`, so read that part too.","causes":["An INSERT or UPDATE with a value the expression refuses, such as a negative quantity or a date before a lower bound.","A default that itself violates the CHECK, so omitting the column fails the insert.","A COPY or INSERT INTO ... SELECT where some source rows fail the expression even though the statement as a whole looks correct.","An UPDATE that changes one column of a multi-column CHECK and leaves the row inconsistent."],"fix":[{"text":"List the rows that would fail before inserting. NULLs pass, so the check excludes them:","sql":"SELECT * FROM stage\nWHERE quantity IS NOT NULL AND NOT (quantity > 0);"},{"text":"Repair or filter the source, then insert:","sql":"INSERT INTO orders\nSELECT * FROM stage WHERE quantity > 0;"},{"text":"DuckDB cannot add or drop a CHECK with ALTER TABLE, so a wrong constraint means rebuilding the table:","sql":"CREATE TABLE orders_new (quantity INTEGER CHECK (quantity > 0));\nINSERT INTO orders_new SELECT * FROM orders;\nALTER TABLE orders RENAME TO orders_old;\nALTER TABLE orders_new RENAME TO orders;"}],"diagnostic":"-- The CHECK expressions declared on the table:\nSELECT constraint_type, constraint_text FROM duckdb_constraints() WHERE table_name = 'orders';\n-- The columns the expression touches:\nDESCRIBE orders;","alternatives":"Where the rule is really a data-quality check rather than an invariant, validate at load time and report rejects instead, since DuckDB cannot alter a CHECK on an existing table. Keep CHECKs for invariants that must never break, such as positive quantities or an end date after the start date.","details":[],"details_title":null,"repro":"CREATE TABLE t(a INT CHECK (a > 0));\nINSERT INTO t VALUES (0);   -- Constraint Error: CHECK constraint failed on table \"t\" with expression CHECK((a > 0))","repro_note":null,"related":["duckdb/constraint-not-null","duckdb/constraint-unique","postgresql/23514","sqlite/sqlite-constraint"],"sqlly":null,"faqs":[{"question":"Does NULL pass a CHECK constraint?","answer":"Yes. A CHECK rejects only rows where the expression evaluates false. To forbid NULL as well, declare the column NOT NULL."},{"question":"Which row failed?","answer":"The message names the constraint, not the row, and the statement fails as a whole. Run the insert as a SELECT with NOT (expression) against the source to list the offending rows."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/constraint-check","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/constraint-not-null","corpus":"errors","engine":"duckdb","language":"en","title":"A NOT NULL column received NULL","description":"An INSERT or UPDATE tried to store NULL in a column declared NOT NULL, and DuckDB rejected the row.","body":{"code":"Constraint Error","slug":"constraint-not-null","name":null,"message":"Constraint Error: NOT NULL constraint failed: t.a","group":"constraint","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE tried to store NULL in a column declared NOT NULL, and DuckDB rejected the row.","meaning":"DuckDB enforces constraints per row at write time. The message names the table and column, `NOT NULL constraint failed: t.a`, and the whole statement fails, so in a multi-row INSERT no row from it lands.\n\nThe NULL does not have to be literal. It can come from a LEFT JOIN that found no match, a DEFAULT that is itself NULL, or a SELECT whose WHERE clause filtered differently than the author expected. In COPY and INSERT from a query, one bad source row aborts the statement.","causes":["An INSERT that omits the column and the table has no non-NULL default for it.","A literal NULL or an expression that evaluates to NULL, often from a LEFT JOIN or a TRY_CAST that failed. A plain CAST that fails raises a Conversion Error instead.","An UPDATE that sets the column to NULL.","A COPY or INSERT INTO ... SELECT where a source row holds NULL in that position."],"fix":[{"text":"Find the rows that would violate the constraint before inserting:","sql":"SELECT * FROM stage WHERE a IS NULL;"},{"text":"Give the column a sensible fallback with COALESCE, or filter the rows out:","sql":"INSERT INTO t (a) SELECT coalesce(a, 0) FROM stage;\nINSERT INTO t (a) SELECT a FROM stage WHERE a IS NOT NULL;"},{"text":"Declare a DEFAULT so omitted columns never become NULL:","sql":"ALTER TABLE t ALTER COLUMN a SET DEFAULT 0;"}],"diagnostic":"-- Which target columns are NOT NULL and what defaults do they have?\nPRAGMA table_info('t');\n-- Or with the catalog views:\nSELECT column_name, is_nullable, column_default FROM information_schema.columns WHERE table_name = 't';\n-- Which source rows would fail:\nSELECT count(*) FROM stage WHERE a IS NULL;","alternatives":"If NULL is a legitimate state for the data, drop the NOT NULL constraint with ALTER TABLE ... ALTER COLUMN ... DROP NOT NULL instead of writing sentinel values such as empty strings or zero, which pollute every later query.","details":[],"details_title":null,"repro":"CREATE TABLE t(a INT NOT NULL);\nINSERT INTO t VALUES (NULL);   -- Constraint Error: NOT NULL constraint failed: t.a","repro_note":null,"related":["duckdb/constraint-unique","duckdb/constraint-check","duckdb/conversion-could-not-convert","postgresql/23502","sqlite/sqlite-constraint"],"sqlly":null,"faqs":[{"question":"Does the whole INSERT fail or just the bad row?","answer":"The whole statement fails and no row from it is inserted. Use an INSERT ... SELECT with a WHERE that excludes the bad rows, or fix the source first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/constraint-not-null","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/constraint-unique","corpus":"errors","engine":"duckdb","language":"en","title":"A duplicate key violates a unique constraint","description":"An INSERT or UPDATE tried to store a value that another row already holds in a PRIMARY KEY or UNIQUE column.","body":{"code":"Constraint Error","slug":"constraint-unique","name":null,"message":"Constraint Error: Duplicate key \"a: 1\" violates primary key constraint.","group":"constraint","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE tried to store a value that another row already holds in a PRIMARY KEY or UNIQUE column.","meaning":"DuckDB keeps indexes for PRIMARY KEY and UNIQUE columns and rejects any write that would create a second row with the same key. The message shows the key as `Duplicate key \"a: 1\" violates primary key constraint.` (or `unique constraint` for a UNIQUE column), so you can see the exact value that collided. Inside an open transaction, when the colliding row was written earlier in that same transaction and not yet committed, DuckDB 2.0.1 reports `Constraint Error: PRIMARY KEY or UNIQUE constraint violation: duplicate key \"1\"` instead, which names no column. Run the repro in autocommit mode to see the message shown above.\n\nIn multi-row writes the statement fails as a whole. ON CONFLICT DO NOTHING or DO UPDATE makes single-row conflicts resolvable, but DuckDB cannot target several unique constraints in one statement. A DO UPDATE on a table with several UNIQUE or PRIMARY KEY constraints must name its target, or DuckDB returns `Binder Error: Conflict target has to be provided for a DO UPDATE operation when the table has multiple UNIQUE/PRIMARY KEY constraints`.","causes":["An INSERT with a key that a committed row already has.","A replayed load or a retry that inserts the same batch twice without idempotency keys.","An UPDATE that moves a key onto a value another row holds.","Two unique constraints on one table with an ON CONFLICT clause that cannot cover both."],"fix":[{"text":"See the row that already holds the key in the message:","sql":"SELECT * FROM t WHERE a = 1;"},{"text":"Upsert instead of plain INSERT when a replay is possible:","sql":"INSERT INTO t (a) VALUES (1) ON CONFLICT (a) DO UPDATE SET a = EXCLUDED.a;"},{"text":"Deduplicate the source before a bulk load, keeping one row per key:","sql":"INSERT INTO t (a) SELECT a FROM (SELECT *, row_number() OVER (PARTITION BY a ORDER BY id) AS rn FROM stage) WHERE rn = 1;"}],"diagnostic":"-- Which keys exist twice in the source you are loading?\nSELECT a, count(*) FROM stage GROUP BY a HAVING count(*) > 1;\n-- The rows already in the target that the load would hit:\nSELECT t.* FROM t JOIN stage s ON t.a = s.a;\n-- The constraints on the table:\nSELECT constraint_type, constraint_text FROM duckdb_constraints() WHERE table_name = 't';","alternatives":"If the data legitimately contains repeats, the constraint is wrong: drop the PRIMARY KEY or UNIQUE and enforce uniqueness at load time with a deduplication step. Keep the constraint only if the table is meant to hold one row per key.","details":[],"details_title":null,"repro":"CREATE TABLE t(a INT PRIMARY KEY);\nINSERT INTO t VALUES (1);\nINSERT INTO t VALUES (1);   -- Constraint Error: Duplicate key \"a: 1\" violates primary key constraint.","repro_note":null,"related":["duckdb/constraint-not-null","duckdb/constraint-check","duckdb/conversion-could-not-convert","postgresql/23505","sqlite/sqlite-constraint"],"sqlly":null,"faqs":[{"question":"Can I catch the conflict and continue with the next row?","answer":"Not inside one statement: the statement fails as a whole. Use ON CONFLICT for known keys, or load into a staging table, keep one row per key (SELECT DISTINCT, or the row_number() step in the fix above), and insert with a WHERE NOT EXISTS against the target. A staging table with repeated keys fails the WHERE NOT EXISTS insert too."},{"question":"Why does DuckDB say primary key when my column is UNIQUE?","answer":"Read the end of the message: it says `unique constraint` for UNIQUE columns and `primary key constraint` for PRIMARY KEY columns."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/constraint-unique","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/conversion-could-not-convert","corpus":"errors","engine":"duckdb","language":"en","title":"The value cannot be cast to the target type","description":"A cast or implicit conversion met a value it cannot represent in the destination type, such as 'abc' as an integer.","body":{"code":"Conversion Error","slug":"conversion-could-not-convert","name":null,"message":"Conversion Error: Could not convert string 'abc' to INT32","group":"conversion","severity":null,"sql_state":null,"summary":"A cast or implicit conversion met a value it cannot represent in the destination type, such as 'abc' as an integer.","meaning":"DuckDB applies casts eagerly: a comparison between text and a number, a COPY into a typed table, or a CSV import all convert values, and the first bad value raises `Conversion Error`. The message shows the offending value and the destination type, for example `Could not convert string 'abc' to INT32`.\n\nConversion and parsing are related but distinct. `Could not convert string` covers plain casts; malformed dates give their own wording (`invalid date field format: \"31/12/2024\", expected format is (YYYY-MM-DD)`), malformed timestamps give `invalid timestamp field format` with their own expected format, and an impossible but well-formed value gives `date field value out of range` (or `timestamp field value out of range`). Arithmetic overflow gives `Out of Range Error` instead.","causes":["A text value with letters, spaces or a wrong separator cast to a numeric type.","A CSV read with an explicit numeric column type, or a COPY into a typed table, where some rows hold text. Auto-detection does not fail on this: it infers VARCHAR for the column.","An implicit cast in a comparison where the two sides have different types, such as `'abc' = 5`.","A malformed date, time or timestamp string that does not match the expected format."],"fix":[{"text":"Find the bad values before casting, so the fix is data-driven:","sql":"SELECT raw_value FROM stage\nWHERE raw_value IS NOT NULL AND NOT regexp_matches(raw_value, '^-?[0-9]+$');"},{"text":"Cast with TRY_CAST, which returns NULL for values it cannot convert instead of failing the query:","sql":"SELECT TRY_CAST(raw_value AS INTEGER) FROM stage;"},{"text":"For CSV files, scan everything as VARCHAR first and convert explicitly with a rule:","sql":"CREATE TABLE stage AS\nSELECT * FROM read_csv('input.csv', all_varchar = true);\nSELECT TRY_CAST(amount AS DECIMAL(12,2)) FROM stage;"},{"text":"Parse nonstandard formats with a format hint rather than a plain cast:","sql":"SELECT strptime(ts_text, '%d/%m/%Y %H:%M') FROM events;"}],"diagnostic":"-- Which rows hold values that will not convert? Count them before fixing:\nSELECT count(*) FROM stage WHERE TRY_CAST(raw_value AS INTEGER) IS NULL AND raw_value IS NOT NULL;\n-- A sample of the offending values:\nSELECT raw_value FROM stage WHERE TRY_CAST(raw_value AS INTEGER) IS NULL AND raw_value IS NOT NULL LIMIT 20;\n-- The inferred types a CSV read would use:\nDESCRIBE SELECT * FROM read_csv_auto('input.csv');","alternatives":"TRY_CAST is the quick fix, but it hides bad rows. For a pipeline, split the load: import as VARCHAR, log the rows that fail the cast, and insert only the clean ones into the typed table.","details":[],"details_title":null,"repro":"SELECT 'abc'::INTEGER;   -- Conversion Error: Could not convert string 'abc' to INT32","repro_note":null,"related":["duckdb/conversion-out-of-range","duckdb/binder-error","postgresql/22P02","postgresql/22003","sqlite/sqlite-error"],"sqlly":null,"faqs":[{"question":"How do I import a CSV that has bad rows without failing the whole load?","answer":"Read with all_varchar = true into a staging table, then TRY_CAST into the typed table and review the rows that came out NULL."},{"question":"Why does the message say INT32 when my column is INTEGER?","answer":"DuckDB stores INTEGER as a 32-bit integer, so messages name the physical type. INTEGER is INT32, BIGINT is INT64, TINYINT is INT8."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/conversion-could-not-convert","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/conversion-invalid-date","corpus":"errors","engine":"duckdb","language":"en","title":"The date or timestamp string is malformed","description":"A string cast to DATE, TIME or TIMESTAMP did not match the format DuckDB expects.","body":{"code":"Conversion Error","slug":"conversion-invalid-date","name":null,"message":"Conversion Error: invalid date field format: \"not a date\", expected format is (YYYY-MM-DD)","group":"conversion","severity":null,"sql_state":null,"summary":"A string cast to DATE, TIME or TIMESTAMP did not match the format DuckDB expects.","meaning":"Casting text to a temporal type uses DuckDB's own expected layout: `YYYY-MM-DD` for dates and the ISO layout for timestamps. When a value does not fit, the error quotes the offending string and the expected format, and the whole statement stops on the first bad value.\n\nA plain cast takes no format argument and is all-or-nothing. Text in another layout, such as `25/12/2024`, is not read as a date at all: parse it with `strptime`, which takes an explicit format string, or with `try_strptime`, which returns NULL for values that do not match instead of failing.","causes":["A CSV column inferred as DATE or TIMESTAMP while some rows hold text in another layout.","Day-first or month-first strings such as 25/12/2024, which no plain cast accepts.","Locale month names such as Dec 25 2024, which no plain cast accepts.","An empty string cast to DATE, which fails instead of becoming NULL."],"fix":[{"text":"See how many values will not parse before changing the load:","sql":"SELECT count(*) FROM stage\nWHERE raw_date IS NOT NULL AND TRY_CAST(raw_date AS DATE) IS NULL;"},{"text":"Parse a known nonstandard layout with strptime:","sql":"SELECT strptime(raw_date, '%d/%m/%Y')::DATE FROM stage;"},{"text":"Read the file as text first and parse deliberately. This assumes every row uses the same layout. For a mixed column, use the try_strptime step below instead:","sql":"CREATE TABLE stage AS\nSELECT * FROM read_csv('input.csv', all_varchar = true);\nSELECT strptime(raw_date, '%d/%m/%Y')::DATE FROM stage;"},{"text":"For values that may be dirty, use try_strptime and inspect what came back NULL:","sql":"SELECT raw_date FROM stage\nWHERE try_strptime(raw_date, '%d/%m/%Y') IS NULL AND raw_date IS NOT NULL;"}],"diagnostic":"-- Rows that refuse the plain cast, with the actual text:\nSELECT raw_date FROM stage\nWHERE raw_date IS NOT NULL AND TRY_CAST(raw_date AS DATE) IS NULL LIMIT 20;\n-- What type a CSV scan would infer for the column:\nDESCRIBE SELECT * FROM read_csv_auto('input.csv');","alternatives":"Fixing the format at the source beats fixing it in SQL: ask the producer for ISO dates if you can. When the file is the constraint, keep the column as VARCHAR in staging and parse once into a typed table, so the rule lives in one place.","details":[],"details_title":null,"repro":"SELECT 'not a date'::DATE;   -- Conversion Error: invalid date field format: \"not a date\", expected format is (YYYY-MM-DD)","repro_note":null,"related":["duckdb/conversion-could-not-convert","duckdb/conversion-out-of-range","postgresql/22007"],"sqlly":null,"faqs":[{"question":"What format does DuckDB expect for dates?","answer":"ISO: YYYY-MM-DD for DATE and YYYY-MM-DD HH:MM:SS for TIMESTAMP. Anything else needs strptime with an explicit format."},{"question":"How do I handle a column with mixed date formats?","answer":"Normalize in staging: read as VARCHAR, try each format with coalesce(try_strptime(x, f1), try_strptime(x, f2)), and route what is left to a rejects list."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/conversion-invalid-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/conversion-out-of-range","corpus":"errors","engine":"duckdb","language":"en","title":"The value is out of range for INT32","description":"A cast met a number the destination type cannot hold, for example 99999999999 cast to INTEGER.","body":{"code":"Conversion Error","slug":"conversion-out-of-range","name":null,"message":"Conversion Error: Type INT64 with value 99999999999 can't be cast because the value is out of range for the destination type INT32","group":"conversion","severity":null,"sql_state":null,"summary":"A cast met a number the destination type cannot hold, for example 99999999999 cast to INTEGER.","meaning":"A cast reached a value that fits the source type but not the destination: `99999999999` is a valid BIGINT, and casting it to INTEGER fails because INTEGER stops at 2147483647. The message names the physical types: `INT64` is BIGINT and `INT32` is INTEGER, so it tells you both the value and the type that refused it.\n\nKeep this class apart from its neighbors. `Could not convert string 'abc' to INT32` means the value is the wrong kind, and `Out of Range Error: Overflow in multiplication of INT8` means arithmetic overflowed after the fact. Here the value exists, the cast is the right idea, and the destination type is too small.","causes":["A literal or computed value wider than the column type, for example loading BIGINT counts into an INTEGER column.","A CSV or Parquet import where the column was declared or inferred narrower than the data it holds.","A DECIMAL(4,2) column receiving 100.00, which needs three digits before the decimal point."],"fix":[{"text":"Count and inspect the values that will not fit before changing anything:","sql":"SELECT count(*) FROM stage\nWHERE amount IS NOT NULL AND TRY_CAST(amount AS INTEGER) IS NULL;"},{"text":"Widen the column to the smallest type that holds the real range:","sql":"ALTER TABLE measurements ALTER COLUMN amount TYPE BIGINT;"},{"text":"For imports, declare the type up front so the scan does not decide for you:","sql":"SELECT * FROM read_csv('input.csv', types = {'amount': 'BIGINT'});"},{"text":"When out-of-range rows are expected, sort them out with TRY_CAST instead of failing the load:","sql":"SELECT TRY_CAST(amount AS INTEGER) FROM stage;"}],"diagnostic":"-- The declared type of the target column:\nDESCRIBE my_table;\n-- How far out of range the source values are, and how many:\nSELECT min(amount), max(amount), count(*) FROM stage\nWHERE TRY_CAST(amount AS INTEGER) IS NULL AND amount IS NOT NULL;","alternatives":"Widening the column is usually right because the data is what it is. Clamping with least and greatest, or dropping rows via TRY_CAST, silently changes data, so only do it with a rule the owner of the numbers would accept.","details":[],"details_title":null,"repro":"SELECT 99999999999::INTEGER;   -- Conversion Error: Type INT64 with value 99999999999 can't be cast because the value is out of range for the destination type INT32","repro_note":null,"related":["duckdb/conversion-could-not-convert","duckdb/conversion-invalid-date","postgresql/22003"],"sqlly":null,"faqs":[{"question":"Why does the message say INT32 when my column is INTEGER?","answer":"DuckDB messages name physical types: INTEGER is INT32, BIGINT is INT64, TINYINT is INT8. Read INT32 as INTEGER."},{"question":"Can I get NULL instead of an error for bad values?","answer":"Use TRY_CAST: it returns NULL when the value does not fit, so you can filter or count the out-of-range rows instead of failing the statement."}],"aliases":["value-out-of-range"]},"source_url":"https://sqlly.app/errors/duckdb/conversion-out-of-range","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/io-file-not-found","corpus":"errors","engine":"duckdb","language":"en","title":"A file could not be opened","description":"DuckDB could not open, create or read a file it was pointed at: a missing database file, a bad path in read_csv, or an unreadable directory.","body":{"code":"IO Error","slug":"io-file-not-found","name":null,"message":"IO Error: Cannot open file \"/tmp/missing/db.duckdb\": No such file or directory","group":"io-file","severity":null,"sql_state":null,"summary":"DuckDB could not open, create or read a file it was pointed at: a missing database file, a bad path in read_csv, or an unreadable directory.","meaning":"`IO Error` is the class for file-level failures outside the engine: ATTACH on a path whose parent directory does not exist (an unknown file name in an existing directory creates a new empty database instead), read_csv over a pattern that matches nothing, or a file operation in a directory the process cannot enter. The message carries the operating system's reason, such as `No such file or directory` or `Permission denied`, after the path.\n\nTwo messages mean different things: `Cannot open file ... No such file or directory` comes from opening a database path such as ATTACH, while read_csv and read_parquet report `No files found that match the pattern ...` for any path that matches no file, including a plain path that does not exist. Relative paths are resolved against the process working directory, which is the usual reason a file that exists is reported missing.","causes":["The database file path is wrong, relative to the wrong directory, or the file was moved or deleted.","A parent directory of the target does not exist, so DuckDB cannot create the file in it.","A read_csv or read_parquet pattern matched no files, for example after an upstream job renamed its outputs.","A network share or removable drive is unmounted, so the path exists in name only."],"fix":[{"text":"Check that the path exists and is reachable from the process, using the exact path the error printed:","sql":"SELECT * FROM glob('/data/exports/*.parquet');"},{"text":"Use absolute paths when opening a database, so the working directory cannot change the meaning:","sql":"ATTACH '/var/lib/myapp/warehouse.duckdb' AS wh;"},{"text":"For reads, check the files exist before querying, and list what a pattern matched:","sql":"SELECT file FROM glob('/data/exports/*.parquet');"},{"text":"Create missing directories outside DuckDB first; it will not mkdir for ATTACH targets.","sql":null}],"diagnostic":"-- Does the pattern match anything, and what exactly?\nSELECT * FROM glob('/data/exports/*.parquet');\n-- What can this process see at the directory level:\nSELECT * FROM glob('/data/*');\n-- For a database file, check the connection actually points where you think:\nSELECT database_name, path FROM duckdb_databases();","alternatives":"If the file is genuinely gone, restore from backup before any write attempt; DuckDB may create a fresh empty database at the same path, which then looks like a data loss. For external files that arrive late, check with glob in the orchestrator before scheduling the query.","details":[],"details_title":null,"repro":"ATTACH '/nonexistent_dir/db.duckdb';   -- IO Error: Cannot open file \"/nonexistent_dir/db.duckdb\": No such file or directory","repro_note":null,"related":["duckdb/io-lock","duckdb/catalog-table-not-exist","duckdb/out-of-memory","sqlite/sqlite-cantopen","postgresql/58P01"],"sqlly":null,"faqs":[{"question":"The file is right there. Why can't DuckDB open it?","answer":"The process's working directory is probably not where you think. A relative path resolves against it, so run the open with an absolute path or print the working directory from the same process."},{"question":"read_csv says no files found but my path is a plain file. Why?","answer":"Table functions like read_csv accept globs, and the pattern message appears when nothing matches. Check the pattern with SELECT * FROM glob('...') to see what it resolves to."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/io-file-not-found","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/io-lock","corpus":"errors","engine":"duckdb","language":"en","title":"The database file is locked by another process","description":"Another process holds the write lock on the DuckDB file, so this process cannot open it read-write.","body":{"code":"IO Error","slug":"io-lock","name":null,"message":"IO Error: Could not set lock on file \"/data/db.duckdb\": Conflicting lock is held by another process. See also https://duckdb.org/docs/current/connect/concurrency","group":"io-file","severity":null,"sql_state":null,"summary":"Another process holds the write lock on the DuckDB file, so this process cannot open it read-write.","meaning":"DuckDB allows many processes on one file only if all of them are read-only. The first read-write connection takes an exclusive lock for the lifetime of its process, and any second process that wants the file read-write fails with this error. Inside a single process several connections share one lock, so the error can only come from a second process.\n\nThe wording varies by version: recent builds name the holder, for example `Conflicting lock is held in /usr/local/bin/duckdb (PID 4242) by user app`, and older builds say `Conflicting lock is held by another process`. Both point at the same file and the same collision.","causes":["A second process opened the same file read-write: a CLI session, a notebook kernel, a background job or another instance of your app.","An orchestrator retry started a new run while the previous one still holds the file.","The file sits on a network share where file locking behaves differently, so who holds the lock is unclear."],"fix":[{"text":"Find the holder with your operating system's tools and close it, then retry. On macOS and Linux, lsof lists the process that has the file open.","sql":null},{"text":"When you only need to query, open read-only. This only works when no read-write process holds the file, so it does not coexist with a running writer:","sql":"ATTACH '/data/db.duckdb' AS wh (READ_ONLY);  -- fails while a read-write process holds the file"},{"text":"Route all writes through one process. DuckDB has no cross-process table or row locks, so the choices are one writer plus readers that open only after the writer exits, or everything read-only.","sql":"SELECT database_name, path FROM duckdb_databases();"},{"text":"Serialize background jobs against each other in the orchestrator so two runs cannot target the same file at once.","sql":null}],"diagnostic":"-- Confirm which file this connection actually opened, and whether it is read-only:\nSELECT database_name, path, readonly FROM duckdb_databases();\n-- Then, in your shell (not in DuckDB), list the processes holding it:\n-- lsof /data/db.duckdb","alternatives":"If several processes must work against the same data at once, give each writer its own DuckDB file and keep the shared data in Parquet or CSV, which every process can read concurrently. A single DuckDB file with one writer and read-only readers is the supported shape.","details":[],"details_title":null,"repro":"ATTACH 'lock_demo.duckdb' AS db;\n-- Keep this session open. In a second session run the same line:\nATTACH 'lock_demo.duckdb' AS db;   -- IO Error: Could not set lock on file \"lock_demo.duckdb\": Conflicting lock is held by another process","repro_note":null,"related":["duckdb/io-file-not-found","sqlite/sqlite-busy","postgresql/55P03"],"sqlly":null,"faqs":[{"question":"Can two processes read the same file at the same time?","answer":"Yes, as long as every one of them opens it read-only. The exclusive lock is for writing, not for reading. A read-only open fails while a read-write process holds the file."},{"question":"I closed everything and it still says locked. Is the lock stale?","answer":"Operating systems release locks when a process dies, so a truly stale lock is rare. The usual leftover is a service, editor plugin or notebook kernel still running. Check with lsof before suspecting corruption."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/io-lock","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/out-of-memory","corpus":"errors","engine":"duckdb","language":"en","title":"The query hit DuckDB's memory limit","description":"A query needed more memory than DuckDB was allowed to use and could not spill it to disk, so the engine aborted it.","body":{"code":"Out of Memory Error","slug":"out-of-memory","name":null,"message":"Out of Memory Error: failed to allocate data of size 32.0 MiB (48.1 MiB/61.0 MiB used)","group":"memory-resource","severity":null,"sql_state":null,"summary":"A query needed more memory than DuckDB was allowed to use and could not spill it to disk, so the engine aborted it.","meaning":"DuckDB caps buffer manager memory with the `memory_limit` setting and spills large sorts, hashes and joins to a temporary directory when it can. `Out of Memory Error` means a query pushed past that cap and the operator holding the data could not reduce its footprint. The parenthetical names the allocation that failed.\n\nThe limit is per database instance, not per query, so several concurrent queries together can trip it even when each alone would fit. Results that stream fine can still fail inside an operator that must materialize everything, such as a full outer join or a DISTINCT over a huge column.","causes":["A query that materializes a very large intermediate: a big GROUP BY with many distinct groups, a DISTINCT, or a self join.","A low memory_limit relative to the data, often left at a small value in a container.","No usable spill target: temp_directory emptied or pointing somewhere unwritable, so DuckDB cannot offload and fails instead.","Many concurrent queries sharing one instance's memory budget."],"fix":[{"text":"Raise the limit to fit the data and the machine, checking what it is now:","sql":"SELECT current_setting('memory_limit');\nSET memory_limit = '8GB';"},{"text":"Point temp_directory somewhere writable so DuckDB can spill instead of failing; a file-backed database already defaults to a folder named <database name>.tmp next to its database file, an in-memory one to .tmp in the working directory:","sql":"SET temp_directory = '/data/duckdb_tmp';"},{"text":"Reduce what the query materializes: aggregate in stages, prune columns early, and avoid DISTINCT over wide rows.","sql":"SELECT key, count(*) FROM big GROUP BY key;"},{"text":"Use out-of-core-friendly joins when possible, and let the optimizer choose by keeping statistics fresh; ANALYZE helps it size operators.","sql":"ANALYZE;"}],"diagnostic":"-- What is the budget and where does spilling go?\nSELECT current_setting('memory_limit') AS memory_limit, current_setting('temp_directory') AS temp_directory;\n-- Which operator classes hold memory now (tag, memory_usage_bytes, temporary_storage_bytes):\nSELECT * FROM duckdb_memory();\n-- Scratch files this database has spilled so far:\nSELECT * FROM duckdb_temporary_files();\n-- Size the inputs before the query (estimated_size reads 0 for a table created inside an uncommitted transaction):\nSELECT estimated_size FROM duckdb_tables() WHERE table_name = 'big';","alternatives":"Raising memory_limit fixes the symptom only if the machine really has the RAM; in a container it must also be raised there or the process will be killed by the OS instead, which looks like a crash rather than this error. For one-off huge jobs, process the data in ranged batches rather than lifting the cap.","details":[],"details_title":null,"repro":"SET memory_limit = '64MB';\nSET temp_directory = '';   -- an in-memory database would otherwise spill to .tmp in the working directory\nSELECT count(DISTINCT i) FROM range(50000000) t(i);   -- Out of Memory Error: could not allocate block of size 256.0 KiB (61.0 MiB/61.0 MiB used)","repro_note":null,"related":["duckdb/io-file-not-found","postgresql/53300","duckdb/conversion-out-of-range","postgresql/53200","sqlite/sqlite-full"],"sqlly":null,"faqs":[{"question":"Why did my query fail with plenty of free RAM?","answer":"DuckDB respects memory_limit, which defaults to about 80 percent of physical RAM but is often set lower, especially in containers. Check current_setting('memory_limit') on the connection that failed."},{"question":"Can DuckDB spill to disk automatically?","answer":"Yes, for many large sorts, aggregations and joins, but at a small budget some still fail: a 4M-row sort at 64MB and a count(DISTINCT) over 50M rows both raised this error on a file-backed database. A file-backed database spills by default: temp_directory then points at a <database name>.tmp folder next to the database file, and an in-memory database uses .tmp in the working directory. Spilling is off only when temp_directory is emptied; then an over-budget query fails with this error. If temp_directory points somewhere unwritable, the query fails with an IO Error (Failed to create directory ... Permission denied) instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/out-of-memory","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/parser-syntax-error","corpus":"errors","engine":"duckdb","language":"en","title":"The SQL does not parse","description":"DuckDB could not parse the statement at all, and the message names the first token that broke the grammar.","body":{"code":"Parser Error","slug":"parser-syntax-error","name":null,"message":"Parser Error: syntax error at or near \"SELEC\"","group":"syntax-parse","severity":null,"sql_state":null,"summary":"DuckDB could not parse the statement at all, and the message names the first token that broke the grammar.","meaning":"`Parser Error: syntax error at or near \"...\"` is DuckDB's pure syntax failure: the text is not valid SQL grammar, so nothing was planned or executed. The quoted token is where the parser gave up, which is usually at or just after the real mistake. Client libraries raise the same class on their side, typically as a `ParserException`.\n\nThe token itself is often innocent; the error is what comes before it, such as a doubled comma, an unclosed parenthesis, a reserved word used as an identifier, or a keyword misspelled. An unclosed quote gives a different message, Parser Error: unterminated string literal. Statements pasted from other dialects fail here too, for example SQL Server's square-bracket identifiers, which DuckDB does not read. Backtick quoting stopped failing in DuckDB 2.0, which now reads MySQL-style backtick identifiers.","causes":["A misspelled keyword such as SELEC, or a keyword used as a column name without quoting.","A missing or extra comma, parenthesis, or closing quote earlier in the statement.","Syntax from another dialect: square-bracket identifiers that are keywords, such as [order], or TOP instead of LIMIT (backtick quoting parses since DuckDB 2.0).","Splitting a script on semicolons and sending a fragment, so a statement starts mid-expression."],"fix":[{"text":"Look at the token before the one named in the message; that is usually where the mistake is.","sql":null},{"text":"Quote identifiers with double quotes when they collide with keywords:","sql":"SELECT \"order\", \"group\" FROM t;"},{"text":"Translate dialect syntax to DuckDB: LIMIT instead of TOP, standard double-quote identifiers:","sql":"SELECT [order] FROM t;\n-- becomes\nSELECT \"order\" FROM t LIMIT 10;"},{"text":"Build statements in code with parameters instead of string splicing, which is where most stray quotes come from:","sql":"SELECT * FROM t WHERE id = ?;"}],"diagnostic":"-- Binary search the statement: run it with parts removed until the error moves.\n-- Check how the text reached DuckDB, character by character, when the SQL looks right:\nSELECT length('  SELEC 1  ');\n-- In application logs, print the statement exactly as bound, with parameters filled in.","alternatives":"If generated SQL keeps failing, switch from string concatenation to the driver's parameter binding; it removes quoting bugs and injection risk at once. For a whole script, run it through the DuckDB CLI or a .sql file rather than splitting on semicolons in code, since that breaks on semicolons inside string literals.","details":[],"details_title":null,"repro":"SELEC 1;   -- Parser Error: syntax error at or near \"SELEC\"","repro_note":null,"related":["duckdb/binder-error","duckdb/catalog-table-not-exist","sqlite/sqlite-error","postgresql/42601","mysql/1064"],"sqlly":null,"faqs":[{"question":"Parser Error or Binder Error: what is the difference?","answer":"A Parser Error means the text is not valid SQL grammar. A Binder Error means the SQL parsed but names or types could not be resolved against the schema."},{"question":"The token in the message looks fine. What now?","answer":"Check before it: an unclosed parenthesis makes the parser fail at the first token after the gap, so the reported position is downstream of the real mistake. An unclosed quote is different: DuckDB reports Parser Error: unterminated string literal with the caret on the opening quote."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/parser-syntax-error","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/duckdb/serialization-error","corpus":"errors","engine":"duckdb","language":"en","title":"The database file version is incompatible","description":"DuckDB could not serialize data for a COPY, export or checkpoint, or a database file was written by an incompatible version.","body":{"code":"Serialization Error","slug":"serialization-error","name":null,"message":"Serialization Error: Loading a database file written by a different DuckDB version is not supported","group":"extension","severity":null,"sql_state":null,"summary":"DuckDB could not serialize data for a COPY, export or checkpoint, or a database file was written by an incompatible version.","meaning":"DuckDB database files record the storage version they were written with. A file written by a newer DuckDB cannot be opened by an older build. Since v0.10 the format is backwards compatible, so a current build reads files from older versions, but never the other way around.\n\nThe wording has changed across versions. Older builds print the classic `Serialization Error: Loading a database file written by a different DuckDB version is not supported`. DuckDB 2.x reports storage version numbers instead, for example `IO Error: Trying to read a database file with version number 69, but we can only read versions between 64 and 68.` A newer-feature file reports `Serialization Error: Failed to deserialize: ...`. All of them mean the same mismatch between the build that wrote the file and the build that opened it.","causes":["An app or driver pinned to an older DuckDB opened a file that a newer tool, CLI or notebook wrote.","Two machines, or a laptop and a container, share one file while running different DuckDB versions.","A CI run wrote the file with the latest build and a deployment with an older library picked it up."],"fix":[{"text":"Check the version of the build that fails, then upgrade it to at least the version that wrote the file:","sql":"SELECT version();"},{"text":"When both versions must stay, copy the data out with the newer build and load it with the older one:","sql":"COPY my_table TO 'my_table.parquet' (FORMAT PARQUET);"},{"text":"To keep sharing a file with older readers, a recent DuckDB can checkpoint against an older storage version:","sql":"ATTACH 'compat.duckdb' (STORAGE_VERSION 'v1.4.0');"}],"diagnostic":"-- Run on both the connection that fails and the one that wrote the file:\nSELECT version();\n-- What storage version this build checkpoints as (DuckDB 2.x):\nSELECT current_setting('storage_compatibility_version') AS written_as;","alternatives":"Parquet and CSV are the interchange formats between incompatible builds, and DuckDB reads both on every version. For teams that must share database files, agree on the oldest DuckDB version in play and pin everyone to it, or keep the shared data in files rather than in a database file.","details":[],"details_title":null,"repro":"-- Not reproducible inside one build: the mismatch happens when the file is opened.\n-- Check both sides of the handoff first:\nSELECT version();","repro_note":null,"related":["duckdb/io-file-not-found","duckdb/io-lock","sqlite/sqlite-error"],"sqlly":null,"faqs":[{"question":"Can a newer DuckDB open a file from an older version?","answer":"Yes. Since v0.10 the storage format is backwards compatible, so current builds read files written by older versions."},{"question":"How do I move a database to a machine that cannot be upgraded?","answer":"Export with the newer build as Parquet or CSV and load it there, or have the newer build write the file with an older storage version using ATTACH ... (STORAGE_VERSION ...)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/duckdb/serialization-error","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/busy","corpus":"errors","engine":"libsql","language":"en","title":"SQLITE_BUSY: the database is busy","description":"A write could not start or commit because another connection held the lock: on remote writes this is one writer contending with itself across connections.","body":{"code":"SQLITE_BUSY","slug":"busy","name":"5","message":"SQLITE_BUSY","group":"local-sqlite","severity":null,"sql_state":null,"summary":"A write could not start or commit because another connection held the lock: on remote writes this is one writer contending with itself across connections.","meaning":"`SQLITE_BUSY` (5) means SQLite could not get the lock it needed because another connection was using the database. On a local file that is classic multi-process contention. On a remote libSQL server the same code surfaces when writes contend at the server, because sqld is still SQLite underneath with one writer at a time. The libsql JS client renders it as `SQLITE_BUSY: database is locked`.","causes":["Two connections wrote to the same remote database at once and one lost the race.","A local file was opened by more than one process.","No busy_timeout was set, so SQLite gave up instead of waiting.","A long transaction held the write lock past other clients' patience."],"fix":[{"text":"On a local file, set a busy timeout so SQLite waits out short contention. On a remote Turso database the pragma is not supported, so retries with backoff are the mechanism there:","sql":"PRAGMA busy_timeout = 5000;\n// @libsql/client local file: createClient({ url: 'file:local.db', timeout: 5000 })"},{"text":"Retry failed writes with backoff instead of hammering:","sql":"for (let i = 0; i < 5; i++) {\n  try { await db.execute('UPDATE t SET v = v + 1 WHERE id = 1'); break; }\n  catch (e) {\n    if (!String(e).includes('SQLITE_BUSY')) throw e;\n    await new Promise(r => setTimeout(r, 100 * 2 ** i));\n  }\n}"},{"text":"Batch writes so a burst commits as one operation instead of many lock races:","sql":"await db.batch([\n  'UPDATE a SET x = 1',\n  'UPDATE b SET y = 2'\n]);"},{"text":"On a local file, find who else holds it open:","sql":"lsof mydata.db"}],"diagnostic":"Look at the timing: a busy error under concurrent writes that goes away with retries is ordinary contention, and busy_timeout plus backoff is the fix. One that never clears points at a stuck transaction: check for long-open `BEGIN` blocks in your code, and on a local file check `lsof` for other processes. On remote databases, correlate the error timestamps with your request concurrency.","alternatives":"Serialize writes through a single connection or queue. For remote databases, batches reduce the number of write transactions and so the number of races. `PRAGMA journal_mode=WAL` helps local file concurrency for readers but does not remove the single-writer rule, and Turso Cloud does not allow changing the journal mode at all.","details":[],"details_title":null,"repro":"Local, honest: in one sqlite3 shell run `BEGIN; INSERT INTO t VALUES (1);` and leave it open. In another shell run `INSERT INTO t VALUES (2);` and it returns `database is locked` (SQLITE_BUSY). Needs any scratch file: `sqlite3 scratch.db 'CREATE TABLE t (a);'`. The remote flavor reproduces with two @libsql/client connections writing concurrently to the same test database.","repro_note":null,"related":["libsql/embedded-replica-locked","libsql/rate-limited-429","libsql/too-many-connections"],"sqlly":"SQLly runs your retry loop's steps one statement at a time, so you can reproduce the contention deliberately: hold a transaction open in one SQLly tab and write to the same table from another to see SQLITE_BUSY on a local file.","faqs":[{"question":"Does PRAGMA busy_timeout work on Turso Cloud?","answer":"No. Turso's limitations page lists `busy_timeout` as not supported: the cloud manages concurrency internally and the pragma has no effect. For remote writes, retry with backoff instead; for local `file:` databases the pragma works, and @libsql/client's `timeout` option sets the same thing."},{"question":"Why do I get SQLITE_BUSY on an embedded replica but not on the remote database?","answer":"The replica is a local SQLite file with one writer at a time, so local lock rules apply on top of the remote behavior. See the embedded-replica-locked entry: two processes or a sync during a local write are the usual causes."},{"question":"What is the difference between SQLITE_BUSY and SQLITE_LOCKED?","answer":"BUSY means the commit-level write lock was held by another connection; LOCKED means a needed table-level lock (often a shared-cache conflict) was unavailable. On remote libSQL servers the code that surfaces is SQLITE_BUSY."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/busy","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/cli-database-not-found","corpus":"errors","engine":"libsql","language":"en","title":"turso CLI: database not found","description":"The CLI cannot find a database with that name in the current organization: typo, wrong org, or the database was destroyed.","body":{"code":"database not found","slug":"cli-database-not-found","name":null,"message":"database not found: <name>","group":"remote-api","severity":null,"sql_state":null,"summary":"The CLI cannot find a database with that name in the current organization: typo, wrong org, or the database was destroyed.","meaning":"The turso CLI resolves database names inside one organization at a time: the active one. `database not found: <name>` means no database with that name exists in that organization, whether the name is misspelled, the active organization is the wrong one, or the database was destroyed. An app using the SDK resolves a full `libsql://` URL instead, so the CLI and the app can disagree about whether a database exists.","causes":["The database name is misspelled.","The CLI is pointed at a different organization than the one holding the database.","The database was destroyed."],"fix":[{"text":"List what the CLI can actually see:","sql":"turso db list"},{"text":"Check the active organization and switch if needed:","sql":"turso org list\nturso org switch <org>"}],"diagnostic":"`turso db list` shows exactly the names the CLI can see in the active organization. If the database is missing there, check `turso org list` and switch with `turso org switch <org>`: names resolve inside one organization, not across them.","alternatives":"In automation, run the CLI non-interactively (`turso auth login --headless`) with an API token scoped to the right organization (`turso auth api-tokens mint <name> --org <org>`). For app connections, skip name resolution entirely and use the URL from `turso db show <name> --url`.","details":[],"details_title":null,"repro":"Honest and free with a real account: `turso db show definitely-not-a-db` with a logged-in CLI prints the error. There is no offline repro; the CLI needs the platform to answer.","repro_note":null,"related":["libsql/database-not-found-404","libsql/unauthorized-401","libsql/cli-no-organization"],"sqlly":"SQLly connects by URL, not by database name, so CLI organization scoping does not affect it: paste the `libsql://` URL from `turso db show` and the connection works or fails on its own merits.","faqs":[{"question":"Why does turso say database not found when the database exists?","answer":"The CLI only looks in the active organization. Run `turso org list` to see the organizations you belong to, `turso org switch <org>` to the one holding the database, then `turso db list` to confirm the name."},{"question":"Does this CLI error mean my app's libsql:// URL is wrong too?","answer":"Not necessarily. The CLI resolves a bare database name against your organization; the SDK resolves a full `<db>-<org>.turso.io` host. A CLI failure with a URL that connects points at CLI login or organization state, not at the URL."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/cli-database-not-found","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/cli-no-organization","corpus":"errors","engine":"libsql","language":"en","title":"turso CLI: no organization","description":"The CLI has no organization to act in: not logged in, no default org set, or the account belongs to none.","body":{"code":"no organization","slug":"cli-no-organization","name":null,"message":"no organization selected or available","group":"auth-token","severity":null,"sql_state":null,"summary":"The CLI has no organization to act in: not logged in, no default org set, or the account belongs to none.","meaning":"The turso CLI acts inside one organization at a time. `turso auth login` picks a default interactively; automation runs without prompts (the `--headless` flag) and relies on its token's organization context. When the CLI has no organization to act in, commands that need one fail with this error. It is CLI state, not a rejected token: a bad token fails with an authentication error instead.","causes":["Not logged in with `turso auth login`.","No default organization selected for the account.","An automation run whose token does not carry the organization context the command needs."],"fix":[{"text":"Log in and set an organization:","sql":"turso auth login\nturso org list\nturso org switch <org>"}],"diagnostic":"`turso auth whoami` shows the account the CLI is using, `turso org list` shows the organizations that account can see, and `turso org switch <org>` sets the active one. If the list is empty, the account belongs to no organization and one must be granted.","alternatives":"For CI, run with the `--headless` flag and an API token minted for the organization the job acts on (`turso auth api-tokens mint <name> --org <org>`), so no interactive login or default organization is needed.","details":[],"details_title":null,"repro":"Needs CLI state with no usable organization, which is CI territory: an automation run whose token carries no organization context, or a login on an account with no organization selected yet. No honest offline repro; the error comes from the platform's answer about the account.","repro_note":null,"related":["libsql/unauthorized-401","libsql/token-expired","libsql/cli-database-not-found"],"sqlly":"SQLly connects straight to a `libsql://` URL with a database token and never needs a CLI organization: a connection that works in SQLly while the CLI reports no organization points at CLI setup, not at the database.","faqs":[{"question":"How do I use the turso CLI in CI without an interactive login?","answer":"Run with the `--headless` flag and authenticate with an API token minted for the organization the job acts on: `turso auth api-tokens mint <name> --org <org>`. If the account can see several organizations, set the active one explicitly."},{"question":"Is 'no organization' the same as a bad token?","answer":"No. The token can be perfectly valid while the CLI still lacks an organization to act in. A rejected token produces an authentication failure instead; `turso auth whoami` separates the two."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/cli-no-organization","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/conflict-409","corpus":"errors","engine":"libsql","language":"en","title":"409 Conflict","description":"The platform request conflicts with existing state, most often creating a database or token whose name already exists.","body":{"code":"409 Conflict","slug":"conflict-409","name":null,"message":"Server returned HTTP status 409 Conflict","group":"remote-api","severity":null,"sql_state":null,"summary":"The platform request conflicts with existing state, most often creating a database or token whose name already exists.","meaning":"Turso's response-code reference lists 409 as `Resource already exists`. On the platform API that is nearly always a create whose name is taken; anything beyond that is speculative. It is a platform API response, not something a SQL pipeline produces.","causes":["Creating a database, token, or group with a name that already exists.","A concurrent change to the same resource won the race."],"fix":[{"text":"List existing resources and pick a new name or reuse the existing one:","sql":"turso db list"}],"diagnostic":"`turso db list` (and `turso group list` for groups) shows the existing resource that owns the name. If nothing appears listed, check the active organization with `turso org list`: names collide inside one org, not globally.","alternatives":"Reuse the existing resource when it matches what you wanted, or pick a new name. In deploy scripts, treat a 409 on create as success when the existing resource matches, which makes the script idempotent.","details":[],"details_title":null,"repro":"Local and honest against the platform: `turso db create name-demo` twice; the second create collides with the first and the API answers 409 (the CLI prints its own wording). Needs a real account; nothing to reproduce offline.","repro_note":null,"related":["libsql/database-not-found-404","libsql/payment-required-402","libsql/internal-server-error-500"],"sqlly":"SQLly never creates databases, so a 409 during provisioning will not appear in the client, but connecting to the already-existing database by name confirms the resource your script collided with is the one you meant.","faqs":[{"question":"Why do I get 409 when creating a Turso database with a name I just deleted?","answer":"Check `turso db list` in the active organization first: the delete may have targeted another org, or another resource (a group, a token name) owns the name. The API answers 409 only when something with that name still exists."},{"question":"Does 409 come from SQL statements?","answer":"No. It is a platform API status for create collisions. A duplicate unique key inside a table is a SQLite constraint error, not HTTP 409."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/conflict-409","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/connection-interrupted","corpus":"errors","engine":"libsql","language":"en","title":"Connection reset or dropped","description":"The network path to the server dropped mid-request: the socket closed, the request timed out, or a proxy cut the connection.","body":{"code":"connection reset / interrupted","slug":"connection-interrupted","name":null,"message":"The connection was interrupted while communicating with the server","group":"remote-api","severity":null,"sql_state":null,"summary":"The network path to the server dropped mid-request: the socket closed, the request timed out, or a proxy cut the connection.","meaning":"Remote libSQL runs over HTTP/WebSocket. Any hop between client and server can drop: TLS handshake failure, a load balancer idle timeout, a WebSocket closed by the server, or plain network loss. The client sees a closed socket or an interrupted request rather than a server error, so no HTTP status arrives. These failures are usually transient, and a retry often succeeds.","causes":["Network loss between client and server, including wifi and VPN blips.","An idle WebSocket closed by a proxy or load balancer timeout.","Server restart or failover on the remote database.","The client gave up on a request that exceeded its own timeout."],"fix":[{"text":"Retry idempotent reads and use transactions for multi-statement writes so a dropped connection cannot leave partial state:","sql":"await db.batch(['INSERT ...', 'UPDATE ...'], 'write');"},{"text":"Check reachability and latency by hand when it recurs:","sql":"curl -s -o /dev/null -w '%{http_code} %{time_total}\\n' https://mydb-myorg.turso.io/v2/pipeline"},{"text":"Wrap remote calls in your own timeout; @libsql/client has no request timeout for remote clients (its `timeout` config is a local-file busy timeout):","sql":"const res = await Promise.race([\n  db.execute(sql),\n  new Promise((_, rej) => setTimeout(() => rej(new Error('client timeout')), 10_000))\n]);"}],"diagnostic":"Decide first whether writes may have been applied before the drop: if the connection died mid-transaction, the transaction rolled back; if it died mid-batch with individual autocommit statements, some may have applied. Check by reading the data. Then look at where it dropped: a timeout with no bytes returned points at the network or proxy; a clean close right after connect points at the server refusing or restarting. `curl` to the same URL from the same machine separates your client from the network.","alternatives":"For HTTP-only clients, prefer the `/v2/pipeline` endpoint, which is stateless per request, over interactive transactions that need a live session. For flaky networks, embedded replicas keep reads local.","details":[],"details_title":null,"repro":"Local and honest: start `turso dev --db-file scratch.db`, open a client, then kill the turso process mid-request to get a socket close. Real-world flakiness (proxies, TLS, wifi) cannot be reproduced offline; the kill-based repro only covers the server-gone-away shape.","repro_note":null,"related":["libsql/database-not-found-404","libsql/embedded-replica-locked","libsql/too-many-connections"],"sqlly":"SQLly's connection test does a single round trip and reports the raw failure, so 'works in SQLly, flaky in the app' usually means the app's own timeout or pool is cutting requests, not the network path.","faqs":[{"question":"If the connection drops mid-transaction, did my writes apply?","answer":"An interactive transaction rolls back when its connection dies. A batch is atomic: all of it applies or none. Individual autocommit statements that already returned stay applied, so read the data back to check rather than replaying blindly."},{"question":"Does @libsql/client have a request timeout option?","answer":"Not for remote clients. The `timeout` config sets a busy timeout and only affects local `file:` databases. For remote calls, wrap the promise in your own timeout (Promise.race with a rejected timer, or an AbortSignal on a custom `fetch`)."},{"question":"Why do my WebSocket connections die after quiet periods?","answer":"Proxies and load balancers close idle sockets. For long idle periods prefer the HTTP pipeline shape, or issue a cheap keepalive statement; either way treat the closed socket as a retryable failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/connection-interrupted","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/database-not-found-404","corpus":"errors","engine":"libsql","language":"en","title":"404 Not Found: unknown database or endpoint","description":"No database exists at the URL: the name is wrong, it was deleted, or the URL points at the wrong host.","body":{"code":"404 Not Found","slug":"database-not-found-404","name":null,"message":"Server returned HTTP status 404 Not Found","group":"remote-api","severity":null,"sql_state":null,"summary":"No database exists at the URL: the name is wrong, it was deleted, or the URL points at the wrong host.","meaning":"A 404 from a remote libSQL connection means the server has no database at that address. The request itself was fine; the target was not. The usual forms: a typo in the database name in the `libsql://` URL, a database deleted while an old URL is still configured, an environment mixup where staging points at a dropped database, or a platform API call to a name that does not exist. The libsql JS client surfaces this as `SERVER_ERROR: Server returned HTTP status 404`.","causes":["The database name in the URL is misspelled.","The database was destroyed and the URL is stale.","The URL belongs to another environment or organization.","A platform API call names a database or resource that does not exist."],"fix":[{"text":"List your databases and compare with the URL your client uses:","sql":"turso db list"},{"text":"Get the exact connect string for the database and paste it into your config verbatim:","sql":"turso db show mydb --url"},{"text":"If the database is gone, recreate it, then re-apply your schema:","sql":"turso db create mydb\nturso db shell mydb < schema.sql"},{"text":"Reproduce the request shape by hand to see the raw status:","sql":"curl -s -o /dev/null -w '%{http_code}\\n' https://mydb-myorg.turso.io/v2/pipeline"}],"diagnostic":"Run `turso db list`. If the name is missing, the URL is stale or wrong. If it is present, compare `turso db show <name> --url` character by character with the URL in your config: libsql URLs are `<db>-<org>.turso.io`, so a wrong org slug produces a valid-looking URL with nothing behind it. A 404 on one environment but not another usually means the database exists in one org only.","alternatives":"If the database is gone and you only need local work, switch to a `file:` URL. To recreate from what still exists, `turso db create mydb --from-db <other-db>` copies an existing database, or re-apply your schema with `turso db shell mydb < schema.sql`.","details":[],"details_title":null,"repro":"Reproducing this honestly needs a real Turso URL: point @libsql/client at `libsql://definitely-not-a-real-db-example.turso.io` and you get SERVER_ERROR with status 404, since nothing lives at that host. You can also create a database, note the URL, destroy it with `turso db destroy <name>`, and reuse the old URL. `turso dev` always answers, so it cannot reproduce a 404.","repro_note":null,"related":["libsql/unauthorized-401","libsql/forbidden-403","libsql/connection-interrupted"],"sqlly":"SQLly keeps the URL per connection, so after a `turso db show mydb --url` copy-paste you can test the corrected URL from the desktop before touching your app's environment variables.","faqs":[{"question":"My libsql URL looks correct but I still get 404. What now?","answer":"URLs are `<db>-<org>.turso.io`, so a wrong org slug produces a valid-looking host with nothing behind it. Compare the URL character by character with `turso db show mydb --url`, then check `turso db list` in the organization you think the database lives in."},{"question":"Can I test a Turso database URL from the command line?","answer":"Yes: `curl -s -o /dev/null -w '%{http_code}\\n' https://mydb-myorg.turso.io/v2/pipeline` returns 404 for a dead host and another status (usually 401) when the host exists but wants a token."},{"question":"Does `turso dev` ever return 404?","answer":"No. The local dev server always answers for its own database, so a 404 means you are pointing at the cloud, not at `turso dev`."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/database-not-found-404","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/embedded-replica-locked","corpus":"errors","engine":"libsql","language":"en","title":"embedded replica file locked","description":"A local embedded replica file could not take or release its lock, usually because another process has the same replica file open for writing.","body":{"code":"SQLITE_BUSY: database is locked","slug":"embedded-replica-locked","name":"5","message":"SQLITE_BUSY: database is locked","group":"replica-consistency","severity":null,"sql_state":null,"summary":"A local embedded replica file could not take or release its lock, usually because another process has the same replica file open for writing.","meaning":"An embedded replica is a local SQLite file that syncs from the remote database. Local reads are plain SQLite, and the sync loop writes the replicated frames into the same file, so local locking rules apply. The file allows one writer at a time. Two processes opening the same replica file, or a long local write while the replication loop applies frames, collide on the file lock and SQLite returns SQLITE_BUSY with the text `database is locked`. Turso's docs describe the layout: reads run locally from the file, and writes are sent to the cloud primary and then reflected back to the replica, so the local file is being written both by your process and by the replication loop.","causes":["Two processes or app instances opened the same replica file, and both tried to write.","A local write held the file lock while `sync()` tried to apply replicated frames.","A crashed process left the file's lock bookkeeping in a state a new opener cannot take.","A raw `BEGIN IMMEDIATE` in the replication-enabled libSQL build can return busy immediately instead of waiting on busy_timeout."],"fix":[{"text":"Give each process its own replica file, or route writes through one process:","sql":"// process A\nconst dbA = createClient({ url: 'file:replica-a.db', authToken: token });\n// process B\nconst dbB = createClient({ url: 'file:replica-b.db', authToken: token });"},{"text":"Set a busy timeout for the local file so SQLite waits instead of failing fast. In @libsql/client the `timeout` option covers `file:` URLs:","sql":"const db = createClient({ url: 'file:replica.db', syncUrl, authToken, timeout: 5000 });"},{"text":"Keep local write transactions short and sync outside them:","sql":"await db.sync();   // outside any open transaction"},{"text":"If a crashed process left the file wedged, check for stale locks by opening it read-only:","sql":"sqlite3 replica.db 'PRAGMA integrity_check;'"}],"diagnostic":"List every process that opens the replica file: `lsof replica.db` shows holders. More than one writer is the cause. If only one process holds it, check whether the error arrives during `sync()` after a long local write, which points at lock contention between your transaction and the replication loop. After a crash, open the file read-only (`sqlite3 'file:replica.db?mode=ro' 'PRAGMA integrity_check;'`) to test whether the file itself is readable.","alternatives":"Use `libsql://` directly for all writes and keep the replica read-only. That removes the local write lock entirely, at the cost of network round trips on writes.","details":[],"details_title":null,"repro":"Local and honest: create two clients on the same file URL and make both write in a loop; the second writer hits `LibsqlError: SQLITE_BUSY: database is locked`. Or with plain sqlite3: hold a transaction open in one shell and run `BEGIN IMMEDIATE` in another on the same file. No remote account needed; the cloud primary never sees the contention.","repro_note":null,"related":["libsql/busy","libsql/too-many-connections","libsql/connection-interrupted"],"sqlly":"SQLly opens the replica file as a plain SQLite database, which is exactly the second writer the error warns about: use it to inspect the file between syncs, and close the SQLly tab (or open the remote `libsql://` connection instead) while your app's writes are failing.","faqs":[{"question":"Do embedded replicas support writes?","answer":"Yes. Per Turso's docs, writes on an embedded replica are sent to the cloud primary and then reflected back to the local file; reads always run locally. That round trip still touches the local file, so local file locks matter."},{"question":"Can two processes share one embedded replica file?","answer":"Reads can coexist, but two writers on the same local file collide with SQLITE_BUSY. Give each process its own replica file, or route writes through the remote `libsql://` URL and keep the replicas read-only."},{"question":"How do I set a busy timeout for a file: database in @libsql/client?","answer":"Pass `timeout` in milliseconds to `createClient({ url: 'file:...', timeout: 5000 })`. The client applies it to every connection it opens, and it only takes effect for local SQLite databases; remote clients ignore it, and Turso Cloud does not support `PRAGMA busy_timeout` at all."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/embedded-replica-locked","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/error-in-remote-response","corpus":"errors","engine":"libsql","language":"en","title":"Error in remote response","description":"The client received a Hrana response whose body reported an error; the server's own message follows this prefix in the client output.","body":{"code":"Error in remote response","slug":"error-in-remote-response","name":null,"message":"Error in remote response","group":"remote-api","severity":null,"sql_state":null,"summary":"The client received a Hrana response whose body reported an error; the server's own message follows this prefix in the client output.","meaning":"Hrana clients wrap server-reported failures behind a generic phrase and append the server's detail. The exact prefix wording varies between client versions (the JS client has shown phrases of this shape), so treat the text after it as the real signal.","causes":["The server rejected a statement in a pipeline; the appended detail names it.","The server hit an internal error while producing the response."],"fix":[{"text":"Read the full error, not the prefix, and match the detail against the rest of this catalog.","sql":null}],"diagnostic":"Read the whole error, not the prefix: everything after the generic phrase is the server's detail and is what matches the rest of this catalog. If the suffix is empty, the server produced an error with no detail, so treat it like the 500 entry.","alternatives":"Prefer clients that expose the structured error code next to the message, so matching happens on the code instead of on prefix wording that changes between versions.","details":[],"details_title":null,"repro":"Local and honest: run `turso dev --db-file scratch.db`, point @libsql/client at it, and run `SELECT * FROM missing_table`; the client shows the generic wrapper plus the server's own message about the missing table. The wrapper prefix itself is what varies between client versions.","repro_note":null,"related":["libsql/internal-server-error-500","libsql/connection-interrupted","libsql/database-not-found-404"],"sqlly":"SQLly shows the full server message it received, so a wrapped error you cannot parse in application logs is usually readable straight from the result pane.","faqs":[{"question":"What does 'Error in remote response' mean in libsql clients?","answer":"The client received a failure the server reported in the response body and wraps it behind a generic phrase, appending the server's own detail. The text after the prefix is the real error."},{"question":"How do I find the actual error under the generic wrapper?","answer":"Read the full error string or the structured `code` field if the client exposes one, and match that against the specific entries in this catalog rather than the prefix."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/error-in-remote-response","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/forbidden-403","corpus":"errors","engine":"libsql","language":"en","title":"403 Forbidden: no permission for this resource","description":"The token is valid but the account or token is not allowed to touch this database or operation.","body":{"code":"403 Forbidden","slug":"forbidden-403","name":null,"message":"Server returned HTTP status 403 Forbidden","group":"auth-token","severity":null,"sql_state":null,"summary":"The token is valid but the account or token is not allowed to touch this database or operation.","meaning":"Turso's docs describe 403 as: you do not have permission to access this resource. Unlike 401, the token itself passed validation. The refusal comes from what the token or your account is allowed to do. Common shapes: a read-only token used for a write, a member account that lacks access to the organization's database, or a plan limit that blocks the operation.","causes":["A read-only token was used for a write statement. Turso lets you mint read-only tokens.","Your account is a member without access to the organization or database the URL points to.","The token was minted for a database in another organization that your account cannot see.","The operation needs platform API access that the database token does not carry."],"fix":[{"text":"Mint a token with the access the statement needs. Read-write is the default:","sql":"turso db tokens create mydb"},{"text":"If you need read-only by design, keep it but do the writes with a separate full token:","sql":"turso db tokens create mydb --read-only"},{"text":"Check which organization and databases you can see:","sql":"turso org list\nturso db list"},{"text":"If the database is in another org, ask an owner to grant access or point your URL at a database you own:","sql":"turso db show mydb --url"}],"diagnostic":"Run `turso db list` and confirm the database appears. If it does not, your account has no access and 403 is expected. If it does appear, the token is the problem: decode it and compare with a freshly minted token for the same database. A read-only token failing only on writes is the clearest signal.","alternatives":"For team setups, use organization membership rather than sharing personal tokens. For local development, `turso dev` or a file URL has no permission model at all.","details":[],"details_title":null,"repro":"Reproducing 403 honestly needs two Turso accounts or a read-only token: create a database with `turso db create repro403`, mint a token with `--read-only`, then run an INSERT through @libsql/client to get SERVER_ERROR 403. `turso dev` cannot reproduce it because it skips auth.","repro_note":null,"related":["libsql/unauthorized-401","libsql/database-not-found-404","libsql/token-expired"],"sqlly":"SQLly sends the write with the saved token and shows the server's refusal unchanged, so a read-only token fails on the first INSERT with 403 while reads keep working, which is the split that identifies the token scope.","faqs":[{"question":"How do I create a read-only token for a Turso database?","answer":"`turso db tokens create mydb --read-only`. A write through a read-only token answers 403. Keep one read-only token for readers and a separate full token only where writes happen."},{"question":"What is the difference between 401 and 403 on Turso?","answer":"401 means the token itself was rejected (missing, malformed, expired, or for another database). 403 means the token was accepted but the account or token is not allowed to touch that resource, for example a read-only token doing a write."},{"question":"Why do I get 403 when I can see the database in the Turso dashboard?","answer":"The dashboard uses your logged-in account; the app uses a token. Run `turso db list` with the same credentials your app has: if the database is not listed, your account lacks access to that organization and an owner must grant it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/forbidden-403","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/interactive-transaction-aborted","corpus":"errors","engine":"libsql","language":"en","title":"interactive transaction aborted","description":"Interactive transactions fail on clients or servers old enough to predate Hrana-over-HTTP streams, or when the server expires an idle stream; batches still work.","body":{"code":"Transaction timed-out","slug":"interactive-transaction-aborted","name":null,"message":"interactive transaction not allowed in HTTP queries","group":"remote-api","severity":null,"sql_state":null,"summary":"Interactive transactions fail on clients or servers old enough to predate Hrana-over-HTTP streams, or when the server expires an idle stream; batches still work.","meaning":"Older sqld versions refused interactive transactions on stateless HTTP requests with exactly this message; current clients open a stream over HTTP (baton streams) and `db.transaction()` works with `https://` URLs. The failure is still real in three shapes: a pinned old client or server, a literal `BEGIN` sent as a pipeline statement, and interactive transactions left idle until the server expires the stream (`The stream has expired due to inactivity`) or times the transaction out (`Transaction timed-out`).","causes":["A client or server old enough to predate Hrana-over-HTTP streams.","A literal `BEGIN` (or `COMMIT`) sent as a statement through a pipeline request.","An interactive transaction held open so long the server expired or timed it out."],"fix":[{"text":"Upgrade the client first. Current @libsql/client runs `db.transaction()` over https URLs; long interactive sessions still do best on a WebSocket (`libsql://`) connection:","sql":"const db = createClient({ url: 'libsql://mydb-myorg.turso.io', authToken });\nconst tx = await db.transaction('write');"},{"text":"On HTTP-only clients, replace the transaction with a batch, which is atomic on the server:","sql":"await db.batch([\n  { sql: 'UPDATE accounts SET bal = bal - 10 WHERE id = 1', args: [] },\n  { sql: 'UPDATE accounts SET bal = bal + 10 WHERE id = 2', args: [] }\n], 'write');"},{"text":"Never send BEGIN/COMMIT yourself over HTTP:","sql":"-- wrong over https:// URLs\n-- BEGIN;\n-- UPDATE ...;\n-- COMMIT;"}],"diagnostic":"Check the client version and URL scheme first: an up-to-date client on `https://` supports transactions, so the refusal points at a pinned old dependency. A bare `BEGIN` in a pipeline is refused or strands state, so use the transaction API or a batch. If the transaction worked and then died, the server expired the idle stream; keep interactive transactions short.","alternatives":"`db.batch()` runs all statements atomically on the server and works over any connection; for logic that decides statements mid-flight, keep the interactive transaction short or move the decision into one SQL statement with CTEs.","details":[],"details_title":null,"repro":"Local and honest for the idle-stream shape: run `turso dev --db-file scratch.db`, open a transaction over any URL scheme with @libsql/client, and wait past the server's inactivity expiry; the next statement fails with the stream expired error. The legacy refusal itself only reproduces on an old pinned client or server version.","repro_note":null,"related":["libsql/connection-interrupted","libsql/busy"],"sqlly":"SQLly runs statements autocommit by default, so the fastest check is the opposite of the usual: if your app fails on `db.transaction()` and SQLly runs the same two statements fine, version skew or a held-open transaction in the app is the difference.","faqs":[{"question":"Can I use db.transaction() with an https:// URL in @libsql/client?","answer":"Yes in current versions: the HTTP client opens a server-side stream and the transaction runs on it. Very old client or server versions refused interactive transactions over HTTP; if you see that refusal, upgrade before restructuring code."},{"question":"Why did my interactive transaction die after a pause?","answer":"The server expires idle streams (`The stream has expired due to inactivity`) and times out stale transactions (`Transaction timed-out`). Keep interactive transactions short, or express the work as a batch, which commits or rolls back as a unit."},{"question":"Can I send BEGIN and COMMIT as plain statements over HTTP?","answer":"No. Over HTTP each pipeline request should be self-contained; use the client's transaction API or `db.batch()`, which run inside an implicit server-side transaction."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/interactive-transaction-aborted","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/internal-server-error-500","corpus":"errors","engine":"libsql","language":"en","title":"server failed on a valid request","description":"The remote server failed while handling a valid request. Retry once or twice, then check status and support; nothing in your SQL is wrong.","body":{"code":"500 Internal Server Error","slug":"internal-server-error-500","name":null,"message":"Server returned HTTP status 500 Internal Server Error","group":"remote-api","severity":null,"sql_state":null,"summary":"The remote server failed while handling a valid request. Retry once or twice, then check status and support; nothing in your SQL is wrong.","meaning":"A 500 means the server itself failed: an internal error in sqld or the platform, not a client mistake. It is rare and usually transient. Repeated 500s on the same statement can point at a server bug or a corrupt state on that database.","causes":["A transient internal failure on the server or platform.","A server bug triggered by a particular statement or load.","A server restart or failover mid-request."],"fix":[{"text":"Retry the request after a short wait:","sql":null},{"text":"If it repeats on the same statement, simplify the statement to isolate the trigger and report it to Turso support or the libsql GitHub issues with the statement and timestamp.","sql":null},{"text":"Check platform status for an ongoing incident.","sql":null}],"diagnostic":"Retry once after a short wait. If the same statement 500s repeatedly, shrink it until the failure isolates, and report it to Turso support or the libsql GitHub issues with the statement and timestamp. Check the platform status page before assuming your code is involved: a 500 is a server-side failure by definition.","alternatives":"Nothing in your SQL fixes a 500. If one statement keeps triggering it, restructure or avoid it while the report is open. If the database itself seems wedged, recreate it from your schema and data rather than waiting on the fix.","details":[],"details_title":null,"repro":"There is no honest offline repro: killing `turso dev` mid-request yields a connection error, not a 500. A real 500 needs a server bug or platform incident, which is exactly why the retry-then-report procedure matters.","repro_note":null,"related":["libsql/connection-interrupted","libsql/rate-limited-429","libsql/error-in-remote-response"],"sqlly":"SQLly retries nothing behind your back: a 500 lands in the result pane with the server's message, so you can rerun it yourself once and decide from there.","faqs":[{"question":"Is a 500 from Turso my fault?","answer":"No. A 500 means the server failed while handling a valid request. Retry once or twice; repeated 500s on the same statement are worth isolating and reporting."},{"question":"What should I include when reporting a Turso 500?","answer":"The exact statement, the timestamp, the database and region, and whether a retry with the same statement succeeded. That separates a server bug from a transient platform failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/internal-server-error-500","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/payment-required-402","corpus":"errors","engine":"libsql","language":"en","title":"402 Payment Required","description":"Turso's API returned 402 when the account is past its plan limits or payment lapsed; check billing and plan quotas.","body":{"code":"402 Payment Required","slug":"payment-required-402","name":null,"message":"Server returned HTTP status 402 Payment Required","group":"remote-api","severity":null,"sql_state":null,"summary":"Turso's API returned 402 when the account is past its plan limits or payment lapsed; check billing and plan quotas.","meaning":"Turso's response-code reference lists 402 as payment required, with the advice to check you have an active subscription. Distinguish it from 429: 429 is a rate or quota burst, 402 means the account itself is not in good standing.","causes":["Subscription lapsed or payment failed.","The free or paid plan no longer covers the resource you are using."],"fix":[{"text":"Check plan and billing in the Turso dashboard, then retry.","sql":null}],"diagnostic":"Open the billing portal with `turso org billing` and check the plan with `turso plan show`. Distinguish the three money-adjacent failures: 402 means the account is not in good standing, `BLOCKED` means a monthly quota is exhausted, 429 means a burst rate limit.","alternatives":"Fix the account state, or change plan with `turso plan select <plan>` or `turso plan upgrade`. If overages are the surprise, `turso plan overages enable/disable` controls whether usage past the quota bills.","details":[],"details_title":null,"repro":"Needs an account actually past its billing: there is no honest repro without one, and the docs mapping (402 means you should check you have an active subscription) is the verifiable part. Do not fabricate a billing failure locally.","repro_note":null,"related":["libsql/rate-limited-429","libsql/conflict-409","libsql/unauthorized-401"],"sqlly":"SQLly surfaces the 402 unchanged on connect, so a lapsed subscription is obvious before any query debugging starts: check billing, not the connection string.","faqs":[{"question":"What is the difference between 402, 429, and BLOCKED on Turso?","answer":"402 means the account itself is not in good standing (subscription lapsed or payment failed). 429 is a short-term request-rate limit. BLOCKED means a monthly usage quota (row reads, row writes, storage) is exhausted."},{"question":"How do I fix a 402 from Turso?","answer":"Open `turso org billing` and resolve the subscription or payment, then retry. No connection or query change fixes a billing-state failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/payment-required-402","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/rate-limited-429","corpus":"errors","engine":"libsql","language":"en","title":"request rate limit hit","description":"Turso throttles request rate with 429: back off and retry and it clears, while billing quota exhaustion surfaces as the BLOCKED error code instead.","body":{"code":"429 Too Many Requests","slug":"rate-limited-429","name":null,"message":"Server returned HTTP status 429 Too Many Requests","group":"remote-api","severity":null,"sql_state":null,"summary":"Turso throttles request rate with 429: back off and retry and it clears, while billing quota exhaustion surfaces as the BLOCKED error code instead.","meaning":"Turso throttles bursts of requests with 429. It is a short-term signal: back off and retry, and it clears. Quota exhaustion is different: the docs say exceeding the monthly row-read, row-write, or storage quota fails with the `BLOCKED` error code, and Turso's response-code reference does not list 429 at all. So a 429 points at request rate, not at billing.","causes":["More concurrent requests than the plan allows, often from a connection pool sized for a different database.","A retry loop with no backoff turning one slow request into a storm.","Monthly quota exhaustion, but that surfaces as `BLOCKED`, not 429, so check usage before assuming quota.","A batch job and live traffic sharing one database with no limit on either side."],"fix":[{"text":"Retry the request with exponential backoff and honor any Retry-After header:","sql":"// retry on 429 with backoff\nfor (let i = 0; i < 5; i++) {\n  try { return await db.execute(sql); }\n  catch (e) {\n    if (!String(e).includes('429') || i === 4) throw e;\n    await new Promise(r => setTimeout(r, 500 * 2 ** i));\n  }\n}"},{"text":"Cap the connection pool so live traffic cannot starve the limit:","sql":"// @libsql/client: reuse one client, do not create one per request\nconst db = createClient({ url: process.env.LIBSQL_URL, authToken: process.env.LIBSQL_TOKEN });"},{"text":"Check current usage against the plan's limits:","sql":"turso plan show\nturso db inspect mydb"},{"text":"Collapse many small statements into one batch to cut request count:","sql":"await db.batch([\n  { sql: \"INSERT INTO t (a) VALUES (?)\", args: [1] },\n  { sql: \"INSERT INTO t (a) VALUES (?)\", args: [2] }\n]);"}],"diagnostic":"Check `turso plan show` and `turso db inspect mydb` first: quotas that are exhausted show up as `BLOCKED` rather than 429, so a real 429 is about request rate. Look at how many concurrent clients and retries hit the database in the seconds before the error, and count how many connections your pool opens. A retry loop that fires on every failure with no delay is the classic cause.","alternatives":"Move read-heavy work to an embedded replica, which reads a local file and sends no requests. Move bursty writes into batches. If you are permanently above the quota, change plan instead of masking 429s with retries. If usage itself is the problem, the error will be `BLOCKED`, and no retry pattern helps until the quota resets or the plan changes.","details":[],"details_title":null,"repro":"Reproducing 429 honestly needs a real database and enough traffic to trip the limit, which I would not run against a production database. The shape is easy to demonstrate though: fire a few hundred parallel requests from a loop at one test database with @libsql/client until the server answers 429. Local `turso dev` has no rate limiter, so it cannot reproduce it.","repro_note":null,"related":["libsql/too-many-connections","libsql/busy","libsql/unauthorized-401"],"sqlly":"SQLly issues one request per statement you run, so a burst of 429s in the desktop client usually means an automation elsewhere is hammering the same database; the error text and timing in the result pane make the pattern obvious.","faqs":[{"question":"Why do I get BLOCKED instead of 429 on Turso?","answer":"Quota exhaustion (monthly row reads, row writes, or storage) fails with the `BLOCKED` error code per Turso's usage docs. 429 is the burst request-rate signal. Check `turso plan show` to see which one you hit."},{"question":"How do I check my current Turso usage and limits?","answer":"`turso plan show` prints the current plan usage and limits, and `turso db inspect <db>` shows a database's rows read, rows written, and space used. `turso org billing` opens the billing portal."},{"question":"Does retrying fix a 429 from Turso?","answer":"Only when it is request rate: back off exponentially, honor `Retry-After` if present, and cap concurrent clients. If the real problem is an exhausted quota the error is `BLOCKED`, and retries change nothing until the reset or an upgrade."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/rate-limited-429","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/replica-paused","corpus":"errors","engine":"libsql","language":"en","title":"stale reads from a failing replica","description":"Sync from the primary is failing, so db.sync() throws the underlying error and reads keep returning the last frames the replica applied.","body":{"code":"replica out of date","slug":"replica-paused","name":null,"message":"replica out of date with the primary","group":"replica-consistency","severity":null,"sql_state":null,"summary":"Sync from the primary is failing, so db.sync() throws the underlying error and reads keep returning the last frames the replica applied.","meaning":"An embedded replica only advances when a sync succeeds. When `db.sync()` fails, the replica stops taking new frames and reads keep answering from the last state that was applied: stale reads that fail no check of their own. The failure itself surfaces through `sync()` as whatever the underlying client error is, for example a connection failure or `SERVER_ERROR` with an HTTP status when the token is rejected. Turso's docs describe the flow: reads run locally from the file, and writes are sent to the cloud primary and then reflected back to the replica, so a sync gap sits between your writes and what your reads return.","causes":["The network path to the primary dropped, and every sync since has failed.","The auth token used for sync expired or was invalidated, so the sync request answers 401.","Syncs run rarely (no `syncInterval` and no manual calls), so reads lag behind the primary without any failure."],"fix":[{"text":"Call sync() and read the error it throws; it names the real failure:","sql":"await db.sync();  // throws the underlying connect, HTTP or auth error"},{"text":"For 401-shaped failures, mint a fresh token and update the client config:","sql":"turso db tokens create mydb"},{"text":"When a decision needs current data, read that one query through the remote URL instead of the replica:","sql":"const primary = createClient({ url: 'libsql://mydb-myorg.turso.io', authToken });\nconst row = await primary.execute('SELECT ...');"}],"diagnostic":"Run `db.sync()` and read the thrown error: a socket or DNS failure points at the network, `SERVER_ERROR` with 401 at the token, `SQLITE_BUSY` at a local writer holding the replica file. If sync succeeds but reads still look old, write a known value through the primary and read it back through the replica: the difference is the sync gap.","alternatives":"Reads that must always be current can go through the remote `libsql://` URL; keep the replica for the fast local reads that tolerate a sync gap.","details":[],"details_title":null,"repro":"Local and honest: run `turso dev --db-file scratch.db`, point an embedded replica at it (a `file:` URL with `syncUrl` set to the dev server), sync once, then kill the dev server and call `db.sync()` again; it fails with a connection error while reads keep working. Restart the dev server and sync again to watch the replica catch up.","repro_note":null,"related":["libsql/embedded-replica-locked","libsql/connection-interrupted","libsql/unauthorized-401"],"sqlly":"SQLly opens the replica file as a plain SQLite database, so it shows exactly what the last successful sync left behind: run the same SELECT in SQLly and in the app to confirm a stale-read suspicion.","faqs":[{"question":"What happens to reads when an embedded replica sync fails?","answer":"They keep working locally and answer from the last frames that were applied, so nothing throws on read. The staleness is only visible by comparison, which is why the failing sync() call is the signal to watch."},{"question":"Does @libsql/client sync automatically?","answer":"Yes when you configure `syncInterval`; otherwise the replica syncs when your code calls db.sync(). A long interval or a missing call means reads lag by design, and failures surface wherever sync runs."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/replica-paused","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/sqlite-auth","corpus":"errors","engine":"libsql","language":"en","title":"SQLITE_AUTH: authorization denied","description":"A registered authorizer callback denied an action. Rare in libSQL clients; remote auth failures use HTTP 401 or 403 instead.","body":{"code":"SQLITE_AUTH","slug":"sqlite-auth","name":"23","message":"authorization denied","group":"local-sqlite","severity":null,"sql_state":null,"summary":"A registered authorizer callback denied an action. Rare in libSQL clients; remote auth failures use HTTP 401 or 403 instead.","meaning":"`SQLITE_AUTH` (23) is returned when an application set a `sqlite3_set_authorizer()` callback and that callback returned `SQLITE_DENY` for an action. It is an application-level hook, not something a normal libSQL client sets, so this is rare. Authentication against a remote Turso database does not use this code: it fails with HTTP 401 or 403.","causes":["An embedding application registered an authorizer that denied the action.","An ORM or wrapper enabled an authorizer for row-level policies and your statement hit a denied action."],"fix":[{"text":"Check with the embedding application's authors; the denial comes from its policy, not from SQLite itself.","sql":null}],"diagnostic":"SQLITE_AUTH always comes from application code, never from the database file: search your dependencies for `sqlite3_set_authorizer` (ORMs and sandboxed runtimes register them for row-level policies). If the denial appears only inside one application, its policy is the cause.","alternatives":"Run the same statement against the same file with a tool that sets no authorizer; if it succeeds there, the denial is the embedding's policy, and the fix belongs in that policy, not in the SQL.","details":[],"details_title":null,"repro":"Needs an embedding that registers an authorizer: write a small C or Rust program that calls `sqlite3_set_authorizer()` and returns `SQLITE_DENY` for one action, then run the denied statement. @libsql/client and the Turso SDKs expose no authorizer API, so there is no honest client-only repro.","repro_note":null,"related":["libsql/busy","libsql/unauthorized-401","libsql/forbidden-403"],"sqlly":"SQLly sets no authorizer when it opens a SQLite file, so a statement denied with SQLITE_AUTH inside an embedding usually runs in SQLly, and that contrast pins the denial to the embedding's policy.","faqs":[{"question":"What does SQLITE_AUTH mean in SQLite?","answer":"An application registered a `sqlite3_set_authorizer()` callback and that callback returned SQLITE_DENY for the action. It is result code 23, and it comes from application policy, not from the database file."},{"question":"Do Turso or libSQL servers return SQLITE_AUTH for bad auth tokens?","answer":"No. Remote authentication failures surface as HTTP 401 (invalid or expired token) or 403 (no permission). SQLITE_AUTH belongs to the local authorizer hook."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/sqlite-auth","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/token-expired","corpus":"errors","engine":"libsql","language":"en","title":"Auth token expired","description":"The JWT the connection presents passed its exp claim, so the server answers 401 until you mint a new token.","body":{"code":"auth token expired","slug":"token-expired","name":null,"message":"401 Unauthorized: auth token is invalid or expired","group":"auth-token","severity":null,"sql_state":null,"summary":"The JWT the connection presents passed its exp claim, so the server answers 401 until you mint a new token.","meaning":"Turso auth tokens are JWTs with an expiry. `turso db tokens create` tokens never expire by default: an expiry exists only when the token was minted with `--expiration` (or is a platform token with a built-in lifetime). When the `exp` claim passes, the server rejects the token with 401. The failure shows up as `SERVER_ERROR: Server returned HTTP status 401 Unauthorized`, and the cause is visible in the token itself.","causes":["The token was minted with `--expiration` and aged past it, and the config was never refreshed.","A CI secret stores a token with a short expiry and the job runs after it lapsed.","A long-lived server process loaded a token at startup and never reloads it."],"fix":[{"text":"Mint a fresh token and update the config:","sql":"turso db tokens create mydb --expiration 30d"},{"text":"For services, refresh the token at startup and periodically instead of baking it in:","sql":"// re-read env or re-mint on 401 before giving up\nif (String(err).includes('401')) token = await mintToken();"},{"text":"Check the expiry inside the current token:","sql":"echo \"$LIBSQL_TOKEN\" | cut -d. -f2 | base64 -d 2>/dev/null | grep -o '\"exp\":[0-9]*'; date +%s"}],"diagnostic":"Decode the JWT payload and read `exp` (seconds since epoch). Compare with `date +%s`. An `exp` in the past confirms expiry. If `exp` is in the future but the server still answers 401, the token is not expired: look at database mismatch instead, which is the 401 entry's other causes.","alternatives":"The default token never expires, which is convenient and dangerous: a leaked default token is valid until you revoke it with `turso db tokens invalidate`. Prefer short-lived tokens minted at deploy time.","details":[],"details_title":null,"repro":"Honest repro needs a cloud database: create one with `turso db create repro-exp`, mint a token with `--expiration 1s`, wait a few seconds, then connect. The server answers 401. Offline you can verify only the decode step: a token with a past `exp` is demonstrably expired without any server.","repro_note":null,"related":["libsql/unauthorized-401","libsql/forbidden-403"],"sqlly":"SQLly keeps the token beside the connection, so after re-minting you update it once in the connection settings and every later query runs with the new token, the same edit your app config needs, with immediate feedback that the new token works.","faqs":[{"question":"How long do Turso auth tokens last?","answer":"Database tokens from `turso db tokens create` never expire unless you pass `--expiration` when minting them. If a token has an `exp` claim that passed, it was minted with a deliberate expiry."},{"question":"How do I rotate an expired or leaked Turso token?","answer":"Mint a fresh one with `turso db tokens create mydb --expiration 30d`, update every consumer, then revoke the old one with `turso db tokens invalidate mydb` so copies in old configs stop working."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/token-expired","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/too-many-connections","corpus":"errors","engine":"libsql","language":"en","title":"Too many connections to one database","description":"The database hit its concurrent connection limit: pools opening unbounded connections per request are the usual cause.","body":{"code":"too many connections","slug":"too-many-connections","name":null,"message":"Too many connections to the database","group":"remote-api","severity":null,"sql_state":null,"summary":"The database hit its concurrent connection limit: pools opening unbounded connections per request are the usual cause.","meaning":"A remote database can only carry so many simultaneous connections, and the server refuses new ones past that point. Each serverless request that creates a fresh client counts as a new connection, so a function-per-request setup can blow through the limit even at modest traffic. This is a connection-count limit, distinct from the 429 request-rate limit, though both come from unbounded client fan-out.","causes":["Creating a new client per request instead of reusing one.","A connection pool sized far above what the database plan allows.","Connections left open by interactive transactions that never committed or rolled back.","Many serverless instances each holding their own pool."],"fix":[{"text":"Create the client once at module scope and reuse it:","sql":"// module scope, not per request\nexport const db = createClient({ url: process.env.LIBSQL_URL, authToken: process.env.LIBSQL_TOKEN });"},{"text":"Shrink pool sizes to something the plan can carry:","sql":"// generic pool config\n{ max: 5 }"},{"text":"Always close or roll back interactive transactions, including on error:","sql":"const tx = await db.transaction('write');\ntry { await tx.execute(sql); await tx.commit(); }\ncatch (e) { await tx.rollback(); throw e; }"}],"diagnostic":"Count concurrent clients: grep your code for `createClient` calls. One per request path is the bug. Then estimate concurrency: serverless platforms scale to many instances, each with its own pool, so multiply pool size by instance count and compare with the point where the refusals started. If connections climb over time and never fall, look for transactions opened without commit or rollback.","alternatives":"HTTP-over-request connections (`/v2/pipeline` per request, no persistent session) sidestep the persistent-connection count at the cost of per-request latency. Batching statements also reduces the connection time per unit of work.","details":[],"details_title":null,"repro":"Honest repro needs a real database and opening more connections than the plan allows, which can disturb other users, so I would use a dedicated test database: open a loop of `createClient(...)` connections without closing them until the server refuses. Exact refusal message varies by client; the observable is new connections failing while existing ones still work. `turso dev` has no such limit.","repro_note":null,"related":["libsql/rate-limited-429","libsql/connection-interrupted","libsql/busy"],"sqlly":"SQLly holds one connection per open tab, so it is never the cause, but it is a clean probe: if SQLly connects fine while your service gets refused, your service's pool or per-request clients are what exhausted the limit.","faqs":[{"question":"Should I create a new @libsql/client for every request?","answer":"No. Create it once at module scope and reuse it; each new client is a new connection, and a fresh client per request in a serverless function multiplies into hundreds of connections under load."},{"question":"How many concurrent requests does @libsql/client make at once?","answer":"Up to 20 by default; the `concurrency` config option raises or removes the limit. Keep it aligned with what the database tolerates instead of disabling it."},{"question":"How is this different from a 429?","answer":"429 throttles request rate; this refuses new connections while existing ones still work. Both trace back to unbounded fan-out: per-request clients and pools sized for a different database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/too-many-connections","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/libsql/unauthorized-401","corpus":"errors","engine":"libsql","language":"en","title":"401 Unauthorized: bad or missing auth token","description":"The server rejected the auth token: it is missing, malformed, expired, or was created for a different database.","body":{"code":"401 Unauthorized","slug":"unauthorized-401","name":null,"message":"Server returned HTTP status 401 Unauthorized","group":"auth-token","severity":null,"sql_state":null,"summary":"The server rejected the auth token: it is missing, malformed, expired, or was created for a different database.","meaning":"Turso and sqld check a JWT auth token on every remote request. A 401 means the check failed before any SQL ran. Turso's API docs list 401 as `Invalid or expired auth token`; a missing token fails the same way. The three usual shapes are: no token at all in the URL or header, a token that was created for another database, or a token whose expiry has passed. A 401 with a token you believe is valid is almost always expiry or a mismatch between token and database.","causes":["No auth token was attached to the connection URL or the Authorization header.","The token was created for a different database. Turso tokens are database-scoped.","The token expired. By default `turso db tokens create` tokens never expire, so an expired token means it was minted with `--expiration` and the date passed, or a platform token with a built-in expiry aged out.","The token string was truncated or wrapped somewhere, for example in an env file or a CI secret."],"fix":[{"text":"Create a fresh token for the database you connect to and check the expiry:","sql":"turso db tokens create mydb --expiration 7d"},{"text":"Confirm the URL and token point at the same database. The URL is in the database's connect string:","sql":"turso db show mydb --url"},{"text":"Decode the token to inspect its claims and expiry. It is a JWT, so the payload is base64:","sql":"echo '<token>' | cut -d. -f2 | base64 -d 2>/dev/null; echo"},{"text":"For local testing without the cloud, run sqld yourself and skip the platform token path entirely:","sql":"turso dev --db-file scratch.db"}],"diagnostic":"Decode the token payload and read the `exp` claim. If `exp` is in the past, the token expired. Compare the database name in the token's audience or in your URL with `turso db show <name> --url`. A 401 on every request with a valid, unexpired, matching token points at the token never reaching the server, so check the client's URL scheme: `libsql://` URLs need the token in the URL or a client option, plain HTTPS platform API calls need an `Authorization: Bearer` header.","alternatives":"For throwaway work, `turso dev` runs a local sqld with no auth, or a plain file URL `file:local.db` skips the server entirely. For CI, mint a short-lived token at job start instead of storing a long-lived one.","details":[],"details_title":null,"repro":"Local: `turso dev --db-file scratch.db` starts a server with auth disabled, so 401 cannot be reproduced against it. To reproduce the real thing you need a Turso Cloud database: create one with `turso db create repro401`, then connect with a deliberately wrong token string and the client returns SERVER_ERROR with status 401. Note this needs a real cloud database and token; there is no honest offline repro.","repro_note":null,"related":["libsql/token-expired","libsql/forbidden-403","libsql/rate-limited-429"],"sqlly":"SQLly stores the token with the connection, so you can paste the exact `libsql://` URL and token from your app config into the desktop client: if SQLly gets the same 401, the token or URL is wrong, and if it connects, your app is sending something different.","faqs":[{"question":"How do I check when my Turso auth token expires?","answer":"Decode the JWT payload: `echo '<token>' | cut -d. -f2 | base64 -d 2>/dev/null` and read the `exp` claim (seconds since epoch). Tokens from `turso db tokens create` have no expiry unless the token was minted with `--expiration`, so an `exp` in the past means someone set one deliberately."},{"question":"Where does the auth token go in a libSQL connection?","answer":"Either in the URL as `?authToken=<token>` or through the client's `authToken` option (`createClient({ url, authToken })` in @libsql/client). Plain HTTPS calls to the platform API take an `Authorization: Bearer` header instead."},{"question":"Why does my token work in `turso db shell` but fail in my app?","answer":"The shell authenticates with your CLI login, not the database token your app uses. Compare `turso db show mydb --url` with the URL in your app config and mint a fresh database token with `turso db tokens create mydb` for the app."}],"aliases":[]},"source_url":"https://sqlly.app/errors/libsql/unauthorized-401","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1040","corpus":"errors","engine":"mysql","language":"en","title":"Too many connections","description":"The server already has max_connections client connections open. Close idle ones, size connection pools properly, or raise the limit.","body":{"code":"1040","slug":"1040","name":"ER_CON_COUNT_ERROR","message":"Too many connections","group":"server","severity":null,"sql_state":"08004","summary":"The server already has max_connections client connections open. Close idle ones, size connection pools properly, or raise the limit.","meaning":"MySQL refuses a new connection once `max_connections` clients are connected. It keeps one extra slot for an account with the `CONNECTION_ADMIN` (or `SUPER`) privilege, so an administrator can still get in to see what's happening.","causes":["Application connection pools that together open more connections than the server allows, for example many app instances each with a large pool.","Connections leaked by code that never closes them.","Slow queries or lock waits that keep connections busy until new requests pile up.","A low `max_connections` for the workload (the default is 151)."],"fix":[{"text":"See how many connections there are and who holds them.","sql":"SHOW STATUS WHERE Variable_name IN ('Threads_connected', 'Max_used_connections');\nSELECT user, host, db, command, time FROM information_schema.processlist ORDER BY time DESC;"},{"text":"Kill idle sessions that are stuck, then fix whatever leaks them.","sql":"KILL 12345;  -- the Id from the process list"},{"text":"Raise the limit if the server has memory to spare, and persist it.","sql":"SET PERSIST max_connections = 500;"},{"text":"Cap pool sizes so that pool size times the number of app instances stays below `max_connections`.","sql":null}],"diagnostic":"-- Is the limit actually reached, and by whom?\nSHOW GLOBAL STATUS LIKE 'Threads_connected';\nSHOW GLOBAL STATUS LIKE 'Max_used_connections';\nSHOW VARIABLES LIKE 'max_connections';\nSELECT user, host, db, command, time, state,\n       LEFT(info, 80) AS current_sql\nFROM information_schema.processlist\nORDER BY time DESC;\n-- Idle-in-transaction or sleeping connections leak from the app if command='Sleep' and time is huge.\n-- Per-account view (8.0+):\nSELECT user, COUNT(*) AS conns\nFROM information_schema.processlist\nGROUP BY user ORDER BY conns DESC;\n-- Has it been chronically near the ceiling?\nSHOW GLOBAL STATUS LIKE 'Max_used_connections_time';\nSHOW GLOBAL STATUS LIKE 'Aborted_connects';","alternatives":"Raising max_connections only helps if the server has RAM for it; each connection costs memory and the per-thread buffers matter under load. A short-term lever is wait_timeout to reap abandoned sleepers (SET GLOBAL wait_timeout = 120 applies to new sessions only). The real fix is usually pool sizing in the application or a pooler such as ProxySQL to multiplex connections.","details":[],"details_title":null,"repro":"-- Safe on a scratch server with a low limit. Do not run this on production.\nSET PERSIST max_connections = 5;   -- or SET GLOBAL on 5.7\n-- From several terminals (or a tiny loop), open connections without closing them:\n-- for i in $(seq 1 10); do mysql -h 127.0.0.1 -u app_user -p'pass' -e 'SELECT SLEEP(300);' & done\n-- Once 5 are up, the 6th gets: ERROR 1040 (08004): Too many connections\n-- (A root login holds CONNECTION_ADMIN, so it gets the extra slot: the 6th root session succeeds and the 7th gets 1040.)\n-- Cleanup: kill the sleepers, then SET PERSIST max_connections = DEFAULT;\n-- 8.0.16+ also allows a controlled test:\n-- SET GLOBAL max_connections = 5; then in another session: SELECT 1;  -- 1040 if you are not the admin slot","repro_note":null,"related":["mysql/1203","mysql/1205","sql-server/701","oracle/ora-00020","oracle/ora-00018","postgresql/53300"],"sqlly":"SQLly's activity monitor for MySQL lists sessions with what they're running and lets you kill one, which helps when you need to find the connections filling up the server.","faqs":[{"question":"What is the one extra admin connection?","answer":"MySQL reserves one connection slot for users with CONNECTION_ADMIN (8.0+) or SUPER (5.7), so max_connections+1st admin connection still works. If even that fails, no new session can connect. Wait for an idle session to reach wait_timeout, or restart the server."},{"question":"How do I find the right max_connections value?","answer":"Look at Max_used_connections over a normal peak period, add headroom, and check the server's memory budget. There is no formula that fits all workloads; watch peak usage over a week rather than copying a number."},{"question":"Why did connections spike suddenly?","answer":"Most often a slow query or lock wait makes every request hold its connection longer, so the pool grows to its cap across all app instances. Fix the query or the lock contention; raising the limit just delays the failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1040","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1044","corpus":"errors","engine":"mysql","language":"en","title":"Access denied for user to database","description":"The login worked, but the account has no privileges on the database it tried to use. Grant privileges on that database or connect to one the account can use.","body":{"code":"1044","slug":"1044","name":"ER_DBACCESS_DENIED_ERROR","message":"Access denied for user '%s'@'%s' to database '%s'","group":"access","severity":null,"sql_state":"42000","summary":"The login worked, but the account has no privileges on the database it tried to use. Grant privileges on that database or connect to one the account can use.","meaning":"Unlike 1045, the password check passed: MySQL knows who you are. 1044 means the account has no privilege at all on the named database, so it can't select it with `USE`, name it in the connection, or create it.\n\nPrivileges are granted per account (`'user'@'host'`), so the same user name connecting from another host can have different rights. A grant to `'app'@'%'` also covers a socket login as `'app'@'localhost'`, but a grant to `'app'@'localhost'` does not cover a TCP login as `'app'@'%'`.","causes":["The account was created but never granted anything on the database.","Privileges were granted to a different host part, for example `'app'@'localhost'` while you connect as `'app'@'%'`.","The connection string names the wrong database, or a database the account was never meant to use.","Trying to `CREATE DATABASE` without the global `CREATE` privilege."],"fix":[{"text":"See which account you are and what it may do.","sql":"SELECT CURRENT_USER();\nSHOW GRANTS FOR CURRENT_USER();"},{"text":"As an administrator, create the account if it does not exist yet, then grant the privileges it needs on that database.","sql":"CREATE USER IF NOT EXISTS 'app'@'%' IDENTIFIED BY 'change-me';\nGRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'app'@'%';"},{"text":"If the grant went to another host part, check the accounts that exist for the user name.","sql":"SELECT user, host FROM mysql.user WHERE user = 'app';"}],"diagnostic":"-- Who am I, and what may I do?\nSELECT CURRENT_USER();\nSHOW GRANTS FOR CURRENT_USER();\n-- As admin: every account with that name, in case the grant went to another host part.\nSELECT user, host FROM mysql.user WHERE user = 'app';","alternatives":"On MySQL 8.0 you can grant a role to several accounts once instead of repeating per-database grants; 5.7 has no roles, so grant per account. If the goal is read-only inspection, GRANT SELECT on the database is enough; resist granting ALL.","details":[],"details_title":null,"repro":"-- Run as an administrator, then reconnect as 'limited' in a second session.\nCREATE DATABASE IF NOT EXISTS scratch_repro;\nCREATE USER IF NOT EXISTS 'limited'@'localhost' IDENTIFIED BY 'pw123';\n-- No grants on purpose.\n-- As 'limited'@'localhost':\nUSE scratch_repro;  -- ERROR 1044 (42000): Access denied for user 'limited'@'localhost' to database 'scratch_repro'","repro_note":null,"related":["mysql/1045","mysql/1142","mysql/1227","mysql/1049","sql-server/916","postgresql/42501"],"sqlly":"SQLly's schema sidebar lists only the databases the profile's account can actually see, so a grant that landed on the wrong host part shows up as a missing database.","faqs":[{"question":"How do 1044 and 1045 differ?","answer":"1045 fails at login: wrong password or no matching account. 1044 means you are logged in but hold no privilege on that specific database. The 1044 message names the database; the 1045 message names the account."},{"question":"Why does the same user name work on one machine and fail on another?","answer":"Accounts are per host part. 'app'@'localhost' and 'app'@'%' are separate accounts, and a grant on one does not automatically cover the other. A grant to 'app'@'%' does reach a 'localhost' login over the socket, so test the exact client host you use. Query mysql.user for the user name and grant the variant that matches your client host."},{"question":"Can I create the database I was denied?","answer":"Only with the global CREATE privilege, which is separate from any per-database grant. Without it, CREATE DATABASE fails with 1044 even though the database doesn't exist yet."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1044","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1045","corpus":"errors","engine":"mysql","language":"en","title":"Access denied for user","description":"MySQL rejected the user name, host and password combination. Usually a wrong password or no 'user'@'host' account matching the host you connect from.","body":{"code":"1045","slug":"1045","name":"ER_ACCESS_DENIED_ERROR","message":"Access denied for user '%s'@'%s' (using password: %s)","group":"access","severity":null,"sql_state":"28000","summary":"MySQL rejected the user name, host and password combination. Usually a wrong password or no 'user'@'host' account matching the host you connect from.","meaning":"A MySQL account is a user name plus the host it connects from: `'app'@'localhost'` and `'app'@'%'` are two different accounts with their own passwords. When you connect, the server picks the most specific account matching your user name and client host, then checks the password. If no account matches, or the password is wrong, you get 1045.\n\n`(using password: YES)` means a password was sent and was wrong or the account doesn't exist; `(using password: NO)` means the client sent no password at all.","causes":["Wrong password, or a password with special characters mangled by the shell or a connection string.","The account exists for a different host. `'app'@'localhost'` doesn't match a connection from another machine, and a more specific anonymous account (`''@'localhost'`) can win over `'app'@'%'`.","`(using password: NO)`: the client didn't send the password, for example `-p` was missing or an option file overrode it.","On Ubuntu and Debian, `root` uses socket authentication (`auth_socket`) and can only log in as the operating-system root user, without a password.","The account was created with an authentication plugin the client library doesn't support."],"fix":[{"text":"Connect as an administrator and list the accounts for that user name and their hosts.","sql":"SELECT user, host, plugin FROM mysql.user WHERE user = 'app';"},{"text":"Reset the password for the exact account (user and host) you connect as.","sql":"ALTER USER 'app'@'%' IDENTIFIED BY 'new-strong-password';"},{"text":"If no account covers your client host, create one and grant it what it needs.","sql":"CREATE USER 'app'@'10.0.0.%' IDENTIFIED BY 'strong-password';\nGRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'app'@'10.0.0.%';"},{"text":"Check which account the server matched you to. After you can connect, `CURRENT_USER()` shows the account used and `USER()` the name and host you sent.","sql":"SELECT USER(), CURRENT_USER();"},{"text":"If you lost the root password entirely, restart the server with `--skip-grant-tables --skip-networking`, connect, run `FLUSH PRIVILEGES;` then `ALTER USER` to set a new password, and restart normally.","sql":null}],"diagnostic":"-- Which accounts exist for this user name, and with which auth plugin?\nSELECT user, host, plugin FROM mysql.user WHERE user = 'app';\n-- Once you get in: the account the server actually matched vs. what you sent.\nSELECT USER(), CURRENT_USER();","alternatives":"On Debian and Ubuntu, connecting as the OS root over the socket usually works without a password because of auth_socket, so you can fix other accounts from there. A [client] section in an option file avoids shell quoting problems with special characters in passwords.","details":[],"details_title":null,"repro":"# Shell repro (auth errors only happen at connect time, not inside a session):\nmysql -uroot -p -e \"CREATE USER IF NOT EXISTS 'scratch'@'localhost' IDENTIFIED BY 'right-password';\"\nmysql -uscratch -pwrong-password -h127.0.0.1 -e \"SELECT 1;\"\n# ERROR 1045 (28000): Access denied for user 'scratch'@'127.0.0.1' (using password: YES)","repro_note":null,"related":["mysql/1044","mysql/1130","mysql/1251","mysql/1698","mysql/2059","sql-server/18456","postgresql/28P01","oracle/ora-01017"],"sqlly":"SQLly's connection test reports the exact 1045 text including `(using password: YES/NO)` for the profile's user and host, so a wrong password is distinguishable from a missing account before you touch the server.","faqs":[{"question":"What does using password: NO mean?","answer":"The client didn't send any password. Pass one (`mysql -u app -p`), or check that your option file or connection string actually includes it."},{"question":"Why can I log in locally but not from another machine?","answer":"MySQL accounts are per host. You probably have `'user'@'localhost'` but no account matching the remote host, such as `'user'@'%'`. Also check that the server listens on a network interface (`bind_address`)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1045","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1046","corpus":"errors","engine":"mysql","language":"en","title":"No database selected","description":"The statement names a table without a database, and the session has no default database. Run USE first or qualify the table as db.table.","body":{"code":"1046","slug":"1046","name":"ER_NO_DB_ERROR","message":"No database selected","group":"objects","severity":null,"sql_state":"3D000","summary":"The statement names a table without a database, and the session has no default database. Run USE first or qualify the table as db.table.","meaning":"MySQL resolves an unqualified table name in the session's default database. If you connected without one and never ran `USE`, there's nowhere to look, so the statement fails with 1046 before any table lookup.","causes":["Connecting without a database (for example `mysql -u app -p` with no database argument) and then querying a table by name.","Running a dump or script that doesn't start with `USE` or `CREATE DATABASE ... ; USE ...`.","A connection pool or tool that opens connections without a default schema."],"fix":[{"text":"Select the database for the session.","sql":"USE shop;"},{"text":"Or qualify every table with its database.","sql":"SELECT * FROM shop.orders LIMIT 10;"},{"text":"Put the database in the connection itself, for example `mysql -u app -p shop`, or the `database` setting of your driver.","sql":null}],"diagnostic":"-- Is a default database set for this session? NULL means none.\nSELECT DATABASE();\nSHOW DATABASES;","alternatives":"In scripts and dumps, put USE at the top so the script runs correctly from any client. Many drivers and tools accept a default schema in the connection settings, which fixes it for every query on that connection.","details":[],"details_title":null,"repro":"-- Connect without a database, then:\nSELECT * FROM orders;  -- ERROR 1046 (3D000): No database selected","repro_note":null,"related":["mysql/1049","mysql/1146","postgresql/3D000"],"sqlly":"SQLly shows the tab's active database in the status bar and a database picker in the toolbar.","faqs":[{"question":"Why do some queries work without USE?","answer":"Statements that qualify every table with its database (shop.orders) never touch the default database. Only unqualified table names need one."},{"question":"Does SELECT DATABASE() error out when nothing is selected?","answer":"No. It returns NULL, which makes it the quickest check before running your statements."},{"question":"Why does a dump file fail with this?","answer":"A dump of individual tables has no USE statement. Run it with the database as an argument (mysql -u app -p shop < dump.sql) or add USE shop at the top of the file."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1046","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1048","corpus":"errors","engine":"mysql","language":"en","title":"Column cannot be null","description":"An INSERT or UPDATE put NULL into a column declared NOT NULL. Supply a value, give the column a default, or allow NULL.","body":{"code":"1048","slug":"1048","name":"ER_BAD_NULL_ERROR","message":"Column '%s' cannot be null","group":"constraints","severity":null,"sql_state":"23000","summary":"An INSERT or UPDATE put NULL into a column declared NOT NULL. Supply a value, give the column a default, or allow NULL.","meaning":"The named column is `NOT NULL`, and the statement explicitly set it to `NULL` (or to an expression that evaluated to `NULL`). Omitting the column instead uses its default; if it has none, you get 1364 instead in strict mode.","causes":["Application code passing `null` for a required field.","An `INSERT ... SELECT` or `UPDATE ... JOIN` where a lookup found no row and produced `NULL`.","A CSV import where empty fields map to `NULL`."],"fix":[{"text":"Supply a value, or substitute one for `NULL`.","sql":"INSERT INTO customers (name, country) VALUES ('Ada', COALESCE(@country, 'GB'));"},{"text":"Give the column a default and omit it from the insert.","sql":"ALTER TABLE customers MODIFY country CHAR(2) NOT NULL DEFAULT 'GB';"},{"text":"If the value really can be unknown, allow `NULL`.","sql":"ALTER TABLE customers MODIFY country CHAR(2) NULL;"}],"diagnostic":"-- Which columns are required on the table you're writing to?\nSELECT column_name, is_nullable, column_default, extra\nFROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'customers'\nORDER BY ordinal_position;\n\n-- If the NULL came from a join or lookup, find which rows produce it.\nSELECT o.id, c.name\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE c.id IS NULL;","alternatives":"If an empty string is an acceptable stand-in during imports, wrap the expression in COALESCE(col, '') or IFNULL. For INSERT ... SELECT gaps, use a LEFT JOIN plus a fallback value rather than letting the missing row become NULL.","details":[],"details_title":null,"repro":"CREATE TEMPORARY TABLE t (a INT NOT NULL);\nINSERT INTO t VALUES (NULL);  -- ERROR 1048 (23000): Column 'a' cannot be null","repro_note":null,"related":["mysql/1364","mysql/1062","mysql/3819","sql-server/515","postgresql/23502","oracle/ora-01400","sqlite/sqlite-constraint-notnull"],"sqlly":"SQLly's grid row editor marks NOT NULL columns and blocks committing a row that leaves them empty, naming the column inline instead of after a failed INSERT.","faqs":[{"question":"What is the difference between 1048 and 1364?","answer":"1048 fires when the statement explicitly sets the column to NULL. 1364 fires when the column is omitted from the insert and has no default. Adding a default fixes 1364 but not 1048. Allowing NULL fixes both."},{"question":"Why did my code work before and fail now?","answer":"In non-strict SQL mode, a multiple-row INSERT, an INSERT ... SELECT or an UPDATE that puts NULL into a NOT NULL column substitutes the implicit default with a warning. A single-row INSERT with an explicit NULL still raises 1048 even in non-strict mode. MySQL 8.4 defaults to strict mode, so the same data raises 1048 there."},{"question":"Can I make one statement tolerate NULLs without changing the table?","answer":"Yes, substitute at write time: INSERT ... VALUES (COALESCE(@v, 'fallback')). Changing the column to nullable or adding a default is the durable fix."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1048","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1049","corpus":"errors","engine":"mysql","language":"en","title":"Unknown database","description":"The database named in the connection or in a USE statement doesn't exist on this server, or its name is spelled or cased differently.","body":{"code":"1049","slug":"1049","name":"ER_BAD_DB_ERROR","message":"Unknown database '%s'","group":"objects","severity":null,"sql_state":"42000","summary":"The database named in the connection or in a USE statement doesn't exist on this server, or its name is spelled or cased differently.","meaning":"MySQL couldn't find a database (schema) with that name. You get it when connecting with a default database, running `USE name`, or referring to `name.table`.\n\nOn Linux, database names are case-sensitive by default (`lower_case_table_names = 0`) because each database is a directory, so `Shop` and `shop` are different databases there. On Windows, and on macOS with its default HFS+ file system, they name the same database; a UFS volume on macOS is case-sensitive again.","causes":["A typo or different case in the database name.","Connecting to the wrong server or port, for example a fresh local instance instead of the one with your data.","The database was never created, or a restore or migration hasn't run yet.","A connection string that passes the database name with quotes or extra spaces."],"fix":[{"text":"List the databases this account can see.","sql":"SHOW DATABASES;"},{"text":"Create it if it should exist.","sql":"CREATE DATABASE shop CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"},{"text":"Check which server you're connected to.","sql":"SELECT @@hostname, @@port, VERSION();"}],"diagnostic":"-- What exists here, and where am I connected?\nSHOW DATABASES;\nSELECT @@hostname, @@port, VERSION();\n-- On Linux this is 0 by default, making names case sensitive:\nSELECT @@lower_case_table_names;","alternatives":"If the database should exist, run the restore or migration before connecting; most migration tools create the schema themselves when pointed at an empty server. If you only want to inspect what is there, connect without a default database and use SHOW DATABASES, which works even with no default selected.","details":[],"details_title":null,"repro":"USE no_such_database;  -- ERROR 1049 (42000): Unknown database 'no_such_database'","repro_note":null,"related":["mysql/1046","mysql/1044","mysql/1146","sql-server/4060","postgresql/3D000"],"sqlly":"SQLly's connection form offers the server's databases after the first successful connect, so the default database is picked from a list rather than typed from memory.","faqs":[{"question":"Why does 'Shop' work on my Mac and fail on the Linux server?","answer":"On Linux, lower_case_table_names is 0 by default and each database is a directory, so the name is case sensitive. Use the exact case or rename the database. On 8.0 you cannot change lower_case_table_names after the server is initialized."},{"question":"SHOW DATABASES lists it, yet I still get 1049. How?","answer":"That can happen when the data directory holds a leftover directory without valid metadata, for example after a crashed copy of the data directory. Check the server error log; drop and recreate or restore the database."},{"question":"Does 1049 mean the server is broken?","answer":"Usually you are on the wrong server or port, such as a fresh local instance instead of the one with your data. SELECT @@hostname, @@port tells you where you landed."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1049","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1050","corpus":"errors","engine":"mysql","language":"en","title":"Table already exists","description":"CREATE TABLE (or RENAME TABLE) uses a name that's already taken in that database by a table or view.","body":{"code":"1050","slug":"1050","name":"ER_TABLE_EXISTS_ERROR","message":"Table '%s' already exists","group":"objects","severity":null,"sql_state":"42S01","summary":"CREATE TABLE (or RENAME TABLE) uses a name that's already taken in that database by a table or view.","meaning":"A database can hold only one table or view with a given name. Creating or renaming to a name that exists fails with 1050. Re-running a migration or setup script is the usual trigger.","causes":["Running the same `CREATE TABLE` script twice.","A migration that already ran partially.","A view with the same name as the table you're creating."],"fix":[{"text":"Make the script idempotent.","sql":"CREATE TABLE IF NOT EXISTS audit_log (\n    id BIGINT AUTO_INCREMENT PRIMARY KEY,\n    msg TEXT\n);"},{"text":"If you meant to replace the table, drop it first (this deletes its data).","sql":"DROP TABLE IF EXISTS audit_log;"}],"diagnostic":"-- Who owns the conflicting name: a table, a view, or something in another schema?\nSELECT table_schema, table_name, table_type\nFROM information_schema.tables\nWHERE table_name = 'audit_log';\n\n-- A dropped table can leave a stale InnoDB file behind; check the data directory\n-- for a leftover .ibd if information_schema shows nothing but CREATE still fails.","alternatives":"For a rename collision, RENAME TABLE old TO backup_old first, then create the new one. If a view holds the name, DROP VIEW is what you need, not DROP TABLE. Tools like Flyway or Liquibase track applied migrations in their own table, which avoids the rerun problem altogether.","details":[],"details_title":null,"repro":"CREATE TABLE t_1050 (id INT PRIMARY KEY);\nCREATE TABLE t_1050 (id INT PRIMARY KEY); -- ERROR 1050: table already exists","repro_note":null,"related":["mysql/1051","mysql/1060","sql-server/2714","oracle/ora-00955","postgresql/42P07"],"sqlly":"SQLly's schema browser shows whether a name is already taken by a table or a view, so a rerun migration fails visibly before DDL.","faqs":[{"question":"I dropped the table but CREATE TABLE still says it exists. Why?","answer":"A view with the same name, a different default database than you think (MySQL has no search path; check with SELECT DATABASE()), or an orphaned InnoDB .ibd file from an unclean drop can all trigger 1050. Run the information_schema query above to see what the server actually sees."},{"question":"Is CREATE TABLE IF NOT EXISTS safe to leave in production scripts?","answer":"For idempotent setup scripts, yes. The risk is silent drift: if the existing table's columns differ from the CREATE statement, MySQL keeps the old definition and reports only a warning. Some teams treat that warning as an error in CI."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1050","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1051","corpus":"errors","engine":"mysql","language":"en","title":"Unknown table","description":"DROP TABLE (or a similar statement) names a table that doesn't exist in that database.","body":{"code":"1051","slug":"1051","name":"ER_BAD_TABLE_ERROR","message":"Unknown table '%s'","group":"objects","severity":null,"sql_state":"42S02","summary":"DROP TABLE (or a similar statement) names a table that doesn't exist in that database.","meaning":"1051 is what `DROP TABLE` reports for a table that isn't there. In a multi-table `DROP TABLE a, b, c`, nothing is dropped if any named table is missing. The statement fails and lists the missing ones. With `IF EXISTS`, the tables that exist are dropped and each missing one becomes a note.","causes":["Dropping a table twice, or in the wrong database.","A typo or letter-case difference on a case-sensitive server."],"fix":[{"text":"Use `IF EXISTS` so a missing table is only a note.","sql":"DROP TABLE IF EXISTS staging_orders;"},{"text":"Check the current database.","sql":"SELECT DATABASE();"}],"diagnostic":"-- Confirm the name and the schema you're really in:\nSELECT DATABASE();\nSELECT table_schema, table_name, table_type\nFROM information_schema.tables\nWHERE table_name = 'staging_orders';\n\n-- Views fail DROP TABLE with 1051 too. Check table_type before deciding\n-- whether you need DROP TABLE or DROP VIEW.","alternatives":"DROP TABLE IF EXISTS is the standard fix for teardown and test scripts. If the drop is part of a migration that should have something to remove, the 1051 itself is a signal your migration bookkeeping is off, worth checking before adding IF EXISTS everywhere.","details":[],"details_title":null,"repro":"CREATE TABLE t_1051 (id INT PRIMARY KEY);\nDROP TABLE t_1051;\nDROP TABLE t_1051;  -- ERROR 1051 (42S02): Unknown table 'mydb.t_1051'","repro_note":null,"related":["mysql/1146","mysql/1050","sql-server/3701"],"sqlly":"SQLly's destructive-statement confirmations for DROP TABLE make the wrong-database case visible, because 1051 usually means the table was already gone or you are in another schema.","faqs":[{"question":"In DROP TABLE a, b, c, do the existing tables get dropped when one is missing?","answer":"No. Without IF EXISTS, MySQL drops nothing and reports 1051 for the first missing name. With IF EXISTS, the tables that exist are dropped and each missing one is a note. If you need the tables dropped in one go, check information_schema.tables first and build the statement from what's actually there."},{"question":"What's the difference between 1051 and 1146?","answer":"1146 is for referencing a missing table in a SELECT, INSERT or similar statement. 1051 comes from DROP TABLE and DROP VIEW. Same root cause, different statements."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1051","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1052","corpus":"errors","engine":"mysql","language":"en","title":"Column is ambiguous","description":"A column name appears in more than one table of the query and wasn't qualified, so MySQL can't tell which one you mean.","body":{"code":"1052","slug":"1052","name":"ER_NON_UNIQ_ERROR","message":"Column '%s' in %s is ambiguous","group":"syntax","severity":null,"sql_state":"23000","summary":"A column name appears in more than one table of the query and wasn't qualified, so MySQL can't tell which one you mean.","meaning":"When two joined tables both have a column called, say, `id`, an unqualified `id` could mean either. MySQL refuses to guess and names the column and the clause (`in field list`, `in where clause`, ...).","causes":["Joining tables that share column names such as `id`, `name` or `created_at`, and using the bare name.","Adding a join to a working query, which brings in a second column with the same name."],"fix":[{"text":"Qualify the column with the table name or alias.","sql":"SELECT o.id, c.name\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nWHERE o.id > 100;"},{"text":"For shared join keys, `USING (col)` merges them into one column you can name without a qualifier.","sql":null}],"diagnostic":"-- Which tables share the column name?\nSELECT table_name, column_name\nFROM information_schema.columns\nWHERE table_schema = 'shop' AND column_name = 'id'\nORDER BY table_name;\n-- Then qualify every occurrence of that column in the statement.","alternatives":"USING (id) collapses the two join columns into one when they are the join key, which also removes the ambiguity. Table aliases (o, c) keep the qualified form short enough to read.","details":[],"details_title":null,"repro":"CREATE DATABASE shop;\nUSE shop;\nCREATE TABLE orders (id INT PRIMARY KEY, customer_id INT);\nCREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100));\nSELECT id FROM orders JOIN customers ON customers.id = orders.customer_id;\n-- ERROR 1052 (23000) at line 3: Column 'id' in field list is ambiguous","repro_note":null,"related":["mysql/1054","sql-server/209","oracle/ora-00918","postgresql/42702"],"sqlly":"SQLly's completion offers the qualified form (`o.id`, `c.id`) when a column name exists in more than one joined table, resolving the ambiguity while typing.","faqs":[{"question":"Can I just turn off some setting to let MySQL pick one?","answer":"No. There is no setting for this. MySQL refuses to guess because picking the wrong table silently returns wrong data. Qualify the column."},{"question":"The column is only in one table, why ambiguous?","answer":"Check the select list, WHERE, GROUP BY and ORDER BY: the ambiguity is about the whole statement, and a column you forgot you added to both tables (created_at, status, id) is the usual culprit. The diagnostic query lists every table holding that name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1052","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1054","corpus":"errors","engine":"mysql","language":"en","title":"Unknown column in field list","description":"The statement refers to a column that doesn't exist in the tables it names, or one that isn't visible at that point in the query.","body":{"code":"1054","slug":"1054","name":"ER_BAD_FIELD_ERROR","message":"Unknown column '%s' in '%s'","group":"objects","severity":null,"sql_state":"42S22","summary":"The statement refers to a column that doesn't exist in the tables it names, or one that isn't visible at that point in the query.","meaning":"MySQL couldn't resolve a column name. The second part of the message says where: `in 'field list'` (the select list or `SET`), `in 'where clause'`, `in 'on clause'`, `in 'order clause'` and so on.\n\nA classic case: a string written with double quotes in ANSI_QUOTES mode, or with backticks by mistake, is read as a column name.","causes":["A typo, or a column that was renamed or never added.","Using a select-list alias in `WHERE`, which runs before the select list is computed.","A string value written in backticks instead of single quotes, so `active` is read as a column name rather than the text 'active'.","Referring to a column of a table that isn't joined yet.","In a trigger, missing `NEW.` or `OLD.` before the column."],"fix":[{"text":"List the table's columns.","sql":"SHOW COLUMNS FROM orders;"},{"text":"Use quotes for string values and backticks only for names.","sql":"SELECT * FROM users WHERE status = 'active';"},{"text":"Repeat the expression in `WHERE`, or use `HAVING` or a derived table, instead of a select-list alias.","sql":"SELECT price * qty AS total FROM order_lines HAVING total > 100;"},{"text":"If the column is new, add it.","sql":"ALTER TABLE orders ADD COLUMN shipped_at DATETIME NULL;"}],"diagnostic":"-- Does the column exist at all, and in which table?\nSELECT table_name, column_name FROM information_schema.columns\nWHERE table_schema = DATABASE() AND column_name = 'b';\n-- Compare against what you wrote:\nSHOW COLUMNS FROM t;\n-- A quoted string read as a column name is the other common cause. Check which quote you used:\nSELECT @@sql_mode;  -- if ANSI_QUOTES is set, \"b\" is an identifier, not a string","alternatives":"For a select-list alias referenced in WHERE, repeat the expression or move the filter into a derived table. If the column genuinely should exist, a migration adding it is the fix; check with the schema's owner first, since the mistake is more often in the query than in the schema.","details":[],"details_title":null,"repro":"CREATE TEMPORARY TABLE t (a INT);\nSELECT b FROM t;  -- ERROR 1054 (42S22): Unknown column 'b' in 'field list'","repro_note":null,"related":["mysql/1146","mysql/1052","sql-server/207","postgresql/42703","oracle/ora-00904"],"sqlly":"SQLly's Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V on Windows and Linux) checks a query against the connection's schema without running it and marks unknown tables and columns in the editor.","faqs":[{"question":"The column exists, why does the query still fail?","answer":"Three usual reasons: the statement runs against a different database than you think (check DATABASE()), the column is on a joined table and needs a qualifier, or you wrote the name with the wrong quoting so MySQL reads it as something else, for example a string literal in ANSI_QUOTES mode."},{"question":"Why does WHERE total > 100 fail when I aliased SELECT price*qty AS total?","answer":"MySQL evaluates WHERE before the select list, so aliases aren't visible there. Repeat the expression, or use HAVING, or wrap the query in a derived table and filter outside it."},{"question":"Could this be a case-sensitivity problem?","answer":"Column names are always case-insensitive in MySQL, so no. Table names can be case-sensitive depending on lower_case_table_names and the filesystem, but that produces error 1146 (unknown table), not 1054."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1054","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1055","corpus":"errors","engine":"mysql","language":"en","title":"Expression isn't in GROUP BY","description":"With ONLY_FULL_GROUP_BY on (the default since MySQL 5.7), every selected column must be grouped, aggregated, or functionally dependent on the grouped columns.","body":{"code":"1055","slug":"1055","name":"ER_WRONG_FIELD_WITH_GROUP","message":"'%s' isn't in GROUP BY","group":"syntax","severity":null,"sql_state":"42000","summary":"With ONLY_FULL_GROUP_BY on (the default since MySQL 5.7), every selected column must be grouped, aggregated, or functionally dependent on the grouped columns.","meaning":"In a grouped query each output row stands for a group of input rows. A selected column that is neither in `GROUP BY` nor inside an aggregate has many possible values per group. Older MySQL picked one arbitrarily; with `ONLY_FULL_GROUP_BY`, which is on by default since 5.7, it's an error unless MySQL can prove the column is determined by the grouped columns (for example, grouping by a primary key).","causes":["Queries written for MySQL 5.6 or earlier that relied on the loose behavior.","Grouping by one column and selecting other non-aggregated columns.","Ordering by a column that isn't grouped."],"fix":[{"text":"Add the column to `GROUP BY`, or aggregate it.","sql":"SELECT customer_id, MAX(created_at) AS last_order, COUNT(*) AS n\nFROM orders\nGROUP BY customer_id;"},{"text":"If any value from the group is acceptable, say so with `ANY_VALUE()`.","sql":"SELECT customer_id, ANY_VALUE(status) AS some_status FROM orders GROUP BY customer_id;"},{"text":"Group by the primary key, which lets you select the table's other columns.","sql":null}],"diagnostic":"-- Is ONLY_FULL_GROUP_BY actually on? (default since 5.7, often disabled on upgraded servers)\nSELECT @@sql_mode;\nSELECT @@GLOBAL.sql_mode;\n-- Is the column functionally dependent? Grouping by the primary key of the table always is;\n-- grouping by a unique column is too. Anything else needs an aggregate or ANY_VALUE().\nSHOW CREATE TABLE orders;","alternatives":"If you want one arbitrary value per group and you accept MySQL choosing it, ANY_VALUE(col) makes the intent explicit without touching sql_mode. Disabling ONLY_FULL_GROUP_BY session-wide works but re-enables nondeterministic picks, so prefer rewriting the query. MySQL 5.6 has neither the error nor ANY_VALUE; old queries just run with arbitrary values there.","details":[],"details_title":null,"repro":"CREATE DATABASE shop;\nUSE shop;\nCREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, status VARCHAR(20));\nINSERT INTO orders VALUES (1, 10, 'open'), (2, 10, 'paid'), (3, 11, 'open');\nSELECT customer_id, status FROM orders GROUP BY customer_id;\n-- ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'shop.orders.status' which is not functionally dependent on columns in GROUP BY clause\n-- (only when ONLY_FULL_GROUP_BY is enabled; it is in the default sql_mode since 5.7)","repro_note":null,"related":["sql-server/8120","postgresql/42803","oracle/ora-00979"],"sqlly":"SQLly's Validate SQL flags select-list columns that are neither grouped nor aggregated in a GROUP BY query, before ONLY_FULL_GROUP_BY rejects the statement.","faqs":[{"question":"Can I turn ONLY_FULL_GROUP_BY off permanently?","answer":"You can: SET GLOBAL sql_mode = (SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); plus the same for the session, or set sql_mode in my.cnf. But be aware you're back to MySQL picking an arbitrary row value per group, which can differ between runs and replicas. Most teams keep the mode on and fix the queries."},{"question":"Why does grouping by the primary key work but grouping by another column doesn't?","answer":"ONLY_FULL_GROUP_BY allows selecting columns that are functionally dependent on the grouped columns. The primary key determines every column of its row, so they're all safe. A non-key column doesn't determine anything else, so the others need aggregates."},{"question":"PostgreSQL gives a similar error. Is the fix the same?","answer":"Postgres enforces the same rule but has no ANY_VALUE(); use an aggregate like MIN() or MAX(), or pick the row with DISTINCT ON, or a lateral join to the row you actually want."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1055","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1060","corpus":"errors","engine":"mysql","language":"en","title":"Duplicate column name","description":"A table definition, ALTER TABLE or a view or derived table produces two columns with the same name.","body":{"code":"1060","slug":"1060","name":"ER_DUP_FIELDNAME","message":"Duplicate column name '%s'","group":"objects","severity":null,"sql_state":"42S21","summary":"A table definition, ALTER TABLE or a view or derived table produces two columns with the same name.","meaning":"Column names must be unique within a table, and also within the result of a view or derived table. 1060 names the duplicate. It often comes from `SELECT *` over a join where both tables have an `id` column, used to create a table or view.","causes":["`ALTER TABLE ... ADD COLUMN` for a column that already exists (a migration run twice).","`CREATE TABLE ... AS SELECT *` or `CREATE VIEW` over a join with columns of the same name.","A derived table that selects two columns with the same name."],"fix":[{"text":"Give duplicate columns distinct aliases.","sql":"CREATE VIEW order_view AS\nSELECT o.id AS order_id, c.id AS customer_id, c.name\nFROM orders o JOIN customers c ON c.id = o.customer_id;"},{"text":"Check whether the column already exists before adding it.","sql":"SHOW COLUMNS FROM orders LIKE 'shipped_at';"}],"diagnostic":"-- See which columns the object ends up with before creating it:\nSELECT * FROM t_a a JOIN t_b b ON b.id = a.id LIMIT 0;\n\n-- For an ALTER TABLE failure, list the existing columns first:\nSHOW COLUMNS FROM t_a;","alternatives":"In a CREATE TABLE ... AS SELECT over a join, alias every column explicitly or enumerate them instead of SELECT *. Views have the same constraint: a new CREATE VIEW over SELECT * fails once a colliding column exists. An existing view keeps the column list it was created with, so it does not break when the colliding column is added later; name the columns you need.","details":[],"details_title":null,"repro":"CREATE TABLE t_a (id INT PRIMARY KEY);\nCREATE TABLE t_b (id INT PRIMARY KEY);\n-- Both tables contribute a column called id:\nCREATE TABLE t_join AS SELECT a.id, b.id FROM t_a a JOIN t_b b ON b.id = a.id;\n-- ERROR 1060 (42S21): Duplicate column name 'id'","repro_note":null,"related":["mysql/1050","mysql/1061","sql-server/2705"],"sqlly":"SQLly's schema browser lists a table's columns, so an ADD COLUMN migration that already ran is caught before it fails a second time.","faqs":[{"question":"Why does SELECT * work but CREATE TABLE AS SELECT fails?","answer":"A plain result set is allowed to show two columns named id. A table, view or derived table needs unique column names because you'd have no way to reference them. Alias one of them and the creation goes through."},{"question":"Does 1060 also come from ALTER TABLE ADD COLUMN?","answer":"Yes. Adding a column whose name already exists raises 1060. Check SHOW COLUMNS (or information_schema.columns) before adding; MySQL has no ADD COLUMN IF NOT EXISTS."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1060","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1061","corpus":"errors","engine":"mysql","language":"en","title":"Duplicate key name","description":"CREATE INDEX or ALTER TABLE ADD INDEX uses an index name that already exists on that table.","body":{"code":"1061","slug":"1061","name":"ER_DUP_KEYNAME","message":"Duplicate key name '%s'","group":"constraints","severity":null,"sql_state":"42000","summary":"CREATE INDEX or ALTER TABLE ADD INDEX uses an index name that already exists on that table.","meaning":"Index names must be unique per table. Creating an index whose name is taken fails with 1061, even when the columns are different.","causes":["Re-running a migration that creates an index.","Two migrations that create indexes with the same name."],"fix":[{"text":"List the table's indexes.","sql":"SHOW INDEX FROM orders;"},{"text":"Drop and recreate the index if the definition should change, or choose another name.","sql":"ALTER TABLE orders DROP INDEX idx_customer, ADD INDEX idx_customer (customer_id, created_at);"}],"diagnostic":"-- Index names are per table. List what's already there:\nSHOW INDEX FROM t_orders;\n-- Or with more detail in 8.0:\nSELECT index_name, GROUP_CONCAT(column_name ORDER BY seq_in_index) AS cols\nFROM information_schema.statistics\nWHERE table_schema = DATABASE() AND table_name = 't_orders'\nGROUP BY index_name;","alternatives":"If an existing index already starts with the same columns, a wider index may be redundant; MySQL can use idx_customer (customer_id) for queries on customer_id alone, so adding (customer_id, created_at) under a new name just doubles write cost. Replace the index instead of stacking a second one.","details":[],"details_title":null,"repro":"CREATE TABLE t_orders (id INT PRIMARY KEY, customer_id INT, created_at DATETIME);\nCREATE INDEX idx_customer ON t_orders (customer_id);\n-- Same index name again, different columns, still rejected:\nCREATE INDEX idx_customer ON t_orders (customer_id, created_at);\n-- ERROR 1061 (42000): Duplicate key name 'idx_customer'","repro_note":null,"related":["mysql/1060","mysql/1826","mysql/1091","sql-server/1913"],"sqlly":"SQLly's schema browser lists index names per table, so the duplicate index name in a rerun migration is visible first.","faqs":[{"question":"Can two tables in the same database use the same index name?","answer":"Yes. Index names only need to be unique within one table. idx_customer on orders and idx_customer on customers coexist fine."},{"question":"Why did MySQL create an index I never asked for?","answer":"A FOREIGN KEY constraint gets an index automatically if none suitable exists. That index is often named after the constraint. It shows up in SHOW INDEX and can collide with your own names. A new index with that name on the same FK columns silently replaces the automatic one. A new index with that name that cannot serve the constraint (for example, on (id, pid)) fails with 1061."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1061","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1062","corpus":"errors","engine":"mysql","language":"en","title":"Duplicate entry for key","description":"An INSERT or UPDATE would put a value that already exists into a PRIMARY KEY or UNIQUE index. The message names the value and the key.","body":{"code":"1062","slug":"1062","name":"ER_DUP_ENTRY","message":"Duplicate entry '%s' for key %d","group":"constraints","severity":null,"sql_state":"23000","summary":"An INSERT or UPDATE would put a value that already exists into a PRIMARY KEY or UNIQUE index. The message names the value and the key.","meaning":"MySQL rejects a row whose value in a primary key or unique index matches a row that already exists. The message shows the duplicate value and the index, for example `Duplicate entry 'ada@example.com' for key 'users.email'` (MySQL 8.0 and later include the table name in the key).\n\nWith a multi-row `INSERT`, the rows before the duplicate are kept on non-transactional tables such as MyISAM, but with InnoDB the whole statement is rolled back.","causes":["Re-running an import or seed script that inserts rows that are already there.","Inserting an explicit id that already exists, or an `AUTO_INCREMENT` counter that is behind the data. On InnoDB, `ALTER TABLE ... AUTO_INCREMENT = n` with n below the current maximum is ignored.","An `UPDATE` that changes a unique column to a value another row has.","A unique index on a column with a case-insensitive collation: `Ada@example.com` and `ada@example.com` count as the same value."],"fix":[{"text":"Look at the row that already holds the value.","sql":"SELECT * FROM users WHERE email = 'ada@example.com';"},{"text":"To update the existing row instead, use `INSERT ... ON DUPLICATE KEY UPDATE`. On MySQL 8.0.19 and later, refer to the new values through a row alias; older versions use `VALUES(name)`, which still works but is deprecated.","sql":"INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada') AS new\nON DUPLICATE KEY UPDATE name = new.name;"},{"text":"To skip duplicates on purpose, use `INSERT IGNORE`. It turns the error into a warning, along with some other errors, so check `SHOW WARNINGS` afterwards.","sql":"INSERT IGNORE INTO users (email, name) VALUES ('ada@example.com', 'Ada');"},{"text":"If the duplicate is on `AUTO_INCREMENT`, check the counter against the data.","sql":"SELECT MAX(id) FROM users;\nSHOW CREATE TABLE users;  -- shows AUTO_INCREMENT=n"}],"diagnostic":"-- Which index and columns does the named key cover?\nSHOW INDEX FROM users;\n-- Which row already holds the value?\nSELECT * FROM users WHERE email = 'ada@example.com';\n-- With a case-insensitive collation this also catches the case-variant duplicate:\nSET NAMES utf8mb4;\nSELECT email FROM users WHERE email = 'ada@example.com' COLLATE utf8mb4_0900_ai_ci;","alternatives":"If two rows legitimately need that value, the unique index is too strict: widen it, or switch the column to a case-sensitive collation such as utf8mb4_bin after checking the data. For bulk loads, INSERT IGNORE or ON DUPLICATE KEY UPDATE trades the hard failure for skipped rows or an upsert; run SHOW WARNINGS afterwards to confirm what was skipped.","details":[],"details_title":null,"repro":"CREATE TEMPORARY TABLE t (id INT PRIMARY KEY);\nINSERT INTO t VALUES (1);\nINSERT INTO t VALUES (1);  -- ERROR 1062 (23000): Duplicate entry '1' for key 't.PRIMARY'","repro_note":null,"related":["mysql/1452","mysql/1048","mysql/1586","postgresql/23505","sql-server/2627","oracle/ora-00001","sqlite/sqlite-constraint-unique"],"sqlly":"SQLly's error banner names the key from the message and the grid can jump to the existing row holding that value, so the fix is a choice instead of a search.","faqs":[{"question":"How do I find which key the duplicate is on?","answer":"The message names it: `for key 'PRIMARY'` is the primary key, anything else is the name of a unique index. `SHOW INDEX FROM table_name;` lists the indexes and their columns."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1062","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1064","corpus":"errors","engine":"mysql","language":"en","title":"You have an error in your SQL syntax","description":"MySQL couldn't parse the statement. The text after near shows where parsing stopped; the mistake is usually right there or just before it.","body":{"code":"1064","slug":"1064","name":"ER_PARSE_ERROR","message":"%s near '%s' at line %d","group":"syntax","severity":null,"sql_state":"42000","summary":"MySQL couldn't parse the statement. The text after near shows where parsing stopped; the mistake is usually right there or just before it.","meaning":"1064 is the parse error. The reference message is the format `%s near '%s' at line %d`, where the first part is the generic text `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use`, the quoted part is the SQL from the point where the parser gave up, and the line number counts from the start of the statement.\n\nThe parser stops at the first token it can't fit, so the real mistake is often the token just before the quoted text: a missing comma, an unclosed quote, or a reserved word used as a name.","causes":["A reserved word used as a table or column name without backticks, such as `order`, `group`, `key` or `rank` (reserved since 8.0).","A missing or extra comma, parenthesis or quote.","Syntax from another database: `TOP`, `[brackets]`, or `::` casts and `RETURNING` from PostgreSQL. SQL Server's two-argument `ISNULL(a, b)` is not a 1064: MySQL's `ISNULL()` takes one argument and returns error 1582 instead.","Syntax newer than the server, such as window functions or CTEs on MySQL 5.7.","A script with `DELIMITER` or stored-program bodies sent through a driver that doesn't understand `DELIMITER` (it's a mysql client command, not SQL)."],"fix":[{"text":"Look at the quoted text after `near` and the token just before it. If the quoted text is empty (`near ''`), the statement ended too early, usually an unclosed parenthesis. An unclosed quote shows the quote and the rest of the statement, for example `near ''abc'`.","sql":null},{"text":"Quote identifiers that are reserved words with backticks.","sql":"SELECT `order`, `rank` FROM `group` WHERE `key` = 1;"},{"text":"Check the server version before using newer syntax.","sql":"SELECT VERSION();"},{"text":"Rewrite other dialects' syntax: `LIMIT` instead of `TOP`, backticks instead of brackets, `CAST(x AS ...)` instead of `::`.","sql":null}],"diagnostic":"-- Isolate the statement: run it alone in the mysql client rather than inside a script or migration,\n-- so the line number refers to the real statement.\nSELECT VERSION();\n-- A frequent trap: the mysql client strips a statement at the first semicolon,\n-- so a semicolon in the body of a routine/procedure ends the statement early and yields 1064. A semicolon inside a quoted string does not.\n-- Another: check whether your client sends the statement with a trailing delimiter the server rejects,\n-- e.g. a stored routine body needs DELIMITER // in the command-line client.","alternatives":"Paste the failing statement into a client that shows the caret position, or rebuild it from scratch in small pieces to find the token the parser rejects. Tools like sqlfluff with a MySQL dialect catch many of these before execution.","details":[],"details_title":null,"repro":"SELECT * FROM orders WHERE id = 1 ORDER date;\n-- ERROR 1064 (42000): You have an error in your SQL syntax; ... near 'date' at line 1","repro_note":null,"related":["mysql/1149","mysql/1054","sql-server/102","postgresql/42601","oracle/ora-00933"],"sqlly":"When MySQL rejects a statement, SQLly highlights the failing token in the editor and moves the cursor to it, so you don't have to count lines in a long script.","faqs":[{"question":"The query works in phpMyAdmin / Workbench but fails in my code. Why?","answer":"Usually the application layer mangles the SQL: an ORM or driver escaping, a missing backtick, or an unescaped quote in an interpolated value. Log the exact final string the server receives (the query log can show it) and run that string by hand."},{"question":"Why does the error say line 1 when the mistake is further down?","answer":"The line number counts from the start of the statement, not the file. If you pasted a multi-statement script, the statement boundaries are different from the line numbers in your editor. Run the statement on its own."},{"question":"Syntax that works on MySQL 8.0 fails on 5.7 with 1064. What changed?","answer":"Common cases: CTEs (WITH) and window functions are 8.0 only, CHECK constraints are enforced from 8.0.16, and DEFAULT (expression) in columns is 8.0 only. Check SELECT @@version and the 8.0 release notes for the feature you are using."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1064","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1067","corpus":"errors","engine":"mysql","language":"en","title":"Invalid default value","description":"A column's DEFAULT isn't valid for its type or the current SQL mode, typically DEFAULT '0000-00-00' on a DATETIME or TIMESTAMP column.","body":{"code":"1067","slug":"1067","name":"ER_INVALID_DEFAULT","message":"Invalid default value for '%s'","group":"data","severity":null,"sql_state":"42000","summary":"A column's DEFAULT isn't valid for its type or the current SQL mode, typically DEFAULT '0000-00-00' on a DATETIME or TIMESTAMP column.","meaning":"MySQL checks a column's default when you create or alter the table. 1067 names the column whose default is invalid. The usual case is an old schema with zero-date defaults, which `NO_ZERO_DATE` rejects when strict mode is also on (both are on by default). With strict mode off, MySQL accepts the zero date with warning 1264.","causes":["`DEFAULT '0000-00-00 00:00:00'` on `DATETIME` or `TIMESTAMP` columns from an older dump.","A `DEFAULT` expression on a type or version that doesn't allow it (expression defaults need parentheses and MySQL 8.0.13 or later). Without the parentheses MySQL reports `ERROR 1064 (42000)` syntax error instead of 1067.","A default longer than the column or outside an `ENUM` list."],"fix":[{"text":"Use a valid default, or none.","sql":"CREATE TABLE events (\n    id INT PRIMARY KEY,\n    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    deleted_at DATETIME NULL DEFAULT NULL\n);"},{"text":"For an old dump, replace zero-date defaults with `NULL` or `CURRENT_TIMESTAMP` before importing.","sql":null}],"diagnostic":"USE your_database;\n-- Look at the full definition MySQL is rejecting\nSHOW CREATE TABLE events;\n-- List every column with a default in the table\nSELECT column_name, column_type, column_default, is_nullable\nFROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'events';\n-- Which mode flags are on? NO_ZERO_DATE with STRICT_TRANS_TABLES rejects zero-date defaults; NO_ZERO_IN_DATE with STRICT_TRANS_TABLES rejects partial zero dates such as '2020-00-01'\nSELECT @@sql_mode;\n-- Same settings as the server will use on restart\nSHOW VARIABLES LIKE 'sql_mode';","alternatives":"For a dump from an old server, preprocess it before importing: replace DEFAULT '0000-00-00 00:00:00' with DEFAULT NULL plus a nullable column, or CURRENT_TIMESTAMP. If legacy zero dates must survive, a session that strips NO_ZERO_DATE and strict mode from sql_mode will accept them, but that reintroduces the data quality problems those modes exist to catch, so treat it as a last resort for one import.","details":[],"details_title":null,"repro":"-- Zero-date default under default 5.7/8.0 sql_mode\nCREATE TABLE scratch_1067 (\n    id INT PRIMARY KEY,\n    deleted_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'\n);\n-- ERROR 1067 (42000): Invalid default value for 'deleted_at'\nCREATE TABLE scratch_1067b (\n    id INT PRIMARY KEY,\n    n INT NOT NULL DEFAULT 'abc'\n);\n-- ERROR 1067 (42000): Invalid default value for 'n'\nDROP TABLE IF EXISTS scratch_1067b;","repro_note":null,"related":["mysql/1292","mysql/1364"],"sqlly":"SQLly's error panel names the column whose DEFAULT was rejected and the schema browser shows the definition, so the zero-date default under NO_ZERO_DATE is obvious.","faqs":[{"question":"Why did this table create fine on the old server?","answer":"Older versions or a relaxed sql_mode accepted zero-date defaults. MySQL 5.7 made strict mode and NO_ZERO_DATE part of the default sql_mode, so definitions that used to pass now fail with 1067. The table didn't change, the rules did."},{"question":"Can I keep a zero-date default on purpose?","answer":"Yes, by removing NO_ZERO_DATE and NO_ZERO_IN_DATE from sql_mode, but avoid it. NULL or CURRENT_TIMESTAMP covers the same needs without special-casing the magic date everywhere in queries."},{"question":"What other defaults trigger 1067?","answer":"Any default that fails the column's type: text where a number is expected, an ENUM value not in the list, or a string longer than the column. In MySQL 8.0.13+ expression defaults (DEFAULT (NOW() + INTERVAL 1 HOUR)) are also allowed but must be wrapped in parentheses."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1067","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1071","corpus":"errors","engine":"mysql","language":"en","title":"Specified key was too long","description":"An index is wider than InnoDB allows (3072 bytes, or 767 bytes with older row formats), typically on a long utf8mb4 VARCHAR.","body":{"code":"1071","slug":"1071","name":"ER_TOO_LONG_KEY","message":"Specified key was too long; max key length is %d bytes","group":"constraints","severity":null,"sql_state":"42000","summary":"An index is wider than InnoDB allows (3072 bytes, or 767 bytes with older row formats), typically on a long utf8mb4 VARCHAR.","meaning":"The maximum key length counts bytes, not characters. With `utf8mb4` each character can take 4 bytes, so `VARCHAR(255)` needs up to 1020 bytes per column. InnoDB with the `DYNAMIC` or `COMPRESSED` row format allows 3072 bytes per index; the older `COMPACT` and `REDUNDANT` formats allow 767, which is where `VARCHAR(255)` in `utf8mb4` fails.","causes":["A unique index on a long `utf8mb4` `VARCHAR`, especially on MySQL 5.6 or with an old row format.","A composite index whose columns add up to more than the limit."],"fix":[{"text":"Use the `DYNAMIC` row format (the default, set by innodb_default_row_format).","sql":"ALTER TABLE users ROW_FORMAT = DYNAMIC;"},{"text":"Index a prefix of the column, which works for non-unique indexes.","sql":"CREATE INDEX idx_users_bio ON users (bio(191));"},{"text":"Shorten the column if long values aren't needed, for example `VARCHAR(191)` for an indexed email in `utf8mb4` under the 767-byte limit.","sql":null}],"diagnostic":"-- Bytes per character: utf8mb4 is 4, utf8mb3 is 3, latin1 is 1.\nSELECT COLUMN_NAME, CHARACTER_SET_NAME, CHARACTER_OCTET_LENGTH, DATA_TYPE\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users';\n-- Row format drives the per-index byte limit (3072 for DYNAMIC/COMPRESSED,\n-- 767 for COMPACT/REDUNDANT without innodb_large_prefix on old versions).\nSELECT ROW_FORMAT FROM information_schema.TABLES\nWHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users';\n-- Server version matters: 5.7 defaults to DYNAMIC and 3072; 5.6 defaults to COMPACT.\nSELECT @@version;\n-- Add up the columns in your composite index: sum their CHARACTER_OCTET_LENGTH\n-- (or numeric byte sizes) and compare with the limit.","alternatives":"If the index is for uniqueness enforcement, a prefix index will not do; instead shorten the column, or add a generated column holding a hash (for example SHA2(email, 256) truncated) and put the unique index on that. If it is for lookups only, a prefix index of the length you actually search on usually performs fine.","details":[],"details_title":null,"repro":"CREATE TABLE keylen (email VARCHAR(255)) CHARACTER SET utf8mb4 ROW_FORMAT=COMPACT;\nCREATE UNIQUE INDEX uq_email ON keylen (email); -- ERROR 1071 on 767-byte-limit tables: 255*4 = 1020 bytes\n-- Same column, DYNAMIC row format, works (3072-byte limit):\nALTER TABLE keylen ROW_FORMAT=DYNAMIC;\nCREATE UNIQUE INDEX uq_email ON keylen (email);\n-- Prefix index variant, works even under COMPACT:\nCREATE INDEX ix_email_prefix ON keylen (email(191));","repro_note":null,"related":["mysql/1061"],"sqlly":"SQLly's schema browser shows column byte widths (CHARACTER_OCTET_LENGTH), so a composite index past 3072 bytes is visible before the DDL.","faqs":[{"question":"Why does VARCHAR(255) fail when the docs say 3072 bytes are allowed?","answer":"Your table is on an old row format or an old version. 255 characters in utf8mb4 is 1020 bytes, which fits 3072 but not the 767-byte limit that COMPACT tables and MySQL 5.6 defaults use. Check ROW_FORMAT in information_schema.TABLES."},{"question":"Can I use a prefix index on a UNIQUE column?","answer":"MySQL does allow the syntax, but it is a trap: uniqueness is then enforced only on the prefix, so a@example.com and a@example.org with the same first N bytes would collide incorrectly for your data model. Use the full column or a hash column instead."},{"question":"What changed in MySQL 8.0?","answer":"DYNAMIC is the default row format, so the 3072-byte limit applies out of the box and 1071 became rare. It still shows up on imports from old 5.6-era dumps and on composite indexes whose columns add up past 3072 bytes."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1071","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1075","corpus":"errors","engine":"mysql","language":"en","title":"Only one auto column, and it must be a key","description":"A table definition has an AUTO_INCREMENT column that isn't indexed, or more than one AUTO_INCREMENT column.","body":{"code":"1075","slug":"1075","name":"ER_WRONG_AUTO_KEY","message":"Incorrect table definition; there can be only one auto column and it must be defined as a key","group":"constraints","severity":null,"sql_state":"42000","summary":"A table definition has an AUTO_INCREMENT column that isn't indexed, or more than one AUTO_INCREMENT column.","meaning":"MySQL allows one `AUTO_INCREMENT` column per table, and it must be the first column of some index, usually the primary key. Violating either rule makes `CREATE TABLE` or `ALTER TABLE` fail with 1075.","causes":["Declaring `id INT AUTO_INCREMENT` without making it a key.","Dropping the primary key from an `AUTO_INCREMENT` column.","Putting `AUTO_INCREMENT` on two columns."],"fix":[{"text":"Make the column a key.","sql":"CREATE TABLE notes (\n    id INT NOT NULL AUTO_INCREMENT,\n    body TEXT,\n    PRIMARY KEY (id)\n);"},{"text":"When changing the primary key, keep an index on the `AUTO_INCREMENT` column.","sql":"ALTER TABLE notes DROP PRIMARY KEY, ADD PRIMARY KEY (id, created_at);"}],"diagnostic":"-- Show how the table is actually defined. The AUTO_INCREMENT column\n-- must appear as the first column of some index in the output.\nSHOW CREATE TABLE broken;\n\n-- List every index on the table and its columns, in order.\nSELECT index_name, seq_in_index, column_name\nFROM information_schema.statistics\nWHERE table_schema = DATABASE() AND table_name = 'broken'\nORDER BY index_name, seq_in_index;","alternatives":"If you want a sequence but not a key, use a separate counter table or, in MySQL 8.0, a window function like ROW_NUMBER() at query time instead of a stored AUTO_INCREMENT column.","details":[],"details_title":null,"repro":"-- One AUTO_INCREMENT column per table, and it must be indexed.\nCREATE TABLE broken (\n    id INT NOT NULL AUTO_INCREMENT,\n    body TEXT\n);","repro_note":null,"related":["mysql/1062"],"sqlly":"SQLly's schema browser marks the AUTO_INCREMENT column and its indexes, so dropping the primary key that anchored it is caught before the ALTER fails.","faqs":[{"question":"Does it have to be the primary key?","answer":"No. The column just has to be the first column of some index. A plain KEY(id) satisfies the rule, and a composite index like PRIMARY KEY (id, tenant_id) does too, because id leads it. PRIMARY KEY (tenant_id, id) does not: id is in the index but not first, so MySQL returns 1075."},{"question":"Why did this appear after I dropped the primary key?","answer":"The AUTO_INCREMENT column was only indexed through the primary key. Once that index is gone, MySQL re-checks the rule and fails. Add a replacement index on the column in the same ALTER TABLE statement."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1075","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1091","corpus":"errors","engine":"mysql","language":"en","title":"Can't DROP; check that column/key exists","description":"ALTER TABLE tries to drop a column, index or key that isn't on the table.","body":{"code":"1091","slug":"1091","name":"ER_CANT_DROP_FIELD_OR_KEY","message":"Can't DROP '%s'; check that column/key exists","group":"objects","severity":null,"sql_state":"42000","summary":"ALTER TABLE tries to drop a column, index or key that isn't on the table.","meaning":"MySQL couldn't find the column or index named in `DROP COLUMN`, `DROP INDEX` or `DROP FOREIGN KEY`. For foreign keys, note that the constraint name and the index MySQL created for it can differ.","causes":["The column or index was already dropped (a migration run twice).","Using the index name in `DROP FOREIGN KEY`, or the constraint name in `DROP INDEX`.","A typo."],"fix":[{"text":"Check the real names of columns, indexes and foreign keys.","sql":"SHOW CREATE TABLE orders;"},{"text":"MySQL 8.0 doesn't support `IF EXISTS` for dropping columns or indexes, so check `information_schema` in your migration before dropping.","sql":"SELECT constraint_name FROM information_schema.table_constraints\nWHERE table_schema = DATABASE() AND table_name = 'orders' AND constraint_type = 'FOREIGN KEY';"}],"diagnostic":"-- Columns already defined on the table, including generated columns:\nSHOW COLUMNS FROM my_table;\n-- Every column name the table defines, including generated and index expressions:\nSELECT column_name, generation_expression FROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'my_table'\nORDER BY column_name;","alternatives":"For foreign keys, remember you drop the constraint by its constraint name: ALTER TABLE t DROP FOREIGN KEY fk_name. The index MySQL created to back it usually has the same name, but it can differ; drop the constraint first, then the index if it's still there and no longer needed. MySQL 5.7 and 8.0 both lack DROP COLUMN IF EXISTS, so migrations that may run twice need an information_schema check.","details":[],"details_title":null,"repro":"CREATE TABLE t_orders (id INT PRIMARY KEY, customer_id INT);\nCREATE INDEX idx_cust ON t_orders (customer_id);\n-- Name spelled differently from the real index:\nALTER TABLE t_orders DROP INDEX idx_customer;\n-- ERROR 1091 (42000): Can't DROP 'idx_customer'; check that column/key exists\n-- (the real name is idx_cust)","repro_note":null,"related":["mysql/1061","mysql/1051"],"sqlly":"SQLly's schema browser shows index and constraint names exactly as the server stores them, so DROP uses the real name rather than the one in the migration file.","faqs":[{"question":"The column shows in SHOW COLUMNS but DROP COLUMN says 1091. How?","answer":"Column names are case-insensitive in MySQL, so a case difference alone does not cause 1091. If the table isn't in the schema the statement names, MySQL reports 1146 (Table doesn't exist) instead. 1091 means the table exists in that schema but has no column or key with the name you used. Qualify the table with its database and copy the name exactly from SHOW CREATE TABLE."},{"question":"Why is DROP FOREIGN KEY separate from DROP INDEX?","answer":"The constraint and the index are different objects. Dropping the constraint doesn't drop its backing index, whether MySQL auto-created that index or you created it. Drop the index yourself with DROP INDEX once you no longer need it. On MySQL 8.4.11, SHOW INDEX still lists an auto-created index named after the constraint after DROP FOREIGN KEY."},{"question":"Does MySQL support ALTER TABLE DROP COLUMN IF EXISTS?","answer":"No, not in 5.7 or 8.0 as of current releases. Unlike DROP TABLE IF EXISTS, there's no IF EXISTS for columns or indexes. Guard the statement with a check against information_schema.columns or statistics in your migration script."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1091","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1093","corpus":"errors","engine":"mysql","language":"en","title":"Can't specify target table for update","description":"An UPDATE or DELETE uses a subquery that reads the same table it is changing, which MySQL doesn't allow directly.","body":{"code":"1093","slug":"1093","name":"ER_UPDATE_TABLE_USED","message":"You can't specify target table '%s' for update in FROM clause","group":"syntax","severity":null,"sql_state":"HY000","summary":"An UPDATE or DELETE uses a subquery that reads the same table it is changing, which MySQL doesn't allow directly.","meaning":"MySQL won't let a subquery in an `UPDATE` or `DELETE` read from the table being modified, for example `DELETE FROM t WHERE id IN (SELECT id FROM t ...)`. The fix is to make MySQL materialize the subquery first, or to rewrite it as a join.","causes":["Deleting duplicates or old rows using a subquery on the same table.","Updating rows based on an aggregate of the same table."],"fix":[{"text":"Rewrite as a multi-table `UPDATE` or `DELETE` with a join.","sql":"DELETE t1 FROM users t1\nJOIN users t2 ON t1.email = t2.email AND t1.id > t2.id;"},{"text":"Or wrap the subquery in a derived table so it is materialized first.","sql":"UPDATE products\nSET featured = 1\nWHERE id IN (SELECT id FROM (SELECT id FROM products ORDER BY sales DESC LIMIT 10) AS top10);"}],"diagnostic":"-- Confirm the subquery really reads the same table named in the DELETE/UPDATE target.\n-- EXPLAIN the DELETE to see whether the subquery on the target table is what MySQL objects to:\nEXPLAIN DELETE FROM users WHERE id IN (SELECT id FROM users WHERE email = 'a@x.com');\n-- Some 8.0 plans rewrite an IN subquery so the restriction never fires, but that is an\n-- optimizer choice, not guaranteed behavior; the self-join and derived-table forms work\n-- on every version. Test on the version you deploy to.","alternatives":"For deletes, a self-join form (DELETE t1 FROM t t1 JOIN t t2 ON ...) usually works on every version. For updates, a derived table wrapper forces materialization. If the row set is small, select the ids first in your application and delete by explicit id list.","details":[],"details_title":null,"repro":"CREATE DATABASE shop;\nUSE shop;\nCREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(200));\nINSERT INTO users VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com');\nDELETE FROM users WHERE id IN (SELECT id FROM users WHERE email = 'a@x.com');\n-- ERROR 1093 (HY000): You can't specify target table 'users' for update in FROM clause","repro_note":null,"related":["mysql/1242","mysql/1442","mysql/1248"],"sqlly":"SQLly's editor moves the cursor to the subquery reading the target table, where the derived-table or self-join rewrite belongs.","faqs":[{"question":"Why does wrapping the subquery in another SELECT fix it?","answer":"The derived table (the inner SELECT wrapped in a FROM with an alias) is materialized first, so by the time the DELETE runs, the subquery no longer reads the target table directly. It's a workaround for the restriction, not a change in what the statement does."},{"question":"Does this apply to INSERT ... SELECT on the same table?","answer":"No. INSERT ... SELECT from the same table is allowed and is a common pattern. The restriction is specific to UPDATE and DELETE targets."},{"question":"Same statement works on MySQL 8.0 but fails on 5.7?","answer":"Some 8.0 plans rewrite an IN-subquery into a semi-join or materialize it, so the same statement that fails on 5.7 can pass on 8.0. Treat that as luck rather than a contract: the restriction is documented, so a join or derived-table rewrite is the dependable form."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1093","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1114","corpus":"errors","engine":"mysql","language":"en","title":"The table is full","description":"MySQL couldn't add rows to a table: the disk or tablespace is full, or an in-memory or temporary table hit its size limit.","body":{"code":"1114","slug":"1114","name":"ER_RECORD_FILE_FULL","message":"The table '%s' is full","group":"server","severity":null,"sql_state":"HY000","summary":"MySQL couldn't add rows to a table: the disk or tablespace is full, or an in-memory or temporary table hit its size limit.","meaning":"1114 means the storage behind the table can't grow. For InnoDB that's usually the disk or a fixed-size tablespace; for `MEMORY` tables it's `max_heap_table_size`; and for internal temporary tables built during big `GROUP BY` or `ORDER BY` queries it can be the temporary storage limit. The server error log usually says which.","causes":["The disk holding the data directory (or `tmpdir`) is full.","An InnoDB system or shared tablespace with a maximum size (`innodb_data_file_path` without `autoextend`, or with `max`).","A `MEMORY` table larger than `max_heap_table_size`.","A large query whose internal temporary table exceeds its limit in MySQL 8.0 and earlier (not verified here; MySQL 8.4 converts overflow to an on-disk table)."],"fix":[{"text":"Check free disk space on the data and temporary directories, and the server error log.","sql":null},{"text":"Check the settings that cap table sizes.","sql":"SHOW VARIABLES WHERE Variable_name IN ('innodb_data_file_path', 'max_heap_table_size', 'tmp_table_size', 'tmpdir');"},{"text":"Free or add disk space, and let the tablespace autoextend. For `MEMORY` tables, raise the limit for the session and recreate the table.","sql":"SET SESSION max_heap_table_size = 512 * 1024 * 1024;"}],"diagnostic":"-- Which limit is in play? Start with the server error log, then check the\n-- settings that cap table and temporary storage growth.\nSHOW VARIABLES WHERE variable_name IN ('innodb_data_file_path', 'max_heap_table_size',\n    'tmp_table_size', 'tmpdir', 'temptable_max_ram', 'temptable_max_mmap');\n\n-- Is the table InnoDB or MEMORY?\nSELECT engine, table_rows, data_length, max_data_length\nFROM information_schema.tables\nWHERE table_schema = DATABASE() AND table_name = 'scratch';\n\n-- How much space is left on the data directory? On the shell:\n-- df -h /var/lib/mysql","alternatives":"For a scratch table that has outgrown MEMORY, switch to InnoDB, which grows to the disk limit instead. If an internal temporary table is the trigger, rewrite the query to sort or group fewer rows, add an index so MySQL can avoid the temporary table, or raise tmp_table_size so it stays in memory longer.","details":[],"details_title":null,"repro":"-- A MEMORY table capped by max_heap_table_size.\nSET SESSION max_heap_table_size = 1024 * 1024;\nCREATE TABLE scratch (payload VARCHAR(255)) ENGINE=MEMORY;\nINSERT INTO scratch\nSELECT repeat('x', 255) FROM information_schema.columns s1, information_schema.columns s2\nLIMIT 100000;","repro_note":null,"related":["mysql/1206","sql-server/1105","sql-server/1101","postgresql/53100"],"sqlly":"SQLly's server overview shows free disk and the schema browser shows each table's engine and size, so which limit filled up is identifiable from one screen.","faqs":[{"question":"I raised max_heap_table_size but the error still happens. Why?","answer":"The limit is applied per table at creation time in effect, and tmp_table_size also matters for tables created by queries. Set the variable before creating the table or before running the query, in the same session, and a new connection starts from the global value, so a session setting does not carry over to another connection."},{"question":"How do I tell a disk-full 1114 from a tablespace-limit 1114?","answer":"Check free space on the volume holding the data directory with df. If the disk has room, look at innodb_data_file_path: a file sized with a max and no :autoextend caps the tablespace at that size, and the error log usually names the tablespace file that refused to grow."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1114","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1130","corpus":"errors","engine":"mysql","language":"en","title":"Host is not allowed to connect","description":"No account exists for the host you're connecting from, so the server refuses the connection before checking any password.","body":{"code":"1130","slug":"1130","name":"ER_HOST_NOT_PRIVILEGED","message":"Host '%s' is not allowed to connect to this MySQL server","group":"access","severity":null,"sql_state":"HY000","summary":"No account exists for the host you're connecting from, so the server refuses the connection before checking any password.","meaning":"MySQL matches every connection to an account by user name and client host. On MySQL 8.4.11 a host mismatch returned ERROR 1045 (28000) in our tests; the condition that produces 1130 has not been reproduced. It's common right after installing MySQL, where `root` exists only as `'root'@'localhost'`.","causes":["Connecting over TCP when the account exists only for `localhost` (on MySQL 8.4.11 this gives 1045, not 1130).","Connecting from a Docker container or another machine whose address the account's host pattern doesn't cover.","The server resolves your IP to a host name that doesn't match the account (when `skip_name_resolve` is off)."],"fix":[{"text":"On the server, see which hosts the user can connect from.","sql":"SELECT user, host FROM mysql.user WHERE user = 'app';"},{"text":"Create an account for the client's host or network and grant it what it needs. Avoid opening `root` to `%`.","sql":"CREATE USER 'app'@'192.168.1.%' IDENTIFIED BY 'strong-password';\nGRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'app'@'192.168.1.%';"},{"text":"If you can't reach the server at all from the remote host afterwards, check `bind_address` and the firewall (see error 2003).","sql":null}],"diagnostic":"-- On the server: which host patterns exist for this user? Account matching is exact per (user, host).\nSELECT user, host FROM mysql.user ORDER BY user, host;\n-- What does the server think your client's host is? Connect with any account and check:\nSELECT user(), current_user();\n-- user() shows what you typed; current_user() shows the account that matched. If current_user()\n-- isn't the account you expected, host resolution or the host pattern is the problem.\n-- With skip_name_resolve OFF, check that forward/reverse DNS agree for the client IP:\n-- On the server: getent hosts <client-ip>\n-- Sort-order matters too: when several accounts match the user, MySQL picks by host specificity\n-- (see the docs on account sorting). An anonymous '' host sorts after '%', so a '%' row for the same user is matched first and the '' row's password is not tried.","alternatives":"Instead of opening '%' to an application user, create a host-specific or subnet-specific account ('app'@'10.0.%'). If hosts are dynamic, consider tunneling over SSH so MySQL only ever sees a local connection, or put a proxy with a fixed IP in front.","details":[],"details_title":null,"repro":"-- Safe on a scratch server.\nCREATE USER 'hosttest'@'192.168.50.%' IDENTIFIED BY 'S3cure-pass!';\nGRANT SELECT ON *.* TO 'hosttest'@'192.168.50.%';\n-- From a machine NOT in 192.168.50.0/24:\n-- mysql -h <server> -u hosttest -p\n-- Observed on MySQL 8.4.11 (validation run): ERROR 1045 (28000): Access denied for user 'hosttest'@'<your-ip>' (using password: YES).\n-- The 1130 message was not produced by this setup.\n-- Cleanup: DROP USER 'hosttest'@'192.168.50.%';","repro_note":null,"related":["mysql/1045","mysql/2003","mysql/1044"],"sqlly":"SQLly's connection test shows the client address it connected from, which is the exact value the server's account matching evaluated when it answered 1130.","faqs":[{"question":"Why did it work from one machine and fail from another with the same user?","answer":"Accounts are (user, host) pairs. 'app'@'10.0.0.5' does not cover 'app' connecting from 10.0.0.6. Create an account per subnet or per host as needed."},{"question":"Does 1130 mean the password was wrong?","answer":"No. The server refuses the login because no account row matches the user and client host. On MySQL 8.4.11 that is ERROR 1045 (28000) with either password, so the password does not decide the result."},{"question":"MySQL 8.0 doesn't accept GRANT to create users anymore?","answer":"Correct. In 8.4, GRANT to a nonexistent user fails with ERROR 1410 (42000): You are not allowed to create a user with GRANT, so you must CREATE USER first. (The 5.7 default was not verified.)"}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1130","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1136","corpus":"errors","engine":"mysql","language":"en","title":"Column count doesn't match value count","description":"An INSERT gives a different number of values than columns: the column list and the VALUES row (or the SELECT) don't line up.","body":{"code":"1136","slug":"1136","name":"ER_WRONG_VALUE_COUNT_ON_ROW","message":"Column count doesn't match value count at row %ld","group":"syntax","severity":null,"sql_state":"21S01","summary":"An INSERT gives a different number of values than columns: the column list and the VALUES row (or the SELECT) don't line up.","meaning":"Each row in `VALUES`, or each row of an `INSERT ... SELECT`, must have exactly one value per target column. Without a column list, the target is every column of the table, in table order. 1136 names the first row that doesn't fit.","causes":["`INSERT INTO t VALUES (...)` without a column list, after a column was added to the table.","A missing or extra value. A stray comma, such as a trailing one before the closing parenthesis, is a syntax error (1064) instead.","`INSERT ... SELECT` whose select list has a different number of columns."],"fix":[{"text":"Always name the columns, so later schema changes don't break the statement.","sql":"INSERT INTO customers (name, email) VALUES ('Ada', 'ada@example.com');"},{"text":"Check the table's columns and their order.","sql":"SHOW COLUMNS FROM customers;"}],"diagnostic":"-- Count the table's columns versus the values per row you are inserting:\nSELECT COUNT(*) FROM information_schema.columns\nWHERE table_schema = 'shop' AND table_name = 'customers';\n-- And check the order you assumed matches the real order:\nSELECT ordinal_position, column_name FROM information_schema.columns\nWHERE table_schema = 'shop' AND table_name = 'customers' ORDER BY ordinal_position;\nSHOW CREATE TABLE customers;","alternatives":"Naming the columns explicitly (INSERT INTO t (a, b) VALUES ...) prevents this class of error entirely and keeps the statement valid when a column is added later. For INSERT ... SELECT, make sure the SELECT list matches the target column list in count and order.","details":[],"details_title":null,"repro":"USE shop;\nCREATE TEMPORARY TABLE t (a INT, b INT);\nINSERT INTO t VALUES (1);  -- ERROR 1136 (21S01)","repro_note":null,"related":["mysql/1054","mysql/1364"],"sqlly":"SQLly's grid-based row entry builds the value list from the table's columns, so the count can't drift from the column list.","faqs":[{"question":"The error names a row number. Which row?","answer":"The first row in the VALUES list whose value count doesn't match the target column count. Rows before it were fine by shape; none are inserted because the whole statement fails as one unit."},{"question":"Can NULL fill the missing value?","answer":"Not implicitly. The count must match exactly. Write NULL explicitly if that's the value you want, or name the columns and omit the ones you don't have."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1136","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1142","corpus":"errors","engine":"mysql","language":"en","title":"Command denied to user for table","description":"The account lacks the table privilege the statement needs, such as SELECT, INSERT, UPDATE, DELETE, DROP or ALTER on that table.","body":{"code":"1142","slug":"1142","name":"ER_TABLEACCESS_DENIED_ERROR","message":"%s command denied to user '%s'@'%s' for table '%s'","group":"access","severity":null,"sql_state":"42000","summary":"The account lacks the table privilege the statement needs, such as SELECT, INSERT, UPDATE, DELETE, DROP or ALTER on that table.","meaning":"MySQL checks privileges for each table a statement touches. The message names the command (`SELECT`, `INSERT`, ...), the account and the table that failed. Privileges can come from global, database, table or column grants; none of them allowed this command here.","causes":["An application account granted only `SELECT` trying to write.","Grants given on one database while the statement touches a table in another.","A trigger whose definer lacks rights on a table it touches (view access to a missing base table raises 1356 instead).","Grants given to a different host part of the account."],"fix":[{"text":"Check the account's grants.","sql":"SHOW GRANTS FOR CURRENT_USER();"},{"text":"Grant the missing privilege at the narrowest level that works.","sql":"GRANT INSERT, UPDATE ON shop.orders TO 'app'@'%';"}],"diagnostic":"-- Which privileges does the account actually hold, and at which level?\nSHOW GRANTS FOR CURRENT_USER();\nSHOW GRANTS FOR 'app'@'%';\n-- Every grant row for the account, including table and column level:\nSELECT * FROM information_schema.user_privileges WHERE grantee LIKE \"'app'%\";\nSELECT * FROM information_schema.schema_privileges WHERE grantee LIKE \"'app'%\";\nSELECT * FROM information_schema.table_privileges WHERE grantee LIKE \"'app'%\";","alternatives":"If the DBA won't grant table access, a view exposing only the needed rows and columns, with grants on the view, is a common middle ground. Read-only replicas or a BI export can cover cases where the account only needs SELECT.","details":[],"details_title":null,"repro":"-- Scratch DB, run as a non-root user. As admin:\nCREATE DATABASE shop;\nCREATE USER 'app'@'%' IDENTIFIED BY 'pw';\nGRANT SELECT ON shop.orders TO 'app'@'%';\nCREATE TABLE shop.orders (id INT PRIMARY KEY, total DECIMAL(10,2));\n-- Then as 'app':\nINSERT INTO shop.orders VALUES (1, 9.99);\n-- ERROR 1142 (42000): INSERT command denied to user 'app'@'localhost' for table 'orders'","repro_note":null,"related":["mysql/1143","mysql/1044","mysql/1227","sql-server/229","postgresql/42501","oracle/ora-01031"],"sqlly":"SQLly's schema browser marks tables the current account cannot write, so a missing INSERT grant is visible before the statement runs.","faqs":[{"question":"The user has global privileges on *.*, why does this fail?","answer":"It usually doesn't, so first check that you granted to the exact host part MySQL matched. An account 'app'@'10.0.%' connecting from another host resolves to a different account row with no privileges. Run SELECT CURRENT_USER() as the failing session to see the account MySQL actually matched, then SHOW GRANTS for that exact account string."},{"question":"I just ran GRANT, why does the connection still get 1142?","answer":"Privilege changes take effect for the next statement in the same session for table-level grants, but global and database privilege changes apply to new connections (and to the next USE for database privileges), per the MySQL 8.4 docs. FLUSH PRIVILEGES is only needed when editing the grant tables directly. If it still fails, reconnect and re-check with SHOW GRANTS FOR CURRENT_USER();"},{"question":"Does the host part in the error match what I configured?","answer":"MySQL reports the account it matched, which may be an anonymous or catch-all entry like ''@'localhost' if one exists and sorted first. Check mysql.user for entries that could shadow your intended account and remove stale anonymous users."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1142","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1143","corpus":"errors","engine":"mysql","language":"en","title":"Command denied to user for column","description":"The account has column-level grants, and the statement used a column it has no privilege on for that command.","body":{"code":"1143","slug":"1143","name":"ER_COLUMNACCESS_DENIED_ERROR","message":"%s command denied to user '%s'@'%s' for column '%s' in table '%s'","group":"access","severity":null,"sql_state":"42000","summary":"The account has column-level grants, and the statement used a column it has no privilege on for that command.","meaning":"MySQL can grant privileges on individual columns. When an account's access to a table comes only from column grants, reading or changing any other column fails with 1143, which names the column.","causes":["`SELECT *` on a table where the account may read only some columns.","An `UPDATE` that sets a column the account was not granted `UPDATE` on."],"fix":[{"text":"List only the columns the account may use, or check its grants.","sql":"SHOW GRANTS FOR CURRENT_USER();"},{"text":"Grant the column privilege if it should be allowed.","sql":"GRANT SELECT (email) ON shop.customers TO 'app'@'%';"}],"diagnostic":"-- SHOW GRANTS lists column-level grants too, as GRANT SELECT (id, email) ON ...;\n-- information_schema.column_privileges shows one row per column privilege:\nSELECT * FROM information_schema.column_privileges WHERE grantee LIKE \"'app'%\";\nSHOW GRANTS FOR 'app'@'%';","alternatives":"If the goal is hiding sensitive columns, a restricted view is often easier to maintain than a pile of column grants, since grants on the view are enough. MySQL Enterprise Edition (commercial) also has a data masking and de-identification extension if the requirement is compliance-driven rather than a one-off restriction. It is not in MySQL Community Edition.","details":[],"details_title":null,"repro":"-- Scratch DB, run as a non-root user. As admin:\nCREATE DATABASE shop;\nCREATE TABLE shop.customers (id INT PRIMARY KEY, name VARCHAR(100), email VARCHAR(200));\nCREATE USER 'app'@'%' IDENTIFIED BY 'pw';\nGRANT SELECT (id, email) ON shop.customers TO 'app'@'%';\n-- Then as 'app':\nSELECT name FROM shop.customers;\n-- ERROR 1143 (42000): SELECT command denied to user 'app'@'localhost' for column 'name' in table 'customers'","repro_note":null,"related":["mysql/1142"],"sqlly":"SQLly's column list shows column-level grants from information_schema.column_privileges, so a SELECT over an ungranted column is caught while writing the query.","faqs":[{"question":"Why doesn't SHOW GRANTS list my column privileges?","answer":"SHOW GRANTS lists column privileges inside the table-level grant line, for example GRANT SELECT (id, email) ON shop.customers TO 'app'@'%'. information_schema.column_privileges gives one row per column and grantee, which is easier to scan when a table has several. Check both before concluding a grant is missing."},{"question":"I granted SELECT on the whole table, why does it still fail?","answer":"A table-level SELECT grant covers every column, even when the account also holds column-level grants. If it still fails, check which account MySQL matched with SELECT CURRENT_USER()."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1143","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1146","corpus":"errors","engine":"mysql","language":"en","title":"Table doesn't exist","description":"MySQL can't find the table in the named or current database. Check the database, the spelling and, on Linux, the letter case of the name.","body":{"code":"1146","slug":"1146","name":"ER_NO_SUCH_TABLE","message":"Table '%s.%s' doesn't exist","group":"objects","severity":null,"sql_state":"42S02","summary":"MySQL can't find the table in the named or current database. Check the database, the spelling and, on Linux, the letter case of the name.","meaning":"The message shows the database and table MySQL looked for: `Table 'shop.orders' doesn't exist`. That tells you which database it searched, which is often the real problem.\n\nWhether table names are case-sensitive depends on `lower_case_table_names`: by default they are on Linux and not on Windows or macOS, so code that works on a laptop can fail with 1146 on a Linux server.","causes":["Connected to a different database than the one holding the table.","A typo, or a different letter case on a Linux server.","The table hasn't been created yet: a migration didn't run, or a restore is incomplete.","An InnoDB table whose data dictionary entry exists but whose `.ibd` file is missing or damaged (the server error log will say so)."],"fix":[{"text":"Check which database you're in and what tables it has.","sql":"SELECT DATABASE();\nSHOW TABLES LIKE '%order%';"},{"text":"Search every database for the table.","sql":"SELECT table_schema, table_name\nFROM information_schema.tables\nWHERE LOWER(table_name) = 'orders';"},{"text":"Qualify the name with the database, or `USE` the right one.","sql":"SELECT * FROM shop.orders LIMIT 10;"}],"diagnostic":"-- The message already names the database it searched. Confirm what you're connected to:\nSELECT DATABASE(), @@hostname;\n\n-- Was the table ever there, in another schema, or with different casing?\nSELECT table_schema, table_name, engine\nFROM information_schema.tables\nWHERE LOWER(table_name) = LOWER('orders');\n\n-- On Linux, check how the server handles case:\nSHOW VARIABLES LIKE 'lower_case_table_names';","alternatives":"If the table lives in another schema, qualify it (shop.orders) instead of switching connections. If this is an app startup hitting a fresh database, run your schema migration before the app starts. For case mismatch across environments, standardize on lowercase table names so lower_case_table_names never matters.","details":[],"details_title":null,"repro":"USE shop;\nSELECT * FROM no_such_table;  -- ERROR 1146 (42S02): Table 'shop.no_such_table' doesn't exist","repro_note":null,"related":["mysql/1049","mysql/1046","mysql/1054","mysql/1051","sql-server/208","postgresql/42P01","oracle/ora-00942"],"sqlly":"SQLly's schema browser shows the tables the connection can see with their exact stored names, so an unknown table reads as a spelling or letter-case difference before the statement runs.","faqs":[{"question":"The table shows in SHOW TABLES but SELECT fails. How?","answer":"Usually you're connected to a different database than you think, or the case differs and lower_case_table_names=0 on Linux treats Orders and orders as different tables. Check SELECT DATABASE() and compare the exact spelling."},{"question":"Can a corrupt InnoDB data dictionary cause 1146?","answer":"Yes, though rarely. If the .ibd file or the data dictionary entry is damaged, the table can vanish from the catalog. Check the error log and information_schema.tables; recovery from that state is a separate, more serious job."},{"question":"Why does my local MySQL work but the server throws 1146?","answer":"Most often it's the case-sensitivity difference: Windows defaults to lower_case_table_names=1, macOS to 2, and Linux to 0. A query written as SELECT * FROM Users works on your laptop and fails on the Linux server."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1146","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1149","corpus":"errors","engine":"mysql","language":"en","title":"SQL syntax error","description":"A syntax error with only the generic message and no position. Most parse errors are reported as 1064, which also shows where parsing stopped.","body":{"code":"1149","slug":"1149","name":"ER_SYNTAX_ERROR","message":"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use","group":"syntax","severity":null,"sql_state":"42000","summary":"A syntax error with only the generic message and no position. Most parse errors are reported as 1064, which also shows where parsing stopped.","meaning":"1149 (`ER_SYNTAX_ERROR`) carries the text `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use` without the `near ... at line` part. That same text is the start of most 1064 messages, so if you're searching for the message, 1064 is the error you most likely have. Where 1149 reaches you directly, it comes from paths that drop the position: prepared-statement handling in some connectors, statements replayed by replication threads, or a proxy that forwards only the server's text.","causes":["A connector or prepared-statement path that reports the parse failure without the parser's position.","A statement forwarded through replication or a proxy that surfaces only the generic text.","The same mistakes that cause 1064: reserved words as names, missing commas or quotes, syntax from another database."],"fix":[{"text":"Check the statement as for 1064: reserved words, punctuation and syntax supported by your server version.","sql":null},{"text":"Run the statement on its own in the mysql client to get the 1064 message with a position.","sql":null}],"diagnostic":"-- Compare the statement your driver actually sends with what you meant: enable the general log\n-- briefly with SET GLOBAL log_output='TABLE'; SET GLOBAL general_log='ON';\n-- then read mysql.general_log for the statement as received. Stop the log afterwards:\n-- SET GLOBAL general_log='OFF';\n-- Run the same statement in the mysql client: there the identical mistake reports as 1064\n-- with 'near ... at line N', which narrows the problem to the exact token.","alternatives":"Since 1149 carries no position, bisect the statement: comment out half, rerun, repeat. Or split a multi-statement string into single statements and send them one at a time to find which one fails.","details":[],"details_title":null,"repro":"-- Most clients route this to 1064 with a position; 1149 surfaces from paths that skip the position info,\n-- for example some connectors and prepared-statement paths:\n-- ERROR 1149 (42000): You have an error in your SQL syntax; ...\nSELEC 1;","repro_note":null,"related":["mysql/1064"],"sqlly":"SQLly's Validate SQL checks a statement before it runs, so the syntax mistake behind 1149 is flagged in the editor, where the marker sits on the token the server's positionless message leaves unnamed.","faqs":[{"question":"Is 1149 different from 1064?","answer":"Same underlying syntax error. 1064 is the usual code and includes the text after the failure point plus a line number. 1149 carries only the generic message, typically from driver or replication paths where the position isn't available."},{"question":"How do I find where the mistake is if there's no position?","answer":"Run the statement manually in the mysql client. The server will report 1064 with the near-text and line number for the same input, which narrows it to a token."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1149","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1153","corpus":"errors","engine":"mysql","language":"en","title":"Got a packet bigger than max_allowed_packet","description":"A statement or row is larger than max_allowed_packet allows, often a big BLOB or a huge multi-row INSERT from a dump. Raise the limit on both sides.","body":{"code":"1153","slug":"1153","name":"ER_NET_PACKET_TOO_LARGE","message":"Got a packet bigger than 'max_allowed_packet' bytes","group":"server","severity":null,"sql_state":"08S01","summary":"A statement or row is larger than max_allowed_packet allows, often a big BLOB or a huge multi-row INSERT from a dump. Raise the limit on both sides.","meaning":"MySQL limits the size of one protocol packet, which is roughly one statement sent or one row returned, to `max_allowed_packet` (64 MB by default in MySQL 8.0). The server rejects anything bigger with 1153 and usually closes the connection, so the client may report 2006 or 2013 instead.\n\nThe client has its own `max_allowed_packet`, which also has to be large enough.","causes":["Inserting large BLOB or TEXT values, such as files or images.","Restoring a dump with very long extended `INSERT` statements.","Selecting rows with very large values through a client with a small limit. That case reports ERROR 2020 (Got packet bigger than 'max_allowed_packet' bytes), not 1153."],"fix":[{"text":"Check the server's limit.","sql":"SHOW VARIABLES LIKE 'max_allowed_packet';"},{"text":"Raise it on the server (new connections pick it up) and persist it.","sql":"SET PERSIST max_allowed_packet = 256 * 1024 * 1024;"},{"text":"Raise it on the client too, for example `mysql --max_allowed_packet=256M`, and when dumping use `mysqldump --max_allowed_packet=256M` or `--net-buffer-length` to keep statements smaller.","sql":null}],"diagnostic":"-- Server limit (the one named in the error):\nSHOW VARIABLES LIKE 'max_allowed_packet';\n-- Your own session view of it, if the client sets one:\nSELECT @@session.max_allowed_packet;\n-- How big are the values you are sending? Check the largest row in bytes.\nSELECT id, OCTET_LENGTH(data) AS bytes FROM blob_t ORDER BY bytes DESC LIMIT 5;\n-- If a dump restore fails, look at the longest INSERT line in the file:\n-- awk '{ if (length($0) > m) m = length($0) } END { print m }' dump.sql","alternatives":"Instead of raising the limit, make the packets smaller. When restoring a dump, mysqldump --net-buffer-length=65536 (with --skip-extended-insert as a blunt option) writes shorter INSERT statements. For big files, store them on disk or object storage and keep a path in the database rather than the bytes in a BLOB.","details":[],"details_title":null,"repro":"CREATE TABLE blob_t (id INT PRIMARY KEY, data LONGBLOB);\nSET SESSION max_allowed_packet = 1024 * 1024; -- 1 MB on the client too if your driver allows\n-- Build a value bigger than 1 MB, for example:\nINSERT INTO blob_t (data) SELECT REPEAT('x', 2 * 1024 * 1024); -- ERROR 1153, and the connection may drop\n-- The server side needs the same or a larger value: SHOW VARIABLES LIKE 'max_allowed_packet';","repro_note":null,"related":["mysql/2006","mysql/2013"],"sqlly":"SQLly shows the size of the statement it is about to send for large grid edits, so crossing max_allowed_packet is predictable rather than a dropped connection.","faqs":[{"question":"I raised the server limit but still get the error. Why?","answer":"The server limit applies to the statements the client sends. The client's own max_allowed_packet applies to rows it receives, and an oversized row there gives ERROR 2020 instead. Existing connections keep the old server value; reconnect after raising it. mysql and mysqldump both take --max_allowed_packet=256M."},{"question":"Why did my client report error 2006 or 2013 instead?","answer":"When the server rejects an oversized packet it usually closes the connection. The next read then fails with 2006 (MySQL 5.7 and older style) or 2013 (lost connection during query). On the MySQL 8.4 validation container the 1153 does not appear in the server error log, so take the 1153 from the client output."},{"question":"What is the actual default?","answer":"64 MB on the server in MySQL 8.0 (4 MB in 5.7). The client default is smaller, historically 16 MB in the mysql command-line client and 24 MB for mysqldump in some releases, so check rather than assume."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1153","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1158","corpus":"errors","engine":"mysql","language":"en","title":"Error reading communication packets","description":"The server got a read error on a client connection. Usually the client went away without closing it: a crash, a killed process or a network drop.","body":{"code":"1158","slug":"1158","name":"ER_NET_READ_ERROR","message":"Got an error reading communication packets","group":"connection","severity":null,"sql_state":"08S01","summary":"The server got a read error on a client connection. Usually the client went away without closing it: a crash, a killed process or a network drop.","meaning":"1158 is mostly seen in the server's error log as an aborted connection, not by the client. It means the server tried to read from the connection and the read failed. Occasional ones are normal; many of them point at clients that don't close connections or network problems.","causes":["Application processes that exit or crash without closing their connections.","Network equipment dropping connections.","A packet larger than `max_allowed_packet` is reported as error 1153 (ER_NET_PACKET_TOO_LARGE), not 1158."],"fix":[{"text":"Count aborted connections and see whether they keep rising.","sql":"SHOW GLOBAL STATUS LIKE 'Aborted_%';"},{"text":"Make applications close connections properly and pools recycle them; check the network between client and server if counts keep climbing.","sql":null}],"diagnostic":"-- Are aborted clients accumulating? Note the number and check again in an hour.\nSHOW GLOBAL STATUS LIKE 'Aborted_clients';\nSHOW GLOBAL STATUS LIKE 'Aborted_connects';\n-- Who is connected and from where? Old idle connections from dead app servers show up here.\nSELECT id, user, host, db, command, time, state, LEFT(info, 60) AS query\nFROM information_schema.processlist\nORDER BY time DESC;\n-- Oversized packets are reported as 1153 (ER_NET_PACKET_TOO_LARGE), not 1158. Compare the largest values you serve\n-- against the limit:\nSHOW VARIABLES LIKE 'max_allowed_packet';","alternatives":"If the count is stable and small, no action is needed; the occasional aborted client is normal. If it climbs, fix the application side first: proper connection closing, pool validation, and a matching wait_timeout so servers and pools agree on when connections die.","details":[],"details_title":null,"repro":"-- 1158 is a server-side log message, so reproduce it by killing a connection mid-read.\n-- Session 1:\nSELECT CONNECTION_ID();\n-- From the shell, kill the client process of session 1 outright while a large result\n-- is streaming (kill <pid>). KILL QUERY would only end the statement and leave the\n-- connection open, which does not log 1158.\n-- Then check the server error log for 'Got an error reading communication packets'\n-- and the aborted counters:\nSHOW GLOBAL STATUS LIKE 'Aborted_clients';","repro_note":null,"related":["mysql/1159","mysql/2013","mysql/1153"],"sqlly":"SQLly's connection badge marks connections that died without a clean close, the exact pattern 1158 records server-side, so the client side can be fixed first.","faqs":[{"question":"Should I worry about a few of these in the error log?","answer":"No. Every server gets some, from laptops going to sleep to deploys restarting app servers. Worry when the count rises steadily, especially at the same time each day, which usually points at a specific job or deploy."},{"question":"What is the difference between Aborted_clients and Aborted_connects?","answer":"Aborted_connects counts connections that never got started: bad handshake, wrong credentials, network failures at connect time. Aborted_clients counts connections that opened fine and then died without the client closing them properly. 1158 in the log usually matches the second."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1158","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1159","corpus":"errors","engine":"mysql","language":"en","title":"Got timeout reading communication packets","description":"The server waited longer than net_read_timeout for data from a client in the middle of a command, or a connection sat idle past wait_timeout.","body":{"code":"1159","slug":"1159","name":"ER_NET_READ_INTERRUPTED","message":"Got timeout reading communication packets","group":"connection","severity":null,"sql_state":"08S01","summary":"The server waited longer than net_read_timeout for data from a client in the middle of a command, or a connection sat idle past wait_timeout.","meaning":"Like 1158, this is usually logged by the server as an aborted connection. A read from the client took longer than `net_read_timeout` (30 seconds by default), or a command stalled partway through sending its packets past `wait_timeout`, so the server closed the connection.","causes":["Commands stalled partway through sending their packets for longer than `wait_timeout`.","Clients that pause mid-command, for example while streaming `LOAD DATA LOCAL` over a slow link.","A slow or congested network."],"fix":[{"text":"Check the relevant timeouts.","sql":"SHOW VARIABLES WHERE Variable_name IN ('net_read_timeout', 'wait_timeout');"},{"text":"Raise `net_read_timeout` for slow LOAD DATA LOCAL uploads (session scope suffices), and have connection pools retire connections before `wait_timeout`.","sql":"SET GLOBAL net_read_timeout = 120;"}],"diagnostic":"-- Timeouts in play. wait_timeout closed the stalled command in testing; net_read_timeout\n-- applies to reads during LOAD DATA LOCAL.\nSHOW VARIABLES WHERE Variable_name IN ('net_read_timeout', 'wait_timeout', 'net_write_timeout');\n-- Was the connection idle or mid-command when it died? Look at the processlist\n-- from another session while the problem runs, and check the general log briefly\n-- if you need the last command:\nSELECT id, user, host, command, time, state FROM information_schema.processlist ORDER BY time DESC;\nSHOW GLOBAL STATUS LIKE 'Aborted_clients';","alternatives":"For slow bulk loads, chunk the data so no single read stalls past the timeout, and keep the default net_read_timeout. For idle-pool problems, the fix belongs in the pool configuration, not in raising wait_timeout to an enormous value.","details":[],"details_title":null,"repro":"-- Server side: reproduce by making the server wait for a client that stalls.\n-- Open a connection, send a partial LOAD DATA LOCAL INFILE from a throttled client,\n-- or pause the client process (SIGSTOP) mid-command. When net_read_timeout passes\n-- the server logs 1159 and drops the connection.\nSHOW VARIABLES LIKE 'net_read_timeout';\n-- Check it happened:\nSHOW GLOBAL STATUS LIKE 'Aborted_clients';","repro_note":null,"related":["mysql/1158","mysql/4031","mysql/2013"],"sqlly":"SQLly's connection test reports round-trip time, so a link slow enough to cross net_read_timeout is visible before a bulk load stalls.","faqs":[{"question":"How is 1159 different from 1158?","answer":"Both end up as aborted connections in the server log. 1158 means the read failed outright, for example the socket closed or a packet was invalid. 1159 means the read was still waiting when a timeout hit."},{"question":"My LOAD DATA LOCAL INFILE of a big CSV keeps dying with this. What now?","answer":"Raise net_read_timeout for that session (SET SESSION net_read_timeout = 300) or load in smaller files. Over slow or lossy links, compressing the file and loading closer to the server usually beats a large timeout."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1159","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1175","corpus":"errors","engine":"mysql","language":"en","title":"Safe update mode blocked the statement","description":"sql_safe_updates is on, and the UPDATE or DELETE has no WHERE on a key column and no LIMIT, so MySQL refuses to change possibly every row.","body":{"code":"1175","slug":"1175","name":"ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE","message":"You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. %s","group":"server","severity":null,"sql_state":"HY000","summary":"sql_safe_updates is on, and the UPDATE or DELETE has no WHERE on a key column and no LIMIT, so MySQL refuses to change possibly every row.","meaning":"With `sql_safe_updates = 1` (MySQL Workbench turns it on by default, and the `mysql` client turns it on only when you pass `--safe-updates`), MySQL rejects `UPDATE` and `DELETE` statements that don't filter on a key column or use `LIMIT`. It's a guard against accidentally changing a whole table.","causes":["An `UPDATE` or `DELETE` without `WHERE`.","A `WHERE` on a column that isn't indexed, so MySQL can't prove it is selective.","Running in MySQL Workbench, which enables safe updates by default."],"fix":[{"text":"Filter on a key column, or add a `LIMIT`.","sql":"UPDATE customers SET status = 'inactive' WHERE id IN (17, 42);"},{"text":"If you really mean to change every matching row, turn the guard off for the statement and back on afterwards.","sql":"SET SQL_SAFE_UPDATES = 0;\nUPDATE customers SET status = 'inactive' WHERE last_login < '2020-01-01';\nSET SQL_SAFE_UPDATES = 1;"}],"diagnostic":"-- Is safe update mode actually on in this session?\nSELECT @@sql_safe_updates;\n-- Is your WHERE column indexed? If the EXPLAIN shows no possible_keys,\n-- safe updates will reject the statement.\nEXPLAIN SELECT * FROM cust WHERE status = 'a';\nSHOW INDEX FROM cust;\n-- Where did it get turned on? Workbench enables it per connection;\n-- the server default in a my.cnf would show here:\nSELECT @@global.sql_safe_updates;","alternatives":"Adding an index on the column you filter by is often the better fix: the statement becomes fast and safe-mode accepts it. For a genuine one-off whole-table change inside a script, wrap it in SET sql_safe_updates = 0 / = 1 rather than turning it off in your editor settings permanently.","details":[],"details_title":null,"repro":"CREATE TABLE cust (id INT PRIMARY KEY, status VARCHAR(20), note VARCHAR(100));\nINSERT INTO cust VALUES (1, 'a', 'x'), (2, 'a', 'y');\nSET SESSION sql_safe_updates = 1;\nUPDATE cust SET note = 'z' WHERE status = 'a'; -- ERROR 1175: status has no index\nUPDATE cust SET note = 'z' WHERE id = 1; -- fine, filters on the key\nDELETE FROM cust LIMIT 1; -- fine, has LIMIT","repro_note":null,"related":["mysql/1290"],"sqlly":"SQLly has its own guardrail for this: before running an UPDATE or DELETE without a WHERE clause it shows a review prompt, and connections can be marked read-only or production so risky statements need confirmation.","faqs":[{"question":"Workbench keeps rejecting my UPDATE even with a WHERE clause. Why?","answer":"Safe updates needs the WHERE to use a key column, or a LIMIT. A WHERE on an unindexed column still fails. Check EXPLAIN: if key is NULL, safe mode rejects it, even when possible_keys lists an index (for example a string column compared to a number)."},{"question":"How do I turn safe updates off for good?","answer":"In Workbench: Preferences, SQL Editor, uncheck Safe Updates, then reconnect. On the command line it is the --safe-updates flag; leave it out. You can also SET SESSION sql_safe_updates = 0 per session. Think twice before disabling it on a production connection."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1175","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1203","corpus":"errors","engine":"mysql","language":"en","title":"User has more than max_user_connections","description":"This account already has as many open connections as max_user_connections, or the account's own MAX_USER_CONNECTIONS limit, allows.","body":{"code":"1203","slug":"1203","name":"ER_TOO_MANY_USER_CONNECTIONS","message":"User %s already has more than 'max_user_connections' active connections","group":"server","severity":null,"sql_state":"42000","summary":"This account already has as many open connections as max_user_connections, or the account's own MAX_USER_CONNECTIONS limit, allows.","meaning":"Besides the server-wide `max_connections`, MySQL can cap connections per account, either globally with `max_user_connections` or for one account with `MAX_USER_CONNECTIONS` in `CREATE USER` or `ALTER USER`. Hitting an account's cap normally returns ERROR 1226 (ER_USER_LIMIT_REACHED, \"User '%s' has exceeded the '%s' resource\"). MySQL documents 1203 (ER_TOO_MANY_USER_CONNECTIONS) for the edge case where a disconnect is followed quickly by a connect.","causes":["A connection pool configured larger than the account's limit.","Leaked connections from one application using a shared account.","A deliberately low per-account limit on a hosted database."],"fix":[{"text":"Check the limits that apply.","sql":"SHOW VARIABLES LIKE 'max_user_connections';\nSELECT user, host, max_user_connections FROM mysql.user WHERE user = 'app';"},{"text":"Raise the account's limit if appropriate.","sql":"ALTER USER 'app'@'%' WITH MAX_USER_CONNECTIONS 50;"},{"text":"Reduce the application's pool size or fix connection leaks.","sql":null}],"diagnostic":"-- Which cap applies: account-level or global?\nSELECT user, host, max_user_connections FROM mysql.user WHERE user = 'app';\nSHOW VARIABLES LIKE 'max_user_connections';\n-- Both apply: the account-level limit wins only if it is nonzero, otherwise the global one.\n-- Who is connected under that account right now?\nSELECT id, user, host, db, command, time\nFROM information_schema.processlist\nWHERE user = 'app'\nORDER BY time DESC;\n-- Multiple app instances sharing one account is the usual reason this looks 'mysterious'.","alternatives":"If the account is shared by several services, give each its own MySQL account with its own MAX_USER_CONNECTIONS instead of raising the shared limit. Or keep one account and put a connection pooler such as ProxySQL in front so the MySQL-side connection count stays fixed regardless of app instance count.","details":[],"details_title":null,"repro":"-- Safe on a scratch server.\nCREATE USER 'pooltest'@'localhost' IDENTIFIED BY 'S3cure-pass!';\nALTER USER 'pooltest'@'localhost' WITH MAX_USER_CONNECTIONS 2;\n-- Open three connections as pooltest (each in its own terminal, keep them open):\n-- mysql -u pooltest -p -e 'SELECT SLEEP(300);'\n-- The third gets: ERROR 1203 (42000): User pooltest already has more than\n-- 'max_user_connections' active connections\n-- Cleanup: DROP USER 'pooltest'@'localhost';  (connections die with the user)","repro_note":null,"related":["mysql/1040"],"sqlly":"SQLly's activity monitor groups open connections by user, so the account that hit its MAX_USER_CONNECTIONS cap is visible as a count against mysql.user's limit.","faqs":[{"question":"max_user_connections is 0 for my user. Doesn't that mean zero connections?","answer":"No. 0 at the account level means 'no account-specific limit', so the global max_user_connections applies. If the global is also 0, there is no per-user cap at all and 1203 won't fire from this limit."},{"question":"I hit 1226 (or 1203) but SHOW STATUS says Threads_connected is well under max_connections. Why?","answer":"That is exactly the signature of a per-account cap: the server has room, but your account used up its slice. Compare the processlist count for the account with MAX_USER_CONNECTIONS from mysql.user."},{"question":"Does ALTER USER take effect for existing connections?","answer":"The new limit applies when sessions are (re)established and the server re-evaluates it on new connection attempts. Already-open sessions are not killed by the ALTER itself."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1203","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1205","corpus":"errors","engine":"mysql","language":"en","title":"Lock wait timeout exceeded","description":"A statement waited longer than innodb_lock_wait_timeout for a row lock another transaction holds. Only that statement is rolled back by default.","body":{"code":"1205","slug":"1205","name":"ER_LOCK_WAIT_TIMEOUT","message":"Lock wait timeout exceeded; try restarting transaction","group":"locking","severity":null,"sql_state":"HY000","summary":"A statement waited longer than innodb_lock_wait_timeout for a row lock another transaction holds. Only that statement is rolled back by default.","meaning":"InnoDB makes a statement wait when it needs a row lock that another transaction holds. If the wait exceeds `innodb_lock_wait_timeout` (50 seconds by default), it gives up with 1205. By default only the waiting statement is rolled back, not the whole transaction (unless `innodb_rollback_on_timeout` is on), so your transaction is still open and you must decide whether to retry the statement or roll back.\n\nThe real issue is whichever transaction held the lock that long.","causes":["A transaction left open: an interactive session or an application that started a transaction and didn't commit.","Long-running updates or batch jobs that lock many rows.","An `UPDATE` or `DELETE` without a usable index, which locks far more rows than it changes.","Hot rows (counters, queues) updated by many sessions at once."],"fix":[{"text":"Find who is blocking whom (MySQL 8.0 and later).","sql":"SELECT * FROM sys.innodb_lock_waits;"},{"text":"Look for long-open transactions and kill the culprit if appropriate.","sql":"SELECT trx_mysql_thread_id, trx_started, trx_query\nFROM information_schema.innodb_trx ORDER BY trx_started;\nKILL 12345;"},{"text":"Index the columns used in the `WHERE` of updates and deletes so they lock only the rows they change, and keep transactions short.","sql":null},{"text":"If waits are legitimately long, raise the timeout for that session.","sql":"SET SESSION innodb_lock_wait_timeout = 120;"}],"diagnostic":"-- MySQL 8.0: the whole blocking graph in one view\nSELECT waiting_pid, waiting_trx_id, blocking_pid, blocking_trx_started,\n       blocking_query, sql_kill_blocking_query\nFROM sys.innodb_lock_waits;\n-- The transactions currently open, with how long they have been running\nSELECT trx_id, trx_started, trx_state, trx_rows_locked, trx_query\nFROM information_schema.innodb_trx\nORDER BY trx_started;\n-- Who is holding locks on a given table (5.7 compatible)\nSELECT * FROM information_schema.innodb_lock_waits;\n-- A long-running idle transaction is the usual culprit\nSELECT trx_mysql_thread_id, trx_started, trx_state\nFROM information_schema.innodb_trx\nWHERE trx_state = 'LOCK WAIT' OR trx_query IS NULL;\n-- Current timeout setting\nSHOW VARIABLES LIKE 'innodb_lock_wait_timeout';","alternatives":"Restructure writes to touch rows in a consistent order and keep transactions short, which prevents most timeouts. If a long report or batch job only reads, run it with a consistent snapshot in REPEATABLE READ and plain SELECTs, or against a replica, so it never takes row locks. SELECT ... FOR UPDATE SKIP LOCKED (8.0+) lets workers share a queue without queueing on each other.","details":[],"details_title":null,"repro":"-- Session 1: take and hold a row lock\nCREATE TABLE scratch_1205 (id INT PRIMARY KEY, qty INT);\nINSERT INTO scratch_1205 VALUES (1, 10);\nSTART TRANSACTION;\nUPDATE scratch_1205 SET qty = 11 WHERE id = 1;\n-- Session 2: now wait for that row\n-- SET SESSION innodb_lock_wait_timeout = 2;\n-- UPDATE scratch_1205 SET qty = 12 WHERE id = 1;\n-- ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction\n-- Cleanup: commit or ROLLBACK in session 1, then DROP TABLE scratch_1205;","repro_note":null,"related":["mysql/1213","mysql/3572","mysql/1206","sql-server/1222","postgresql/55P03","oracle/ora-00054","sqlite/sqlite-busy"],"sqlly":"SQLly's activity monitor for MySQL shows sessions and blocking chains, so you can find the transaction holding the lock and kill it. A tab in manual-commit mode shows the number of pending changes in the status bar and asks before you close it with a transaction open.","faqs":[{"question":"After a 1205, is my transaction still open?","answer":"Yes, by default only the statement that timed out was rolled back; the transaction stays open with its earlier locks held. That makes the situation worse the longer you sit there. Either retry the statement or issue ROLLBACK. innodb_rollback_on_timeout cannot be changed at runtime (SET SESSION and SET GLOBAL both fail with 1238); set it in the server configuration and restart if you want the whole transaction to unwind on a timeout."},{"question":"I killed the blocking query but the timeout still happens. Why?","answer":"KILL QUERY stops the running statement but the transaction stays open and keeps its locks. Use KILL CONNECTION, or better, find the idle-in-transaction session (trx_query IS NULL in information_schema.innodb_trx) and close it at the application level. An uncommitted transaction left open by an app bug is the classic cause."},{"question":"Should I just raise innodb_lock_wait_timeout?","answer":"Only if waits of tens of seconds are genuinely expected, like a long legitimate batch. A higher timeout turns a fast failure into a pile of stuck sessions. Usually the right fix is shorter transactions, better indexing so fewer rows are locked, and retry logic on 1205 in the application."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1205","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1206","corpus":"errors","engine":"mysql","language":"en","title":"Locks exceed the lock table size","description":"InnoDB ran out of memory for row locks during a very large transaction. Commit in smaller batches or enlarge the buffer pool.","body":{"code":"1206","slug":"1206","name":"ER_LOCK_TABLE_FULL","message":"The total number of locks exceeds the lock table size","group":"locking","severity":null,"sql_state":"HY000","summary":"InnoDB ran out of memory for row locks during a very large transaction. Commit in smaller batches or enlarge the buffer pool.","meaning":"InnoDB keeps its lock structures in the buffer pool. A single statement or transaction that locks a huge number of rows, such as an `UPDATE` or `DELETE` over millions of rows, can exhaust that memory, and the statement fails with 1206. It's most common on servers with a small `innodb_buffer_pool_size`.","causes":["One `UPDATE`, `DELETE` or `INSERT ... SELECT` over a very large table.","An undersized `innodb_buffer_pool_size` (the default is 128 MB)."],"fix":[{"text":"Process the rows in batches, committing between them.","sql":"DELETE FROM events WHERE created_at < '2023-01-01' LIMIT 10000;\n-- repeat until 0 rows affected"},{"text":"Give InnoDB more memory if the server has it.","sql":"SET PERSIST innodb_buffer_pool_size = 2 * 1024 * 1024 * 1024;"}],"diagnostic":"-- How many rows would the statement touch?\nSELECT COUNT(*) FROM events WHERE created_at < '2023-01-01';\n-- Rows are not always rows scanned; check the plan too.\nEXPLAIN SELECT * FROM events WHERE created_at < '2023-01-01';\n-- Buffer pool size: small pools hit 1206 with fewer locked rows.\nSELECT @@innodb_buffer_pool_size / 1024 / 1024 AS buffer_pool_mb;\n-- Current transactions holding many locks (run as root or with PROCESS privilege).\nSELECT trx_id, trx_rows_locked, trx_rows_modified, trx_query\nFROM information_schema.innodb_trx\nORDER BY trx_rows_locked DESC;","alternatives":"If you cannot raise the buffer pool, batch the work by primary key ranges instead of LIMIT, which avoids re-scanning. mysqldump-style one-off rewrites can also run on a replica first, so the primary only takes the small batches.","details":[],"details_title":null,"repro":"-- Run on a scratch database with a small buffer pool.\nCREATE TABLE big (id INT PRIMARY KEY AUTO_INCREMENT, v INT);\nINSERT INTO big (v) SELECT 1 FROM information_schema.columns a, information_schema.columns b, information_schema.columns c LIMIT 5000000;\nSET GLOBAL innodb_buffer_pool_size = 134217728; -- 128 MB\nBEGIN;\nUPDATE big SET v = v + 1; -- locks every row; on MySQL 8.4.11 with a 128 MB pool this completed for 60 million rows, so 1206 needs a smaller pool or a different workload\nCOMMIT;","repro_note":null,"related":["mysql/1205","mysql/1114","sql-server/1204"],"sqlly":"SQLly's activity monitor shows lock-wait blocking pairs from information_schema.innodb_lock_waits joined to information_schema.innodb_trx, so the transaction holding the locks is visible before retrying the work in batches.","faqs":[{"question":"Why does MySQL 8.0 still have this limit if the buffer pool is huge?","answer":"Lock memory is tied to the memory InnoDB devotes to lock management. On MySQL 8.4.11 with a 128 MB buffer pool, an UPDATE locking 60 million rows completed without 1206, so the threshold depends on the server and workload. Batching avoids the error regardless of pool size."},{"question":"Does a failed 1206 statement roll back my whole transaction?","answer":"The statement is rolled back. Earlier statements in the same transaction stay open, so issue an explicit ROLLBACK or COMMIT depending on what you want before retrying in smaller batches."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1206","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1213","corpus":"errors","engine":"mysql","language":"en","title":"Deadlock found when trying to get lock","description":"Two transactions were each waiting for a lock the other held. InnoDB rolled one back; run the whole transaction again.","body":{"code":"1213","slug":"1213","name":"ER_LOCK_DEADLOCK","message":"Deadlock found when trying to get lock; try restarting transaction","group":"locking","severity":null,"sql_state":"40001","summary":"Two transactions were each waiting for a lock the other held. InnoDB rolled one back; run the whole transaction again.","meaning":"A deadlock is a cycle of lock waits that can't resolve itself. InnoDB detects it right away (with `innodb_deadlock_detect` on, the default) and rolls back the transaction it estimates is cheaper to undo, releasing its locks. 1213 tells the rolled-back session to retry.\n\nThe whole transaction was rolled back, not just the last statement, so retry it from the start.","causes":["Two transactions updating the same rows in a different order.","Range or gap locks from `UPDATE`, `DELETE` or `SELECT ... FOR UPDATE` on non-unique or missing indexes in REPEATABLE READ.","Concurrent inserts into a unique index combined with deletes on the same key range.","Foreign key checks taking shared locks on parent rows."],"fix":[{"text":"Catch 1213 in the application and retry the whole transaction, a few times with a short back-off. Occasional deadlocks are normal.","sql":null},{"text":"Read the details of the last deadlock: both transactions, the locks held and wanted.","sql":"SHOW ENGINE INNODB STATUS;  -- LATEST DETECTED DEADLOCK"},{"text":"Access rows in a consistent order and keep transactions short.","sql":"START TRANSACTION;\nSELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;\nUPDATE accounts SET balance = balance - 100 WHERE id = 1;\nUPDATE accounts SET balance = balance + 100 WHERE id = 2;\nCOMMIT;"},{"text":"To log every deadlock, not just the latest, turn on `innodb_print_all_deadlocks`.","sql":"SET PERSIST innodb_print_all_deadlocks = ON;"}],"diagnostic":"-- The full detail of the most recent deadlock\nSHOW ENGINE INNODB STATUS;\n-- In the output, read the LATEST DETECTED DEADLOCK section:\n-- each transaction's queries, the locks held and the lock waited on.\n-- SHOW ENGINE INNODB STATUS keeps only the most recent deadlock; innodb_print_all_deadlocks logs each one\nSELECT * FROM performance_schema.data_locks;\nSELECT * FROM performance_schema.data_lock_waits;\n-- Which transactions are open right now, to spot the pattern\nSELECT trx_id, trx_started, trx_rows_locked, trx_query\nFROM information_schema.innodb_trx;\n-- Enable deadlock logging to the error log for a longer window\nSHOW VARIABLES LIKE 'innodb_print_all_deadlocks';","alternatives":"Lock rows in a single deterministic order across the application, or fetch them FOR UPDATE sorted by primary key, and the cycle disappears. For hot counters, serialize on one row or move the counter to a queue instead of read-modify-write on many rows. If retries keep failing, lowering isolation to READ COMMITTED shrinks the lock footprint in many workloads.","details":[],"details_title":null,"repro":"-- Session 1\nCREATE TABLE scratch_1213 (id INT PRIMARY KEY, n INT);\nINSERT INTO scratch_1213 VALUES (1, 0), (2, 0);\n-- Session 1:\n-- START TRANSACTION;\n-- UPDATE scratch_1213 SET n = n + 1 WHERE id = 1;\n-- Session 2:\n-- START TRANSACTION;\n-- UPDATE scratch_1213 SET n = n + 1 WHERE id = 2;\n-- Session 1:\n-- UPDATE scratch_1213 SET n = n + 1 WHERE id = 2;  -- now waits on session 2\n-- Session 2:\n-- UPDATE scratch_1213 SET n = n + 1 WHERE id = 1;\n-- ERROR 1213 (40001) at line 5: Deadlock found when trying to get lock; try restarting transaction\n-- Session 2's transaction is rolled back and session 1 proceeds. InnoDB picks the victim by rows changed; with a tie the choice is not documented, so the victim may differ.\n-- Cleanup: commit session 1, DROP TABLE scratch_1213;","repro_note":null,"related":["mysql/1205","postgresql/40P01","postgresql/40001","sql-server/1205","oracle/ora-00060"],"sqlly":"SQLly's activity monitor for MySQL shows sessions and blocking chains and lets you kill a session that is holding locks.","faqs":[{"question":"Is a deadlock a bug in MySQL?","answer":"No. Deadlocks are a normal consequence of concurrent writes to overlapping rows, and InnoDB detects and breaks them automatically at a small cost. One every so often is fine. A steady stream means two code paths fight over the same rows in different orders, and the deadlock log tells you exactly which queries."},{"question":"Which transaction gets rolled back?","answer":"The one InnoDB estimates is cheaper to undo, based on the number of rows it inserted, updated or deleted. That is not always the one that waited. The error arrives as 1213 on the victim's connection; the other transaction continues normally."},{"question":"How should I retry after 1213?","answer":"Retry the whole transaction from the start, not just the failed statement, since InnoDB rolled back everything the victim had done. Wrap it in a retry loop with a limit and a small random back-off so two clients don't deadlock each other again in lockstep. SQLSTATE 40001 identifies retryable deadlock errors."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1213","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1215","corpus":"errors","engine":"mysql","language":"en","title":"Cannot add foreign key constraint","description":"MySQL rejected a FOREIGN KEY definition: the column types differ, the parent isn't indexed, or the table engine doesn't support foreign keys.","body":{"code":"1215","slug":"1215","name":"ER_CANNOT_ADD_FOREIGN","message":"Cannot add foreign key constraint","group":"constraints","severity":null,"sql_state":"HY000","summary":"MySQL rejected a FOREIGN KEY definition: the column types differ, the parent isn't indexed, or the table engine doesn't support foreign keys.","meaning":"1215 says the foreign key couldn't be created but not why. MySQL 8.0 often reports a more specific error instead (3780 for incompatible columns, 1822 for a missing parent index, 1824 for a missing parent table). For the details, run `SHOW ENGINE INNODB STATUS` and read the `LATEST FOREIGN KEY ERROR` section.","causes":["The child and parent columns have different types, signedness (`INT` versus `INT UNSIGNED`), length, or character set and collation.","The referenced columns aren't a PRIMARY or UNIQUE key in the parent. MySQL 8.4 reports 6125 for this, not 1215.","A MyISAM parent gives 1824 on MySQL 8.4. A MyISAM or MEMORY child accepts the constraint silently and does not create it.","The parent table doesn't exist yet when the child is created. MySQL 8.4 reports 1824 for this, not 1215.","`ON DELETE SET NULL` on a column declared `NOT NULL` (MySQL 8.4 reports 1830)."],"fix":[{"text":"Read the detailed reason.","sql":"SHOW ENGINE INNODB STATUS;  -- LATEST FOREIGN KEY ERROR"},{"text":"Compare the column definitions on both sides and make them identical.","sql":"SHOW CREATE TABLE customers;\nSHOW CREATE TABLE orders;"},{"text":"Make the column types match, then add the key.","sql":"ALTER TABLE orders MODIFY customer_id INT UNSIGNED NOT NULL;\nALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id);"},{"text":"Convert MyISAM tables to InnoDB.","sql":"ALTER TABLE customers ENGINE = InnoDB;"}],"diagnostic":"-- The generic message hides the real cause. InnoDB writes the specifics here:\nSHOW ENGINE INNODB STATUS;  -- read the LATEST FOREIGN KEY ERROR section\n\n-- Compare the two columns: type, signedness, charset, collation.\nSELECT table_name, column_name, column_type, character_set_name, collation_name\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND ((table_name = 'parent' AND column_name = 'id')\n    OR (table_name = 'child' AND column_name = 'p_id'));\n\n-- Is there an index starting with the referenced column?\nSHOW INDEX FROM parent;\n\n-- Both tables must be InnoDB (or another FK-aware engine).\nSELECT table_name, engine FROM information_schema.tables\nWHERE table_schema = DATABASE() AND table_name IN ('parent', 'child');","alternatives":"On 8.0 you rarely need to debug 1215 directly; fix the specific error it names instead (3780, 1822, 1824). For legacy dumps that fail on ordering, add the foreign keys with ALTER TABLE after all CREATE TABLE statements run, rather than embedding them.","details":[],"details_title":null,"repro":"-- MySQL 8.4 reports 3780 here. (MySQL 5.7 raising 1215 is not verified here.)\nCREATE TABLE parent (id INT UNSIGNED PRIMARY KEY);\nCREATE TABLE child (id INT PRIMARY KEY, p_id INT,\n  FOREIGN KEY (p_id) REFERENCES parent (id));  -- ERROR 3780 (HY000) on MySQL 8.4\nDROP TABLE IF EXISTS child, parent;","repro_note":null,"related":["mysql/3780","mysql/1822","mysql/1824","mysql/1452"],"sqlly":"SQLly's ER diagram highlights the failed foreign key edge and the error panel points at the LATEST FOREIGN KEY ERROR section of SHOW ENGINE INNODB STATUS for the real reason.","faqs":[{"question":"Why does MySQL 8.0 give a different error than 5.7 for the same statement?","answer":"8.0 added specific checks that report the exact problem: 3780 for incompatible column types, 1822 for a missing parent index, 1824 for a missing parent table. 5.7 collapses them all into 1215."},{"question":"Can both columns be INT and it still fails?","answer":"Yes. INT and INT UNSIGNED are incompatible for foreign keys, and so are columns with different collations. Signedness and collation must match too."},{"question":"Does foreign_key_checks = 0 bypass 1215?","answer":"No. It disables row-level checking, not definition checks. The columns and indexes must still be valid when the key is created."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1215","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1216","corpus":"errors","engine":"mysql","language":"en","title":"Cannot add or update a child row","description":"The older form of the foreign key failure on insert or update, without the constraint details. Current servers report 1452 instead.","body":{"code":"1216","slug":"1216","name":"ER_NO_REFERENCED_ROW","message":"Cannot add or update a child row: a foreign key constraint fails","group":"constraints","severity":null,"sql_state":"23000","summary":"The older form of the foreign key failure on insert or update, without the constraint details. Current servers report 1452 instead.","meaning":"1216 has the same meaning as 1452: the row you are writing references a parent row that doesn't exist. The difference is only that the message doesn't include the constraint definition. On 5.7 and 8.0 the usual way to meet it is a privileges case: when the invoker lacks REFERENCES or SELECT on the parent table, MySQL masks the 1452 details and reports 1216 instead.","causes":["Inserting or updating a child row whose parent doesn't exist, on servers that still report the short form.","Inserting or updating a child row while the invoker lacks REFERENCES or SELECT on the parent table: MySQL drops the constraint details from the 1452 message. On 8.4.11 the code stays 1452; 5.7 and 8.0 were not tested."],"fix":[{"text":"Follow the steps for error 1452: insert the parent first, or fix the foreign key value.","sql":null},{"text":"Use `SHOW ENGINE INNODB STATUS` to see the latest foreign key error in detail.","sql":"SHOW ENGINE INNODB STATUS;"}],"diagnostic":"-- Confirm the parent row really is missing.\nSELECT id FROM p WHERE id = 99;\n\n-- If the row exists, check what the invoker may see on the parent table: without\n-- REFERENCES or SELECT there, MySQL masks the error as 1216 on 5.7 and 8.0.\nSHOW GRANTS FOR CURRENT_USER();\n\n-- Get the full constraint definition, which 1216's short message omits.\nSELECT table_name, column_name, referenced_table_name, referenced_column_name\nFROM information_schema.key_column_usage\nWHERE constraint_schema = DATABASE() AND referenced_column_name IS NOT NULL;\n\n-- InnoDB keeps the details of the last failure here.\nSHOW ENGINE INNODB STATUS;","alternatives":"Nothing differs in the remedy from 1452: insert the parent first, or fix the key value. On MySQL 8.4.11 the server reports 1452. Behaviour on 5.7, 8.0 and older servers was not verified here.","details":[],"details_title":null,"repro":"CREATE TABLE p (id INT PRIMARY KEY);\nCREATE TABLE c (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES p (id));\nINSERT INTO c VALUES (1, 99);  -- ERROR 1452 (23000) on MySQL 8.4.11\nDROP TABLE c, p;","repro_note":null,"related":["mysql/1452","mysql/1217"],"sqlly":"SQLly treats 1216 like 1452: the ER diagram shows the parent relationship so the missing parent row can be inserted first.","faqs":[{"question":"Is 1216 different from 1452?","answer":"Not in meaning. Both mean the parent row is missing. 1452 is the modern message and includes the constraint definition; 1216 is the older, terser one."},{"question":"My app got 1216 against MySQL 8.0. Is that a bug?","answer":"It can still surface from replication of old binlog events or unusual code paths. Treat it exactly like 1452 and check the referenced row."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1216","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1217","corpus":"errors","engine":"mysql","language":"en","title":"Cannot delete or update a parent row","description":"The older form of the foreign key failure on delete or update of a referenced row. Current servers usually report 1451 instead.","body":{"code":"1217","slug":"1217","name":"ER_ROW_IS_REFERENCED","message":"Cannot delete or update a parent row: a foreign key constraint fails","group":"constraints","severity":null,"sql_state":"23000","summary":"The older form of the foreign key failure on delete or update of a referenced row. Current servers usually report 1451 instead.","meaning":"1217 has the same meaning as 1451: child rows still reference the row you are deleting or changing, and the foreign key doesn't cascade. The message omits the constraint details. `DROP TABLE` on a parent table can also raise it. On 5.7 and 8.0 it is also the masked form of 1451: deleting a parent row while the invoker lacks REFERENCES or SELECT on the child table reports 1217 instead.","causes":["Deleting a referenced row, or dropping a table that other tables reference.","Deleting a referenced row while the invoker lacks privileges on the child table: On 8.4 MySQL reports 1451 with the short message and no constraint details (5.7 and 8.0 not verified here)."],"fix":[{"text":"Follow the steps for error 1451, and drop child tables (or their foreign keys) before the parent table.","sql":null},{"text":"Find the tables that reference the parent.","sql":"SELECT table_name, constraint_name\nFROM information_schema.referential_constraints\nWHERE constraint_schema = DATABASE() AND referenced_table_name = 'customers';"}],"diagnostic":"-- Find every table that references the one you tried to change.\nSELECT rc.constraint_name, rc.table_name, rc.delete_rule\nFROM information_schema.referential_constraints rc\nWHERE rc.constraint_schema = DATABASE()\n  AND rc.referenced_table_name = 'p';\n\n-- Show the child rows that block the delete.\nSELECT * FROM c WHERE p_id = 1;\n\n-- Confirm no cascading rule explains the refusal.\nSELECT delete_rule FROM information_schema.referential_constraints\nWHERE constraint_schema = DATABASE() AND constraint_name = '<name from error>';\n\n-- If children exist but you still see the short message, check privileges on the\n-- child table: without REFERENCES or SELECT there, MySQL masks 1451 as 1217.\nSHOW GRANTS FOR CURRENT_USER();","alternatives":"Same remedy as 1451: delete or reassign children first, or recreate the key with ON DELETE CASCADE. For DROP TABLE failures, drop the child foreign keys (ALTER TABLE child DROP FOREIGN KEY ...) before the parent table.","details":[],"details_title":null,"repro":"CREATE TABLE p (id INT PRIMARY KEY);\nCREATE TABLE c (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES p (id));\nINSERT INTO p VALUES (1);\nINSERT INTO c VALUES (1, 1);\nDELETE FROM p WHERE id = 1;  -- ERROR 1451 (23000)\nDROP TABLE c, p;","repro_note":null,"related":["mysql/1451","mysql/1216"],"sqlly":"SQLly's ER diagram lists the referencing child tables, so they can be emptied or their keys dropped before the parent goes.","faqs":[{"question":"Why do I see 1217 instead of 1451?","answer":"The 1217 code is the older name for this failure (not verified on older servers here). On 8.4 the short message comes back under code 1451 when the invoker lacks privileges on the child table. The meaning and the fix are identical."},{"question":"Does DROP DATABASE hit this too?","answer":"Dropping a whole database works without dropping child keys first, but dropping a single referenced table does not. Check referential_constraints before dropping tables in a shared schema."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1217","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1227","corpus":"errors","engine":"mysql","language":"en","title":"Access denied; you need a privilege","description":"The operation needs a global or dynamic privilege the account doesn't have, such as SUPER, SYSTEM_VARIABLES_ADMIN or PROCESS.","body":{"code":"1227","slug":"1227","name":"ER_SPECIFIC_ACCESS_DENIED_ERROR","message":"Access denied; you need (at least one of) the %s privilege(s) for this operation","group":"access","severity":null,"sql_state":"42000","summary":"The operation needs a global or dynamic privilege the account doesn't have, such as SUPER, SYSTEM_VARIABLES_ADMIN or PROCESS.","meaning":"Some statements need administrative privileges rather than table privileges: setting global variables, killing other users' threads, creating objects with a different `DEFINER`, and so on. The message lists the privileges that would allow it. It's common when importing a dump from another server into a managed database where you aren't a superuser.","causes":["Importing a dump containing `DEFINER=` clauses for another user, or `SET @@GLOBAL...` statements.","`SET GLOBAL` or `SET PERSIST` without `SYSTEM_VARIABLES_ADMIN` (or `SUPER`).","Killing another user's query without `CONNECTION_ADMIN` (or `SUPER`). `KILL` returns 1095 `You are not owner of thread N` instead of 1227, so this is not a 1227 cause.","Managed services that never grant `SUPER`."],"fix":[{"text":"Read the privilege names in the message and grant one of them if you administer the server.","sql":"GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO 'admin'@'%';"},{"text":"For dumps, strip or rewrite `DEFINER` clauses and global `SET` statements, or create the dump with options that leave them out, for example `mysqldump --set-gtid-purged=OFF` for GTID statements.","sql":null}],"diagnostic":"-- Compare the account's privileges against the names in the error message:\nSHOW GRANTS FOR 'dev'@'%';\nSELECT @@version;\n-- Check whether the server is managed (RDS, Cloud SQL, Aurora) where SUPER is never grantable:\n-- on Amazon RDS the admin account holds a marker privilege, visible via:\nSELECT * FROM information_schema.user_privileges WHERE privilege_type = 'SUPER';","alternatives":"On managed services use the provider's parameter groups or admin API instead of SET GLOBAL. For DEFINER errors in dumps, re-create the dump with --single-transaction and no DEFINER clauses, or sed the DEFINER lines out of the file. Some operations (like killing your own queries) need no special privilege at all.","details":[],"details_title":null,"repro":"-- Scratch DB, run as a limited user:\nCREATE USER 'dev'@'%' IDENTIFIED BY 'pw';\n-- Then as 'dev':\nSET GLOBAL max_connections = 200;\n-- ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation\n-- (on MySQL 5.7 the message names only SUPER; the split into SYSTEM_VARIABLES_ADMIN and friends arrived in 8.0)","repro_note":null,"related":["mysql/1142","mysql/1419","mysql/1449"],"sqlly":"SQLly's error panel shows the privilege names from the 1227 message verbatim, and profiles can hold a read-only flag that stops such statements from being sent at all.","faqs":[{"question":"Why can't I grant SUPER on Amazon RDS or Cloud SQL?","answer":"Those platforms withhold SUPER from customers because it would let a session bypass replication controls and kill internal threads. The dynamic privileges added in 8.0 (SYSTEM_VARIABLES_ADMIN, CONNECTION_ADMIN and so on) cover most needs, and each provider documents which ones its admin account can grant. On 5.7 some operations simply can't be done by a customer account."},{"question":"The error names SUPER, I'm on 8.0, and I granted a dynamic privilege. Still failing?","answer":"Dynamic privileges only exist on 8.0+. Check the exact names in the message: MySQL lists every privilege that would satisfy the operation, and granting any one of them is enough. Verify with SHOW GRANTS that the grant actually took, then reconnect."},{"question":"Why does my dump fail with 1227 on DEFINER lines?","answer":"A dump from a server where objects were created by root or another admin carries DEFINER=`root`@`localhost` clauses. Recreating those objects on a server where you lack the SET_USER_ID (8.0) or SUPER privilege fails. Strip the DEFINER clauses or dump with mysqldump options that omit them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1227","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1242","corpus":"errors","engine":"mysql","language":"en","title":"Subquery returns more than 1 row","description":"A subquery used as a single value, for example after = or in the select list, returned several rows.","body":{"code":"1242","slug":"1242","name":"ER_SUBQUERY_NO_1_ROW","message":"Subquery returns more than 1 row","group":"syntax","severity":null,"sql_state":"21000","summary":"A subquery used as a single value, for example after = or in the select list, returned several rows.","meaning":"A scalar subquery must return at most one row. If it returns more, MySQL can't turn it into one value and raises 1242. The query may have worked for months and fail now because the data changed.","causes":["Comparing with `=` to a subquery that can match several rows.","A lookup subquery in the select list on a column that isn't unique.","Duplicate rows that weren't there when the query was written."],"fix":[{"text":"Use `IN` (or `EXISTS`) when several rows are valid.","sql":"SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE country = 'NL');"},{"text":"Or reduce the subquery to one row with an aggregate or `LIMIT 1` and a defined order.","sql":"SELECT o.id,\n       (SELECT p.amount FROM payments p WHERE p.order_id = o.id ORDER BY p.paid_at DESC LIMIT 1) AS last_payment\nFROM orders o;"}],"diagnostic":"-- Count what the subquery actually returns per key. Any row over 1 is your offender.\nSELECT c.country, COUNT(*) AS matches\nFROM t_customers c\nGROUP BY c.country\nHAVING COUNT(*) > 1;\n\n-- For the general case, run the subquery with a GROUP BY on the join key\n-- and list the values that appear more than once:\nSELECT customer_id, COUNT(*)\nFROM customers\nGROUP BY customer_id\nHAVING COUNT(*) > 1;","alternatives":"If you genuinely need one row, a correlated subquery with ORDER BY and LIMIT 1 works but runs per outer row. A join with ROW_NUMBER() in a derived table is usually faster on MySQL 8.0. On 5.7 a user variable trick or a join against an aggregate does the same job.","details":[],"details_title":null,"repro":"CREATE TABLE t_customers (id INT PRIMARY KEY, country VARCHAR(2));\nCREATE TABLE t_orders (id INT PRIMARY KEY, customer_id INT);\nINSERT INTO t_customers VALUES (1, 'NL'), (2, 'NL');\nINSERT INTO t_orders VALUES (100, 1);\n-- Scalar subquery now matches two rows:\nSELECT o.id,\n       (SELECT c.id FROM t_customers c WHERE c.country = o.country_id) AS x\nFROM (SELECT 100 AS id, 'NL' AS country_id) o;\n-- ERROR 1242 (21000): Subquery returns more than 1 row","repro_note":null,"related":["mysql/1055","sql-server/512","oracle/ora-01427","postgresql/21000"],"sqlly":"SQLly lets you select the scalar subquery in the editor and run just that piece, showing the row count that broke the one-row limit.","faqs":[{"question":"Why did this query work yesterday and fail today?","answer":"The statement is fine; the data isn't. The subquery matched one row before and matches two now. Find the duplicated key with a GROUP BY/HAVING count and decide whether the data or the query is wrong."},{"question":"Is IN safer than = for subqueries?","answer":"For row counts, yes. IN and EXISTS tolerate multiple rows by design, so error 1242 can't happen with them. Use a scalar subquery with = only when you know the subquery can return at most one row, for example against a unique column."},{"question":"Does LIMIT 1 fix it correctly?","answer":"It silences the error but picks an arbitrary row unless you add ORDER BY. If the ordering isn't defined, you'll get a different row each run. Decide which row you want and order by it explicitly."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1242","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1248","corpus":"errors","engine":"mysql","language":"en","title":"Every derived table must have its own alias","description":"A subquery in the FROM clause has no alias. MySQL requires a name for every derived table, even if you never refer to it.","body":{"code":"1248","slug":"1248","name":"ER_DERIVED_MUST_HAVE_ALIAS","message":"Every derived table must have its own alias","group":"syntax","severity":null,"sql_state":"42000","summary":"A subquery in the FROM clause has no alias. MySQL requires a name for every derived table, even if you never refer to it.","meaning":"A subquery used as a table in `FROM` or `JOIN` is a derived table, and MySQL requires it to have an alias. Without one, the statement fails with 1248.","causes":["`SELECT COUNT(*) FROM (SELECT ...)` with nothing after the closing parenthesis.","Queries copied from databases that allow unnamed subqueries."],"fix":[{"text":"Add an alias after the closing parenthesis.","sql":"SELECT COUNT(*) FROM (SELECT DISTINCT customer_id FROM orders) AS buyers;"}],"diagnostic":"-- The alias belongs right after the closing parenthesis of the derived table.\n-- To find the offending spot in a long query, check that every FROM (...)\n-- and JOIN (...) is followed by AS name (or just name).\nSELECT * FROM (SELECT 1) AS d;  -- correct\nSELECT * FROM (SELECT 1) d;     -- also correct, AS is optional","alternatives":"For a subquery you reuse several times, MySQL 8.0 supports CTEs: WITH d AS (SELECT ...) SELECT * FROM d. That reads better than nested derived tables and the alias requirement becomes the CTE name. MySQL 5.7 has no CTEs, so derived-table aliases are the only option there.","details":[],"details_title":null,"repro":"SELECT * FROM (SELECT 1);  -- ERROR 1248 (42000)","repro_note":null,"related":["mysql/1064"],"sqlly":"SQLly's error panel shows the corrected `FROM (...) AS alias` form and the editor's cursor lands at the missing alias.","faqs":[{"question":"Does this apply to subqueries in SELECT or WHERE too?","answer":"No. Only subqueries used as a table in FROM or JOIN need an alias. Scalar subqueries in the select list or IN subqueries in WHERE are expressions, not tables, and need no alias."},{"question":"Does the alias matter anywhere else?","answer":"It's the name the outer query uses to reference the derived table's columns. In MySQL 8.0, the columns of a derived table can also be renamed in the clause itself: SELECT * FROM (SELECT 1) AS d(my_col)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1248","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1251","corpus":"errors","engine":"mysql","language":"en","title":"Client doesn't support auth protocol","description":"The server asked for an authentication method the client is too old to speak. Upgrade the client or driver, or change the account's plugin.","body":{"code":"1251","slug":"1251","name":"ER_NOT_SUPPORTED_AUTH_MODE","message":"Client does not support authentication protocol requested by server; consider upgrading MySQL client","group":"connection","severity":null,"sql_state":"08004","summary":"The server asked for an authentication method the client is too old to speak. Upgrade the client or driver, or change the account's plugin.","meaning":"During login the server tells the client which authentication method to use. A client library that predates it, such as the old `mysql` package for Node.js talking to MySQL 8's `caching_sha2_password`, can't continue and reports 1251.","causes":["An old driver or client library connecting to MySQL 8.0 or later.","The Node.js `mysql` package, which doesn't support `caching_sha2_password`; `mysql2` does.","Very old clients that only know the pre-4.1 password hashing."],"fix":[{"text":"Upgrade the client or driver (for Node.js, move to `mysql2`).","sql":null},{"text":"Check the account's plugin.","sql":"SELECT user, host, plugin FROM mysql.user WHERE user = 'app';"},{"text":"As a stopgap where the server still allows it, switch the account to `mysql_native_password`. It is deprecated, and disabled by default in MySQL 8.4; on a stock 8.4 server the statement below fails with ERROR 1524 (Plugin 'mysql_native_password' is not loaded) and only works once an operator has enabled the plugin.","sql":"ALTER USER 'app'@'%' IDENTIFIED WITH mysql_native_password BY 'password';"}],"diagnostic":"-- What does the account ask for?\nSELECT user, host, plugin FROM mysql.user WHERE user = 'app';\n-- What is the client library's version? From the mysql CLI:\nSELECT VERSION();  -- server version, for reference\n-- and the client banner printed at login, or from code:\n-- C: mysql_get_client_info();  PHP: mysqli_get_client_version();  Node: package version of the driver.\n-- If the plugin is caching_sha2_password and the client predates MySQL 8.0-era connectors,\n-- 1251 is the expected result. Check whether your driver has an upgrade with 8.0 support.","alternatives":"The durable fix is upgrading the client library. If that can't happen this week, ALTER USER ... IDENTIFIED WITH mysql_native_password keeps the account usable on servers that still allow it; MySQL 8.4 ships with it disabled by default, and 9.x removes it, so this is a countdown. A second workaround is pointing a current proxy (ProxySQL) that speaks both protocols at the server and letting old clients talk to the proxy.","details":[],"details_title":null,"repro":"-- Fails in the client, not in SQL. Safe repro: old client against a modern account.\n-- On a dev server:\nCREATE USER 'oldclient'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'S3cure-pass!';\n-- Connect with any pre-4.1-protocol client, or with the Node.js 'mysql' package (not mysql2):\n-- node -e \"require('mysql').createConnection({user:'oldclient',password:'S3cure-pass!'}).connect(e=>console.log(e.code))\"\n-- Expected: ER_NOT_SUPPORTED_AUTH_MODE, error 1251.\nDROP USER 'oldclient'@'localhost';","repro_note":null,"related":["mysql/2059","mysql/2061","mysql/1045"],"sqlly":"SQLly speaks the current authentication protocol, so accounts stay on `caching_sha2_password` instead of being downgraded to `mysql_native_password` for an old client.","faqs":[{"question":"Are 1251 and 2059 the same problem?","answer":"No. 1251 means the client is too old to speak the requested protocol at all. 2059 means the client knew about the protocol but couldn't load the plugin code. Both usually trace back to the same root cause: an old client library meeting caching_sha2_password."},{"question":"I changed the user to mysql_native_password and it still fails.","answer":"Check that the server has the plugin enabled (SHOW PLUGINS) and that you altered the exact account that matched, including the host part. Also confirm the client really reconnected; some poolers cache connections and keep reporting the old failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1251","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1264","corpus":"errors","engine":"mysql","language":"en","title":"Out of range value for column","description":"A number is too large or too small for the column's type, such as 300 into TINYINT or a negative value into an UNSIGNED column.","body":{"code":"1264","slug":"1264","name":"ER_WARN_DATA_OUT_OF_RANGE","message":"Out of range value for column '%s' at row %ld","group":"data","severity":null,"sql_state":"22003","summary":"A number is too large or too small for the column's type, such as 300 into TINYINT or a negative value into an UNSIGNED column.","meaning":"Every numeric type has a range: `TINYINT` is -128 to 127 (0 to 255 unsigned), `INT` about ±2.1 billion, and `DECIMAL(5,2)` up to 999.99. A value outside it fails with 1264 in strict mode, or is clipped to the nearest limit with a warning otherwise.","causes":["An `INT` id or counter that outgrew its type.","Negative values in `UNSIGNED` columns, sometimes from subtraction in an `UPDATE`.","A `DECIMAL` with too few digits before the decimal point."],"fix":[{"text":"Widen the column.","sql":"ALTER TABLE orders MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE products MODIFY price DECIMAL(10,2) NOT NULL;"},{"text":"Guard subtractions on unsigned columns.","sql":"UPDATE stock SET qty = GREATEST(CAST(qty AS SIGNED) - 5, 0) WHERE product_id = 7;"}],"diagnostic":"-- What range does the column actually allow?\nSELECT column_name, data_type, column_type, numeric_precision, numeric_scale\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND table_name = 'orders' AND column_name = 'id';\n-- How close are existing values to the ceiling?\nSELECT MAX(id) FROM orders;\n-- Unsigned subtraction is a classic source: check the signedness\nSELECT column_name, column_type FROM information_schema.columns\nWHERE table_schema = DATABASE() AND column_type LIKE '%unsigned%';\n-- Strict or clip?\nSELECT @@sql_mode;","alternatives":"If you expect occasional overflow on a computed value, clamp it in SQL with GREATEST/LEAST before writing, or store counters as SIGNED even when the domain is non-negative so decrements can't wrap. For auto-increment columns that are running out of headroom, BIGINT UNSIGNED costs 8 bytes and removes the ceiling for practical purposes.","details":[],"details_title":null,"repro":"CREATE TEMPORARY TABLE t (n TINYINT);\nINSERT INTO t VALUES (300);  -- ERROR 1264 (22003)","repro_note":null,"related":["mysql/1366","mysql/1406","sql-server/8115","postgresql/22003","oracle/ora-01438"],"sqlly":"SQLly's CSV import preview checks numeric ranges against the column type (TINYINT, UNSIGNED, DECIMAL scale) and lists out-of-range rows before loading.","faqs":[{"question":"What happens to AUTO_INCREMENT ids at the top of the range?","answer":"The counter stops at the column maximum, so once that value is taken the next insert without an id fails with error 1062 (Duplicate entry '255' for key 'PRIMARY'), not 1264. MySQL does not wrap around to 0. Migrating the column to BIGINT UNSIGNED is the fix; in 8.0 you can also check the current counter with SHOW CREATE TABLE or information_schema.tables.auto_increment."},{"question":"Why did a simple UPDATE make a number go negative?","answer":"On an UNSIGNED column, qty = qty - 5 when qty is 3 fails with error 1690 (BIGINT UNSIGNED value is out of range in '(qty - 5)'), in strict and non-strict mode alike, because MySQL does the subtraction as unsigned. Error 1264 appears when a negative literal is written straight into the column, such as qty = -2. Cast to SIGNED and clamp with GREATEST."},{"question":"Is overflow the same in non-strict mode?","answer":"No. Without strict mode MySQL clamps to the nearest boundary of the range and emits warning 1264, the same code as the error. With strict mode on you get error 1264 and the statement is rejected."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1264","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1265","corpus":"errors","engine":"mysql","language":"en","title":"Data truncated for column","description":"A value was cut or adjusted to fit the column. It's usually a warning in non-strict mode; in strict mode, or for some values, the statement fails.","body":{"code":"1265","slug":"1265","name":"WARN_DATA_TRUNCATED","message":"Data truncated for column '%s' at row %ld","group":"data","severity":null,"sql_state":"01000","summary":"A value was cut or adjusted to fit the column. It's usually a warning in non-strict mode; in strict mode, or for some values, the statement fails.","meaning":"1265 (SQLSTATE 01000, a warning class) means MySQL changed the value to store it: a string cut to the column length, an `ENUM` value that isn't in the list stored as `''`, or decimals rounded. Check `SHOW WARNINGS` after the statement. In strict mode, many of these cases are errors instead.","causes":["A value not in an `ENUM` or `SET` column's list.","A string longer than the column in non-strict mode.","An empty string into a DATE column (a numeric column warns with 1366 Incorrect integer value instead).","`ALTER TABLE` that shortens a column holding longer values."],"fix":[{"text":"See exactly what was changed.","sql":"SHOW WARNINGS;"},{"text":"For `ENUM` columns, add the value to the list or map it before inserting.","sql":"ALTER TABLE orders MODIFY status ENUM('new', 'paid', 'shipped', 'cancelled', 'refunded') NOT NULL;"},{"text":"Before shortening a column, find values that wouldn't fit.","sql":"SELECT id, CHAR_LENGTH(name) FROM customers WHERE CHAR_LENGTH(name) > 50;"}],"diagnostic":"-- After the statement that warned, see what was changed\nSHOW WARNINGS;\n-- Rows at exactly the column length may have been cut; compare against the raw source table to confirm, since legitimate values of that length also match\nSELECT id, CHAR_LENGTH(code) FROM scratch_1265 WHERE CHAR_LENGTH(code) = 3;\n-- For ENUM columns, find rows that were stored as empty string, the sign of a rejected value\nSELECT id, status FROM orders WHERE status = '';\n-- For decimals, compare rounded vs original during a load\nSELECT col, CAST(col AS DECIMAL(10,2)) AS rounded FROM stage\nWHERE CAST(col AS DECIMAL(10,2)) <> col;\n-- Is strict mode off? That is the usual reason 1265 appears instead of a hard error\nSELECT @@sql_mode;","alternatives":"If you're loading data and want the bad rows recorded instead of the whole load failing, keep non-strict mode for the load session, run SHOW WARNINGS, and log the affected rows from the staging table before validating into the real tables. With LOAD DATA, IGNORE (or LOCAL) turns data-interpretation errors into warnings and the load continues even in strict mode, so a non-strict load session is often unnecessary; run SHOW WARNINGS right after the load either way.","details":[],"details_title":null,"repro":"-- Data cut off: warning instead of error because strict mode is off for this demo\nCREATE TABLE scratch_1265 (id INT PRIMARY KEY, code VARCHAR(3));\nSET SESSION sql_mode = REPLACE(@@sql_mode, 'STRICT_TRANS_TABLES', '');\nSET SESSION sql_mode = REPLACE(@@sql_mode, 'STRICT_ALL_TABLES', '');\nINSERT INTO scratch_1265 VALUES (1, 'ABCD');\n-- Query OK, 1 warning\nSHOW WARNINGS;\n-- Warning 1265: Data truncated for column 'code' at row 1\nDROP TABLE scratch_1265;","repro_note":null,"related":["mysql/1406","mysql/1366","mysql/1264"],"sqlly":"SQLly's import run reports the per-column truncation warnings SHOW WARNINGS would give, with the affected rows kept aside for review.","faqs":[{"question":"What is the difference between 1265 and 1406?","answer":"1265 is the warning you get when MySQL truncated or converted a value and continued. In strict mode, an overlong string raises 1406, but an ENUM value not in the list and an ALTER TABLE that shortens a column raise the 1265 error itself (ERROR 1265 (01000)). A SELECT cast truncation warns with 1292, not 1265."},{"question":"How do I find which rows lost data during a bulk load?","answer":"Load into a staging table with wider columns, run SHOW WARNINGS right after the load, and compare CHAR_LENGTH or exact values between staging and target. Rows whose values differ are the truncated ones."},{"question":"Can 1265 ever be acceptable?","answer":"During a one-off import where you knowingly round decimals or trim overlong free text, yes, as long as you review the warnings. As a steady state it hides data loss, so turn strict mode back on for application sessions."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1265","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1290","corpus":"errors","engine":"mysql","language":"en","title":"Server option prevents this statement","description":"A server option forbids the statement, such as --read-only, --super-read-only or --secure-file-priv. The message names the option.","body":{"code":"1290","slug":"1290","name":"ER_OPTION_PREVENTS_STATEMENT","message":"The MySQL server is running with the %s option so it cannot execute this statement","group":"server","severity":null,"sql_state":"HY000","summary":"A server option forbids the statement, such as --read-only, --super-read-only or --secure-file-priv. The message names the option.","meaning":"MySQL refuses statements that a startup or global option disallows. The common ones: `--read-only` or `--super-read-only` on a replica or failover target blocks writes; `--secure-file-priv` restricts `LOAD DATA INFILE` and `SELECT ... INTO OUTFILE` to one directory (or disables them); `--skip-grant-tables` blocks account statements until you run `FLUSH PRIVILEGES`.","causes":["Writing to a replica, or to a primary that was set read-only during maintenance or failover.","`LOAD DATA INFILE` or `INTO OUTFILE` with a path outside `secure_file_priv`.","Running `ALTER USER` while the server runs with `--skip-grant-tables`."],"fix":[{"text":"See which option applies.","sql":"SELECT @@read_only, @@super_read_only, @@secure_file_priv;"},{"text":"Point writes at the primary. Turn read-only off only if this server should accept writes.","sql":"SET GLOBAL super_read_only = OFF;\nSET GLOBAL read_only = OFF;"},{"text":"For file import and export, use the directory `secure_file_priv` names, or `LOAD DATA LOCAL INFILE` from the client if `local_infile` is enabled.","sql":null},{"text":"With `--skip-grant-tables`, run `FLUSH PRIVILEGES;` first, then the account statement.","sql":null}],"diagnostic":"-- Which option is it? The message names it, and these confirm:\nSELECT @@read_only, @@super_read_only, @@secure_file_priv, @@local_infile;\n-- Is this server a replica? If yes, read-only is expected and writes belong on the primary.\nSHOW REPLICA STATUS\\G -- MySQL 8.0.22+; SHOW SLAVE STATUS\\G on older versions\n-- What does the server log say at startup about read-only or skip-grant-tables?\n-- (Check the error log file, not SQL.)","alternatives":"When writing to a read-only replica is the goal, point the application at the primary or at a proxy that routes writes. When secure_file_priv blocks an export, write the file inside the allowed directory, or use the mysql client's own output redirection (mysql -e \"SELECT ...\" > out.csv) which bypasses server-side files entirely.","details":[],"details_title":null,"repro":"-- Run on a scratch server you control (needs an account with SYSTEM_VARIABLES_ADMIN or SUPER). SET GLOBAL changes the whole server for every session, so run the super_read_only part only on a server no one else is using.\n-- read_only alone does not block you here: accounts with CONNECTION_ADMIN (root holds it)\n-- can still write while read_only = ON. super_read_only blocks those accounts too.\nCREATE TABLE t (id INT);\nSET GLOBAL super_read_only = ON;\nINSERT INTO t VALUES (1); -- ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement\nSET GLOBAL super_read_only = OFF;\nDROP TABLE t;\n-- With plain read_only, run the INSERT from an account without CONNECTION_ADMIN to see\n-- the same error naming --read-only.\n-- For the secure_file_priv case:\nSELECT @@secure_file_priv;\n-- If it names a directory, this fails:\nSELECT * FROM some_table INTO OUTFILE '/tmp/out.csv';","repro_note":null,"related":["mysql/1792","mysql/1175","mysql/1227"],"sqlly":"SQLly's error panel names the option from the 1290 message and the server overview page shows read_only, super_read_only and secure_file_priv values side by side.","faqs":[{"question":"What is the difference between read_only and super_read_only?","answer":"read_only blocks writes for normal accounts but users with the CONNECTION_ADMIN or SUPER privilege can still write. super_read_only blocks them too. Replicas are often put in super_read_only so no one accidentally drifts from the primary."},{"question":"I turned read_only off but writes still fail. Why?","answer":"Check super_read_only separately; setting read_only = OFF does not clear it. Also check that you are on the server you think you are, since a proxy or DNS change can send you back to the replica."},{"question":"The server is running with skip-grant-tables. How do I fix an account?","answer":"Run FLUSH PRIVILEGES first so the grant tables load and account statements work, then make the change and restart the server normally. Do not leave a server on skip-grant-tables any longer than needed; it lets anyone connect with full privileges."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1290","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1292","corpus":"errors","engine":"mysql","language":"en","title":"Truncated incorrect value","description":"MySQL couldn't convert a value to the needed type, often a malformed date or a string compared with a number. Strict mode turns it into an error.","body":{"code":"1292","slug":"1292","name":"ER_TRUNCATED_WRONG_VALUE","message":"Truncated incorrect %s value: '%s'","group":"data","severity":null,"sql_state":"22007","summary":"MySQL couldn't convert a value to the needed type, often a malformed date or a string compared with a number. Strict mode turns it into an error.","meaning":"1292 says a value had to be cut off or replaced while converting it, for example `Truncated incorrect DOUBLE value: '12abc'` or `Incorrect datetime value: '2024-02-30'`. In a `SELECT` it is usually a warning; in `INSERT`, `UPDATE` and `DELETE` under strict mode it becomes an error.","causes":["Dates in the wrong format (`31/12/2024`) or impossible dates (`2024-02-30`).","Zero dates `0000-00-00` with `NO_ZERO_DATE` in the SQL mode (the default).","Comparing a string column to a number, for example `WHERE code = 123` when some codes contain letters.","Updating a date column with an impossible date such as '2024-02-30' (1292). A numeric column updated from a string gives 1366 for a non-numeric string such as 'abc' and 1265 for a numeric prefix such as '12abc'."],"fix":[{"text":"Convert dates explicitly with `STR_TO_DATE`.","sql":"INSERT INTO events (happened_at) VALUES (STR_TO_DATE('31/12/2024', '%d/%m/%Y'));"},{"text":"Compare strings with strings.","sql":"SELECT * FROM products WHERE code = '123';"},{"text":"Replace zero dates with `NULL` before tightening the SQL mode or migrating.","sql":"UPDATE events SET happened_at = NULL WHERE CAST(happened_at AS CHAR) = '0000-00-00';"}],"diagnostic":"-- Find the offending value in the table. String comparisons against a numeric column trigger this, so look for columns compared across types\nSELECT id, qty FROM scratch_1292 WHERE qty <> '' AND qty NOT REGEXP '^-?[0-9]+$';\n-- What does the server accept for dates? Check the format variables\nSELECT @@sql_mode;\n-- Strict mode decides error vs warning\nSELECT @@GLOBAL.sql_mode, @@SESSION.sql_mode;\n-- Reproduce the cast outside the table to see the exact complaint\nSELECT CAST('12abc' AS SIGNED);\nSELECT CAST('2024-02-30' AS DATE);","alternatives":"For dates in a non-ISO format, load them into a VARCHAR staging column and convert with STR_TO_DATE, so rows that don't parse land as NULL and can be reviewed instead of killing the batch. For numeric strings with stray characters, clean them with TRIM and REGEXP_REPLACE (8.0+) before the cast.","details":[],"details_title":null,"repro":"-- Truncated incorrect value on a numeric cast\nCREATE TABLE scratch_1292 (id INT PRIMARY KEY, note VARCHAR(50), qty INT);\nINSERT INTO scratch_1292 VALUES (1, 'x', '12abc');\n-- In strict mode this raises 1265, not 1292: a value with a numeric prefix truncates.\n-- ERROR 1265 (01000): Data truncated for column 'qty' at row 1\n-- (fully non-numeric text such as 'abc' raises 1366; 1292 is the cast and date case)\n-- Invalid date literal\nCREATE TABLE scratch_1292b (id INT PRIMARY KEY, happened_at DATE);\nINSERT INTO scratch_1292b VALUES (1, '2024-02-30');\n-- ERROR 1292 (22007): Incorrect date value: '2024-02-30' for column 'happened_at'\nDROP TABLE scratch_1292, scratch_1292b;","repro_note":null,"related":["mysql/1366","mysql/1264","sql-server/241","postgresql/22007","oracle/ora-01861"],"sqlly":"SQLly's error panel shows the offending value from the message next to the column's type, and the import preview flags values that fail the column's format.","faqs":[{"question":"Why do I get 1292 on a SELECT that touches no weird data?","answer":"Usually the query itself mixes types: comparing an INT column to a non-numeric string makes MySQL cast the column to DOUBLE for every row. Any row whose string side isn't a clean number raises the warning or error. Fix the comparison, use matching types."},{"question":"Is a 1292 warning dangerous?","answer":"In non-strict mode the statement still runs and MySQL substitutes the closest value: 0 for a non-numeric string such as 'abc', 12 for '12abc', and the zero date 0000-00-00 for an impossible date such as '2024-02-30' (reported as 1264 Out of range value, not 1292). Data gets changed quietly. Treat the warning as a data bug and fix the values or the cast."},{"question":"What about zero dates like '0000-00-00'?","answer":"They are allowed only if NO_ZERO_DATE and NO_ZERO_IN_DATE are off in sql_mode. The defaults in 5.7, 8.0 and 8.4 include both, so writing a zero date raises 1292 Incorrect date value. Error 1067 Invalid default value is a different error, raised by CREATE TABLE with a DEFAULT '0000-00-00'."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1292","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1305","corpus":"errors","engine":"mysql","language":"en","title":"Function or procedure does not exist","description":"The stored function or procedure you called isn't defined in that database, or a built-in function name was misspelled or followed by a space.","body":{"code":"1305","slug":"1305","name":"ER_SP_DOES_NOT_EXIST","message":"%s %s does not exist","group":"objects","severity":null,"sql_state":"42000","summary":"The stored function or procedure you called isn't defined in that database, or a built-in function name was misspelled or followed by a space.","meaning":"MySQL looked for a stored routine with that name in the current (or named) database and didn't find one. The message names the kind (`FUNCTION` or `PROCEDURE`) and the qualified name.","causes":["Calling a routine that lives in another database without qualifying it.","A typo, or a built-in function that doesn't exist in this MySQL version.","A space between a built-in function name and its parenthesis, which makes MySQL treat it as a user function (unless `IGNORE_SPACE` is set). MySQL reports this as ERROR 1630 (42000), not 1305.","Restoring a dump without its routines (`mysqldump` needs `--routines`)."],"fix":[{"text":"List the routines in the database.","sql":"SHOW PROCEDURE STATUS WHERE Db = DATABASE();\nSHOW FUNCTION STATUS WHERE Db = DATABASE();"},{"text":"Qualify the routine with its database.","sql":"CALL reporting.refresh_totals();"},{"text":"When dumping, include routines: `mysqldump --routines --triggers shop > shop.sql`.","sql":null}],"diagnostic":"-- Which routines does this database actually have?\nSELECT routine_schema, routine_name, routine_type\nFROM information_schema.routines\nWHERE routine_name = 'refresh_totals';\n\n-- If it exists somewhere, qualify the call: CALL reporting.refresh_totals();\n-- Also check the DEFINER and the character case of the name on Linux servers,\n-- where routine names follow the same case rules as tables.","alternatives":"If the routine should exist, recreate it from source control rather than hunting a backup. For dumps and restores, mysqldump needs --routines (and --triggers is on by default) or the routines simply aren't in the file; that omission is the classic way a restored database ends up without its procedures.","details":[],"details_title":null,"repro":"CREATE DATABASE IF NOT EXISTS scratch;\nUSE scratch;\n-- Calling a routine that was never created:\nCALL refresh_totals();\n-- ERROR 1305 (42000): PROCEDURE scratch.refresh_totals does not exist","repro_note":null,"related":["mysql/1318","sql-server/2812","oracle/ora-06508"],"sqlly":"SQLly's schema browser splits procedures and functions per database, so an unqualified CALL against the wrong schema is visible before you run it.","faqs":[{"question":"Does the procedure exist but under another database?","answer":"That's the most common cause. Routines live per schema, and an unqualified call searches only the current database. Run the information_schema.routines query across all schemas to find where it actually lives, then qualify the name."},{"question":"Why does my restored database have no procedures?","answer":"mysqldump skips stored routines unless you pass --routines. Re-dump with that flag, or extract the routine definitions from the old server and run them as scripts."},{"question":"Can the error say FUNCTION when I called a procedure?","answer":"The message names the kind of routine it looked for. If it says FUNCTION xyz does not exist, something tried to use xyz as a function, perhaps in a SELECT. Check the calling code; also note that some built-in function removals between versions surface as 1305 after an upgrade."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1305","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1318","corpus":"errors","engine":"mysql","language":"en","title":"Incorrect number of arguments","description":"A stored procedure or function was called with more or fewer arguments than it declares. MySQL routines have no optional parameters.","body":{"code":"1318","slug":"1318","name":"ER_SP_WRONG_NO_OF_ARGS","message":"Incorrect number of arguments for %s %s; expected %u, got %u","group":"syntax","severity":null,"sql_state":"42000","summary":"A stored procedure or function was called with more or fewer arguments than it declares. MySQL routines have no optional parameters.","meaning":"The message tells you what was expected and what you passed. Unlike some databases, MySQL stored routines can't have default values, so every parameter must be supplied, including `OUT` and `INOUT` ones, which need a variable.","causes":["Leaving out a parameter, expecting a default.","Not passing a variable for an `OUT` parameter.","The routine's definition changed and callers weren't updated."],"fix":[{"text":"Check the routine's parameters.","sql":"SHOW CREATE PROCEDURE your_schema.your_procedure;"},{"text":"Pass every parameter, using a user variable for `OUT` parameters.","sql":"CALL place_order(42, 3, @order_id);\nSELECT @order_id;"}],"diagnostic":"-- The signature tells you exactly what to pass, including direction:\nSHOW CREATE PROCEDURE scratch.place_order;\n\n-- Or query the catalog for one row per parameter:\nSELECT parameter_name, data_type, parameter_mode\nFROM information_schema.parameters\nWHERE specific_schema = 'scratch' AND specific_name = 'place_order'\nORDER BY ordinal_position;","alternatives":"If the signature changed recently, update every caller in one pass; there's no overloading in MySQL, one name means one signature, so old callers break loudly rather than silently. For optional behavior, either add a parameter and update all callers, or split the procedure into a simple and a full variant.","details":[],"details_title":null,"repro":"CREATE DATABASE IF NOT EXISTS scratch;\nUSE scratch;\nDELIMITER $$\nCREATE PROCEDURE place_order(IN p_customer INT, IN p_qty INT, OUT p_order INT)\nBEGIN\n  SET p_order = p_customer * 100 + p_qty;\nEND$$\nDELIMITER ;\n-- Two arguments instead of three:\nCALL place_order(42, 3);\n-- ERROR 1318 (42000): Incorrect number of arguments for PROCEDURE scratch.place_order; expected 3, got 2","repro_note":null,"related":["mysql/1305","sql-server/8144"],"sqlly":"SQLly's completion inserts the full parameter list from information_schema.parameters, including OUT parameters that need a user variable.","faqs":[{"question":"Do I have to pass a variable for OUT parameters?","answer":"Yes. OUT and INOUT parameters need a user variable (a name starting with @) or a local variable in a routine context. Passing a literal or omitting them both fail; every parameter in the signature must be supplied."},{"question":"Can I give parameters default values so callers can skip them?","answer":"No. MySQL stored procedures don't support default parameter values, unlike SQL Server or PostgreSQL. The common workaround is a wrapper procedure that fills in the missing values and calls the main one."},{"question":"Why does the error say expected 3, got 2 when I count 2 parameters in the code?","answer":"The count includes OUT and INOUT parameters, which are easy to overlook when reading the definition. Compare your call against SHOW CREATE PROCEDURE; it must supply every parameter in the signature."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1318","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1364","corpus":"errors","engine":"mysql","language":"en","title":"Field doesn't have a default value","description":"An INSERT left out a NOT NULL column that has no default. In strict mode that's an error; name the column or give it a default.","body":{"code":"1364","slug":"1364","name":"ER_NO_DEFAULT_FOR_FIELD","message":"Field '%s' doesn't have a default value","group":"data","severity":null,"sql_state":"HY000","summary":"An INSERT left out a NOT NULL column that has no default. In strict mode that's an error; name the column or give it a default.","meaning":"When an `INSERT` omits a column, MySQL uses the column's default. A `NOT NULL` column without a `DEFAULT` has none to use. In strict SQL mode (the default since 5.7) the insert fails with 1364; in non-strict mode MySQL inserts the type's implicit default (0, '' or a zero date) with a warning.","causes":["Adding a `NOT NULL` column without a default and not updating the code that inserts rows.","An application tested on a server with strict mode off, deployed to one with it on.","Expecting an `id` column to fill itself when it isn't `AUTO_INCREMENT`."],"fix":[{"text":"Include the column in the insert.","sql":"INSERT INTO orders (customer_id, status) VALUES (42, 'new');"},{"text":"Or give it a default.","sql":"ALTER TABLE orders MODIFY status VARCHAR(20) NOT NULL DEFAULT 'new';"},{"text":"If the column is meant to be generated, make it `AUTO_INCREMENT` or a generated column. Avoid turning off strict mode to hide the error; it hides data errors too.","sql":null}],"diagnostic":"-- Which columns lack both a default and nullability?\nSELECT column_name, is_nullable, column_default, extra\nFROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'orders'\n  AND is_nullable = 'NO' AND column_default IS NULL\n  AND extra NOT LIKE '%auto_increment%';\n\n-- Is strict mode on? Off, this insert would only warn.\nSELECT @@sql_mode;\nSELECT @@GLOBAL.sql_mode;","alternatives":"If the column is TIMESTAMP or DATETIME, DEFAULT CURRENT_TIMESTAMP (and ON UPDATE CURRENT_TIMESTAMP) covers created/updated columns so callers can omit them. For tables where most callers omit a status, a DEFAULT in the schema beats changing every INSERT.","details":[],"details_title":null,"repro":"CREATE TABLE t (id INT PRIMARY KEY AUTO_INCREMENT, status VARCHAR(20) NOT NULL);\nINSERT INTO t () VALUES ();  -- ERROR 1364 (HY000): Field 'status' doesn't have a default value\nDROP TABLE t;","repro_note":null,"related":["mysql/1048","mysql/1136","mysql/1067","mysql/1075"],"sqlly":"SQLly's insert form shows each column's default and nullability, so a NOT NULL column without a DEFAULT is visible before the statement runs.","faqs":[{"question":"Why is strict mode the default now?","answer":"Since MySQL 5.7. Non-strict mode silently inserted 0, empty strings, or zero dates for missing values, which corrupted data quietly. 1364 is the loud version of that old warning."},{"question":"Should I disable strict mode to stop this error?","answer":"No. It hides other data errors too, and MySQL recommends the same SQL mode on the source and replica. Give the column a default or send a value."},{"question":"Why doesn't my id column fill itself?","answer":"AUTO_INCREMENT is what does that. A plain INT PRIMARY KEY NOT NULL without it has no default, so omitting it raises 1364. Add AUTO_INCREMENT or always supply the id."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1364","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1366","corpus":"errors","engine":"mysql","language":"en","title":"Incorrect value for column","description":"A value can't be stored in the column's type or character set: text in a numeric column, an invalid date, or characters such as emoji that utf8mb3 can't hold.","body":{"code":"1366","slug":"1366","name":"ER_TRUNCATED_WRONG_VALUE_FOR_FIELD","message":"Incorrect %s value: '%s' for column '%s' at row %ld","group":"data","severity":null,"sql_state":"HY000","summary":"A value can't be stored in the column's type or character set: text in a numeric column, an invalid date, or characters such as emoji that utf8mb3 can't hold.","meaning":"MySQL couldn't convert the value to the column's type. The message gives the type, the value, the column and the row number. With string columns the type shown is `string` and the value is shown as bytes like `\\xF0\\x9F\\x98\\x80`, which means the characters don't fit the column's character set.\n\nIn strict mode this is an error; in non-strict mode MySQL stores a converted or truncated value with a warning.","causes":["Emoji or other 4-byte characters stored in a `utf8` (that is, `utf8mb3`) or `latin1` column.","An empty string `''` inserted into an `INT` or `DECIMAL` column. An empty string in a `DATE` column raises 1292 (`Incorrect date value`) instead.","Text such as `N/A` in a numeric column, often from a CSV import. A value such as `1,234` in an `INT` column raises 1265 (`Data truncated`) instead.","The connection's character set doesn't match the data sent."],"fix":[{"text":"For character errors, convert the table and connection to `utf8mb4`.","sql":"ALTER TABLE comments CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;\nSET NAMES utf8mb4;"},{"text":"For numbers and dates, send `NULL` instead of `''` and clean values before inserting.","sql":"INSERT INTO products (name, price) VALUES ('Widget', NULLIF(@price, ''));"},{"text":"When loading files, convert values in `LOAD DATA` with `SET`.","sql":"LOAD DATA INFILE '/tmp/products.csv' INTO TABLE products\nFIELDS TERMINATED BY ','\n(name, @price)\nSET price = NULLIF(REPLACE(@price, ',', ''), '');"}],"diagnostic":"-- What charset is the column really using?\nSELECT table_name, column_name, character_set_name, collation_name\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND column_name = 'comment';\n-- The connection charset matters too; a latin1 client stores 4-byte characters as corrupted bytes with no error, and a utf8mb4 client gets error 1366.\nSHOW VARIABLES LIKE 'character_set_client';\nSHOW VARIABLES LIKE 'character_set_connection';\n-- Is strict mode on? That decides error vs silent conversion\nSELECT @@sql_mode;\n-- Non-string variant: is the column numeric but the app sends text?\nSELECT data_type FROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'scratch_1366b' AND column_name = 'qty';","alternatives":"If you can't alter the table yet, reject or sanitize the value in the application before sending it. For a one-off load, a staging column of TEXT plus a validated cast into the real column keeps bad rows visible instead of failing the whole batch.","details":[],"details_title":null,"repro":"-- 1. Set up a table with a narrow charset so a 4-byte character fails\nCREATE TABLE scratch_1366 (\n    id INT PRIMARY KEY,\n    comment VARCHAR(100) CHARSET utf8\n);\n-- 2. Insert a 4-byte emoji through a utf8mb3 column\nINSERT INTO scratch_1366 (id, comment) VALUES (1, 'ok \uD83D\uDE00');\n-- ERROR 1366 (HY000): Incorrect string value: '\\xF0\\x9F\\x98\\x80' for column 'comment' at row 1\n-- 3. Same failure for numbers when a string can't be cast; add a row first, because\n--    an UPDATE that matches no rows never evaluates the value\nCREATE TABLE scratch_1366b (qty INT);\nINSERT INTO scratch_1366b VALUES (1);\nUPDATE scratch_1366b SET qty = 'twelve';\n-- ERROR 1366 (HY000): Incorrect integer value: 'twelve' for column 'qty' at row 1\nDROP TABLE scratch_1366, scratch_1366b;","repro_note":null,"related":["mysql/1292","mysql/1406","mysql/1265","mysql/1264","sql-server/245","postgresql/22P02","oracle/ora-01722"],"sqlly":"SQLly's CSV import previews the parsed rows and lists rejected values with their row, column and reason before it inserts anything.","faqs":[{"question":"Why does the error show bytes like \\xF0 instead of the emoji?","answer":"MySQL prints the raw bytes of the value it couldn't store. A 4-byte UTF-8 sequence is the giveaway: utf8mb3 columns can only hold up to 3 bytes per character, so anything with emoji or rare CJK ideographs needs utf8mb4."},{"question":"Does this change data on disk?","answer":"In strict mode (the default since 5.7) the statement fails and nothing is written. With STRICT_TRANS_TABLES removed from sql_mode, MySQL stores a best-effort replacement or truncated value and only raises a warning, which is usually worse than the error."},{"question":"The column says utf8 but it still fails. Why?","answer":"In MySQL, utf8 is an alias for utf8mb3, a 3-byte-per-character charset. The real full Unicode charset is utf8mb4. Convert the column to utf8mb4 and make sure the connection charset is utf8mb4 too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1366","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1396","corpus":"errors","engine":"mysql","language":"en","title":"Operation CREATE USER failed","description":"A user-management statement failed for the named account, most often CREATE USER for an account that exists or DROP USER for one that doesn't.","body":{"code":"1396","slug":"1396","name":"ER_CANNOT_USER","message":"Operation %s failed for %s","group":"access","severity":null,"sql_state":"HY000","summary":"A user-management statement failed for the named account, most often CREATE USER for an account that exists or DROP USER for one that doesn't.","meaning":"The message names the operation (`CREATE USER`, `DROP USER`, `ALTER USER`, `RENAME USER`) and the accounts it failed for. Remember that an account is user plus host: `'app'@'%'` and `'app'@'localhost'` are separate.","causes":["Creating an account that already exists.","Dropping or altering an account that doesn't exist, often because of a different host part.","Leftover rows from editing the `mysql.user` table directly in old versions."],"fix":[{"text":"Use the conditional forms.","sql":"CREATE USER IF NOT EXISTS 'app'@'%' IDENTIFIED BY 'strong-password';\nDROP USER IF EXISTS 'old_app'@'%';"},{"text":"Check the exact account names.","sql":"SELECT user, host FROM mysql.user WHERE user LIKE 'app%';"}],"diagnostic":"-- Accounts are user plus host. Check both parts before creating or dropping.\nSELECT user, host FROM mysql.user WHERE user = 'app';\n\n-- On MySQL 8.0 you can also check through the information_schema view\n-- without reading the grant tables directly.\nSELECT user, host FROM information_schema.user_privileges WHERE grantee LIKE \"'app'%\";","alternatives":"The conditional forms CREATE USER IF NOT EXISTS and DROP USER IF EXISTS turn the error into a warning and are fine in setup scripts and migrations. GRANT to a nonexistent account no longer auto-creates it in MySQL 8.0, so create first, then grant.","details":[],"details_title":null,"repro":"-- CREATE USER fails when the account already exists.\nCREATE USER 'app'@'%' IDENTIFIED BY 'pw1';\nCREATE USER 'app'@'%' IDENTIFIED BY 'pw2';\n-- And DROP USER fails when it does not exist.\nDROP USER 'app'@'localhost';","repro_note":null,"related":["mysql/1045","mysql/1449","sql-server/15025"],"sqlly":"SQLly's user manager lists accounts as user plus host, so the missing host part behind 1396 is visible before CREATE USER or DROP USER.","faqs":[{"question":"'app'@'%' exists but MySQL says the user doesn't. Why?","answer":"Host matching is exact for administration. 'app'@'%' and 'app'@'localhost' are separate accounts, and DROP USER 'app'@'localhost' fails if only 'app'@'%' was created. Run the query against mysql.user to see which host values actually exist."},{"question":"How do I find leftover accounts after a botched grant-table edit?","answer":"No built-in repair removes orphaned account rows. mysql_upgrade is deprecated as of MySQL 8.0.16 and only upgrades system tables and checks or repairs table files. Listing mysql.user shows the rows that exist. Remove an account you no longer need with DROP USER, using the exact user and host values shown."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1396","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1406","corpus":"errors","engine":"mysql","language":"en","title":"Data too long for column","description":"A string or binary value is longer than the column allows, for example 300 characters into VARCHAR(255). Widen the column or shorten the value.","body":{"code":"1406","slug":"1406","name":"ER_DATA_TOO_LONG","message":"Data too long for column '%s' at row %ld","group":"data","severity":null,"sql_state":"22001","summary":"A string or binary value is longer than the column allows, for example 300 characters into VARCHAR(255). Widen the column or shorten the value.","meaning":"The value exceeds the column's declared length (in characters for text types, bytes for binary types). In strict mode the statement fails with 1406 and names the column and row. In non-strict mode MySQL truncates the value and only warns (1265).","causes":["User input longer than the column, such as a long name or URL.","A `VARCHAR` whose values now have more characters than its declared length. The limit counts characters, not bytes, so multibyte text alone does not trigger this error.","Inserting into a `TEXT` column more than its 65,535-byte limit (use `MEDIUMTEXT`).","A `BIT` or `BINARY` column given more bits or bytes than it holds."],"fix":[{"text":"Find the longest value you need to store, then widen the column.","sql":"ALTER TABLE customers MODIFY website VARCHAR(2048);"},{"text":"Or validate and shorten values in the application before inserting.","sql":null}],"diagnostic":"-- How wide is the column, and what is the longest value in it now?\nSELECT column_name, character_maximum_length, data_type\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND table_name = 'customers' AND column_name = 'website';\nSELECT MAX(CHAR_LENGTH(website)) AS longest FROM customers;\n-- Which other columns in the table could hit the same limit?\nSELECT column_name, character_maximum_length\nFROM information_schema.columns\nWHERE table_schema = DATABASE() AND table_name = 'customers'\n  AND character_maximum_length IS NOT NULL\nORDER BY character_maximum_length;\n-- Non-strict mode hides this as a warning instead. Check what you're running\nSELECT @@sql_mode;","alternatives":"If widening the column isn't an option, enforce the limit at the application layer and return a clear validation message, or move unbounded text to a TEXT/MEDIUMTEXT column, which has no per-row declared length. A TEXT column has no per-row declared length, but a value over its byte limit (65,535 bytes for TEXT) still fails with 1406, so use MEDIUMTEXT or LONGTEXT for longer values.","details":[],"details_title":null,"repro":"CREATE TEMPORARY TABLE t (code VARCHAR(3));\nINSERT INTO t VALUES ('ABCD');  -- ERROR 1406 (22001): Data too long for column 'code' at row 1","repro_note":null,"related":["mysql/1265","mysql/1366","sql-server/8152","sql-server/2628","postgresql/22001","oracle/ora-12899"],"sqlly":"SQLly's CSV import preview compares field lengths against the target column sizes and lists the rows that would exceed them.","faqs":[{"question":"Does VARCHAR length count characters or bytes?","answer":"Characters, in MySQL 5.0.3 and later. A VARCHAR(100) utf8mb4 column can store 100 characters even though those characters may take up to 400 bytes. Binary types (BINARY, VARBINARY, BLOB) count bytes."},{"question":"Why did my insert work yesterday and fail today?","answer":"Someone probably turned strict mode on, or you moved to a server with the default sql_mode. In non-strict mode the same insert truncates to 3 characters and raises warning 1265 instead of error 1406."},{"question":"Will widening the column rewrite the whole table?","answer":"Usually yes, for VARCHAR it may need a table rebuild depending on the length change and version. On MySQL 8.0 increasing VARCHAR length can be done in place with ALGORITHM=INPLACE in many cases, but plan for lock time on big tables anyway."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1406","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1419","corpus":"errors","engine":"mysql","language":"en","title":"SUPER privilege needed with binary logging","description":"With binary logging on, creating a stored function or trigger needs SUPER unless log_bin_trust_function_creators is enabled.","body":{"code":"1419","slug":"1419","name":"ER_BINLOG_CREATE_ROUTINE_NEED_SUPER","message":"You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)","group":"access","severity":null,"sql_state":"HY000","summary":"With binary logging on, creating a stored function or trigger needs SUPER unless log_bin_trust_function_creators is enabled.","meaning":"When binary logging is enabled, MySQL is careful about stored functions and triggers because unsafe ones could make replicas diverge. By default it requires extra privilege to create them. 1419 says you don't have it. Declaring the function `DETERMINISTIC`, `NO SQL` or `READS SQL DATA` is part of what the check looks at.","causes":["Creating functions or triggers on a server with `log_bin` on (the default in MySQL 8.0) as a non-administrator.","Importing a dump with functions or triggers into a managed MySQL service."],"fix":[{"text":"Check the two requirements separately: the privilege (SUPER) and the safe characteristic (DETERMINISTIC, NO SQL or READS SQL DATA). Declaring the characteristic alone never clears 1419; without it you get 1418 instead.","sql":null},{"text":"If you administer the server and accept the replication risk, allow function creators.","sql":"SET PERSIST log_bin_trust_function_creators = 1;"},{"text":"On managed services, set `log_bin_trust_function_creators` through the provider's parameter group or flags.","sql":null}],"diagnostic":"-- Is binary logging even on? If log_bin is 0 the error has another cause.\nSHOW VARIABLES LIKE 'log_bin';\n\n-- What does the server currently require of function creators?\nSHOW VARIABLES LIKE 'log_bin_trust_function_creators';\n\n-- What can this account actually do globally?\nSHOW GRANTS FOR CURRENT_USER();","alternatives":"Declare the routine with the right characteristics: DETERMINISTIC, NO SQL or READS SQL DATA, whichever is true. That clears 1418, not 1419: the privilege requirement stands either way. On 5.7 the privilege is SUPER; SET_USER_ID is an 8.0 alternative. On managed services, change log_bin_trust_function_creators through the provider's parameter group rather than SET PERSIST, which may be blocked.","details":[],"details_title":null,"repro":"-- Requires log_bin enabled (default on 8.0) and a non-privileged user.\nCREATE USER 'dev'@'%' IDENTIFIED BY 'pw';\nGRANT ALL ON appdb.* TO 'dev'@'%';\n-- as dev:\nCREATE FUNCTION add_tax(amount DECIMAL(10,2))\nRETURNS DECIMAL(10,2)\nRETURN amount * 1.2;","repro_note":null,"related":["mysql/1227","mysql/1449"],"sqlly":"SQLly's server overview shows log_bin and log_bin_trust_function_creators, so the precondition for 1419 is visible before creating a function on a managed server.","faqs":[{"question":"Why is this the default in MySQL 8.0 when it wasn't in 5.6?","answer":"Binary logging is on by default from 8.0 onward, and the safety check is tied to log_bin being enabled. With 5.6's default configuration logging was often off, so the check never fired."},{"question":"Is setting log_bin_trust_function_creators = 1 dangerous?","answer":"It removes the check that non-privileged creators mark their functions as safe. A function marked DETERMINISTIC that actually reads nondeterministic data can make replicas diverge. On servers without replication or where you trust every developer with write access, the risk is small."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1419","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1442","corpus":"errors","engine":"mysql","language":"en","title":"Can't update table in function/trigger","description":"A trigger or stored function tries to modify the same table as the statement that fired it, which MySQL doesn't allow.","body":{"code":"1442","slug":"1442","name":"ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG","message":"Can't update table '%s' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.","group":"objects","severity":null,"sql_state":"HY000","summary":"A trigger or stored function tries to modify the same table as the statement that fired it, which MySQL doesn't allow.","meaning":"In MySQL a trigger can't run `INSERT`, `UPDATE` or `DELETE` on the table the triggering statement is changing, and a stored function can't modify a table the calling statement uses. The way to change the row being written is to set `NEW.column` in a `BEFORE` trigger.","causes":["An `AFTER UPDATE` trigger that runs `UPDATE` on its own table, for example to set a timestamp.","A function called from a statement that modifies the same table."],"fix":[{"text":"Change the row itself in a `BEFORE` trigger.","sql":"CREATE TRIGGER orders_touch BEFORE UPDATE ON orders\nFOR EACH ROW SET NEW.updated_at = NOW();"},{"text":"Or let the column do it: `updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`.","sql":null},{"text":"Move changes to other rows of the same table into application code or a stored procedure called after the statement.","sql":null}],"diagnostic":"-- Look at the trigger body. Any INSERT/UPDATE/DELETE naming the same\n-- table as the trigger's own table is the problem.\nSELECT trigger_name, event_manipulation, action_timing, action_statement\nFROM information_schema.triggers\nWHERE event_object_schema = DATABASE()\n  AND event_object_table = 'orders';\n\n-- If the error came from a function, check what the failing statement touches.\nSELECT routine_name, routine_definition FROM information_schema.routines\nWHERE routine_schema = DATABASE();","alternatives":"For a per-row change, set NEW.column in a BEFORE trigger, which is the supported way to modify the row being written. For column-level behavior that needs no code at all, use DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP on a TIMESTAMP or DATETIME column. Cascading changes to other rows of the same table belong in application code or a procedure called after the statement.","details":[],"details_title":null,"repro":"-- A trigger cannot modify the table it fires on.\nCREATE TABLE orders (id INT PRIMARY KEY, updated_at TIMESTAMP NULL);\nCREATE TRIGGER orders_touch AFTER UPDATE ON orders\nFOR EACH ROW\n  UPDATE orders SET updated_at = NOW() WHERE id = NEW.id;\nUPDATE orders SET id = id WHERE id = 1;","repro_note":null,"related":["mysql/1093","oracle/ora-04091"],"sqlly":"SQLly's editor moves the cursor to the trigger body statement that touches its own table, where the `BEFORE ... SET NEW.col` rewrite belongs.","faqs":[{"question":"Why can't the trigger just update other rows of the same table?","answer":"The statement that fired the trigger already holds the table in a partially applied state. Re-entering it mid-statement would make the outcome order-dependent, so MySQL forbids it outright rather than trying to define what would happen."},{"question":"Does the same rule apply in a stored function?","answer":"Yes, and it is broader: a function called from a statement can't modify any table that statement uses, even when the calling statement only reads that table. Functions are meant to compute values; writes belong in procedures or triggers on other tables."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1442","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1449","corpus":"errors","engine":"mysql","language":"en","title":"Definer user does not exist","description":"A view, trigger, procedure or event was created with a DEFINER account that no longer exists on this server, so it can't run.","body":{"code":"1449","slug":"1449","name":"ER_NO_SUCH_USER","message":"The user specified as a definer ('%s'@'%s') does not exist","group":"access","severity":null,"sql_state":"HY000","summary":"A view, trigger, procedure or event was created with a DEFINER account that no longer exists on this server, so it can't run.","meaning":"Stored programs and views run with the privileges of their `DEFINER` (unless declared `SQL SECURITY INVOKER`). If that account is missing, for example after a dump from another server, using the object fails with 1449, which names the missing definer.","causes":["Restoring a dump whose objects were defined by a user that doesn't exist on the new server.","Dropping the account that created views or triggers."],"fix":[{"text":"Find the objects with the missing definer.","sql":"-- DEFINER is stored with quotes, as 'olduser'@'%': the comparison must include them.\nSELECT table_name FROM information_schema.views WHERE definer = \"'olduser'@'%'\";\nSELECT trigger_name FROM information_schema.triggers WHERE definer = \"'olduser'@'%'\";\nSELECT routine_name FROM information_schema.routines WHERE definer = \"'olduser'@'%'\";\n-- Under ANSI_QUOTES double quotes name identifiers; use CHAR(39) instead, for example:\n-- WHERE definer = CONCAT(CHAR(39), 'olduser', CHAR(39), '@', CHAR(39), '%', CHAR(39))"},{"text":"Create the missing account, or recreate the objects with an existing definer.","sql":"CREATE USER 'olduser'@'%' IDENTIFIED BY 'strong-password';\n-- or, for a view:\nALTER DEFINER = 'app'@'%' VIEW v_orders AS SELECT * FROM orders;"},{"text":"When dumping for another server, strip `DEFINER` clauses or recreate objects afterwards.","sql":null}],"diagnostic":"-- Find every object whose definer no longer exists. DEFINER is stored quoted\n-- ('owner'@'%'), so put the quotes in the comparison; replace the account with\n-- the one named in the error.\nSELECT 'view' AS kind, table_schema, table_name FROM information_schema.views\n  WHERE definer = \"'owner'@'%'\"\nUNION ALL\nSELECT 'trigger', trigger_schema, trigger_name FROM information_schema.triggers\n  WHERE definer = \"'owner'@'%'\"\nUNION ALL\nSELECT 'routine', routine_schema, routine_name FROM information_schema.routines\n  WHERE definer = \"'owner'@'%'\";\n\n-- Confirm whether the account really is gone.\nSELECT user, host FROM mysql.user WHERE user = 'owner';","alternatives":"Recreating the missing account with the same name and host unblocks the objects only after the account is granted the privileges the objects use (until then the view fails with 1356 ER_VIEW_INVALID). If the original account should stay gone, recreate each object under a surviving definer. Views can also be declared SQL SECURITY INVOKER so they run as the caller instead of a stored definer.","details":[],"details_title":null,"repro":"-- Object defined by an account that later disappears.\nCREATE USER 'owner'@'%' IDENTIFIED BY 'pw';\nGRANT SELECT ON appdb.orders TO 'owner'@'%';\n-- as owner:\nCREATE VIEW v_recent AS SELECT * FROM orders;\n-- back as admin:\nDROP USER 'owner'@'%';\nSELECT * FROM v_recent;","repro_note":null,"related":["mysql/1227","mysql/1419","mysql/1396"],"sqlly":"SQLly's schema browser shows each view's DEFINER, so objects left pointing at a dropped account can be found before they fail at query time.","faqs":[{"question":"Why do dumps break this so often?","answer":"mysqldump writes DEFINER clauses for views and triggers, and for routines and events when run with --routines and --events. Restoring on a server where that account was never created leaves objects pointing at a definer that doesn't exist, and the first SELECT against the view fails."},{"question":"Can I edit the definer without dropping the view?","answer":"For views, ALTER VIEW with a new DEFINER clause works if you have the SUPER or SET_ANY_DEFINER privilege. ALTER EVENT also accepts a DEFINER clause. Triggers and stored procedures and functions have no ALTER DEFINER, so drop and recreate them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1449","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1451","corpus":"errors","engine":"mysql","language":"en","title":"Foreign key fails: cannot delete parent row","description":"You tried to delete or change the key of a row that child rows still reference, and the foreign key doesn't cascade.","body":{"code":"1451","slug":"1451","name":"ER_ROW_IS_REFERENCED_2","message":"Cannot delete or update a parent row: a foreign key constraint fails%s","group":"constraints","severity":null,"sql_state":"23000","summary":"You tried to delete or change the key of a row that child rows still reference, and the foreign key doesn't cascade.","meaning":"With the default `ON DELETE RESTRICT` (or `NO ACTION`), MySQL won't delete a parent row, or change its key, while child rows point to it. The message ends with the constraint definition naming the child table.","causes":["Deleting a customer who still has orders.","Deleting a parent table's rows before the child tables. TRUNCATE on the parent fails with 1701 instead, and DROP TABLE on it fails with 3730.","Updating a primary key value that child rows reference."],"fix":[{"text":"Find the child rows that block the delete.","sql":"SELECT * FROM orders WHERE customer_id = 42;"},{"text":"Delete or reassign the children first, in one transaction.","sql":"START TRANSACTION;\nDELETE FROM orders WHERE customer_id = 42;\nDELETE FROM customers WHERE id = 42;\nCOMMIT;"},{"text":"If child rows should always go with the parent, look up the constraint name (see the diagnostics), then change the foreign key to cascade.","sql":"ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;\nALTER TABLE orders ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id)\n  REFERENCES customers (id) ON DELETE CASCADE;"}],"diagnostic":"-- Which child table and constraint block the delete? The message names the constraint; look up its details.\nSELECT constraint_name, table_name, column_name\nFROM information_schema.key_column_usage\nWHERE constraint_schema = DATABASE()\n  AND referenced_table_name = 'customers';\n\n-- Show the delete rule for each referencing key.\nSELECT rc.constraint_name, rc.table_name, rc.update_rule, rc.delete_rule\nFROM information_schema.referential_constraints rc\nWHERE rc.constraint_schema = DATABASE()\n  AND rc.referenced_table_name = 'customers';\n\n-- The actual child rows in the way.\nSELECT * FROM orders WHERE customer_id = 42;","alternatives":"Use soft deletes: set a deleted_at flag on the parent instead of removing the row, so history in child tables stays valid. If the key really should cascade, recreate the foreign key with ON DELETE CASCADE or ON DELETE SET NULL, whichever matches the data.","details":[],"details_title":null,"repro":"CREATE TABLE parent (id INT PRIMARY KEY);\nCREATE TABLE child (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES parent (id));\nINSERT INTO parent VALUES (1);\nINSERT INTO child VALUES (1, 1);\nDELETE FROM parent WHERE id = 1;  -- ERROR 1451 (23000)\nDROP TABLE child, parent;","repro_note":null,"related":["mysql/1452","mysql/1217","mysql/1701","sql-server/547","postgresql/23503","oracle/ora-02292"],"sqlly":"SQLly's ER diagram shows which child tables reference the row's table, and the grid makes it easy to select and delete or reassign those children first.","faqs":[{"question":"TRUNCATE on the parent also fails. Why?","answer":"TRUNCATE on an InnoDB table referenced by a foreign key is refused (error 1701, SQLSTATE 42000) even with no rows. Setting foreign_key_checks = 0 let TRUNCATE succeed on a populated parent in MySQL 8.4; the manual does not document that exception. DELETE FROM the table instead, or drop the child foreign keys first."},{"question":"Should I just add ON DELETE CASCADE?","answer":"Only if child rows truly have no meaning without the parent. Cascades make big deletes slow, can chain across many tables, and destroy data you may have wanted to keep."},{"question":"Can I see the constraint name without triggering the error?","answer":"Yes. Query information_schema.referential_constraints for rows where referenced_table_name is your table. The constraint_name there matches the one in the error message."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1451","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1452","corpus":"errors","engine":"mysql","language":"en","title":"Foreign key fails: cannot add child row","description":"An INSERT or UPDATE sets a foreign key column to a value with no matching row in the parent table. Insert the parent first or fix the value.","body":{"code":"1452","slug":"1452","name":"ER_NO_REFERENCED_ROW_2","message":"Cannot add or update a child row: a foreign key constraint fails%s","group":"constraints","severity":null,"sql_state":"23000","summary":"An INSERT or UPDATE sets a foreign key column to a value with no matching row in the parent table. Insert the parent first or fix the value.","meaning":"A foreign key says every value in the child column must exist in the parent table's referenced column. 1452 means the row you're writing points at a parent that isn't there. The message ends with the full constraint definition, which names both tables and columns.","causes":["Inserting child rows before their parent rows, for example loading `order_lines` before `orders`.","A typo or stale id in the foreign key column.","Adding a foreign key to a table whose existing data already has orphans (the `ALTER TABLE` fails with 1452).","Columns that look equal but differ in trailing spaces, for example a VARCHAR value 'abc ' against 'abc'. A collation or signedness mismatch stops the foreign key from being created (error 3780), so it cannot cause this error on insert."],"fix":[{"text":"Check whether the parent exists.","sql":"SELECT id FROM orders WHERE id = 1001;"},{"text":"Insert the parent first, or load tables in dependency order.","sql":null},{"text":"Before adding a foreign key, find orphaned rows.","sql":"SELECT l.*\nFROM order_lines l\nLEFT JOIN orders o ON o.id = l.order_id\nWHERE o.id IS NULL;"},{"text":"For a bulk load where order can't be controlled, turn checks off for the session, then verify there are no orphans before turning them back on. Rows loaded while checks are off are not re-checked later.","sql":"SET foreign_key_checks = 0;\n-- load data\nSET foreign_key_checks = 1;"}],"diagnostic":"-- Which constraint is involved? The message tail names it; confirm and find the tables it links.\nSELECT constraint_name, table_name, column_name, referenced_table_name, referenced_column_name\nFROM information_schema.key_column_usage\nWHERE constraint_schema = DATABASE()\n  AND referenced_column_name IS NOT NULL\n  AND table_name = 'order_lines';\n\n-- Is checking on at all? If it was off during a load, orphans are possible.\nSELECT @@foreign_key_checks;\n\n-- List every orphan in the child table.\nSELECT l.id, l.order_id\nFROM order_lines l\nLEFT JOIN orders o ON o.id = l.order_id\nWHERE o.id IS NULL;","alternatives":"Load the data with foreign_key_checks = 0 and clean up orphans afterward, or use LOAD DATA into a staging table and insert into the real tables in parent-first order with INSERT ... SELECT. For code-driven inserts, wrap parent and child inserts in one transaction so a missing parent rolls the child back.","details":[],"details_title":null,"repro":"CREATE TABLE p (id INT PRIMARY KEY);\nCREATE TABLE c (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES p (id));\nINSERT INTO c VALUES (1, 99);  -- ERROR 1452 (23000)\nDROP TABLE c, p;","repro_note":null,"related":["mysql/1451","mysql/1216","mysql/1215","mysql/1062","sql-server/547","postgresql/23503","oracle/ora-02291","sqlite/sqlite-constraint-foreignkey"],"sqlly":"SQLly's ER diagram draws the foreign keys between tables, so you can see which parent a child table depends on before loading data in the right order.","faqs":[{"question":"I inserted the parent row. Why does the child insert still fail?","answer":"The parent insert probably ran in a different connection that never committed, or it failed silently. Check in the same session that SELECT finds the parent row before inserting the child."},{"question":"Does turning off foreign_key_checks corrupt anything?","answer":"No, but rows inserted while it is off are never re-checked. If you load orphans that way, they stay broken until you fix or delete them, and later deletes can fail in confusing ways."},{"question":"Why did this fail on a value that looks identical in both tables?","answer":"Watch for trailing spaces on CHAR/VARCHAR keys. A signedness or collation mismatch stops the foreign key from being created (error 3780), so it cannot cause this error on insert. Comparing with HEX(col) on both sides shows invisible differences."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1452","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1586","corpus":"errors","engine":"mysql","language":"en","title":"Duplicate entry for key (with key name)","description":"The form of the duplicate-key error that names the index. It means the same as 1062: the value already exists in a unique index.","body":{"code":"1586","slug":"1586","name":"ER_DUP_ENTRY_WITH_KEY_NAME","message":"Duplicate entry '%s' for key '%s'","group":"constraints","severity":null,"sql_state":"23000","summary":"The form of the duplicate-key error that names the index. It means the same as 1062: the value already exists in a unique index.","meaning":"1586 (`ER_DUP_ENTRY_WITH_KEY_NAME`) carries the message `Duplicate entry '%s' for key '%s'`, with the key name rather than its number. The MySQL reference notes that 1062 is returned using this format string, so the text you see under 1062 comes from here. Treat it exactly like 1062.","causes":["Inserting or updating a row whose value already exists in a primary key or unique index.","A parser or monitoring tool that matches on message text: 1586 is the format string behind the 1062 you usually see, so text-based matchers may report either code."],"fix":[{"text":"Confirm the code your driver reports (MySQL 8.4 sends 1062; 1586 is the message template); the remedy is the same: find the existing row, then upsert with `ON DUPLICATE KEY UPDATE` or skip duplicates.","sql":"SHOW INDEX FROM users;\nSELECT * FROM users WHERE email = 'a@x.com';"}],"diagnostic":"-- The message names the key. Confirm which columns and table it covers.\nSELECT table_name, index_name, non_unique, column_name, seq_in_index\nFROM information_schema.statistics\nWHERE table_schema = DATABASE()\n  AND index_name = 'uq_users_email';\n\n-- Then find the row already holding that value.\nSELECT * FROM users WHERE email = 'a@x.com';","alternatives":"Everything that applies to 1062 applies here: clean the source data, use INSERT IGNORE when duplicates are acceptable, or INSERT ... ON DUPLICATE KEY UPDATE for an upsert. There is no separate handling for this code.","details":[],"details_title":null,"repro":"-- The internal message format for a duplicate key, shown with the key name.\nCREATE TABLE users (email VARCHAR(100), UNIQUE KEY uq_users_email (email));\nINSERT INTO users VALUES ('a@x.com');\nINSERT INTO users VALUES ('a@x.com');","repro_note":null,"related":["mysql/1062"],"sqlly":"SQLly's error banner resolves the key name in the message to its table and columns and offers to jump to the row already holding the value.","faqs":[{"question":"What is the difference between 1062 and 1586?","answer":"For practical purposes, none. 1586 is the message template MySQL uses to report a duplicate entry with the key name instead of the key number. The error you catch is 1062 carrying this text."},{"question":"The key name in the message doesn't match any index I created. Why?","answer":"MySQL 8.4 prefixes the key in the message with its table name (for example 'users.uq_users_email'), so compare the part after the dot. The name may also be a generated name from an inline column constraint, or a name picked up from a dump from another server. Check information_schema.statistics for that index_name to see which table and columns it actually covers."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1586","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1698","corpus":"errors","engine":"mysql","language":"en","title":"Access denied for user (no password)","description":"Login denied for an account that authenticates without a password check, most often root using auth_socket on Ubuntu or Debian.","body":{"code":"1698","slug":"1698","name":"ER_ACCESS_DENIED_NO_PASSWORD_ERROR","message":"Access denied for user '%s'@'%s'","group":"access","severity":null,"sql_state":"28000","summary":"Login denied for an account that authenticates without a password check, most often root using auth_socket on Ubuntu or Debian.","meaning":"1698 is an access-denied error for accounts whose plugin doesn't take a password. On Ubuntu and Debian, `'root'@'localhost'` uses `auth_socket`, which lets you in only if your operating-system user is also `root`. Logging in as root from a normal user, or from an app with a password, fails with 1698.","causes":["Running `mysql -u root -p` as a normal operating-system user on a system where root uses `auth_socket`.","An application connecting as `root` with a password to such a server."],"fix":[{"text":"Log in as the operating-system root user, which `auth_socket` accepts: `sudo mysql`.","sql":null},{"text":"Create a separate account with a password for applications and tools, instead of changing root.","sql":"CREATE USER 'admin'@'localhost' IDENTIFIED BY 'strong-password';\nGRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION;"},{"text":"Or, if you really want password login for root, change its plugin.","sql":"ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'strong-password';"}],"diagnostic":"-- Which plugin does the account use? auth_socket (or unix_socket on MariaDB) is the giveaway.\nSELECT user, host, plugin FROM mysql.user WHERE user = 'root';\n-- Confirm the plugin is active:\nSHOW PLUGINS;\n-- Confirm what OS user you are, since that is what auth_socket compares:\n-- whoami\n-- And check the server was reached over a Unix socket, which auth_socket requires:\n-- mysql -e 'STATUS' and read the Connection line: \"Localhost via UNIX socket\" (TCP shows \"127.0.0.1 via TCP/IP\") -- plus `lsof -p $(pidof mysqld) | grep sock` on the server if needed","alternatives":"The usual advice is to leave root alone and create a passworded admin account for clients and applications. If you must have password login for the socket account, ALTER USER ... IDENTIFIED WITH caching_sha2_password BY '...' switches it. Note MariaDB renamed the plugin to unix_socket and its behavior is the same idea.","details":[],"details_title":null,"repro":"-- Requires a server with the auth_socket plugin (Ubuntu/Debian packages ship it).\n-- On a scratch dev server:\nINSTALL PLUGIN auth_socket SONAME 'auth_socket.so';   -- if not already installed\nCREATE USER 'socktest'@'localhost' IDENTIFIED WITH auth_socket;\n-- As a NON-root OS user:\n-- mysql -u socktest -p\n-- Expected: ERROR 1698 (28000): Access denied for user 'socktest'@'localhost'\n-- (no password prompt helps; the plugin matches OS user names, not passwords).\n-- As the matching OS user (sudo -u socktest if it exists), the same command succeeds.\nDROP USER 'socktest'@'localhost';","repro_note":null,"related":["mysql/1045","mysql/1130"],"sqlly":"SQLly's error panel explains the auth_socket case (OS user must match) instead of inviting a password retry loop.","faqs":[{"question":"I type the right password and still get 1698. Why?","answer":"auth_socket never looks at passwords. It compares your operating-system user with the MySQL account's user part. The password you type is ignored, so a correct one changes nothing."},{"question":"Why does sudo mysql work but mysql -u root -p not?","answer":"sudo makes you the OS root user, and root's auth_socket account accepts OS root on localhost. Your normal user isn't root at the OS level, so the plugin denies the match."},{"question":"Can applications use auth_socket accounts?","answer":"Only if they run on the same host as the server, connect over the Unix socket, and run as the matching OS user. That fits system maintenance scripts, not typical web apps; give the app a passworded account."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1698","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1701","corpus":"errors","engine":"mysql","language":"en","title":"Can't truncate a table with foreign keys","description":"TRUNCATE TABLE is refused because another table has a foreign key pointing at this one, even if no child rows exist.","body":{"code":"1701","slug":"1701","name":"ER_TRUNCATE_ILLEGAL_FK","message":"Cannot truncate a table referenced in a foreign key constraint (%s)","group":"constraints","severity":null,"sql_state":"42000","summary":"TRUNCATE TABLE is refused because another table has a foreign key pointing at this one, even if no child rows exist.","meaning":"`TRUNCATE TABLE` drops and recreates the table rather than deleting rows one by one, so InnoDB can't check foreign keys row by row. It refuses to truncate any table that other tables reference, regardless of whether child rows exist.","causes":["Truncating a parent table such as `customers` in a test reset or data reload.","Truncating a referenced table while its foreign key still exists, whatever the order, including children first."],"fix":[{"text":"Use `DELETE` instead, which checks foreign keys row by row. With the default RESTRICT action it fails while child rows exist (error 1451), so clear the child tables first or define `ON DELETE CASCADE`.","sql":"DELETE FROM customers;"},{"text":"For a full reset of related tables, disable foreign key checks for the session while truncating them all, then turn checks back on.","sql":"SET foreign_key_checks = 0;\nTRUNCATE TABLE order_lines;\nTRUNCATE TABLE orders;\nTRUNCATE TABLE customers;\nSET foreign_key_checks = 1;"}],"diagnostic":"-- Which tables reference the one you are trying to truncate?\nSELECT table_name, constraint_name\nFROM information_schema.key_column_usage\nWHERE referenced_table_name = 'customers'\n  AND referenced_table_schema = DATABASE();\n\n-- Do child rows actually exist? Empty children still block TRUNCATE,\n-- because the check is on the constraint, not the data.\nSELECT (SELECT COUNT(*) FROM orders) AS child_rows;","alternatives":"Child-first ordering does not avoid this error, because the foreign key still blocks TRUNCATE of the parent. Use DELETE, or the SET foreign_key_checks reset in fix 2. Or drop the foreign keys, truncate, and re-add them, but only after the child tables are empty; re-adding with orphan child rows fails with error 1452. A dedicated test database that you DROP and recreate from a seed script also avoids the problem.","details":[],"details_title":null,"repro":"-- A parent that a child references cannot be truncated.\nSET foreign_key_checks = 1;\nCREATE TABLE customers (id INT PRIMARY KEY);\nCREATE TABLE orders (\n    id INT PRIMARY KEY,\n    customer_id INT NOT NULL,\n    CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)\n);\nINSERT INTO customers VALUES (1);\nTRUNCATE TABLE customers;","repro_note":null,"related":["mysql/1451","mysql/1217","postgresql/0A000"],"sqlly":"SQLly's ER diagram shows which tables reference the one being truncated, so the children-first reset order is visible before the TRUNCATE.","faqs":[{"question":"Why does TRUNCATE fail even when the child table is empty?","answer":"TRUNCATE drops and re-creates the table rather than deleting rows, and MySQL refuses it for any table that a foreign key in another table references, whether or not child rows exist."},{"question":"Does disabling foreign_key_checks in one session affect other connections?","answer":"No. foreign_key_checks is a session variable. Other connections keep enforcing their own checks, and the setting reverts when your session ends."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1701","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1792","corpus":"errors","engine":"mysql","language":"en","title":"Write in a READ ONLY transaction","description":"A write was attempted inside a transaction started as READ ONLY, or on a session whose default is read-only.","body":{"code":"1792","slug":"1792","name":"ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION","message":"Cannot execute statement in a READ ONLY transaction.","group":"locking","severity":null,"sql_state":"25006","summary":"A write was attempted inside a transaction started as READ ONLY, or on a session whose default is read-only.","meaning":"A transaction started with `START TRANSACTION READ ONLY`, or a session with `transaction_read_only` on, may not change nontemporary tables. DML on a temporary table that already exists is allowed.. Any `INSERT`, `UPDATE` or `DELETE` fails with 1792. A DDL statement such as `CREATE TABLE` or `ALTER TABLE` implicitly commits and ends the read-only transaction, so it runs outside the transaction. `CREATE TEMPORARY TABLE` inside the transaction does fail with 1792. Drivers and frameworks often mark transactions read-only for queries they think are reads.","causes":["A framework read-only transaction (for example a read-only annotation or replica routing) that ends up running a write.","`SET SESSION transaction_read_only = ON` left on a pooled connection."],"fix":[{"text":"Check the session setting.","sql":"SELECT @@transaction_read_only;"},{"text":"Start a read-write transaction for the write, or fix the code path that marked it read-only.","sql":"START TRANSACTION READ WRITE;"}],"diagnostic":"-- Is this session read-only?\nSELECT @@transaction_read_only, @@session.transaction_read_only;\n-- Is the whole server defaulting to read-only for new sessions?\nSELECT @@global.transaction_read_only;\n-- Which transaction are you in, and is it marked read-only?\nSELECT trx_id, trx_is_read_only, trx_started\nFROM information_schema.innodb_trx\nWHERE trx_mysql_thread_id = CONNECTION_ID();\n-- Frameworks often set this per transaction; check the driver logs for\n-- SET TRANSACTION READ ONLY right before the failing statement.","alternatives":"If your framework routes reads to replicas and marks those transactions read-only, make sure the write goes through the read-write connection or unit of work. For quick one-off scripts, plain BEGIN without a READ ONLY clause is read-write unless the session has transaction_read_only on, so check that variable first.","details":[],"details_title":null,"repro":"CREATE TABLE t (id INT PRIMARY KEY, v INT);\nSTART TRANSACTION READ ONLY;\nINSERT INTO t VALUES (1, 1); -- ERROR 1792\nCOMMIT;","repro_note":null,"related":["mysql/1290","postgresql/25006"],"sqlly":"SQLly's manual-commit tabs show a pending-statement count in the status bar. A READ ONLY transaction or session set on the MySQL side is not shown there, so check `@@transaction_read_only` first.","faqs":[{"question":"Can I write to a temporary table inside a read-only transaction?","answer":"Yes, for a temporary table that already exists. INSERT, UPDATE and DELETE on it are allowed inside a READ ONLY transaction, but CREATE TEMPORARY TABLE inside the transaction fails with 1792. Writes to regular tables trigger 1792."},{"question":"Does this error mean the server itself is read-only?","answer":"No. That would be error 1290 with the read-only option named in the message. 1792 comes from the transaction or session being marked read-only while the server is fine with writes."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1792","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1822","corpus":"errors","engine":"mysql","language":"en","title":"Missing index for foreign key constraint","description":"The parent's referenced columns lack an index the foreign key can use. Reference the primary key or a UNIQUE index. MySQL 8.4 refuses a non-unique index with 6125.","body":{"code":"1822","slug":"1822","name":"ER_FK_NO_INDEX_PARENT","message":"Failed to add the foreign key constraint. Missing index for constraint '%s' in the referenced table '%s'","group":"constraints","severity":null,"sql_state":"HY000","summary":"The parent's referenced columns lack an index the foreign key can use. Reference the primary key or a UNIQUE index. MySQL 8.4 refuses a non-unique index with 6125.","meaning":"InnoDB needs an index on the referenced columns, with those columns first and in the same order, so it can check parent rows quickly. If there isn't one, creating the foreign key fails with 1822, which names the constraint and parent table.","causes":["Referencing a column that isn't the primary key and has no index.","A composite foreign key whose column order doesn't match any index on the parent."],"fix":[{"text":"Add a unique index (or primary key) on the referenced columns, then create the foreign key.","sql":"ALTER TABLE customers ADD UNIQUE INDEX ux_customers_code (code);\nALTER TABLE orders ADD CONSTRAINT fk_orders_customer_code\n  FOREIGN KEY (customer_code) REFERENCES customers (code);"}],"diagnostic":"-- Does an index start with the referenced column, in order?\nSHOW INDEX FROM parent;\n\n-- Cross-check via the dictionary: the referenced columns and any covering index.\nSELECT index_name, seq_in_index, column_name, non_unique\nFROM information_schema.statistics\nWHERE table_schema = DATABASE() AND table_name = 'parent'\nORDER BY index_name, seq_in_index;","alternatives":"If the parent column should be unique anyway, add a UNIQUE index, which also prevents duplicate parents. If uniqueness is wrong, a plain non-unique index with the foreign key columns first satisfies InnoDB and still speeds up checks.","details":[],"details_title":null,"repro":"CREATE TABLE parent (code VARCHAR(20));  -- no index on code\nCREATE TABLE child (id INT PRIMARY KEY, p_code VARCHAR(20));\nALTER TABLE child ADD CONSTRAINT fk_c\n  FOREIGN KEY (p_code) REFERENCES parent (code);  -- ERROR 1822 (HY000)\nDROP TABLE child, parent;","repro_note":null,"related":["mysql/1215","mysql/3780"],"sqlly":"SQLly's schema browser marks which parent columns carry an index, so the missing index behind 1822 is visible before creating the constraint.","faqs":[{"question":"Does the parent index have to be UNIQUE?","answer":"Yes on MySQL 8.4 by default. A non-unique parent index fails with ERROR 6125 unless restrict_fk_on_non_standard_key is OFF; with it OFF, non-unique parents are accepted and duplicate parents become possible."},{"question":"Does InnoDB create the child-side index for me?","answer":"Yes. If no suitable index exists on the child's referencing columns, InnoDB creates one automatically when you add the key. The parent side has no such convenience."},{"question":"What about a composite foreign key where the index has extra leading columns?","answer":"That fails. The foreign key columns must be the first columns of the index, in the same order."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1822","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1824","corpus":"errors","engine":"mysql","language":"en","title":"Failed to open the referenced table","description":"A foreign key refers to a parent table that doesn't exist, often because the tables are created in the wrong order.","body":{"code":"1824","slug":"1824","name":"ER_FK_CANNOT_OPEN_PARENT","message":"Failed to open the referenced table '%s'","group":"constraints","severity":null,"sql_state":"HY000","summary":"A foreign key refers to a parent table that doesn't exist, often because the tables are created in the wrong order.","meaning":"When creating a foreign key, InnoDB opens the referenced table to check it. If that table doesn't exist (or is named in another database or case), creation fails with 1824.","causes":["Creating the child table before the parent in a schema script.","A typo or wrong database in `REFERENCES`.","Letter-case differences on a case-sensitive server."],"fix":[{"text":"Create the parent table first, or add foreign keys at the end of the script with `ALTER TABLE`.","sql":null},{"text":"When a script must create tables in any order, disable checks while creating them.","sql":"SET foreign_key_checks = 0;\n-- CREATE TABLE statements\nSET foreign_key_checks = 1;"}],"diagnostic":"-- Does the parent table exist, spelled exactly as in REFERENCES?\nSELECT table_schema, table_name, engine\nFROM information_schema.tables\nWHERE table_name = 'parent';\n\n-- On Linux servers, name case matters. Check the setting.\nSELECT @@lower_case_table_names;\n\n-- Confirm the referenced database is the one you think.\nSELECT DATABASE();","alternatives":"If the script genuinely needs tables in any order, wrap the CREATE TABLE statements in foreign_key_checks = 0 / = 1 and add the keys afterwards. If the parent lives in another schema, qualify it: REFERENCES other_db.parent (id).","details":[],"details_title":null,"repro":"CREATE TABLE child (id INT PRIMARY KEY, p_id INT,\n  CONSTRAINT fk_c FOREIGN KEY (p_id) REFERENCES parent (id));  -- ERROR 1824 (HY000)\nCREATE TABLE parent (id INT PRIMARY KEY);","repro_note":null,"related":["mysql/1215","mysql/1146"],"sqlly":"SQLly's Validate SQL resolves the REFERENCES target against the connection's schema, so a missing or misspelled parent table is caught before the DDL runs.","faqs":[{"question":"The table exists. Why does MySQL say it cannot open it?","answer":"Usually a case difference on a case-sensitive filesystem (lower_case_table_names = 0 on Linux), or the table is in a different schema than the unqualified REFERENCES assumes."},{"question":"Can a foreign key point at a table in another database?","answer":"Yes, with a qualified name. The referenced table must still be InnoDB and satisfy the usual index and type requirements. A MyISAM parent fails with 1824 as well, not 1215."},{"question":"Why does my dump restore fine on one server and fail on another?","answer":"mysqldump writes SET FOREIGN_KEY_CHECKS=0 around table creation, so it tolerates ordering, including a partial restore. A hand-written script without that hits 1824 when a referenced table is missing, and so does a dump whose SET FOREIGN_KEY_CHECKS lines were removed."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1824","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/1826","corpus":"errors","engine":"mysql","language":"en","title":"Duplicate foreign key constraint name","description":"A foreign key's name is already used. In MySQL foreign key names must be unique across the whole database, not just the table.","body":{"code":"1826","slug":"1826","name":"ER_FK_DUP_NAME","message":"Duplicate foreign key constraint name '%s'","group":"constraints","severity":null,"sql_state":"HY000","summary":"A foreign key's name is already used. In MySQL foreign key names must be unique across the whole database, not just the table.","meaning":"InnoDB stores foreign key constraint names per database, so two tables can't each have a constraint called `fk_customer`. Creating the second one fails with 1826.","causes":["Copying a table definition, including its constraint names, to create a similar table.","Naming conventions that don't include the table name."],"fix":[{"text":"Find where the name is used.","sql":"SELECT table_name, constraint_name FROM information_schema.referential_constraints\nWHERE constraint_schema = DATABASE() AND constraint_name = 'fk_customer';"},{"text":"Use names that include the table, such as `fk_orders_customer` and `fk_invoices_customer`, or leave the name out and let MySQL generate one.","sql":null}],"diagnostic":"-- Where is that constraint name already used?\nSELECT table_name, constraint_name, referenced_table_name\nFROM information_schema.referential_constraints\nWHERE constraint_schema = DATABASE()\n  AND constraint_name = 'fk_customer';","alternatives":"Leave out the CONSTRAINT name clause and let MySQL generate a unique name, though generated names are harder to read in later errors. Adopting a convention like fk_<table>_<column> from the start avoids collisions entirely.","details":[],"details_title":null,"repro":"-- Foreign key names must be unique per database.\nCREATE TABLE customers (id INT PRIMARY KEY);\nCREATE TABLE orders (\n    id INT PRIMARY KEY,\n    customer_id INT,\n    CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers (id)\n);\nCREATE TABLE invoices (\n    id INT PRIMARY KEY,\n    customer_id INT,\n    CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers (id)\n);","repro_note":null,"related":["mysql/1061","mysql/1215","mysql/1071"],"sqlly":"","faqs":[{"question":"Can two tables in different databases share a foreign key name?","answer":"Yes. The namespace is the schema, so customers and orders can each have fk_customer as long as they live in different databases."},{"question":"Does this apply to index names too?","answer":"No, index names only need to be unique within a table. That is error 1061. Constraint names for foreign keys are the ones that must be unique per database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/1826","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2002","corpus":"errors","engine":"mysql","language":"en","title":"Can't connect through socket","description":"The client tried the local Unix socket and found no server there. The server isn't running, uses another socket path, or you meant a TCP connection.","body":{"code":"2002","slug":"2002","name":"CR_CONNECTION_ERROR","message":"Can't connect to local MySQL server through socket '%s' (%d)","group":"connection","severity":null,"sql_state":null,"summary":"The client tried the local Unix socket and found no server there. The server isn't running, uses another socket path, or you meant a TCP connection.","meaning":"When you connect to `localhost` on Unix, MySQL clients use a Unix socket file instead of TCP. 2002 means the socket file doesn't exist or nothing is listening on it. The number in brackets is the operating-system error, such as `(2)` for no such file, `(13)` for permission denied and `(111)` for connection refused on Linux (`(61)` on macOS). A TCP connection that is refused is error 2003, not 2002.\n\nThis is a client error: the request never reached a server.","causes":["The MySQL server isn't running, or it crashed at startup.","The server's socket is in a different place than the client expects (for example `/var/run/mysqld/mysqld.sock` versus `/tmp/mysql.sock`).","The server runs in Docker or on another machine, so there is no local socket; you need TCP.","Permissions on the socket directory stop the client from reaching it."],"fix":[{"text":"Check that the server is running and read its error log if it isn't, for example with `systemctl status mysql` on Linux or `brew services list` on macOS.","sql":null},{"text":"Connect over TCP instead of the socket by using `127.0.0.1` rather than `localhost`, or `--protocol=TCP`.","sql":"mysql -h 127.0.0.1 -P 3306 -u app -p"},{"text":"If the server runs locally, find its socket path and point the client at it.","sql":"-- On the server:\nSHOW VARIABLES LIKE 'socket';\n-- Client:\nmysql --socket=/var/run/mysqld/mysqld.sock -u app -p"}],"diagnostic":"-- On the server, from another way in: where is the socket supposed to be?\nSHOW VARIABLES LIKE 'socket';\n# From the shell: does the file exist and is mysqld running?\n# ls -l /tmp/mysql.sock /var/run/mysqld/mysqld.sock 2>/dev/null; ps aux | grep '[m]ysqld'","alternatives":"Connecting to 127.0.0.1 instead of localhost forces TCP and sidesteps the socket path entirely. If the server is local, aligning the socket path under both [client] and [mysqld] in my.cnf makes client and server agree for good.","details":[],"details_title":null,"repro":"# Shell repro (2002 happens before any SQL reaches a server):\nbrew services stop mysql   # or systemctl stop mysql on Linux\nmysql -u root\n# ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)","repro_note":null,"related":["mysql/2003","mysql/2005","mysql/2013","sql-server/53","postgresql/08006"],"sqlly":"SQLly's connection test shows whether the server answered, the round-trip time and the exact last error, so you can tell a server that isn't there from one rejecting your login.","faqs":[{"question":"Why does localhost fail but 127.0.0.1 work?","answer":"On Unix, localhost means the socket file while 127.0.0.1 means TCP. A socket path mismatch between client and server breaks the first but not the second, which makes TCP the fastest workaround."},{"question":"The socket file is gone. Is the server broken?","answer":"Usually the server just isn't running, or it was configured with a different socket path. Start it and read the error log, which names the socket file it actually created."},{"question":"What does the number in parentheses mean?","answer":"An operating-system error: 2 is no such file, 13 is permission denied, 111 is connection refused on Linux (61 on macOS). Permission denied points at permissions on the socket directory rather than at the server."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2002","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2003","corpus":"errors","engine":"mysql","language":"en","title":"Can't connect to MySQL server on host","description":"The client couldn't open a TCP connection to the host and port. The server is down, listens elsewhere, or a firewall is in the way.","body":{"code":"2003","slug":"2003","name":"CR_CONN_HOST_ERROR","message":"Can't connect to MySQL server on '%s:%u' (%d)","group":"connection","severity":null,"sql_state":null,"summary":"The client couldn't open a TCP connection to the host and port. The server is down, listens elsewhere, or a firewall is in the way.","meaning":"2003 is raised by the client when the TCP connection itself fails. The number in brackets is the operating-system error, and the values differ by platform: on Linux `(111)` means connection refused (nothing listening), `(110)` means timed out (usually a firewall dropping packets) and `(113)` means no route to host; macOS reports 61, 60 and 65 for the same cases, Windows 10061 and 10060.\n\nThe server never saw the login, so the password and grants don't matter yet.","causes":["The server isn't running, or listens on another port than 3306.","The server only listens on `127.0.0.1` (`bind_address`), so remote connections are refused.","A firewall, security group or cloud network rule blocks port 3306.","Wrong host name or IP address in the connection settings."],"fix":[{"text":"On the server, check that MySQL is running and which address and port it listens on.","sql":"SHOW VARIABLES WHERE Variable_name IN ('bind_address', 'port', 'skip_networking');"},{"text":"To accept remote connections, set `bind_address = 0.0.0.0` (or the server's own IP) in the `[mysqld]` section of the configuration file and restart MySQL. Make sure an account exists for the remote host.","sql":null},{"text":"Open the port in the server's firewall and any cloud security group, then test from the client machine, for example with `nc -vz db.example.com 3306`.","sql":null}],"diagnostic":"-- On the server, if you can get in locally: is TCP on, and where?\nSHOW VARIABLES WHERE Variable_name IN ('port', 'bind_address', 'skip_networking');\n-- skip_networking = 1 means TCP is off entirely.\n# From the client machine, test the port directly:\n# nc -vz db.example.com 3306","alternatives":"If the port can't be opened, an SSH tunnel is the standard workaround: ssh -L 3306:localhost:3306 user@db-server, then connect to 127.0.0.1 as if the server were local. For containers, publish the port with -p 3306:3306 instead of reaching the container's internal IP from outside.","details":[],"details_title":null,"repro":"# Shell repro (the TCP connect fails before MySQL sees anything):\nmysql -h 127.0.0.1 -P 3307 -u root\n# With nothing listening on 3307:\n# ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3307' (61 on macOS, 111 on Linux)","repro_note":null,"related":["mysql/2002","mysql/2005","mysql/1130","mysql/2013","sql-server/53","postgresql/08006","oracle/ora-12541"],"sqlly":"SQLly's connection test shows whether the server answered, the round-trip time and the exact last error, so you can see at once whether the problem is the network or the login.","faqs":[{"question":"Connection refused on my own machine, but MySQL is installed. Now what?","answer":"The server process is most likely not running. Check the service status (systemctl status mysql, brew services list) and the error log; a startup that failed partway explains a refused connection."},{"question":"Why does it work on the server itself but not from my machine?","answer":"Three usual answers: bind_address limits listening to 127.0.0.1, a firewall or cloud security group blocks 3306, or no account exists for your client host (that last one shows up as 1130 or 1045, after the port is open). nc -vz tells you which half is failing."},{"question":"Could my password be wrong?","answer":"No. The TCP connection never completed, so the server never asked for credentials. Fix the network first; auth problems surface later as 1045."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2003","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2005","corpus":"errors","engine":"mysql","language":"en","title":"Unknown MySQL server host","description":"The client couldn't resolve the host name to an address. Check the spelling, DNS, and whether the name only resolves inside a VPN or a Docker network.","body":{"code":"2005","slug":"2005","name":"CR_UNKNOWN_HOST","message":"Unknown MySQL server host '%s' (%d)","group":"connection","severity":null,"sql_state":null,"summary":"The client couldn't resolve the host name to an address. Check the spelling, DNS, and whether the name only resolves inside a VPN or a Docker network.","meaning":"Before connecting, the client looks up the host name. 2005 means that lookup failed, so no connection was attempted. The number in parentheses is the resolver's error code.","causes":["A typo in the host name, or a scheme or port pasted into the host field (`mysql://db:3306`).","The name only resolves on a private network or VPN you're not connected to.","A Docker Compose service name used from outside the Compose network, where it doesn't resolve.","DNS problems on the client machine."],"fix":[{"text":"Check that the name resolves from the client machine, for example with `nslookup db.example.com` or `ping db.example.com`.","sql":null},{"text":"Put only the host name in the host field and the port in the port field.","sql":null},{"text":"From the host machine, a container's port is reached through `127.0.0.1` and the published port, not the service name.","sql":null}],"diagnostic":"-- There is no SQL to run; the lookup failed before connecting.\n# From the shell on the client machine:\n# nslookup db.example.com\n# getent hosts db.example.com   -- Linux\n# ping -c1 db.example.com       -- confirms resolution, not MySQL reachability","alternatives":"Use the IP address to rule out DNS, or add an /etc/hosts entry for a name that stays stable. In Docker Compose, service names resolve only inside the Compose network; from the host machine, connect to 127.0.0.1 and the published port.","details":[],"details_title":null,"repro":"# Shell repro (this fails in DNS before any connection attempt):\nmysql -h no-such-host.example -u root\n# ERROR 2005 (HY000): Unknown MySQL server host 'no-such-host.example' (-2)","repro_note":null,"related":["mysql/2003","mysql/2002","oracle/ora-12154"],"sqlly":"SQLly's connection form checks the host name's text before saving a profile. The DNS lookup happens when you test or connect, and a resolver failure then shows as 'the host name ... could not be found', so a DNS or VPN problem is named at connect time.","faqs":[{"question":"The name resolves with ping, but the client still fails. Why?","answer":"Check that the client isn't being handed a mangled value, like a URL with a scheme or an embedded port pasted into the host field. Some drivers cache DNS, so a restart of the app may be needed to pick up a fixed record."},{"question":"Why does the container name work for my teammate and not me?","answer":"Docker Compose service names resolve only inside their network. Your teammate is probably running the client in a container on that network; from the host, use 127.0.0.1 and the published port."},{"question":"Is this a MySQL problem?","answer":"No. The client never opened a connection; the operating system's resolver failed first. Nothing on the MySQL side can cause 2005."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2005","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2006","corpus":"errors","engine":"mysql","language":"en","title":"MySQL server has gone away","description":"The connection was closed before or while the client sent a command: an idle timeout, a packet bigger than max_allowed_packet, or a server restart.","body":{"code":"2006","slug":"2006","name":"CR_SERVER_GONE_ERROR","message":"MySQL server has gone away","group":"connection","severity":null,"sql_state":null,"summary":"The connection was closed before or while the client sent a command: an idle timeout, a packet bigger than max_allowed_packet, or a server restart.","meaning":"The client tried to use a connection the server had already closed. MySQL closes connections that sit idle longer than `wait_timeout` (8 hours by default), kills connections that send a packet larger than `max_allowed_packet`, and drops all of them when it restarts or crashes.\n\nThe statement you just sent didn't run, unless the connection dropped while it was running, in which case you may see 2013 instead.","causes":["An application or pool kept a connection idle longer than `wait_timeout` or `interactive_timeout`.","A query or `INSERT` with a large BLOB or a big multi-row statement exceeded `max_allowed_packet`.","The server restarted, ran out of memory, or the connection was killed with `KILL`.","A proxy, load balancer or firewall dropped an idle TCP connection."],"fix":[{"text":"Check the server's limits.","sql":"SHOW VARIABLES WHERE Variable_name IN ('wait_timeout', 'interactive_timeout', 'max_allowed_packet');"},{"text":"If large statements are the cause, raise `max_allowed_packet` on the server (and in the client, which has its own limit).","sql":"SET GLOBAL max_allowed_packet = 64 * 1024 * 1024;  -- new connections only; also set it in my.cnf"},{"text":"In applications, let the pool validate or recycle connections before `wait_timeout` (for example a max lifetime a little below it), and reconnect and retry when a connection turns out to be dead.","sql":null},{"text":"Read the server error log around the time of the failure to rule out a crash or restart.","sql":null}],"diagnostic":"-- Is the connection actually dead? If this fails, yes.\nSELECT 1;\n-- The limits that close idle or oversized connections:\nSHOW VARIABLES WHERE Variable_name IN ('wait_timeout', 'interactive_timeout', 'max_allowed_packet');\n-- Did the server restart? A small Uptime means yes.\nSHOW GLOBAL STATUS LIKE 'Uptime';","alternatives":"When a pool keeps losing idle connections, set its max lifetime below wait_timeout instead of raising the timeout; many pools can also validate or ping a connection on checkout. If big BLOBs trigger it, compressing or streaming the payload is often better than raising max_allowed_packet on every tier.","details":[],"details_title":null,"repro":"-- Shorten the session's idle limit, go past it, then use the connection again.\nSET SESSION wait_timeout = 2;\nSELECT 1;\n-- Stay idle for more than 2 seconds, then send the next statement (the mysql CLI must run with --skip-reconnect, otherwise it reconnects silently):\nSELECT 1;  -- ERROR 4031 (HY000): The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.","repro_note":null,"related":["mysql/2013","mysql/1153","mysql/4031","mysql/2055","postgresql/08006","oracle/ora-03113"],"sqlly":"SQLly detects a dead connection when a tab regains focus and offers reconnect-and-replay of the failed statement, with the server's wait_timeout shown alongside.","faqs":[{"question":"Did my statement run or not?","answer":"With 2006 the client couldn't deliver the statement, so treat it as not run, unless the drop happened after the server committed but before the response arrived. Check the data before retrying writes; 2013 is the variant where the drop happened during the query."},{"question":"2006 vs 2013: what's the difference?","answer":"2006 means the server was already gone when you sent the statement; 2013 means the connection broke while a statement was in flight. The causes overlap (idle timeout, restart, packet limits), so the server error log settles which one you had."},{"question":"I get it every morning. Why?","answer":"Connections idle overnight and cross wait_timeout, and NAT gateways or load balancers often drop idle TCP even sooner. Recycle or validate pooled connections before reuse rather than raising timeouts."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2006","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2013","corpus":"errors","engine":"mysql","language":"en","title":"Lost connection to MySQL server during query","description":"The connection dropped while a query was running or results were being read: a server timeout, a killed query, a crash, or a network or proxy timeout.","body":{"code":"2013","slug":"2013","name":"CR_SERVER_LOST","message":"Lost connection to MySQL server during query","group":"connection","severity":null,"sql_state":null,"summary":"The connection dropped while a query was running or results were being read: a server timeout, a killed query, a crash, or a network or proxy timeout.","meaning":"2013 is raised by the client when the connection breaks in the middle of a query. The server may have finished the statement, partly run it, or never started it, so you can't assume either way; for writes, check the data before retrying.\n\nVariants of the message add `at 'reading initial communication packet'` (the server closed the connection right after accepting it) or `at 'reading authorization packet'`, which point at connection setup rather than the query.","causes":["The query ran longer than a client, proxy or load-balancer read timeout.","Sending a result took longer than `net_write_timeout`, for example when the client reads a big result slowly.","The query was killed (`KILL`) or the server crashed or restarted; check the server error log. A `max_execution_time` timeout does not cause 2013: it raises error 3024 and keeps the connection open.","During connection setup: the server rejected the host, or `connect_timeout` was too short on a slow network."],"fix":[{"text":"Look at the server error log and `SHOW PROCESSLIST` to see whether the server restarted or the query is still running.","sql":null},{"text":"Raise the timeouts that apply to long queries and slow clients.","sql":"SHOW VARIABLES LIKE 'net_%_timeout';\nSET GLOBAL net_read_timeout = 120;\nSET GLOBAL net_write_timeout = 120;"},{"text":"Raise the read timeout on the client side too (your driver's socket or read timeout, and any proxy in between).","sql":null},{"text":"Make the query faster or smaller: add indexes, page through big results, or batch large writes.","sql":null}],"diagnostic":"-- Did the server restart or crash? A small Uptime means yes.\nSHOW GLOBAL STATUS LIKE 'Uptime';\n-- Timeouts that break long queries and slow result reads:\nSHOW VARIABLES WHERE Variable_name IN ('net_read_timeout', 'net_write_timeout', 'connect_timeout', 'max_execution_time');\n-- The 'reading initial communication packet' variant points at setup, not your query.\n-- The server error log around the failure time is the deciding evidence.","alternatives":"If the result set is the problem, page through it with LIMIT and a keyset condition instead of fetching millions of rows in one go. If a driver or proxy timeout is the problem, raise it there; no server setting helps when a middle hop closes the connection first.","details":[],"details_title":null,"repro":"-- Two sessions. Session A runs a long query; session B kills A's connection.\n-- Session B, find A's connection id:\nSHOW PROCESSLIST;\n-- Session B, kill it (use A's id):\nKILL 42;\n-- Session A, mid-query, then reports:\n-- ERROR 2013 (HY000): Lost connection to MySQL server during query","repro_note":null,"related":["mysql/2006","mysql/2055","mysql/1159","mysql/3024","postgresql/08006","oracle/ora-03113"],"sqlly":"SQLly's query history keeps the interrupted statement with its timestamp, so you can compare it against the server log's restart time before deciding to retry a write.","faqs":[{"question":"Did my INSERT commit before the connection dropped?","answer":"Maybe. The server may have finished the statement before the client noticed the drop. Check the table, or the binary log, before retrying; retrying blind is how you get duplicate rows."},{"question":"It says 'reading initial communication packet'. Is that my query?","answer":"No. That variant means the server closed the connection right after accepting it, before your query was sent. Usual causes: your host is blocked after repeated failed connections (the error log says 'blocked because of many connection errors', clear it with mysqladmin flush-hosts) or connect_timeout is too short."},{"question":"Can I just retry?","answer":"For reads, usually yes. For writes, confirm the first attempt's outcome first. 2013 gives you no promise either way, which is exactly why the check matters."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2013","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2026","corpus":"errors","engine":"mysql","language":"en","title":"SSL connection error","description":"The TLS handshake between client and MySQL server failed: a certificate the client won't trust, mismatched TLS versions, or SSL required but disabled.","body":{"code":"2026","slug":"2026","name":"CR_SSL_CONNECTION_ERROR","message":"SSL connection error: %s","group":"connection","severity":null,"sql_state":null,"summary":"The TLS handshake between client and MySQL server failed: a certificate the client won't trust, mismatched TLS versions, or SSL required but disabled.","meaning":"The client and server couldn't set up an encrypted connection. The text after `SSL connection error:` is the TLS library's reason, for example a certificate verification failure or no common protocol version, and is the part to read.","causes":["The client verifies the server certificate (`--ssl-mode=VERIFY_CA` or `VERIFY_IDENTITY`) and the certificate is self-signed or the host name doesn't match.","The client is configured to require TLS and the server has it disabled.","An old client or server only supports TLS versions the other side has turned off.","Wrong paths or permissions for the CA, certificate or key files."],"fix":[{"text":"Check what the server offers.","sql":"SHOW VARIABLES LIKE '%ssl%';\nSHOW VARIABLES LIKE 'tls_version';"},{"text":"Give the client the CA certificate that signed the server's certificate, for example `mysql --ssl-mode=VERIFY_CA --ssl-ca=ca.pem -h db.example.com -u app -p`.","sql":null},{"text":"If both sides are old, upgrade the client library rather than re-enabling old TLS versions on the server.","sql":null}],"diagnostic":"-- What does the server offer? have_ssl and have_openssl were removed in 8.4;\n-- check the configured TLS versions and certificate files instead:\nSHOW GLOBAL VARIABLES LIKE 'tls_version';\nSHOW GLOBAL VARIABLES LIKE 'ssl_ca';\nSHOW GLOBAL VARIABLES LIKE 'ssl_cert';\n-- Which TLS version and cipher did your session negotiate? (per session, 8.0+):\nSELECT variable_name, variable_value\nFROM performance_schema.session_status\nWHERE variable_name IN ('Ssl_version','Ssl_cipher');\n-- With the user of the session that owns the status, join through threads:\nSELECT t.processlist_user, s.variable_name, s.variable_value\nFROM performance_schema.session_status s\nJOIN performance_schema.threads t ON t.thread_id = s.thread_id\nWHERE s.variable_name IN ('Ssl_version','Ssl_cipher');\n-- From the client, ask for TLS without auth to separate handshake from account problems:\n-- mysql --ssl-mode=REQUIRED -h host -u nosuchuser -p   (1045 here means the handshake succeeded and only the login was refused; 2026 means the handshake itself failed)","alternatives":"If you can't fix the certificate chain quickly, --ssl-mode=REQUIRED (no identity verification) restores encryption without the hostname check, which is still better than DISABLED. Never drop to DISABLED to make the error go away if the traffic leaves the machine.","details":[],"details_title":null,"repro":"-- TLS handshake failures are client-side; no SQL repro on a scratch DB.\n-- Safe repro on a dev server: create a self-signed cert and require verification.\n-- mysql_ssl_rsa_setup (5.7) or the server's auto-generated certs (8.0) give you test certs.\n-- Then force a strict client against a mismatched host name:\nmysql --ssl-mode=VERIFY_IDENTITY --ssl-ca=/var/lib/mysql/ca.pem -h 127.0.0.1 -u root -p\n-- Expected: ERROR 2026 (HY000): SSL connection error: ... certificate verify failed\n-- (the certificate's CN/SAN doesn't contain '127.0.0.1').\n-- For a version mismatch repro, point an old client compiled without TLS 1.2 at a server\n-- with tls_version=TLSv1.2,TLSv1.3.","repro_note":null,"related":["mysql/3159","mysql/2055","mysql/2059"],"sqlly":"SQLly's connection settings expose the TLS mode per profile and show whether TLS is in use after connecting, so a VERIFY_CA failure reads differently from a server without TLS.","faqs":[{"question":"MySQL 5.7 uses --ssl-mode too, right?","answer":"Yes, --ssl-mode exists in 5.7 as well, but 5.7 defaulted to SSL-mode=PREFERRED with auto-generated self-signed certificates, so VERIFY_CA/VERIFY_IDENTITY need the real CA passed explicitly. 8.0 behaves the same way; the difference is mostly that older clients only had --ssl-ca style flags."},{"question":"The error text is empty or says 'unknown protocol'. What now?","answer":"Usually a TLS version mismatch: one side offers only TLSv1.0/1.1 which modern OpenSSL refuses. Check tls_version on the server and the TLS library version your client was built against. Upgrading the client library is the fix; re-enabling old TLS versions on the server should be the last resort."},{"question":"Does 2026 mean my password was wrong?","answer":"No. The handshake failed before any credentials were sent. Fix the certificate and protocol configuration first; authentication comes after."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2026","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2055","corpus":"errors","engine":"mysql","language":"en","title":"Lost connection to MySQL server at stage","description":"The connection broke at a named stage of the protocol, with the operating-system error that caused it. Read the stage to see where it failed.","body":{"code":"2055","slug":"2055","name":"CR_SERVER_LOST_EXTENDED","message":"Lost connection to MySQL server at '%s', system error: %d","group":"connection","severity":null,"sql_state":null,"summary":"The connection broke at a named stage of the protocol, with the operating-system error that caused it. Read the stage to see where it failed.","meaning":"2055 is the extended form of a lost connection: the message names where in the protocol the client was (for example `reading initial communication packet`) and the system error number.\n\nA failure at the initial packet means the server, or something in front of it, closed the connection before the login started.","causes":["A proxy, load balancer or port forward accepts the TCP connection but can't reach MySQL behind it.","The server closes the connection right away, for example because it can't resolve the client's host name in time or `max_connect_errors` blocked the host.","TLS negotiation failing between client and server versions.","Network drops or timeouts between client and server."],"fix":[{"text":"Read the stage and system error in the message, then check the server error log at the same time for a matching line.","sql":null},{"text":"If a host was blocked after too many failed connects, clear the host cache.","sql":"TRUNCATE TABLE performance_schema.host_cache;\n-- FLUSH HOSTS did the same job but was removed in MySQL 8.3 (deprecated in 8.0.23);\n-- it still works on 5.7 and older 8.0 releases. TRUNCATE needs the DROP privilege on\n-- performance_schema.host_cache instead of RELOAD."},{"text":"Test directly against the server (bypassing proxies or tunnels) to find which hop drops the connection.","sql":null}],"diagnostic":"-- Where did it break? The stage in the message tells you the hop.\n-- 'reading initial communication packet' means the TCP connect succeeded but no server greeting arrived.\n-- From the client machine, test whether anything answers on that port:\nnc -vz db.example.com 3306\n-- On the server host, check whether mysqld is listening and on what address:\n-- Linux: ss -lntp | grep 3306\n-- Then check the server error log for lines matching your connection attempt:\n-- tail -n 100 /var/log/mysql/error.log\n-- If the host was blocked by failed connects, the cache shows it (MySQL 8.0+):\nSELECT ip, host, host_validated, sum_connect_errors, count_authentication_errors\nFROM performance_schema.host_cache;","alternatives":"For blocked hosts, TRUNCATE performance_schema.host_cache clears the block without a restart. For flaky networks, raising net_read_timeout or the client's connect timeout hides the symptom but fixes nothing; fix the hop that drops packets.","details":[],"details_title":null,"repro":"-- You can't reproduce 2055 with SQL alone; it needs a mid-handshake connection failure.\n-- Easiest safe repro: point a client at a port where nothing listens.\n-- 1. Note the free port, then run:\nmysql -h 127.0.0.1 -P 3399 -u root -p\n-- Expected: ERROR 2003 first on some platforms, or 2055 at 'reading initial communication packet'\n-- when the port accepts TCP but the server dies mid-response.\n-- 2. Simulate the server dropping you: connect to a real MySQL with an OS firewall rule\n-- that rejects packets after the SYN, or point the client at a proxy that closes the socket.","repro_note":null,"related":["mysql/2013","mysql/2006","mysql/2026","mysql/2003"],"sqlly":"SQLly's connection test surfaces the stage string from the 2055 message ('reading initial communication packet'), which tells you the greeting never arrived and points at a proxy or blocked host.","faqs":[{"question":"Why does it only happen after the server restarts?","answer":"Restarting clears the cached authentication hash and reconnects can race with the server still binding its port. If clients get 2055 in a burst after a restart, retry with backoff rather than reconnecting in a tight loop."},{"question":"Can I turn on error 2055 without any proxy involved?","answer":"The mysql 8.4 CLI and mysqlsh report the same message text under error 2013 when the server closes before the greeting, so check the error code your client library actually reports. A firewall that drops packets after the TCP handshake is the other common cause; this was not tested."},{"question":"Does FLUSH HOSTS still work in MySQL 8.0?","answer":"Not on MySQL 8.4 and later, where it is rejected with a syntax error. It was deprecated in 8.0.23 and still works on 8.0 releases before 8.4. Use TRUNCATE TABLE performance_schema.host_cache instead; it needs the DROP privilege on that table rather than RELOAD. On 5.7 and older 8.0 releases FLUSH HOSTS still works."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2055","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2059","corpus":"errors","engine":"mysql","language":"en","title":"Authentication plugin cannot be loaded","description":"The account uses an authentication plugin the client library doesn't have, typically caching_sha2_password with an older client or connector.","body":{"code":"2059","slug":"2059","name":"CR_AUTH_PLUGIN_CANNOT_LOAD","message":"Authentication plugin '%s' cannot be loaded: %s","group":"connection","severity":null,"sql_state":null,"summary":"The account uses an authentication plugin the client library doesn't have, typically caching_sha2_password with an older client or connector.","meaning":"Each MySQL account has an authentication plugin. Since MySQL 8.0 the default is `caching_sha2_password`. A client library that doesn't include that plugin (older libmysqlclient, older MariaDB clients, some older drivers) can't complete the login and reports 2059 with the plugin name.","causes":["Connecting to MySQL 8.0 or later with a client or connector built for MySQL 5.7 or earlier.","A MariaDB client library talking to MySQL 8 without the plugin installed.","The account was created with a plugin such as `authentication_ldap_sasl` that the client doesn't ship."],"fix":[{"text":"Upgrade the client library or driver to a version that supports `caching_sha2_password`. This is the proper fix.","sql":null},{"text":"Check which plugin the account uses.","sql":"SELECT user, host, plugin FROM mysql.user WHERE user = 'app';"},{"text":"If you can't upgrade the client, switch that account to `mysql_native_password`, where your server still supports it. It is deprecated in MySQL 8.0 and disabled by default in 8.4.","sql":"ALTER USER 'app'@'%' IDENTIFIED WITH mysql_native_password BY 'password';"}],"diagnostic":"-- Which plugin does the account want?\nSELECT user, host, plugin FROM mysql.user WHERE user = 'plugtest';\n-- Which plugins does the server actually have loaded?\nSHOW PLUGINS;\nSELECT plugin_name, plugin_status FROM information_schema.plugins\nWHERE plugin_type = 'AUTHENTICATION';\n-- Then check the client side: for libmysqlclient, plugins live in the path from\n-- mysql_get_client_version()-matched PLUGIN_DIR; for Connector/J 8+, caching_sha2_password is built in.","alternatives":"If the driver can't be upgraded, ALTER USER ... IDENTIFIED WITH mysql_native_password switches the account to a plugin nearly every client supports. That is deprecated in 8.0 and off by default in 8.4, so treat it as a bridge. For MariaDB clients, the MariaDB Connector/C caching_sha2 plugin can sometimes be dropped into the plugin directory instead.","details":[],"details_title":null,"repro":"-- No SQL-only repro; 2059 comes from the client library, not the server.\n-- The server refuses a plugin it has not loaded, so this fails before any client sees it:\nCREATE USER 'plugtest'@'localhost' IDENTIFIED WITH authentication_fido;\n-- ERROR 1524 (HY000): Plugin 'authentication_fido' is not loaded\n-- (8.0.27+; pick authentication_ldap_sasl if you have the plugin installed instead.)\n-- Then try to log in from a client built without that plugin. The client reports 2059 naming the plugin.\nDROP USER 'plugtest'@'localhost';","repro_note":null,"related":["mysql/1251","mysql/2061","mysql/1045"],"sqlly":"SQLly ships a current client library, so `caching_sha2_password` accounts connect without the plugin errors older drivers raise.","faqs":[{"question":"I got 2059 with caching_sha2_password but the docs say every modern client has it. Why?","answer":"Older bundled libraries don't. PHP's mysqlnd before PHP 7.4, the Node.js 'mysql' package, and some distro builds of libmysqlclient 5.7 lack it. Check the exact version of the library your process links against, not the server version."},{"question":"Can I install the plugin on the client instead of changing the user?","answer":"Often yes. libmysqlclient loads client-side plugins from its plugin dir, and Connector/J and Connector/NET ship caching_sha2_password built in from certain versions on. Upgrading the connector is usually simpler than extracting plugins."},{"question":"Does this error expose anything about the password?","answer":"No. It happens before any credential exchange; the client can't even start the agreed authentication method."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2059","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/2061","corpus":"errors","engine":"mysql","language":"en","title":"Authentication plugin reported error","description":"The authentication plugin failed during login. With caching_sha2_password this is usually a request for a secure connection to send the password.","body":{"code":"2061","slug":"2061","name":"CR_AUTH_PLUGIN_ERR","message":"Authentication plugin '%s' reported error: %s","group":"connection","severity":null,"sql_state":null,"summary":"The authentication plugin failed during login. With caching_sha2_password this is usually a request for a secure connection to send the password.","meaning":"The client had the plugin but the plugin refused to go on. The most common text is `Authentication requires secure connection.` from `caching_sha2_password`: when the server has no cached hash for the account, the password must travel over TLS or be encrypted with the server's RSA public key, and the client was set up for neither.","causes":["Connecting with TLS disabled (`--ssl-mode=DISABLED`) to an account using `caching_sha2_password` whose hash isn't cached yet, for example after a server restart.","A driver option that turns off TLS and doesn't allow fetching the server's public key."],"fix":[{"text":"Connect with TLS. Make sure the client's ssl-mode is not DISABLED (check the client's default).","sql":null},{"text":"If you can't use TLS, let the client fetch the server's RSA key: `--get-server-public-key` for the mysql client, or the driver's equivalent (`allowPublicKeyRetrieval=true` in Connector/J).","sql":null},{"text":"Log in once over TLS; the server then caches the hash and later non-TLS logins can succeed until the cache is cleared (a restart, FLUSH PRIVILEGES, or changing or dropping that account).","sql":null}],"diagnostic":"-- Confirm the account uses caching_sha2_password:\nSELECT user, host, plugin FROM mysql.user WHERE user = 'sectest';\n-- Confirm TLS is actually off on the failing connection:\n-- On the client: mysql --ssl-mode=DISABLED ... then after connecting (if it succeeds):\nSHOW STATUS LIKE 'Ssl_version';   -- empty or 'None' means no TLS\n-- On the server, watch failed logins with the reason (8.0):\nSELECT * FROM performance_schema.host_cache WHERE host_validated <> ''\\G\n-- And grep the error log for 'Authentication requires secure connection' alongside your timestamp.","alternatives":"If TLS genuinely can't be enabled on that hop, allowPublicKeyRetrieval=true (Connector/J), --get-server-public-key (mysql client), or allow_public_key_retrieval in other drivers lets the RSA path work. Be aware this trusts the server key on first use without a CA. An RSA public key file shipped to the client (--server-public-key-path) avoids that trust-on-first-use exposure.","details":[],"details_title":null,"repro":"-- Requires a real server and a client; not reproducible with SQL alone.\n-- Safe repro on a dev server: an account with caching_sha2_password, no TLS, no RSA key retrieval.\nCREATE USER 'sectest'@'%' IDENTIFIED BY 'S3cure-pass!';\n-- Restart the server, run FLUSH PRIVILEGES, or just\n-- use a fresh account, then connect with TLS off:\n-- mysql --ssl-mode=DISABLED --skip-get-server-public-key -h 127.0.0.1 -u sectest -p\n-- Depending on client version you'll see 2061 'Authentication requires secure connection.'\n-- Connecting once WITH TLS, then retrying without it, succeeds until the next restart.\nDROP USER 'sectest'@'localhost';","repro_note":null,"related":["mysql/2059","mysql/1251","mysql/2026"],"sqlly":"SQLly's connection error panel shows the plugin's full message and lets you retry the profile with TLS required, which resolves the `caching_sha2_password` full-authentication case.","faqs":[{"question":"Why did it work yesterday and fail after the deploy?","answer":"Common pattern: the deploy restarted MySQL, clearing the server's cached fast-auth entry, and the connection also lost TLS somewhere in the new configuration. The first login after a restart needs the full RSA exchange, which requires either TLS or explicit public key retrieval."},{"question":"Is full authentication over plain TCP dangerous?","answer":"Yes. Without TLS the password can be obfuscated with the server's RSA public key, but you have no server identity check, so an active man-in-the-middle could capture traffic. Use TLS if the connection crosses any network you don't fully control."},{"question":"Does this happen with mysql_native_password accounts?","answer":"No. The secure-transport requirement is specific to caching_sha2_password's full authentication path."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/2061","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/3024","corpus":"errors","engine":"mysql","language":"en","title":"Maximum statement execution time exceeded","description":"A SELECT ran longer than max_execution_time (or a MAX_EXECUTION_TIME hint) and the server stopped it.","body":{"code":"3024","slug":"3024","name":"ER_QUERY_TIMEOUT","message":"Query execution was interrupted, maximum statement execution time exceeded","group":"locking","severity":null,"sql_state":"HY000","summary":"A SELECT ran longer than max_execution_time (or a MAX_EXECUTION_TIME hint) and the server stopped it.","meaning":"MySQL can cap how long a read-only `SELECT` may run, through the `max_execution_time` variable (in milliseconds; 0 means no limit) or a `MAX_EXECUTION_TIME(n)` optimizer hint. When the limit passes, the statement is interrupted with 3024. It doesn't apply to writes or to `SELECT` inside stored programs.","causes":["A slow query hitting a limit set for the session or the server.","A hosting provider or proxy that sets `max_execution_time`."],"fix":[{"text":"Check the limit.","sql":"SELECT @@max_execution_time;"},{"text":"Speed the query up: look at its plan, add indexes, page through results.","sql":"EXPLAIN ANALYZE SELECT ...;"},{"text":"Raise the limit for one query when it really needs longer.","sql":"SELECT /*+ MAX_EXECUTION_TIME(60000) */ COUNT(*) FROM events;"}],"diagnostic":"-- What limit applies to this session?\nSELECT @@max_execution_time;\n-- The limit is the global or session variable plus any MAX_EXECUTION_TIME(n) hint in the\n-- statement itself; there is no per-account max_execution_time setting.\n-- Does the query have its own hint? Search the SQL text for MAX_EXECUTION_TIME.\n-- Then see where the time actually goes:\nEXPLAIN ANALYZE SELECT COUNT(*) FROM events WHERE created_at < '2023-01-01';","alternatives":"If the query is a legitimate long report, run it with an explicit larger MAX_EXECUTION_TIME hint, or page through results with keyset pagination (WHERE id > last_id ORDER BY id LIMIT n) so each statement is short. For nightly reports, a scheduled job with its own session settings beats raising the global limit.","details":[],"details_title":null,"repro":"CREATE TABLE slow_t (id INT PRIMARY KEY, a INT, b INT);\nSET SESSION cte_max_recursion_depth = 1000000;\nINSERT INTO slow_t\nWITH RECURSIVE seq AS (SELECT 1 AS n UNION ALL SELECT n + 1 FROM seq WHERE n < 1000000)\nSELECT n, n, n FROM seq;\nSET SESSION max_execution_time = 100; -- 100 ms\nSELECT SLEEP(2) FROM slow_t LIMIT 1; -- ERROR 3024 after 100 ms\nSET SESSION max_execution_time = 0; -- back to no limit","repro_note":null,"related":["mysql/2013","postgresql/57014"],"sqlly":"SQLly can show a query's execution plan for MySQL with findings such as full table scans, and it cancels a running query on the server (KILL QUERY) when you stop it.","faqs":[{"question":"Does max_execution_time kill UPDATE and DELETE statements?","answer":"No. It only applies to read-only SELECT statements. SELECT statements inside stored programs are also exempt. Long-running writes need a different tool, such as pt-kill or your own timeout on the connection."},{"question":"Is max_execution_time in seconds or milliseconds?","answer":"Milliseconds, both in the system variable and in the MAX_EXECUTION_TIME hint. 30000 is 30 seconds. 0 means no limit."},{"question":"Which versions support this?","answer":"max_execution_time and the hint arrived in MySQL 5.7.8. EXPLAIN ANALYZE, used above to see where time goes, needs MySQL 8.0.18 or newer; on 5.7 use plain EXPLAIN."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/3024","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/3159","corpus":"errors","engine":"mysql","language":"en","title":"Insecure transport prohibited","description":"The server has require_secure_transport turned on and the client connected without TLS. Connect with TLS or a local socket.","body":{"code":"3159","slug":"3159","name":"ER_SECURE_TRANSPORT_REQUIRED","message":"Connections using insecure transport are prohibited while --require_secure_transport=ON.","group":"connection","severity":null,"sql_state":"HY000","summary":"The server has require_secure_transport turned on and the client connected without TLS. Connect with TLS or a local socket.","meaning":"With `require_secure_transport = ON`, MySQL accepts only connections using TLS, a Unix socket or shared memory. A plain TCP connection is rejected at login with 3159, or with 2061 (caching_sha2_password needs a secure channel for a password on a cold cache). Many managed MySQL services turn this on by default.","causes":["A client or driver with TLS disabled (`--ssl-mode=DISABLED`, `useSSL=false`).","An old client that doesn't negotiate TLS.","Connecting through a tool configured to never use TLS."],"fix":[{"text":"Enable TLS in the client, for example `mysql --ssl-mode=REQUIRED -h db.example.com -u app -p`, or your driver's TLS option.","sql":null},{"text":"If you control the server and the network is trusted, you can turn the requirement off.","sql":"SET PERSIST require_secure_transport = OFF;"}],"diagnostic":"-- Confirm the server policy:\nSHOW VARIABLES LIKE 'require_secure_transport';\n-- After a successful connection, confirm TLS was actually used (not a local socket exception):\nSHOW SESSION STATUS LIKE 'Ssl_version';\nSHOW SESSION STATUS LIKE 'Ssl_cipher';\n-- Which accounts are affected? All of them, when the global is ON. Per-account control\n-- isn't a thing for this variable; it is server-wide in both 5.7 and 8.0.\n-- If a job or host suddenly fails, check what changed: a driver flag like useSSL=false,\n-- a JDK upgrade disabling old TLS versions, or a load balancer that strips TLS.","alternatives":"If one legacy client can't do TLS but everything else must stay locked down, you can't exempt a single account from require_secure_transport. Options: fix or upgrade that client, move it onto the same host and use the Unix socket (which counts as secure), or front it with a local TLS-terminating proxy such as ProxySQL that speaks TLS to the server.","details":[],"details_title":null,"repro":"-- Safe on a scratch server.\nSET PERSIST require_secure_transport = ON;   -- SET GLOBAL on 5.7\n-- From a client with TLS off:\n-- mysql --ssl-mode=DISABLED -h 127.0.0.1 -u root -p\n-- Expected: ERROR 3159 (HY000): Connections using insecure transport are prohibited\n-- while --require_secure_transport=ON.\n-- Same connection with --ssl-mode=REQUIRED (default direction on modern clients) succeeds.\n-- Cleanup: SET PERSIST require_secure_transport = OFF;","repro_note":null,"related":["mysql/2026","mysql/1045"],"sqlly":"SQLly's profile stores the TLS mode explicitly, so a server with require_secure_transport=ON is met with a REQUIRED setting rather than a plaintext attempt.","faqs":[{"question":"Does a Unix socket connection violate require_secure_transport?","answer":"No. Unix domain sockets and shared memory count as secure transport, so localhost socket connections are allowed with the setting ON."},{"question":"TLS is on in my driver but I still get 3159.","answer":"Verify the negotiation actually happened: connect and run SHOW SESSION STATUS LIKE 'Ssl_version'. Some drivers only request TLS when a certificate option is set, or fall back to plaintext silently when SSL_FAILED isn't fatal. Connector/J for example needs useSSL=true (or sslMode) explicitly on older versions."},{"question":"Where did this requirement come from if I didn't set it?","answer":"Managed MySQL services (Azure Database for MySQL, Google Cloud SQL options) enable require_secure_transport by default and sometimes lock the variable. Check SHOW VARIABLES; if it is read-only on your platform, the fix has to be on the client side."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/3159","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/3572","corpus":"errors","engine":"mysql","language":"en","title":"Lock couldn't be acquired with NOWAIT","description":"A SELECT ... FOR UPDATE NOWAIT or FOR SHARE NOWAIT found a row locked by another transaction and failed at once instead of waiting.","body":{"code":"3572","slug":"3572","name":"ER_LOCK_NOWAIT","message":"Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.","group":"locking","severity":null,"sql_state":"HY000","summary":"A SELECT ... FOR UPDATE NOWAIT or FOR SHARE NOWAIT found a row locked by another transaction and failed at once instead of waiting.","meaning":"`NOWAIT` (MySQL 8.0 and later) tells InnoDB not to wait for row locks. If any row the statement needs is locked, the statement fails immediately with 3572. It's the expected outcome of using `NOWAIT`, which applications use to try something else rather than block.","causes":["Another transaction holds a lock on one of the selected rows.","Several workers trying to claim the same job rows."],"fix":[{"text":"Handle 3572 in code as a busy signal: retry later or pick other work.","sql":null},{"text":"For job queues, `SKIP LOCKED` is usually better: it skips locked rows instead of failing.","sql":"START TRANSACTION;\nSELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED;\n-- process and update the claimed rows\nCOMMIT;"}],"diagnostic":"-- Check the version, NOWAIT and SKIP LOCKED need 8.0\nSELECT @@version;\n-- NOWAIT never waits, so this view stays empty for a 3572; it only shows plain FOR UPDATE waiters. The holder is in data_locks below.\nSELECT waiting_pid, blocking_pid, blocking_query, sql_kill_blocking_connection\nFROM sys.innodb_lock_waits;\n-- All current row locks and the transactions that own them\nSELECT engine_transaction_id, index_name, lock_type, lock_mode, lock_data\nFROM performance_schema.data_locks\nWHERE object_name = 'scratch_3572';\n-- Confirm the statement you ran actually carried NOWAIT\nSHOW PROCESSLIST;","alternatives":"SKIP LOCKED is the usual alternative when the goal is work distribution: it returns unlocked rows instead of failing, so workers stay busy. For a coarse busy check, a fast advisory lock with GET_LOCK(..., 0) returns success or failure without scanning rows at all.","details":[],"details_title":null,"repro":"-- Requires MySQL 8.0+\nCREATE TABLE scratch_3572 (id INT PRIMARY KEY, status VARCHAR(20));\nINSERT INTO scratch_3572 VALUES (1, 'pending');\n-- Session 1: hold the lock\n-- START TRANSACTION;\n-- SELECT * FROM scratch_3572 WHERE id = 1 FOR UPDATE;\n-- Session 2: NOWAIT fails immediately instead of waiting\n-- SELECT * FROM scratch_3572 WHERE id = 1 FOR UPDATE NOWAIT;\n-- ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.\n-- Cleanup: commit session 1, DROP TABLE scratch_3572;","repro_note":null,"related":["mysql/1205","postgresql/55P03","oracle/ora-00054"],"sqlly":"SQLly's activity monitor shows the transaction holding the rows NOWAIT wanted, so the busy signal becomes a name and a decision instead of a dead end.","faqs":[{"question":"Why use NOWAIT at all if it just errors?","answer":"Because waiting is sometimes worse than failing. A dashboard refresh, a health check or a cache warmer should show stale data or return immediately rather than hang behind a long transaction. 3572 is the cheap, immediate signal to do something else."},{"question":"Does 3572 roll back my transaction?","answer":"The NOWAIT statement itself acquires no locks and makes no changes, so there is nothing to roll back from it. Any earlier statements in your transaction are untouched and the transaction stays open."},{"question":"NOWAIT fails on MySQL 5.7. What are my options?","answer":"NOWAIT and SKIP LOCKED arrived in MySQL 8.0.1. On 5.7, lower innodb_lock_wait_timeout to a second or two for that session, or use an application-level lock with GET_LOCK with a zero timeout to get similar fail-fast behavior."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/3572","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/3780","corpus":"errors","engine":"mysql","language":"en","title":"Foreign key columns are incompatible","description":"The referencing and referenced columns of a foreign key have different data types, lengths, signedness or collations.","body":{"code":"3780","slug":"3780","name":"ER_FK_INCOMPATIBLE_COLUMNS","message":"Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible.","group":"constraints","severity":null,"sql_state":"HY000","summary":"The referencing and referenced columns of a foreign key have different data types, lengths, signedness or collations.","meaning":"InnoDB requires the two sides of a foreign key to be compatible: same integer type and signedness, compatible string types with the same character set and collation. 3780 names both columns and the constraint, which makes it much easier to fix than the older 1215.","causes":["`INT` on one side and `BIGINT` or `INT UNSIGNED` on the other.","`VARCHAR` columns with different character sets or collations, for example after converting only one table to `utf8mb4`."],"fix":[{"text":"Compare the two columns.","sql":"SELECT table_name, column_name, column_type, character_set_name, collation_name\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND ((table_name = 'orders' AND column_name = 'customer_id') OR (table_name = 'customers' AND column_name = 'id'));"},{"text":"Change the child column to match the parent, then create the foreign key.","sql":"ALTER TABLE orders MODIFY customer_id BIGINT UNSIGNED NOT NULL;"}],"diagnostic":"-- The error names both columns. Compare them side by side.\nSELECT table_name, column_name, column_type, is_nullable,\n       character_set_name, collation_name\nFROM information_schema.columns\nWHERE table_schema = DATABASE()\n  AND ((table_name = 'child' AND column_name = 'p_id')\n    OR (table_name = 'parent' AND column_name = 'id'));\n\n-- For string keys, check that both tables use the same charset after any conversion.\nSELECT table_name, table_collation FROM information_schema.tables\nWHERE table_schema = DATABASE() AND table_name IN ('parent', 'child');","alternatives":"If the types genuinely differ, widening the child column to the parent's type is usually right; narrowing the parent is not, since it risks changing stored data. For string columns converted halfway through a charset migration, convert the remaining table first and retry.","details":[],"details_title":null,"repro":"CREATE TABLE parent (id BIGINT UNSIGNED PRIMARY KEY);\nCREATE TABLE child (id INT PRIMARY KEY, p_id INT NOT NULL);\nALTER TABLE child ADD CONSTRAINT fk_c\n  FOREIGN KEY (p_id) REFERENCES parent (id);  -- ERROR 3780 (HY000)\nDROP TABLE child, parent;","repro_note":null,"related":["mysql/1215","mysql/1822"],"sqlly":"SQLly's schema browser shows both FK columns' exact types side by side, so the signedness or charset mismatch is visible before the ALTER.","faqs":[{"question":"Which type should I keep, the child's or the parent's?","answer":"Match the child to the parent. The parent's type is set by the data it holds; widening the child column is harmless and future-proof."},{"question":"Do signed and unsigned count as incompatible even at the same width?","answer":"Yes. INT and INT UNSIGNED fail even though both are 4 bytes. MySQL requires the same signedness for foreign key columns."},{"question":"Did this error exist in 5.7?","answer":"No. 5.7 reports 1215 for the same problem. 3780 arrived with the 8.0 data dictionary and is far more useful."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/3780","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/3819","corpus":"errors","engine":"mysql","language":"en","title":"Check constraint is violated","description":"A row breaks a CHECK constraint on the table. MySQL enforces CHECK constraints from version 8.0.16; older versions parsed and ignored them.","body":{"code":"3819","slug":"3819","name":"ER_CHECK_CONSTRAINT_VIOLATED","message":"Check constraint '%s' is violated.","group":"constraints","severity":null,"sql_state":"HY000","summary":"A row breaks a CHECK constraint on the table. MySQL enforces CHECK constraints from version 8.0.16; older versions parsed and ignored them.","meaning":"The row's values made a `CHECK` condition false, so the insert or update was rejected. The message names the constraint. Before 8.0.16 MySQL accepted `CHECK` clauses but didn't enforce them, so data loaded on an old server can break constraints after an upgrade or when the constraint is added.","causes":["Application data that the constraint was written to keep out, such as a negative price.","Adding a `CHECK` constraint to a table with existing rows that violate it."],"fix":[{"text":"See the constraint's condition.","sql":"SELECT constraint_name, check_clause FROM information_schema.check_constraints\nWHERE constraint_schema = DATABASE();"},{"text":"Fix the data, then retry; or find rows that would fail before adding the constraint.","sql":"SELECT * FROM products WHERE NOT (price >= 0);"}],"diagnostic":"-- Which rows in the table already violate the constraint? Run this before adding one or after a failed write\nSELECT * FROM products WHERE price < 0;\n-- See every CHECK constraint and its expression\nSELECT tc.constraint_name, cc.check_clause\nFROM information_schema.table_constraints tc\nJOIN information_schema.check_constraints cc\n  ON cc.constraint_schema = tc.constraint_schema\n AND cc.constraint_name = tc.constraint_name\nWHERE tc.constraint_schema = DATABASE()\n  AND tc.constraint_type = 'CHECK'\n  AND tc.table_name = 'products';\n-- Was the constraint enforced at all on this server? CHECK is ignored before 8.0.16\nSELECT @@version;\n-- Confirm it is active\nSELECT enforced FROM information_schema.table_constraints\nWHERE constraint_schema = DATABASE() AND constraint_name = 'chk_price';","alternatives":"If the constraint is too strict for real data, drop and re-add it with a corrected expression: ALTER TABLE products DROP CHECK chk_price; then ADD CONSTRAINT ... CHECK (...). You can also add it as NOT ENFORCED in 8.0.16+ to document the rule without blocking writes, which is useful while you clean up historical data.","details":[],"details_title":null,"repro":"USE your_database;\nCREATE TEMPORARY TABLE t (price DECIMAL(10,2), CONSTRAINT chk_price CHECK (price >= 0));\nINSERT INTO t VALUES (-1);  -- ERROR 3819 (HY000): Check constraint 'chk_price' is violated.","repro_note":null,"related":["mysql/1048","postgresql/23514","sql-server/547","sqlite/sqlite-constraint-check"],"sqlly":"SQLly shows the CHECK expression from information_schema.check_constraints next to the rejected row, so the rule the value broke is right there.","faqs":[{"question":"Why didn't MySQL enforce CHECK constraints before?","answer":"MySQL 5.7 and earlier accepted the CHECK syntax and silently ignored it, for parser compatibility. Enforcement landed in 8.0.16. Data written on 5.7 can violate constraints that 8.0.16+ will reject, which is why upgrades surface 3819."},{"question":"How do I add a CHECK to a table with existing data?","answer":"In 8.0.16+ the table is validated during ADD CONSTRAINT; the statement fails if any row violates it. Find the bad rows first, fix or archive them, then add the constraint. If you need the constraint now and cleanup later, add it NOT ENFORCED and flip it once the data is clean."},{"question":"Is the whole statement rolled back on 3819?","answer":"The offending row's write is rejected. In a multi-row insert with strict mode on, the statement fails and rows already inserted in that statement are rolled back. Under IGNORE, violating rows are skipped with a warning instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/3819","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/mysql/4031","corpus":"errors","engine":"mysql","language":"en","title":"Disconnected by the server for inactivity","description":"The connection sat idle longer than wait_timeout (or interactive_timeout) and the server closed it. Newer servers tell the client why.","body":{"code":"4031","slug":"4031","name":"ER_CLIENT_INTERACTION_TIMEOUT","message":"The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.","group":"connection","severity":null,"sql_state":"HY000","summary":"The connection sat idle longer than wait_timeout (or interactive_timeout) and the server closed it. Newer servers tell the client why.","meaning":"Since MySQL 8.0.24 the server sends this error to a client whose idle connection it is closing, instead of just dropping it. The client sees it on its next command. It's the same situation older versions report as 2006 (server has gone away).","causes":["A connection left idle in a pool or a forgotten interactive session for longer than `wait_timeout` (8 hours by default).","A low `wait_timeout` set by a hosting provider."],"fix":[{"text":"Configure the connection pool to retire or test idle connections before `wait_timeout` runs out.","sql":null},{"text":"Raise the timeout if long idle periods are expected.","sql":"SET PERSIST wait_timeout = 28800;"}],"diagnostic":"-- How long is the idle window that applied to this connection?\nSELECT @@session.wait_timeout, @@global.wait_timeout, @@interactive_timeout;\n-- MySQL has no per-account wait_timeout; the only per-account limits are\n-- MAX_QUERIES_PER_HOUR, MAX_UPDATES_PER_HOUR, MAX_CONNECTIONS_PER_HOUR and MAX_USER_CONNECTIONS.\n-- Is the connection actually gone, or is the network dropping packets?\n-- 4031 means the server closed it deliberately; 2013 with no 4031 in the server log\n-- points at the network or a firewall instead.\nSHOW GLOBAL STATUS LIKE 'Aborted_clients';","alternatives":"The clean fix is on the pool side: set the pool's max idle time below wait_timeout, or enable its keepalive/validation query so connections are tested or refreshed before the server retires them. Raising wait_timeout works but keeps dead connections around longer.","details":[],"details_title":null,"repro":"-- Needs MySQL 8.0.24+.\nCREATE TABLE ping (id INT);\nSET SESSION wait_timeout = 5;\nSELECT 1;\n-- wait 10 seconds without sending anything\nSELECT 1; -- ERROR 4031: client was disconnected because of inactivity","repro_note":null,"related":["mysql/2006","mysql/1159"],"sqlly":"SQLly notices an idled-out connection when a tab regains focus and offers to reconnect and rerun the exact statement, with the profile's wait_timeout shown next to it.","faqs":[{"question":"Is 4031 the same thing as 'MySQL server has gone away'?","answer":"Same situation, clearer message. Before 8.0.24 the server just closed the socket, and the client reported 2013 (Lost connection to MySQL server during query) or 2006 (MySQL server has gone away), depending on whether it was reading or writing. Since 8.0.24 the server tells you why, with a pointer to wait_timeout."},{"question":"Which timeout applies, wait_timeout or interactive_timeout?","answer":"wait_timeout is used for normal client connections. interactive_timeout applies to connections that engaged interactive mode, like the mysql command line. If the two differ, your app is governed by wait_timeout."},{"question":"Can I set the timeout per user instead of globally?","answer":"Not directly for wait_timeout; there is no per-user wait_timeout setting. Set it in the account's connection profile on the client side, or connect the batch job with its own user and SET SESSION wait_timeout after connecting."}],"aliases":[]},"source_url":"https://sqlly.app/errors/mysql/4031","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00001","corpus":"errors","engine":"oracle","language":"en","title":"unique constraint violated","description":"An INSERT or UPDATE would duplicate a value in a primary key or unique constraint or index. The message names the constraint as SCHEMA.NAME.","body":{"code":"ORA-00001","slug":"ora-00001","name":null,"message":"unique constraint (string.string) violated","group":"constraints","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE would duplicate a value in a primary key or unique constraint or index. The message names the constraint as SCHEMA.NAME.","meaning":"ORA-00001 means the statement would create a second row with the same key in a primary key, unique constraint or unique index. The message names the constraint, for example `ORA-00001: unique constraint (SALES.ORDERS_PK) violated`; look it up to see its columns.\n\nRecent releases also name the table and columns: `unique constraint (constraint_schema.constraint_name) violated on table table_schema.table_name columns (column_names)`.","causes":["Inserting a row whose key already exists, for example re-running a load.","A sequence that is behind the data, so `NEXTVAL` produces an id already in the table, typically after data was imported with explicit ids.","Two sessions inserting the same key at once; the second waits and then fails if the first commits.","An `UPDATE` that sets a unique column to a value another row has."],"fix":[{"text":"Find the columns behind the constraint named in the message.","sql":"SELECT table_name, column_name, position\nFROM all_cons_columns\nWHERE owner = 'SALES' AND constraint_name = 'ORDERS_PK'\nORDER BY position;"},{"text":"Insert or update in one statement with `MERGE`.","sql":"MERGE INTO customers c\nUSING (SELECT 'ada@example.com' AS email, 'Ada' AS name FROM dual) s\nON (c.email = s.email)\nWHEN MATCHED THEN UPDATE SET c.name = s.name\nWHEN NOT MATCHED THEN INSERT (email, name) VALUES (s.email, s.name);"},{"text":"If a sequence is behind, move it past the current maximum (18c and later).","sql":"SELECT MAX(id) FROM orders;\nALTER SEQUENCE orders_seq RESTART START WITH 100001;"},{"text":"To skip duplicates in a bulk insert, the `IGNORE_ROW_ON_DUPKEY_INDEX` hint or DML error logging (`LOG ERRORS INTO`) can set the bad rows aside.","sql":null}],"diagnostic":"-- Which table and columns does the named constraint cover?\nSELECT cc.table_name, cc.column_name, cc.position\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nWHERE c.constraint_name = 'ORDERS_PK'\nORDER BY cc.position;\n\n-- Which existing rows already hold the value you tried to insert?\nSELECT * FROM orders WHERE customer_id = 42;\n\n-- Find duplicate values that already exist in the table\nSELECT customer_id, COUNT(*)\nFROM orders\nGROUP BY customer_id\nHAVING COUNT(*) > 1;\n\n-- Where could a conflicting insert come from? Check running sessions\n-- (needs privileges on v$session):\nSELECT s.sid, s.serial#, s.username, s.sql_id, s.status\nFROM v$session s\nWHERE s.username IS NOT NULL\nORDER BY s.sid;","alternatives":"If the duplicate row is legitimate, use MERGE to upsert instead of insert-then-update. If the key is generated, sequence-backed or identity columns avoid the race entirely. If the constraint is wrong for the data, decide whether to drop it (`ALTER TABLE ... DROP CONSTRAINT ...`) or make it deferrable; do not disable it and re-enable without checking for duplicates, because the enable will fail and leave the constraint disabled.","details":[],"details_title":null,"repro":"CREATE TABLE t (id NUMBER PRIMARY KEY);\nINSERT INTO t VALUES (1);\nINSERT INTO t VALUES (1);  -- ORA-00001: unique constraint (...) violated\nDROP TABLE t PURGE;","repro_note":null,"related":["oracle/ora-02291","oracle/ora-01400","postgresql/23505","sql-server/2627","mysql/1062","sqlite/sqlite-constraint-unique"],"sqlly":"SQLly's data grid saves each edited row on its own, so a duplicate key fails on that row's save with the constraint name in the error, not in a batch at the end.","faqs":[{"question":"The row I inserted is not visible when I query. Why the violation?","answer":"Another session inserted a row with the same key but has not committed yet. Your insert waits on the unique index, and when that session commits, you get ORA-00001. If it rolls back instead, your insert succeeds. This is the classic sequence or key-generation race."},{"question":"Can I catch this error in PL/SQL?","answer":"Yes. It is `DUP_VAL_ON_INDEX` in the predefined exceptions: `EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ...`. The SQLCODE is -1, so `WHEN OTHERS` with a `SQLCODE = -1` check works too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00018","corpus":"errors","engine":"oracle","language":"en","title":"maximum number of sessions exceeded","description":"The instance already has as many sessions as the SESSIONS parameter allows, so new connections and recursive sessions are refused.","body":{"code":"ORA-00018","slug":"ora-00018","name":null,"message":"maximum number of sessions exceeded","group":"resources","severity":null,"sql_state":null,"summary":"The instance already has as many sessions as the SESSIONS parameter allows, so new connections and recursive sessions are refused.","meaning":"The `SESSIONS` initialization parameter caps the number of sessions in the instance, including background and recursive sessions. ORA-00018 means that cap is reached.","causes":["Connection pools that open more connections than planned, or leak them.","A `SESSIONS` value too low for the workload.","Many idle sessions left connected by clients."],"fix":[{"text":"Check current usage against the limits.","sql":"SELECT resource_name, current_utilization, max_utilization, limit_value\nFROM v$resource_limit WHERE resource_name IN ('sessions', 'processes');"},{"text":"Cap application pool sizes and close idle connections.","sql":null},{"text":"Raise the limit if needed (takes effect after restart).","sql":"ALTER SYSTEM SET sessions = 1500 SCOPE = SPFILE;"}],"diagnostic":"-- Needs SELECT on v$resource_limit. max_utilization tells you whether the\n-- workload ever came close before, which separates a leak from a too-low limit.\nSELECT resource_name, current_utilization, max_utilization, limit_value\nFROM v$resource_limit\nWHERE resource_name IN ('sessions', 'processes');\n\n-- Who is connected right now, and for how long? Many sessions idle for hours\n-- point at missing idle timeouts in the pool or at forgotten SQL*Plus windows.\nSELECT username, program, COUNT(*) AS sessions, MIN(logon_time) AS oldest\nFROM v$session\nWHERE type = 'USER'\nGROUP BY username, program\nORDER BY sessions DESC;","alternatives":"Shared servers or Database Resident Connection Pooling (DRCP) let many clients share fewer sessions. Dead-connection detection (SQLNET.EXPIRE_TIME) clears sessions from crashed clients faster.","details":[],"details_title":null,"repro":"-- Needs SYSDBA on a scratch instance. Sessions must actually connect, so run\n-- the loop from a client that keeps sessions open.\n-- From SQL*Plus as SYSDBA:\n--   CREATE PFILE FROM SPFILE;\n--   ALTER SYSTEM SET sessions = 5 SCOPE = SPFILE;\n--   SHUTDOWN IMMEDIATE; STARTUP;\n-- Then open 6 connections; the sixth fails with ORA-00018.\n-- Restore afterwards:\n--   ALTER SYSTEM SET sessions = 300 SCOPE = SPFILE;\n--   SHUTDOWN IMMEDIATE; STARTUP;\n-- Note: SESSIONS derives from PROCESSES by default, so lower PROCESSES too or\n-- the derived value may stay higher than 5.","repro_note":null,"related":["oracle/ora-00020","oracle/ora-12519","mysql/1040","postgresql/53300"],"sqlly":"SQLly's connection test fails with the server's exact message, so a sessions-limit rejection reads as a capacity problem, not a bad password.","faqs":[{"question":"Does raising SESSIONS take effect immediately?","answer":"No. It is not dynamic, so you set it in the SPFILE and restart the instance. Also check PROCESSES: Oracle derives the default SESSIONS value from it, so a raise may need both."},{"question":"Can I connect at all when the limit is hit?","answer":"Yes, as SYSDBA. SYSDBA sessions are exempt from the SESSIONS limit specifically so you can get in and fix the instance. A regular user gets ORA-00018 or, at the process level, ORA-00020 or the listener's ORA-12519."},{"question":"Sessions hit the limit every morning at peak. Should I keep raising it?","answer":"Raising it just moves the ceiling. Check v$resource_limit max_utilization against your machine's memory and PROCESSES: each dedicated session is a real operating-system process with its own PGA. If the number keeps climbing, look for a pool sized without a cap or sessions that never close."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00018","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00020","corpus":"errors","engine":"oracle","language":"en","title":"maximum number of processes exceeded","description":"The instance reached its PROCESSES limit, so it can't start a server process for a new connection. Usually too many connections from pools.","body":{"code":"ORA-00020","slug":"ora-00020","name":null,"message":"maximum number of processes (string) exceeded","group":"resources","severity":null,"sql_state":null,"summary":"The instance reached its PROCESSES limit, so it can't start a server process for a new connection. Usually too many connections from pools.","meaning":"With dedicated servers each connection uses an operating-system process, and the `PROCESSES` parameter caps how many the instance may have. ORA-00020 means that cap is reached; 19c's message is `maximum number of processes (string) exceeded`. Often even administrators can't connect normally.","causes":["Connection pools or applications opening more connections than the limit, or leaking them.","A `PROCESSES` setting too low for the number of users."],"fix":[{"text":"Check usage.","sql":"SELECT resource_name, current_utilization, max_utilization, limit_value\nFROM v$resource_limit WHERE resource_name = 'processes';"},{"text":"Reduce connections: cap pool sizes, close idle sessions, or use shared servers or DRCP for many short connections.","sql":null},{"text":"Raise the limit and restart.","sql":"ALTER SYSTEM SET processes = 1000 SCOPE = SPFILE;"}],"diagnostic":"-- Needs SELECT on v$resource_limit. max_utilization since startup shows how\n-- close the instance usually runs to the cap.\nSELECT resource_name, current_utilization, max_utilization, limit_value\nFROM v$resource_limit\nWHERE resource_name = 'processes';\n\n-- Count processes by kind to see where they go. A stack of idle dedicated\n-- servers is the usual answer.\nSELECT program, COUNT(*) AS procs\nFROM v$process\nGROUP BY program\nORDER BY procs DESC\nFETCH FIRST 10 ROWS ONLY;","alternatives":"Shared servers let many connections share a smaller process pool. DRCP fits applications with many short-lived connections. Both avoid one OS process per connection, but they change how sessions and PGA memory behave, so test the application against them first.","details":[],"details_title":null,"repro":"-- Needs SYSDBA on a scratch instance.\nALTER SYSTEM SET processes = 10 SCOPE = SPFILE;\nSHUTDOWN IMMEDIATE;\nSTARTUP;\n-- Open 11 dedicated-server connections; the 11th fails with ORA-00020.\n-- Each connection is a real OS process, so background processes are already\n-- using several of the 10.\n-- Restore:\nALTER SYSTEM SET processes = 300 SCOPE = SPFILE;\nSHUTDOWN IMMEDIATE;\nSTARTUP;","repro_note":null,"related":["oracle/ora-00018","oracle/ora-12519","mysql/1040","postgresql/53300"],"sqlly":"SQLly's connection test shows the server's ORA-00020 verbatim, so a processes-limit rejection is distinguishable from listener errors in the dialog.","faqs":[{"question":"ORA-00018 and ORA-00020 look the same. Which one will I see?","answer":"Usually ORA-00020 first: a connection needs a process before it gets a session. If PROCESSES is generous but SESSIONS is tight, you see ORA-00018. Check both parameters together when raising limits."},{"question":"Does PROCESSES affect anything besides user connections?","answer":"Yes. Background processes, parallel execution servers, shared servers and job queue processes all count. Leave headroom above your expected user connection count; Oracle's default derivation sets SESSIONS as roughly 1.5 times PROCESSES plus extra."},{"question":"Can I raise it without a restart?","answer":"No. PROCESSES requires the instance to restart, unlike OPEN_CURSORS which is dynamic. Plan the restart, and remember that in a RAC you change and restart one instance at a time."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00020","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00054","corpus":"errors","engine":"oracle","language":"en","title":"resource busy and acquire with NOWAIT specified","description":"A statement that won't wait for locks (NOWAIT, DDL, or a lock with a timeout) found the table or row locked by another session's uncommitted work.","body":{"code":"ORA-00054","slug":"ora-00054","name":null,"message":"resource busy and acquire with NOWAIT specified or timeout expired","group":"locking","severity":null,"sql_state":null,"summary":"A statement that won't wait for locks (NOWAIT, DDL, or a lock with a timeout) found the table or row locked by another session's uncommitted work.","meaning":"ORA-00054 means a lock was requested without waiting, or with a timeout that expired, and another session holds it. DDL such as `ALTER TABLE`, `DROP TABLE` and `TRUNCATE` needs an exclusive lock and fails immediately by default if any session has uncommitted changes on the table. In 19c the message reads `resource busy and acquire with NOWAIT specified or timeout expired`.\n\nRecent releases describe the lock and its holder: `Failed to acquire a lock (Type: ..., Name: ..., Description: ...) because it is currently held by another session.`","causes":["Running DDL on a table while another session has uncommitted DML on it, often a forgotten session in a GUI tool.","`SELECT ... FOR UPDATE NOWAIT` on rows locked by another transaction.","`LOCK TABLE ... NOWAIT`."],"fix":[{"text":"Find the session holding the lock.","sql":"SELECT s.sid, s.serial#, s.username, s.program, o.object_name\nFROM v$locked_object l\nJOIN dba_objects o ON o.object_id = l.object_id\nJOIN v$session s ON s.sid = l.session_id\nWHERE o.object_name = 'ORDERS';"},{"text":"Have that session commit or roll back. As a last resort, an administrator can end it.","sql":"ALTER SYSTEM KILL SESSION '123,4567' IMMEDIATE;"},{"text":"Let DDL wait for locks instead of failing at once.","sql":"ALTER SESSION SET ddl_lock_timeout = 60;"}],"diagnostic":"-- Who is blocking? Needs privileges on the v$ views (SELECT ON v_$locked_object and friends, often via SELECT_CATALOG_ROLE).\nSELECT s.sid, s.serial#, s.username, s.status, s.program, o.object_name\nFROM v$locked_object l\nJOIN dba_objects o ON o.object_id = l.object_id\nJOIN v$session s ON s.sid = l.session_id\nORDER BY o.object_name;\n-- An INACTIVE session with old rows is usually the forgotten GUI tab.","alternatives":"If you cannot clear the holder, set ddl_lock_timeout in your session so the DDL waits and retries instead of failing, then schedule the change for a quiet window. Online redefinition (DBMS_REDEFINITION) rebuilds a table without an exclusive lock at the start.","details":[],"details_title":null,"repro":"-- Two SQL*Plus sessions on a scratch schema.\n-- Session A:\nCREATE TABLE rb (id NUMBER);\nINSERT INTO rb VALUES (1);\n-- do not commit\n-- Session B:\nALTER TABLE rb ADD (v NUMBER); -- ORA-00054","repro_note":null,"related":["oracle/ora-00060","oracle/ora-04021","sql-server/1222","postgresql/55P03","mysql/1205","sqlite/sqlite-busy"],"sqlly":"SQLly shows when a tab in manual-commit mode has pending changes in the status bar, which makes a forgotten uncommitted change, the usual cause of this error, easy to spot.","faqs":[{"question":"Why does a TRUNCATE fail when an UPDATE works fine?","answer":"DML waits for conflicting row locks. DDL needs an exclusive lock on the object and is typically issued NOWAIT, so it fails at once when anyone holds anything."},{"question":"Is killing the blocking session safe?","answer":"It is an administrator action and it discards that session's uncommitted work. Prefer asking the owner to commit or roll back first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00054","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00060","corpus":"errors","engine":"oracle","language":"en","title":"deadlock detected while waiting for resource","description":"Two sessions were each waiting for a row lock the other held. Oracle rolled back one statement (not the whole transaction) so the other could go on.","body":{"code":"ORA-00060","slug":"ora-00060","name":null,"message":"deadlock detected while waiting for resource","group":"locking","severity":null,"sql_state":null,"summary":"Two sessions were each waiting for a row lock the other held. Oracle rolled back one statement (not the whole transaction) so the other could go on.","meaning":"When Oracle detects a cycle of lock waits, it rolls back the current statement of one of the sessions and raises ORA-00060 there. Unlike some databases, it doesn't roll back that session's whole transaction: earlier work is still pending, and the session must decide whether to roll back or retry. Oracle writes a trace file with a deadlock graph showing the sessions, the rows and the SQL involved.","causes":["Two transactions updating the same rows in opposite orders.","Unindexed foreign key columns: deleting a parent or updating its key locks the whole child table, which makes deadlocks much more likely.","Bitmap indexes on tables with concurrent DML.","`SELECT ... FOR UPDATE` taken in different orders in different code paths."],"fix":[{"text":"Roll back (or retry from a savepoint) in the session that got the error. Retrying the whole transaction is the usual application response.","sql":"ROLLBACK;"},{"text":"Read the deadlock graph in the trace file named in the alert log to see both statements and the rows.","sql":null},{"text":"Index foreign key columns that are joined to parents you update or delete.","sql":"CREATE INDEX orders_customer_ix ON orders (customer_id);"},{"text":"Lock rows in a consistent order everywhere.","sql":"SELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;"}],"diagnostic":"-- Check for unindexed foreign keys, a classic deadlock amplifier.\nSELECT c.table_name, cc.column_name\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nWHERE c.constraint_type = 'R'\n  AND c.owner = USER\n  AND NOT EXISTS (\n    SELECT 1 FROM all_ind_columns ic\n    WHERE ic.table_name = c.table_name\n      AND ic.column_name = cc.column_name\n      AND ic.column_position = cc.position);","alternatives":"If the deadlock is between bitmap index maintenance and DML, drop the bitmap index during bulk loads or move the table to a staging pattern. For hot sequences of row updates, an application-side queue that serializes updates to the same keys removes the cycle.","details":[],"details_title":null,"repro":"-- Two SQL*Plus sessions on a scratch schema.\n-- Session A:\nCREATE TABLE dt (id NUMBER, v NUMBER);\nINSERT INTO dt VALUES (1, 0);\nINSERT INTO dt VALUES (2, 0);\nCOMMIT;\nUPDATE dt SET v = v + 1 WHERE id = 1;\n-- Session B:\nUPDATE dt SET v = v + 1 WHERE id = 2;\nUPDATE dt SET v = v + 1 WHERE id = 1; -- waits\n-- Session A:\nUPDATE dt SET v = v + 1 WHERE id = 2; -- ORA-00060 raised in session A","repro_note":null,"related":["oracle/ora-00054","oracle/ora-08177","sql-server/1205","postgresql/40P01","mysql/1213"],"sqlly":"SQLly shows the server's full ORA-00060 text, which names the trace file, and the tab stays usable so you can roll back and retry the transaction.","faqs":[{"question":"Did Oracle roll back my whole transaction?","answer":"No. Oracle rolls back only the statement that hit the deadlock. The rest of your transaction is still open and uncommitted, so commit or roll back deliberately."},{"question":"Where is the trace file?","answer":"The ORA-00060 message and the alert log name it. The trace holds the deadlock graph: both sessions, their statements, and the rows in contention."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00060","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00257","corpus":"errors","engine":"oracle","language":"en","title":"archiver error","description":"The archiver can't write archived redo logs, usually because the archive destination or fast recovery area is full. Only SYSDBA can connect until it's resolved.","body":{"code":"ORA-00257","slug":"ora-00257","name":null,"message":"archiver error. Connect internal only, until freed.","group":"resources","severity":null,"sql_state":null,"summary":"The archiver can't write archived redo logs, usually because the archive destination or fast recovery area is full. Only SYSDBA can connect until it's resolved.","meaning":"In ARCHIVELOG mode, a redo log can't be reused until it has been archived. If archiving stops, redo fills up and the database stops accepting changes. The message is `Archiver error. Connect AS SYSDBA only until resolved.`","causes":["The fast recovery area or archive destination is full.","`DB_RECOVERY_FILE_DEST_SIZE` is too small for the volume of redo.","The archive destination is unavailable, for example an unmounted file system."],"fix":[{"text":"Check recovery area usage.","sql":"SELECT space_limit/1024/1024 AS limit_mb, space_used/1024/1024 AS used_mb\nFROM v$recovery_file_dest;"},{"text":"Back up and delete archived logs with RMAN (never delete them by hand with operating-system commands): `BACKUP ARCHIVELOG ALL DELETE INPUT;`","sql":null},{"text":"Or give the recovery area more room.","sql":"ALTER SYSTEM SET db_recovery_file_dest_size = 200G SCOPE = BOTH;"}],"diagnostic":"-- Needs SYSDBA or recovery-catalog privileges.\nSELECT space_limit/1024/1024 AS limit_mb,\n       space_used/1024/1024 AS used_mb,\n       space_reclaimable/1024/1024 AS reclaimable_mb,\n       number_of_files\nFROM v$recovery_file_dest;\n\n-- What is eating the area? Archived logs usually.\nSELECT file_type, percent_space_used, percent_space_reclaimable\nFROM v$recovery_area_usage;\n\n-- Is the archiver itself stuck on a bad destination? Check for errors:\nSELECT dest_id, status, error, destination\nFROM v$archive_dest\nWHERE status = 'VALID' OR error IS NOT NULL;","alternatives":"If you cannot back up logs right away, raising DB_RECOVERY_FILE_DEST_SIZE buys time as long as the disk has room. A database in NOARCHIVELOG mode never hits ORA-00257, but it also cannot be recovered past its last backup, so that is not a real option for data you care about.","details":[],"details_title":null,"repro":"-- Needs ARCHIVELOG mode and SYSDBA on a scratch instance.\nSHUTDOWN IMMEDIATE;\nSTARTUP MOUNT;\nALTER DATABASE ARCHIVELOG;\nALTER DATABASE OPEN;\n\n-- Shrink the recovery area quota to force it full.\nALTER SYSTEM SET db_recovery_file_dest_size = 100M;\n-- Generate redo until archiving cannot keep up:\nCREATE TABLE redo_demo AS SELECT ROWNUM AS id FROM all_objects;\nINSERT INTO redo_demo SELECT * FROM redo_demo;\nUPDATE redo_demo SET id = id + 1;\nCOMMIT;\n-- Repeat the INSERT/UPDATE a few times without backing up logs:\n-- then any further change hangs or fails with ORA-00257.\n-- Restore:\nALTER SYSTEM SET db_recovery_file_dest_size = 10G;\nDROP TABLE redo_demo;","repro_note":null,"related":["oracle/ora-01653","sql-server/9002"],"sqlly":"SQLly's connection test reports the archiver error verbatim, so a full recovery area is visible from the dialog with the host it reached.","faqs":[{"question":"Can I just delete archived logs from disk with rm?","answer":"Don't. The database still thinks they exist and the recovery area won't reclaim the space properly. Back them up and remove them with RMAN: BACKUP ARCHIVELOG ALL DELETE INPUT, or DELETE ARCHIVELOG ALL COMPLETED BEFORE 'SYSDATE-1' if they are already backed up elsewhere."},{"question":"Why did the database stop accepting changes instead of just overwriting logs?","answer":"In ARCHIVELOG mode a redo log cannot be reused until it is archived. When every log is full of unarchived redo, there is nothing to write new changes into, so the database suspends rather than lose recoverability."},{"question":"How do I keep this from happening again?","answer":"Size DB_RECOVERY_FILE_DEST_SIZE for your redo rate and log backup schedule, run RMAN backups of archived logs on a regular schedule with DELETE INPUT, and alert on v$recovery_area_usage before it reaches the ceiling."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00257","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00904","corpus":"errors","engine":"oracle","language":"en","title":"invalid identifier","description":"A column or other name in the statement doesn't exist or isn't visible there: a typo, a mixed-case quoted name, a reserved word, or an alias used too early.","body":{"code":"ORA-00904","slug":"ora-00904","name":null,"message":"string: invalid identifier","group":"objects","severity":null,"sql_state":null,"summary":"A column or other name in the statement doesn't exist or isn't visible there: a typo, a mixed-case quoted name, a reserved word, or an alias used too early.","meaning":"ORA-00904 means Oracle couldn't resolve a name in the statement, almost always a column. The message includes the name it couldn't resolve, for example `ORA-00904: \"EMAIL_ADRESS\": invalid identifier`. Oracle stores unquoted names in upper case, so a column created as `\"Email\"` can only be referenced as `\"Email\"`.\n\nRecent releases put the name in front: `identifier: invalid identifier`.","causes":["A misspelled column name, or a column that belongs to a different table in the query.","A column created with a quoted mixed-case or lower-case name, referenced without quotes.","Using a column alias in `WHERE` or `GROUP BY` of the same query level; aliases are only visible in `ORDER BY`.","Using a reserved word as a column name without quoting it.","Referencing a column of an outer table from too deep inside nested subqueries in older releases."],"fix":[{"text":"List the table's real column names.","sql":"SELECT column_name FROM all_tab_columns\nWHERE owner = 'HR' AND table_name = 'EMPLOYEES'\nORDER BY column_id;"},{"text":"Repeat the expression instead of the alias, or wrap the query so the alias exists.","sql":"SELECT *\nFROM (SELECT salary * 12 AS annual FROM hr.employees)\nWHERE annual > 100000;"},{"text":"Quote names that were created in mixed case, exactly as created.","sql":"SELECT \"Email\" FROM customers;"}],"diagnostic":"-- What columns does the table actually have?\nSELECT column_name, data_type FROM all_tab_columns\nWHERE owner = USER AND table_name = 'REP_CUSTOMERS' ORDER BY column_id;\n-- Does the name in the error match exactly, including case?\n-- Is the word you used a reserved word?\nSELECT keyword FROM v$reserved_words WHERE keyword = 'COMMENT';\n-- In the failing statement, check that every alias is defined at or above\n-- the query level where you reference it. Aliases are only visible in ORDER BY.","alternatives":"If the mixed-case name came from a migration tool, consider renaming the column to plain upper case so nothing needs quoting again. If you need the alias inside WHERE, wrap the query in an inline view or use a WITH clause and filter outside it.","details":[],"details_title":null,"repro":"-- On a scratch schema:\nCREATE TABLE rep_customers (id NUMBER PRIMARY KEY, \"Email\" VARCHAR2(200));\nSELECT email FROM rep_customers;\n-- ORA-00904: \"EMAIL\": invalid identifier. The column exists as \"Email\",\n-- so it must be quoted exactly:\nSELECT \"Email\" FROM rep_customers;\nDROP TABLE rep_customers PURGE;","repro_note":null,"related":["oracle/ora-00942","oracle/ora-00918","oracle/ora-01747","sql-server/207","postgresql/42703","mysql/1054"],"sqlly":"SQLly's Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V elsewhere) checks a query against the connection's schema without running it and marks unknown tables and columns, and when a statement fails the editor jumps to the error.","faqs":[{"question":"Why does the same query work in one schema and fail in another?","answer":"Because the name resolves against what is visible to your user. A synonym or a different table in the other schema may have the column. Check all_tab_columns for both schemas rather than assuming the tables match."},{"question":"Can I use a column alias in WHERE?","answer":"No, not in the same query level. Oracle resolves WHERE before the select list, so the alias does not exist yet. Repeat the expression or put the query in a subquery and filter there."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00904","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00907","corpus":"errors","engine":"oracle","language":"en","title":"missing right parenthesis","description":"Oracle hit something it didn't expect inside parentheses. Often the parentheses are balanced and the real problem is a syntax error inside them.","body":{"code":"ORA-00907","slug":"ora-00907","name":null,"message":"missing right parenthesis","group":"syntax","severity":null,"sql_state":null,"summary":"Oracle hit something it didn't expect inside parentheses. Often the parentheses are balanced and the real problem is a syntax error inside them.","meaning":"ORA-00907 means that while parsing a parenthesized part, such as a column list, a function call or a subquery, Oracle met a token where it expected `)`. The name is misleading: the real cause is often invalid syntax inside the parentheses, which makes Oracle think the group should have ended.","causes":["A genuinely missing `)`.","`ORDER BY` inside a subquery used in an `IN` list or as a scalar subquery.","A datatype without its length, or with options from another database, inside `CREATE TABLE`: for example `VARCHAR2` without a size, or `AUTO_INCREMENT`.","A missing comma between column definitions or constraints."],"fix":[{"text":"Check the contents of the parentheses near the reported position, not just the count.","sql":null},{"text":"Remove `ORDER BY` from subqueries where it isn't allowed.","sql":"SELECT * FROM hr.employees\nWHERE department_id IN (SELECT department_id FROM hr.departments WHERE location_id = 1700);"},{"text":"Use Oracle syntax in table definitions, for example an identity column instead of `AUTO_INCREMENT`.","sql":"CREATE TABLE notes (\n    id   NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n    body VARCHAR2(4000)\n);"}],"diagnostic":"-- Read what is inside the parentheses near the reported position and\n-- check it as a standalone piece: a column definition, a function call\n-- or a subquery. In a CREATE TABLE, verify each line has: name, valid\n-- Oracle datatype, size where required (VARCHAR2 always needs one), and\n-- a comma between definitions. In a subquery, remove any ORDER BY and\n-- retry; that alone clears most cases inside IN lists.","alternatives":"Build the CREATE TABLE in an editor that pairs parentheses and format one column per line, which makes a missing comma obvious. For row ordering inside a view or top-level query, keep ORDER BY only where Oracle allows it and sort in the outer query instead.","details":[],"details_title":null,"repro":"-- On a scratch schema:\nCREATE TABLE rep_p (\n  id NUMBER,\n  name VARCHAR2\n);\n-- ORA-00907: missing right parenthesis. The parentheses are balanced;\n-- VARCHAR2 needs a length:\nCREATE TABLE rep_p (id NUMBER, name VARCHAR2(100));\n-- This fails the same way, ORDER BY is not allowed here:\n-- SELECT * FROM rep_p WHERE id IN (SELECT id FROM rep_p ORDER BY id);\nDROP TABLE rep_p PURGE;","repro_note":null,"related":["oracle/ora-00933","oracle/ora-00936","oracle/ora-00917"],"sqlly":"SQLly's editor jumps to the offset Oracle reports for parse errors, which points into the parenthesized group that holds the bad token.","faqs":[{"question":"All my parentheses are balanced. Why this error?","answer":"The message is misleading. A syntax error inside the group makes Oracle expect the group to end there, so it asks for a parenthesis that is not missing. Look for the bad token inside, such as a datatype without a size or a misplaced clause."},{"question":"Which datatypes need a length in Oracle?","answer":"VARCHAR2 always does: VARCHAR2(100). NUMBER, DATE, CLOB and BLOB do not. Datatypes from other databases such as TEXT, DATETIME or AUTO_INCREMENT are not Oracle and will trip the parser here."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00907","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00911","corpus":"errors","engine":"oracle","language":"en","title":"invalid character","description":"The statement contains a character Oracle doesn't accept there, most often a semicolon sent through a driver, or curly quotes pasted from a document.","body":{"code":"ORA-00911","slug":"ora-00911","name":null,"message":"invalid character","group":"syntax","severity":null,"sql_state":null,"summary":"The statement contains a character Oracle doesn't accept there, most often a semicolon sent through a driver, or curly quotes pasted from a document.","meaning":"ORA-00911 means the parser found a character that can't appear at that point. Identifiers may contain letters, digits, `_`, `$` and `#`, and must start with a letter unless quoted.\n\nRecent releases name the character and the token it followed: `character_value: invalid character after token_value`.","causes":["A trailing `;` in SQL sent through JDBC, ODBC or `EXECUTE IMMEDIATE`.","Smart quotes (‘ ’ “ ”) pasted from a word processor or chat instead of straight quotes.","An identifier starting with a digit or containing a hyphen, unquoted.","Non-printing characters such as a non-breaking space copied from a web page."],"fix":[{"text":"Remove the trailing semicolon from single statements sent by a program.","sql":null},{"text":"Retype quotes as straight `'` and `\"`, and remove invisible characters.","sql":null},{"text":"Quote identifiers that need unusual characters, or rename them.","sql":"SELECT \"order-id\" FROM legacy_orders;"}],"diagnostic":"-- Dump the exact bytes of the failing SQL. In Python:\n--   print(repr(sql))\n-- A repr shows smart quotes (\\u2018 \\u201c), non-breaking spaces (\\xa0)\n-- and other characters a plain print hides. In the editor, select the\n-- quoted literal and delete it, then retype straight quotes. Check the\n-- identifier at the reported position: Oracle allows letters, digits,\n-- _ $ and #, and it must start with a letter unless quoted.","alternatives":"If the SQL comes from a document or a chat message, paste it through a plain-text editor first to drop formatting. If an identifier genuinely needs a hyphen or spaces, keep it quoted everywhere it is used, or rename it in the database to something unquoted if you control the schema.","details":[],"details_title":null,"repro":"-- Through a driver or EXECUTE IMMEDIATE:\n--   EXECUTE IMMEDIATE 'SELECT * FROM dual;';\n-- ORA-00911: invalid character (the semicolon).\n-- On a scratch schema, an unquoted identifier with a hyphen:\nCREATE TABLE rep-o (id NUMBER);\n-- ORA-00911. Quoted it works:\nCREATE TABLE \"rep-o\" (id NUMBER);\nDROP TABLE \"rep-o\" PURGE;","repro_note":null,"related":["oracle/ora-00933","oracle/ora-00904"],"sqlly":"SQLly sends statements through the driver exactly as typed, and on this error the editor jumps to the reported position where the offending character sits.","faqs":[{"question":"It looks like a perfectly normal semicolon. Why invalid?","answer":"Because of where it is. In sqlplus a semicolon terminates the statement, but through a driver it arrives as part of the SQL, and the parser refuses it there. Strip it when your program sends the statement."},{"question":"How do I find an invisible character?","answer":"Print the SQL with repr() or hex-dump the segment near the reported position. A non-breaking space from a web page looks identical to a space on screen but is a different byte, and Oracle rejects it as an invalid character."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00911","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00917","corpus":"errors","engine":"oracle","language":"en","title":"missing comma","description":"A list in the statement, usually the column or VALUES list of an INSERT, is missing a comma between items, or has mismatched quotes.","body":{"code":"ORA-00917","slug":"ora-00917","name":null,"message":"missing comma","group":"syntax","severity":null,"sql_state":null,"summary":"A list in the statement, usually the column or VALUES list of an INSERT, is missing a comma between items, or has mismatched quotes.","meaning":"ORA-00917 means Oracle was reading a comma-separated list and found the next item without a comma before it. It is most common in `INSERT ... VALUES` lists, where a missing quote can also make two values run together.","causes":["A missing comma in a `VALUES` or column list.","A string literal with an unescaped single quote, such as `'O'Brien'`, which ends the string early.","Using `VALUES` with several row tuples on releases before 23ai."],"fix":[{"text":"Check commas between every value, and double single quotes inside strings.","sql":"INSERT INTO customers (id, last_name) VALUES (1, 'O''Brien');"},{"text":"To insert several rows before 23ai, use `INSERT ALL` or `INSERT ... SELECT ... UNION ALL`.","sql":"INSERT INTO t (a, b)\nSELECT 1, 'x' FROM dual UNION ALL\nSELECT 2, 'y' FROM dual;"}],"diagnostic":"-- Count the items in the column list and in the VALUES list, then check\n-- the character between each pair. To spot an unescaped quote, look at the\n-- literal in the error's neighborhood: a string with an odd number of\n-- quotes usually swallowed the next item. In code that builds values,\n-- print the final SQL or, better, switch that path to bind variables so\n-- quote escaping stops being your problem.","alternatives":"Bind variables remove the whole class of quoting bugs: pass 'O''Brien' as a parameter value and Oracle handles it. For multi-row inserts before 23ai, INSERT ALL or INSERT ... SELECT ... UNION ALL is safer than concatenating tuples; 23ai and later accept several value tuples directly.","details":[],"details_title":null,"repro":"-- On a scratch schema:\nCREATE TABLE rep_ins (id NUMBER, name VARCHAR2(50));\nINSERT INTO rep_ins (id, name) VALUES (1 'Bob');\n-- ORA-00917: missing comma.\n-- A quote that ends the string early looks the same:\nINSERT INTO rep_ins (id, name) VALUES (2, 'O'Brien');\n-- Fixed:\nINSERT INTO rep_ins (id, name) VALUES (1, 'Bob');\nINSERT INTO rep_ins (id, name) VALUES (2, 'O''Brien');\nDROP TABLE rep_ins PURGE;","repro_note":null,"related":["oracle/ora-00907","oracle/ora-00936","oracle/ora-00933"],"sqlly":"On failure, SQLly's editor moves to the position the database reported in the VALUES list, where the missing comma or unescaped quote sits.","faqs":[{"question":"Why does an apostrophe in a name cause a missing comma error?","answer":"The quote ends the string literal early, so the rest of the name lands outside the string where the parser expects a comma. Double every single quote inside a literal, or pass the text as a bind variable."},{"question":"Can I insert several rows in one statement?","answer":"Yes, several ways. From 23ai: VALUES (1,'a'), (2,'b') works. On older releases use INSERT ALL ... INTO ... SELECT * FROM dual, or INSERT ... SELECT with UNION ALL. A plain multi-tuple VALUES list gives ORA-00917 or a related syntax error before 23ai."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00917","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00918","corpus":"errors","engine":"oracle","language":"en","title":"column ambiguously defined","description":"A column name in a join exists in more than one of the tables, and the statement doesn't say which one. Qualify it with a table alias.","body":{"code":"ORA-00918","slug":"ora-00918","name":null,"message":"column ambiguously defined","group":"syntax","severity":null,"sql_state":null,"summary":"A column name in a join exists in more than one of the tables, and the statement doesn't say which one. Qualify it with a table alias.","meaning":"When several tables in a query have a column with the same name, Oracle needs to know which one you mean. ORA-00918 is raised when an unqualified reference could belong to more than one table.\n\nLater releases carry the column and both tables: `column_name: column ambiguously specified - appears in table_name_1 and table_name_2`.","causes":["An unqualified `id`, `name` or `created_at` in a join where both tables have it.","`SELECT *` in a subquery that joins tables with the same column names, then referencing the column outside.","A column in `ORDER BY` that appears twice in the select list from different tables."],"fix":[{"text":"Prefix every column in a join with its table alias.","sql":"SELECT e.employee_id, d.department_name, e.manager_id\nFROM hr.employees e\nJOIN hr.departments d ON d.department_id = e.department_id;"},{"text":"Give duplicate column names distinct aliases in subqueries.","sql":null}],"diagnostic":"-- List every column name that appears in more than one table of the query\nSELECT c.table_name, c.column_name\nFROM all_tab_columns c\nWHERE c.owner = USER\n  AND c.table_name IN ('DEPT_A', 'DEPT_B')\n  AND c.column_name IN (\n    SELECT column_name FROM all_tab_columns\n    WHERE owner = USER AND table_name IN ('DEPT_A', 'DEPT_B')\n    GROUP BY column_name HAVING COUNT(DISTINCT table_name) > 1\n  )\nORDER BY c.column_name, c.table_name;\n\n-- Or check a single suspect column\nSELECT owner, table_name FROM all_tab_columns\nWHERE owner = USER AND column_name = 'ID'\n  AND table_name IN ('DEPT_A', 'DEPT_B');","alternatives":"Alias every table in the query and qualify all column references, even where the name is unique today. That way a new column on one table cannot break the query later. `USING (id)` in the join also resolves the shared column without per-table prefixes.","details":[],"details_title":null,"repro":"-- ORA-00918: column ambiguously defined\nCREATE TABLE dept_a (id NUMBER, name VARCHAR2(30));\nCREATE TABLE dept_b (id NUMBER, loc VARCHAR2(30));\n\n-- Both tables have ID, and the reference is unqualified\nSELECT id, name FROM dept_a JOIN dept_b ON dept_a.id = dept_b.id;\n-- ORA-00918: column ambiguously defined\n\n-- Qualified, so it works\nSELECT dept_a.id, dept_a.name FROM dept_a JOIN dept_b ON dept_a.id = dept_b.id;","repro_note":null,"related":["oracle/ora-00904","sql-server/209","mysql/1052","postgresql/42702"],"sqlly":"SQLly's schema browser shows each join partner's columns, so duplicated names in a join are visible before you run the query.","faqs":[{"question":"Does this happen in old Oracle versions only?","answer":"No. Very old releases raised ORA-00918 even for `SELECT *` over a join with duplicate column names. Current releases allow `SELECT *` and qualify duplicate names in the output, but an explicit unqualified reference like `SELECT id` still fails."},{"question":"Why does it fail when only one of the tables actually has the column in my schema?","answer":"Oracle resolves the name against every table in the FROM clause, including views and synonyms. If you think only one table has it, check for a view or synonym over another table that also exposes that column name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00918","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00920","corpus":"errors","engine":"oracle","language":"en","title":"invalid relational operator","description":"A condition in WHERE or HAVING has a missing or invalid comparison operator, such as a lone column or an operator Oracle doesn't support.","body":{"code":"ORA-00920","slug":"ora-00920","name":null,"message":"invalid relational operator","group":"syntax","severity":null,"sql_state":null,"summary":"A condition in WHERE or HAVING has a missing or invalid comparison operator, such as a lone column or an operator Oracle doesn't support.","meaning":"ORA-00920 means a condition is missing its comparison, or uses something Oracle doesn't accept as one. Oracle has no boolean column type before 23ai, so `WHERE active` is not a valid condition there.","causes":["A bare column as a condition: `WHERE is_active`.","A typo such as `=>`, `=<` or `==`.","A missing operator before `NULL`: write `IS NULL`, not `= NULL`, and not `NULL` alone."],"fix":[{"text":"Compare explicitly.","sql":"SELECT * FROM users WHERE is_active = 1;\nSELECT * FROM users WHERE deleted_at IS NULL;"}],"diagnostic":"-- Find which token Oracle choked on: read the message position, then check the word before it.\n-- Is it a column that you meant to compare with something? Show its type:\nSELECT column_name, data_type\nFROM all_tab_columns\nWHERE table_name = 'T00920' AND column_name = 'IS_ACTIVE';\n-- NUMBER(1) is not a boolean before 23ai, so it needs = 1 or = 0.\n-- Also check for => (used in named function arguments, illegal in a WHERE comparison) and ==.","alternatives":"On 23ai and later you can declare a real BOOLEAN column and write WHERE is_active, but that syntax still fails on every earlier release, so portable SQL should always compare explicitly. For 1/0 flag columns, a CHECK constraint keeps the values to 0 and 1 so the comparison is reliable.","details":[],"details_title":null,"repro":"-- On releases before 23ai there is no boolean column type, so a bare column is not a condition.\nCREATE TABLE t00920 (id NUMBER, is_active NUMBER(1));\n\nSELECT * FROM t00920 WHERE is_active;\n-- ORA-00920: invalid relational operator\n\n-- Typo operators raise it too:\nSELECT * FROM t00920 WHERE id => 1;\nSELECT * FROM t00920 WHERE id == 1;\n\nDROP TABLE t00920 PURGE;","repro_note":null,"related":["oracle/ora-00936","oracle/ora-00933"],"sqlly":"SQLly's editor jumps to the reported position in the WHERE clause, which lands on or next to the bare column or typo operator.","faqs":[{"question":"Does Oracle 23ai finally allow WHERE active?","answer":"Yes, 23ai added a BOOLEAN type, so a bare boolean column is a valid condition there. On any earlier release a NUMBER or CHAR flag column must be compared explicitly."},{"question":"Why does => fail in WHERE?","answer":"=> is the named-argument operator for function and procedure calls, not a comparison. In a WHERE clause you want >= for at-least or = for equals. There is no == in Oracle SQL."},{"question":"I wrote = NULL and got ORA-00920. Why?","answer":"In Oracle, = NULL is accepted by the parser in many contexts but never matches, and some placements of a bare NULL raise ORA-00920. The correct form for a NULL test is IS NULL or IS NOT NULL."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00920","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00921","corpus":"errors","engine":"oracle","language":"en","title":"unexpected end of SQL command","description":"The statement stops before it is complete, for example a WHERE with no condition or SQL text cut off when it was built or copied.","body":{"code":"ORA-00921","slug":"ora-00921","name":null,"message":"unexpected end of SQL command","group":"syntax","severity":null,"sql_state":null,"summary":"The statement stops before it is complete, for example a WHERE with no condition or SQL text cut off when it was built or copied.","meaning":"ORA-00921 means Oracle reached the end of the statement while it still expected more, such as a condition after `WHERE` or a value after `=`.","causes":["Dynamic SQL that ends with `WHERE` or `AND` because the last condition was empty.","A statement truncated by a client, a variable size limit or a copy and paste."],"fix":[{"text":"Print the final SQL text and complete the clause that is cut off.","sql":null},{"text":"When building conditions in code, add `AND` only between existing conditions, or start with `WHERE 1 = 1`.","sql":null}],"diagnostic":"-- ORA-00921 is about the text of the statement, so inspect the exact string that was sent.\n-- For dynamic SQL, log the final assembled text right before execution and look at the last clause:\n--   if it ends with WHERE, AND, OR, IN ( or a comma, a condition was never appended.\n-- In SQL*Plus you can verify the statement buffer with LIST before running it.\n-- In SQL Developer, check the statement in the SQL History or the worksheet: a truncated\n-- paste or a cut-off CLOB/variable is a common source.","alternatives":"If conditions are built in code, join them with AND between items or start the WHERE clause with 1 = 1 so appending is uniform. If long statements get cut off, send them as a CLOB parameter or from a file rather than through a size-limited client variable.","details":[],"details_title":null,"repro":"-- A statement that ends mid-clause, the usual shape of string-built SQL that lost its condition:\nSELECT * FROM dual WHERE;\n-- ORA-00921: unexpected end of SQL command","repro_note":null,"related":["oracle/ora-00936","oracle/ora-00933"],"sqlly":"SQLly sends the statement text exactly as written and jumps the editor to the reported end position, so a truncated clause is visible immediately.","faqs":[{"question":"Is ORA-00921 the same as ORA-00936?","answer":"They are close. ORA-00936 means a required expression is missing somewhere inside the statement, like SELECT FROM dual. ORA-00921 means the parser hit the actual end of the text while a clause was still open."},{"question":"Why does the same SQL work in SQL Developer but fail from my app?","answer":"The app is usually sending different text: a builder dropped the last condition, a driver truncated the string, or a trailing semicolon and comment handling differ. Log the exact bytes the app sends and compare."},{"question":"Can a comment cause this?","answer":"Yes. If the last condition is inside a /* */ block or after -- and the client strips comments differently than you expect, the statement can arrive ending in WHERE or AND."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00921","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00923","corpus":"errors","engine":"oracle","language":"en","title":"FROM keyword not found where expected","description":"Oracle reached the end of what it thought was the select list without finding FROM: often a missing comma, a bad alias, a quote problem or SELECT without FROM.","body":{"code":"ORA-00923","slug":"ora-00923","name":null,"message":"FROM keyword not found where expected","group":"syntax","severity":null,"sql_state":null,"summary":"Oracle reached the end of what it thought was the select list without finding FROM: often a missing comma, a bad alias, a quote problem or SELECT without FROM.","meaning":"After `SELECT` and the column list, Oracle expects `FROM`. ORA-00923 means something in or after the select list stopped it from getting there.","causes":["A missing comma between two columns, so the second is read as an alias and the third is unexpected.","A column alias with spaces or a reserved word, not in double quotes.","Single quotes around an alias (`AS 'Total'`); aliases use double quotes.","`SELECT 1` with no `FROM` on releases before 23ai, which need `FROM dual`."],"fix":[{"text":"Check commas in the select list and quote aliases with double quotes.","sql":"SELECT first_name, last_name, salary * 12 AS \"Annual Salary\"\nFROM hr.employees;"},{"text":"Select constants from `dual` on releases before 23ai.","sql":"SELECT SYSDATE FROM dual;"}],"diagnostic":"-- There is no catalog query for a syntax error. Read the caret position in the\n-- message instead: it marks where Oracle gave up looking for FROM. Check the\n-- text immediately before that point for an unquoted alias with a space, a\n-- missing comma between select items, or a stray right parenthesis.\n-- To confirm the column names you meant to select exist:\nSELECT column_name FROM all_tab_columns\nWHERE owner = USER AND table_name = 'CUSTOMERS'\nORDER BY column_id;","alternatives":"If the goal was a display header containing spaces, use a quoted alias (`\"CUSTOMER NAME\"`). If the goal was a computed expression, check that every opening parenthesis has a matching close. Formatting the select list one item per line makes a missing comma easy to spot.","details":[],"details_title":null,"repro":"-- ORA-00923: FROM keyword not found where expected\nSELECT customer_id, customer_name CUSTOMER NAME\nFROM customers;\n-- ORA-00923: FROM keyword not found where expected\n-- The alias \"CUSTOMER NAME\" has a space with no quotes, so Oracle reads\n-- CUSTOMER, then NAME, and never finds FROM.\n\n-- Quoted alias, so it works\nSELECT customer_id, customer_name \"CUSTOMER NAME\"\nFROM customers;","repro_note":null,"related":["oracle/ora-00933","oracle/ora-00936","oracle/ora-00904"],"sqlly":"SQLly's editor jumps to the reported error position in the select list, which is where the malformed alias or missing comma sits.","faqs":[{"question":"I typed FROM. Why does Oracle say it is missing?","answer":"The message means Oracle could not reach FROM while parsing the select list. Something before it is malformed, most often an alias with a space and no double quotes, or a missing comma between two columns. The caret shows how far the parser got."},{"question":"Can the FROM clause itself cause ORA-00923?","answer":"Sometimes. A SELECT list ending in a valid expression but followed by a misspelled keyword (FORM, FOM) is reported as ORA-00923 because the parser still expects FROM where it found the typo."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00923","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00932","corpus":"errors","engine":"oracle","language":"en","title":"inconsistent datatypes","description":"An expression combines types Oracle can't convert between, such as comparing a CLOB with =, or mixing DATE and NUMBER where one type is expected.","body":{"code":"ORA-00932","slug":"ora-00932","name":null,"message":"inconsistent datatypes: expected string got string","group":"data","severity":null,"sql_state":null,"summary":"An expression combines types Oracle can't convert between, such as comparing a CLOB with =, or mixing DATE and NUMBER where one type is expected.","meaning":"ORA-00932 means a value of one datatype was used where an incompatible type was required, for example `ORA-00932: inconsistent datatypes: expected NUMBER got DATE`. LOBs are a common source: a `CLOB` can't be compared with `=`, used in `GROUP BY`, `ORDER BY` or `DISTINCT`.\n\nRecent releases spell out the type clash: `expression failed_expression is of data type expression_data_type, which is incompatible with expected data type expected_data_type`.","causes":["Comparing or grouping by a `CLOB` or `BLOB` column.","`CASE` or `DECODE` branches that return different types.","`UNION` members whose columns have incompatible types in the same position.","Passing a value of the wrong type to a function."],"fix":[{"text":"Compare LOBs with `DBMS_LOB` functions, or convert a short CLOB with `TO_CHAR` or `DBMS_LOB.SUBSTR`.","sql":"SELECT * FROM docs WHERE DBMS_LOB.COMPARE(body, TO_CLOB('hello')) = 0;\nSELECT DISTINCT DBMS_LOB.SUBSTR(body, 4000, 1) FROM docs;"},{"text":"Make every `CASE` branch and `UNION` column return the same type, with explicit conversions.","sql":"SELECT CASE WHEN qty > 0 THEN TO_CHAR(qty) ELSE 'none' END FROM stock;"}],"diagnostic":"-- List the types of every column the statement touches; the message names the two clashing types.\nSELECT column_name, data_type\nFROM all_tab_columns\nWHERE owner = USER AND table_name = 'T00932'\nORDER BY column_id;\n-- CLOB or BLOB in a =, IN, GROUP BY, ORDER BY or DISTINCT points at the LOB rules.\n-- For CASE and UNION clashes, check each branch and each UNION position returns the same type:\n-- TO_CHAR(number) and TO_CHAR(date) with a format, or TO_CLOB(text), line types up.","alternatives":"For equality on short CLOBs, convert both sides with TO_CHAR or DBMS_LOB.SUBSTR so the comparison runs on VARCHAR2, mindful of the 4000-byte SQL limit (32767 with extended data types). DBMS_LOB.COMPARE and DBMS_LOB.INSTR work on LOBs of any size. For matching on large text at scale, a function-based index on the extracted prefix or Oracle Text keeps the query usable.","details":[],"details_title":null,"repro":"-- LOBs cannot be compared with = or used in GROUP BY / DISTINCT.\nCREATE TABLE t00932 (id NUMBER, body CLOB);\nINSERT INTO t00932 VALUES (1, 'hello');\n\nSELECT * FROM t00932 WHERE body = 'hello';\n-- ORA-00932: inconsistent datatypes: expected - got CLOB\n\nSELECT DISTINCT body FROM t00932;\n-- ORA-00932\n\n-- Mixed types in CASE branches raise it too:\nSELECT CASE WHEN id > 0 THEN id ELSE 'none' END FROM t00932;\n-- ORA-00932: inconsistent datatypes: expected NUMBER got CHAR\n\nDROP TABLE t00932 PURGE;","repro_note":null,"related":["oracle/ora-01722","oracle/ora-06502","sql-server/8114","postgresql/42804"],"sqlly":"SQLly's schema browser shows each column's type next to its name, so a CLOB used in a comparison is visible while you write the WHERE clause.","faqs":[{"question":"Why can't I use = on a CLOB in Oracle?","answer":"LOBs have no ordering or equality defined in SQL, so =, DISTINCT, GROUP BY and ORDER BY are all rejected for them. SQL Server and MySQL allow it; Oracle requires DBMS_LOB functions or a conversion first."},{"question":"My CASE branches are NUMBER and VARCHAR2. Which conversion should I pick?","answer":"Convert the numeric branch with TO_CHAR if the result is meant for display, or convert the text branch with TO_NUMBER if the result is meant for math. Oracle needs one common type for the whole expression; it will not infer one."},{"question":"Does the 4000-byte limit apply to DBMS_LOB.SUBSTR?","answer":"DBMS_LOB.SUBSTR returns VARCHAR2, so in SQL the result is capped at 4000 bytes, or 32767 when extended data types are enabled. In PL/SQL the VARCHAR2 limit is 32767 regardless."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00932","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00933","corpus":"errors","engine":"oracle","language":"en","title":"SQL command not properly ended","description":"Oracle finished parsing a valid statement and found more text after it: a stray clause, a trailing semicolon passed through a driver, or syntax from another database.","body":{"code":"ORA-00933","slug":"ora-00933","name":null,"message":"SQL command not properly ended","group":"syntax","severity":null,"sql_state":null,"summary":"Oracle finished parsing a valid statement and found more text after it: a stray clause, a trailing semicolon passed through a driver, or syntax from another database.","meaning":"ORA-00933 means the statement was complete up to a point and what followed didn't fit. It often comes from syntax that works in other databases but not in Oracle, or from a semicolon sent to the database through JDBC, ODBC or `EXECUTE IMMEDIATE`, where Oracle doesn't accept it.\n\nLater releases give the position: `unexpected keyword at or near keyword_value`.","causes":["A trailing `;` in SQL sent through a driver or dynamic SQL.","Using `AS` before a table alias (`FROM employees AS e`); Oracle allows `AS` only for column aliases.","`LIMIT` or `TOP` (Oracle uses `FETCH FIRST n ROWS ONLY` from 12c).","An `ORDER BY` inside an `INSERT ... SELECT` subquery or a misplaced clause.","`UPDATE ... FROM` or `DELETE ... JOIN` syntax from SQL Server or MySQL."],"fix":[{"text":"Drop the semicolon when sending a single SQL statement through a driver or `EXECUTE IMMEDIATE`.","sql":null},{"text":"Write table aliases without `AS`.","sql":"SELECT e.last_name FROM hr.employees e;"},{"text":"Use Oracle's row-limiting clause.","sql":"SELECT * FROM hr.employees ORDER BY salary DESC FETCH FIRST 10 ROWS ONLY;"},{"text":"Rewrite joined updates with `MERGE` or a correlated subquery.","sql":"MERGE INTO orders o\nUSING customers c ON (c.id = o.customer_id)\nWHEN MATCHED THEN UPDATE SET o.region = c.region;"}],"diagnostic":"-- Find the token right after the last clause Oracle accepted.\n-- Common markers to grep your SQL for before sending it:\n--   trailing ';' on a single statement sent through a driver\n--   ' AS ' between table name and alias\n--   'LIMIT ' (Oracle uses FETCH FIRST n ROWS ONLY since 12c)\n--   'UPDATE ... FROM' or 'DELETE ... JOIN'\n-- In code that builds SQL, log the final string; in SQLly, the editor\n-- highlights the token the parser stopped at.","alternatives":"If the SQL must run on several databases, keep per-dialect templates or use a query builder that emits Oracle syntax, instead of one string with a semicolon appended. For row limits, FETCH FIRST works from 12c; on 11g use ROWNUM in an outer query.","details":[],"details_title":null,"repro":"-- Through a driver or EXECUTE IMMEDIATE, not a plain client:\n--   EXECUTE IMMEDIATE 'SELECT * FROM dual;';\n-- ORA-00933: SQL command not properly ended.\n-- Other dialect syntax fails the same way:\nSELECT * FROM dual AS d;\n-- ORA-00933. The fix:\nSELECT * FROM dual d;\n-- On a scratch table, the SQL Server pattern fails:\n-- UPDATE t SET c = 1 FROM t;   -- ORA-00933","repro_note":null,"related":["oracle/ora-00936","oracle/ora-00907","oracle/ora-00923","sql-server/102","postgresql/42601","mysql/1064"],"sqlly":"When a statement fails, SQLly highlights the token the database complained about and moves the editor to it.","faqs":[{"question":"The statement runs fine in sqlplus. Why does my app get ORA-00933?","answer":"sqlplus treats the semicolon as a terminator and strips it. Drivers do not, so a trailing semicolon reaches the server as part of the SQL. Remove it from strings sent through JDBC, ODBC or EXECUTE IMMEDIATE."},{"question":"Can I send several statements separated by semicolons?","answer":"Not in one driver call. Oracle's protocol executes one statement per round trip. Use a PL/SQL block with EXECUTE IMMEDIATE per statement, or a script runner that splits them for you."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00933","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00936","corpus":"errors","engine":"oracle","language":"en","title":"missing expression","description":"Oracle expected a value or expression and found something else: an empty select list, a trailing comma, or a missing operand.","body":{"code":"ORA-00936","slug":"ora-00936","name":null,"message":"missing expression","group":"syntax","severity":null,"sql_state":null,"summary":"Oracle expected a value or expression and found something else: an empty select list, a trailing comma, or a missing operand.","meaning":"ORA-00936 is raised when the parser reaches a place that needs an expression, such as a column in the select list or the right side of an operator, and there isn't one.","causes":["A trailing comma before `FROM`: `SELECT a, b, FROM t`.","An empty select list, or `SELECT` immediately followed by `FROM`.","A missing operand: `WHERE salary >` or `WHERE id IN ()`.","A bind placeholder or substitution variable that came through empty."],"fix":[{"text":"Look just before the position Oracle reports, and remove the stray comma or add the missing value.","sql":"SELECT employee_id, last_name\nFROM hr.employees\nWHERE salary > 5000;"},{"text":"If the SQL is built in code, print the final text and check the parts that come from variables.","sql":null}],"diagnostic":"-- List the columns actually in scope for each table in the query,\n-- then read the failing select list against that list:\nSELECT owner, table_name, column_name FROM all_tab_columns\nWHERE table_name = 'REP_T' ORDER BY column_id;\n-- If the SQL is built in code, print the final string and check the spots\n-- where a variable was substituted: an empty bind or missing value leaves\n-- the operator or comma with nothing after it.\n-- In SQLly, the editor jumps to the position the parser reported.","alternatives":"If a filter value can legitimately be empty, build the predicate conditionally in code or use a named bind and pass a real value, rather than letting an empty substitution splice the SQL. For a dynamic IN list, generate the right number of placeholders instead of an empty pair of parentheses.","details":[],"details_title":null,"repro":"-- On a scratch schema:\nCREATE TABLE rep_t (a NUMBER, b NUMBER);\nSELECT a, b, FROM rep_t;\n-- ORA-00936: missing expression (the comma before FROM)\nSELECT a FROM rep_t WHERE b >;\n-- ORA-00936 again: nothing on the right of the operator.\nDROP TABLE rep_t PURGE;","repro_note":null,"related":["oracle/ora-00933","oracle/ora-00907","oracle/ora-00921","sql-server/102","postgresql/42601"],"sqlly":"When a statement fails with a parse error, SQLly moves the editor to the position the database reported, which lands on or next to the stray comma.","faqs":[{"question":"Why does Oracle not name the exact spot?","answer":"Older releases report no position; newer ones add one. Either way the problem is at or just before where the parser stopped, so read backwards from there: a trailing comma, an operator with no operand, or an empty substitution."},{"question":"I used a bind variable. How does ORA-00936 still happen?","answer":"Binds carry values at run time, so they rarely cause this one. The usual bind story is a substitution variable or string interpolation that came through empty and removed the expression from the text before it was sent."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00936","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00937","corpus":"errors","engine":"oracle","language":"en","title":"not a single-group group function","description":"The select list mixes an aggregate like COUNT or SUM with plain columns, and there is no GROUP BY for those columns.","body":{"code":"ORA-00937","slug":"ora-00937","name":null,"message":"not a single-group group function","group":"syntax","severity":null,"sql_state":null,"summary":"The select list mixes an aggregate like COUNT or SUM with plain columns, and there is no GROUP BY for those columns.","meaning":"Without `GROUP BY`, a query with an aggregate returns one row for the whole table, so plain columns in the select list have no single value to show. ORA-00937 means you combined both.","causes":["`SELECT department_id, COUNT(*) FROM employees` with no `GROUP BY`.","Adding a column to a report query and forgetting the `GROUP BY`."],"fix":[{"text":"Group by the non-aggregated columns.","sql":"SELECT department_id, COUNT(*)\nFROM hr.employees\nGROUP BY department_id;"},{"text":"If you want the aggregate next to every row, use an analytic function instead.","sql":"SELECT employee_id, department_id, COUNT(*) OVER (PARTITION BY department_id) AS dept_count\nFROM hr.employees;"}],"diagnostic":"-- Syntax, not data, so no catalog query finds the cause. Review the select\n-- list: every expression must be inside an aggregate (SUM, COUNT, MAX, MIN,\n-- AVG, LISTAGG) or listed in GROUP BY. To check which column names the\n-- query touches exist as typed:\nSELECT column_name, data_type FROM all_tab_columns\nWHERE owner = USER AND table_name = 'ORDERS'\nORDER BY column_id;","alternatives":"If you want one summary row plus a grand total, use `GROUP BY ... GROUPING SETS` or a `ROLLUP`, which produce both levels in one query. If you need per-row values alongside an aggregate, use a window function: `SUM(amount) OVER ()` gives the total on every row without collapsing rows, and needs no GROUP BY.","details":[],"details_title":null,"repro":"-- ORA-00937: not a single-group group function\nCREATE TABLE orders (order_id NUMBER, customer_id NUMBER, amount NUMBER(10,2));\nINSERT INTO orders VALUES (1, 42, 100);\nINSERT INTO orders VALUES (2, 42, 250);\n\nSELECT customer_id, SUM(amount) FROM orders;\n-- ORA-00937: not a single-group group function\n-- customer_id has many values; SUM has one. No single row can hold both.\n\nSELECT SUM(amount) FROM orders;\n-- works: one row, whole table\n\nSELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;\n-- works: one row per customer","repro_note":null,"related":["oracle/ora-00979","sql-server/8118","sql-server/8120","mysql/1055","postgresql/42803"],"sqlly":"SQLly's editor jumps to the reported position for grouping errors, and Validate SQL marks the ungrouped column in the select list.","faqs":[{"question":"Why does COUNT(*) alone work without GROUP BY?","answer":"A select list that contains only aggregates produces one row for the whole table, which is well defined. The error appears the moment a plain column joins them, because that column would need a single value across many rows."},{"question":"Does adding the column to GROUP BY change my results?","answer":"It changes the shape of the result, from one row to one row per distinct value of that column. That is usually what the query meant, but if you truly wanted a grand total across everything, drop the plain column from the select list instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00937","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00942","corpus":"errors","engine":"oracle","language":"en","title":"table or view does not exist","description":"Oracle can't find the table or view, or you have no privilege on it. Usually a missing schema prefix, a typo, quoted mixed-case names or a missing grant.","body":{"code":"ORA-00942","slug":"ora-00942","name":null,"message":"table or view does not exist","group":"objects","severity":null,"sql_state":null,"summary":"Oracle can't find the table or view, or you have no privilege on it. Usually a missing schema prefix, a typo, quoted mixed-case names or a missing grant.","meaning":"Oracle resolves a table name in the current schema first, then through private and public synonyms. If nothing matches, or the object exists but you have no privilege on it, the statement fails with ORA-00942. Oracle deliberately reports a table you can't see the same way as one that doesn't exist.\n\nIn Oracle 23ai and later the message names the object: `table or view \"HR\".\"EMPLOYEES\" does not exist`.","causes":["The table is in another schema and you didn't qualify it, for example `employees` instead of `hr.employees`.","The table was created with a quoted mixed-case name such as `\"Employees\"`. Unquoted names are stored in upper case, so `employees` looks for `EMPLOYEES` and doesn't find it.","You have no `SELECT` (or `INSERT`, `UPDATE`, `DELETE`) privilege on the object, or the privilege came through a role, which doesn't apply inside definer-rights PL/SQL.","A synonym points to a table that was dropped or renamed.","You are connected to a different database, PDB or schema than you think."],"fix":[{"text":"Check which schema you're in and find the object you can see.","sql":"SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM dual;\nSELECT owner, object_name, object_type\nFROM all_objects\nWHERE UPPER(object_name) = 'EMPLOYEES';"},{"text":"Qualify the name with its owner, or switch the default schema for the session.","sql":"SELECT * FROM hr.employees;\nALTER SESSION SET CURRENT_SCHEMA = hr;"},{"text":"If the object exists but you can't see it, ask its owner (or a DBA) for a direct grant. Grant directly, not through a role, if a stored procedure needs it.","sql":"GRANT SELECT ON hr.employees TO app_user;"},{"text":"If the name was created in mixed case, quote it exactly as created.","sql":"SELECT * FROM \"Employees\";"},{"text":"If a synonym is involved, check where it points.","sql":"SELECT owner, synonym_name, table_owner, table_name\nFROM all_synonyms WHERE synonym_name = 'EMPLOYEES';"}],"diagnostic":"-- Which schema am I actually in?\nSELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS current_schema FROM dual;\n-- Does the object exist anywhere I can see, or at all (as DBA)?\nSELECT owner, object_name, object_type FROM all_objects WHERE object_name = UPPER('secret_table');\n-- As DBA, confirm it exists and who owns it:\n-- SELECT owner, object_name, object_type FROM dba_objects WHERE object_name = UPPER('secret_table');\n-- If it exists in all_objects but not all_objects for you, it is a privilege problem, not a missing table.","alternatives":"If you only need read access, ask for a direct object grant (GRANT SELECT ON hidden_owner.secret_table TO scratch_user) instead of a role, because privileges through roles do not apply to definer's-rights code. A view in an intermediate schema with the grant also works and keeps the owner hidden.","details":[],"details_title":null,"repro":"-- Run as a user with CREATE TABLE and CREATE SESSION, e.g. a scratch PDB user.\n-- Create a table in another schema that this user has no privilege on.\nGRANT CREATE SESSION TO scratch_user;\nCREATE TABLE hidden_owner.secret_table (id NUMBER);   -- as a DBA or the hidden_owner schema\n-- As scratch_user, the table exists but is invisible:\nSELECT * FROM hidden_owner.secret_table;\n-- ORA-00942: table or view does not exist\n-- Same error from a plain typo:\nSELECT * FROM no_such_table_xyz;","repro_note":null,"related":["oracle/ora-00904","oracle/ora-01031","oracle/ora-00955","sql-server/208","postgresql/42P01","mysql/1146"],"sqlly":"SQLly's schema browser lists the tables and views you can actually see, so a missing grant or a wrong schema shows up as an empty list before you run the query.","faqs":[{"question":"Why do I get ORA-00942 inside a procedure when the query works in SQL*Plus?","answer":"Privileges granted through a role are not used inside definer-rights PL/SQL. Grant the privilege directly to the procedure's owner, or define the procedure with `AUTHID CURRENT_USER`."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00942","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00955","corpus":"errors","engine":"oracle","language":"en","title":"name is already used by an existing object","description":"A CREATE statement used a name that another object in the same schema already has: a table, view, sequence, synonym or index with that name.","body":{"code":"ORA-00955","slug":"ora-00955","name":null,"message":"name is already used by an existing object","group":"objects","severity":null,"sql_state":null,"summary":"A CREATE statement used a name that another object in the same schema already has: a table, view, sequence, synonym or index with that name.","meaning":"Tables, views, sequences, private synonyms, procedures and other schema objects share one namespace per schema, so you can't have a view and a table with the same name. ORA-00955 is raised when `CREATE` would reuse a taken name. Indexes and constraints have their own namespaces, but an index can still clash with another index.","causes":["Running a creation script a second time.","A different kind of object (a view or synonym) already has the name.","Creating an index whose name is already used by another index in the schema."],"fix":[{"text":"Find what already has the name.","sql":"SELECT object_name, object_type FROM user_objects WHERE object_name = 'ORDERS';"},{"text":"Use `CREATE OR REPLACE` for views, procedures, functions, packages, triggers and synonyms.","sql":"CREATE OR REPLACE VIEW active_orders AS\nSELECT * FROM orders WHERE status = 'OPEN';"},{"text":"On Oracle 23ai and later, use `IF NOT EXISTS` to make table creation repeatable; on older releases, drop the object first or check `user_objects` before creating.","sql":"CREATE TABLE IF NOT EXISTS orders (id NUMBER PRIMARY KEY);"}],"diagnostic":"-- What already holds the name, and what kind of object is it?\nSELECT object_name, object_type, created FROM user_objects WHERE object_name = 'REP_ORDERS';\n-- Include other schemas if you create through a synonym:\nSELECT owner, object_type FROM all_objects WHERE object_name = 'REP_ORDERS';","alternatives":"If the existing object is the thing you wanted, skip the create. If you are writing a rerunnable script, guard it: use CREATE OR REPLACE for views, procedures and synonyms, IF NOT EXISTS on 23ai and later for tables, or query user_objects first and branch in your deploy tool.","details":[],"details_title":null,"repro":"-- On a scratch schema:\nCREATE TABLE rep_orders (id NUMBER PRIMARY KEY);\nCREATE TABLE rep_orders (id NUMBER PRIMARY KEY);\n-- ORA-00955: name is already used by an existing object\n-- Same name on a different kind of object fails too:\nCREATE VIEW rep_orders AS SELECT * FROM rep_orders;\nDROP TABLE rep_orders PURGE;","repro_note":null,"related":["oracle/ora-00942","sql-server/2714","mysql/1050","postgresql/42P07"],"sqlly":"SQLly's schema browser lists every object of a type in the schema, so you can see a name is taken before writing the CREATE.","faqs":[{"question":"The table is gone. Why does CREATE still fail?","answer":"Check user_objects. A view, sequence, private synonym or procedure may still own the name, and those share the table's namespace in your schema. DROP TABLE does not touch them."},{"question":"Does an index name collide with a table name?","answer":"No. Indexes live in their own namespace, so an index and a table can share a name. An index can still collide with another index, and constraints have their own namespace too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00955","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-00979","corpus":"errors","engine":"oracle","language":"en","title":"not a GROUP BY expression","description":"A column or expression in the select list, HAVING or ORDER BY isn't in the GROUP BY clause and isn't inside an aggregate function.","body":{"code":"ORA-00979","slug":"ora-00979","name":null,"message":"not a GROUP BY expression","group":"syntax","severity":null,"sql_state":null,"summary":"A column or expression in the select list, HAVING or ORDER BY isn't in the GROUP BY clause and isn't inside an aggregate function.","meaning":"With `GROUP BY`, each output row stands for a group, so every selected expression must either be one of the grouping expressions or an aggregate. ORA-00979 means one isn't.\n\nLater releases quote the expression itself: `expression: must appear in the GROUP BY clause or be used in an aggregate function`.","causes":["Selecting a column that isn't in `GROUP BY`.","Grouping by an expression but selecting a slightly different one, such as `TRUNC(order_date)` versus `order_date`.","Ordering by a column that isn't grouped."],"fix":[{"text":"Add the column to `GROUP BY`, or wrap it in an aggregate such as `MAX()`.","sql":"SELECT d.department_name, COUNT(*) AS staff\nFROM hr.employees e\nJOIN hr.departments d ON d.department_id = e.department_id\nGROUP BY d.department_name;"},{"text":"Repeat the exact grouping expression in the select list.","sql":"SELECT TRUNC(order_date) AS day, SUM(total)\nFROM orders\nGROUP BY TRUNC(order_date);"}],"diagnostic":"-- Syntax problem again. Compare the select list against the GROUP BY list:\n-- every selected expression must either appear verbatim in GROUP BY or sit\n-- inside an aggregate. Watch for TRUNC(date) in the select but bare date in\n-- GROUP BY, and for expression mismatches like UPPER(name) vs name.\n-- To confirm the columns involved:\nSELECT column_name, data_type FROM all_tab_columns\nWHERE owner = USER AND table_name = 'ORDERS'\nORDER BY column_id;","alternatives":"If the stray column is a row identifier you want alongside the group, an aggregate is usually the honest answer: `MAX(order_id)` or `LISTAGG(order_id, ',')`. Window functions also help: `COUNT(*) OVER (PARTITION BY customer_id)` attaches group-level numbers to individual rows without any GROUP BY, keeping every row visible.","details":[],"details_title":null,"repro":"-- ORA-00979: not a GROUP BY expression\nCREATE TABLE orders (order_id NUMBER, customer_id NUMBER, amount NUMBER(10,2));\n\nSELECT customer_id, order_id, SUM(amount)\nFROM orders\nGROUP BY customer_id;\n-- ORA-00979: not a GROUP BY expression\n-- ORDER_ID is selected but is neither grouped nor aggregated.\n\nSELECT customer_id, COUNT(*), SUM(amount)\nFROM orders\nGROUP BY customer_id;\n-- works","repro_note":null,"related":["oracle/ora-00937","sql-server/8120","mysql/1055","postgresql/42803"],"sqlly":"SQLly's editor jumps to the reported position, which names the expression the database flagged as missing from the GROUP BY.","faqs":[{"question":"I put the column in GROUP BY but still get ORA-00979. Why?","answer":"The expressions must match exactly. If you select `TRUNC(order_date)` you must group by `TRUNC(order_date)`, not `order_date`. The same applies to function calls, concatenations and column aliases; group by the expression, or use a subquery/CTE and group by its output column."},{"question":"How is ORA-00979 different from ORA-00937?","answer":"ORA-00937 means there is no GROUP BY at all while the select list mixes plain columns and aggregates. ORA-00979 means a GROUP BY exists but a selected expression is missing from it. Same family, second is a mismatch against an existing group list."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-00979","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01000","corpus":"errors","engine":"oracle","language":"en","title":"maximum open cursors exceeded","description":"The session has more cursors open than the OPEN_CURSORS limit, nearly always because application code doesn't close statements or result sets.","body":{"code":"ORA-01000","slug":"ora-01000","name":null,"message":"maximum open cursors exceeded","group":"resources","severity":null,"sql_state":null,"summary":"The session has more cursors open than the OPEN_CURSORS limit, nearly always because application code doesn't close statements or result sets.","meaning":"Each open statement and result set uses a cursor, and `OPEN_CURSORS` caps how many a session may have open at once. ORA-01000 means the session hit the cap. Raising the limit hides the problem if the application leaks cursors; the real fix is closing them.","causes":["JDBC or other driver code that doesn't close `ResultSet` and `Statement` objects, often in error paths.","Opening a cursor inside a loop without closing it.","Statement caching configured larger than `OPEN_CURSORS`.","A legitimately high number of concurrent cursors with a low limit."],"fix":[{"text":"See which sessions and SQL hold the most open cursors.","sql":"SELECT s.sid, s.username, COUNT(*) AS open_cursors\nFROM v$open_cursor oc JOIN v$session s ON s.sid = oc.sid\nGROUP BY s.sid, s.username ORDER BY open_cursors DESC;"},{"text":"Close statements and result sets in `finally` blocks or with try-with-resources in Java, and close cursors in PL/SQL loops.","sql":null},{"text":"If the application really needs more, raise the limit.","sql":"ALTER SYSTEM SET open_cursors = 1000 SCOPE = BOTH;"}],"diagnostic":"-- Rank sessions by open cursors. v$open_cursor counts cached cursors per session;\n-- needs SELECT on the v$ views.\nSELECT s.sid, s.serial#, s.username, s.program,\n       COUNT(*) AS open_cursors\nFROM v$open_cursor oc\nJOIN v$session s ON s.sid = oc.sid\nGROUP BY s.sid, s.serial#, s.username, s.program\nORDER BY open_cursors DESC\nFETCH FIRST 10 ROWS ONLY;\n\n-- What SQL do the worst offenders hold open? Repeated one-row results here are\n-- the signature of cursors opened in a loop and never closed.\nSELECT sid, SUBSTR(sql_text, 1, 80) AS sql_text, COUNT(*) AS copies\nFROM v$open_cursor\nWHERE sid = :suspect_sid\nGROUP BY sid, SUBSTR(sql_text, 1, 80)\nORDER BY copies DESC;","alternatives":"If the application code is clean, raising OPEN_CURSORS is reasonable; it is per session, so 1000 costs little. Statement caches in JDBC drivers also count against the limit, so keep the driver cache size below OPEN_CURSORS.","details":[],"details_title":null,"repro":"-- Run as a non-DBA user in a scratch session. OPEN_CURSORS defaults to 50.\nALTER SESSION SET open_cursors = 10;\n\nDECLARE\n  TYPE cur_t IS TABLE OF SYS_REFCURSOR;\n  cursors cur_t := cur_t();\nBEGIN\n  FOR i IN 1 .. 15 LOOP\n    DECLARE c SYS_REFCURSOR;\n    BEGIN\n      OPEN c FOR SELECT * FROM all_objects;\n      cursors.EXTEND;\n      cursors(cursors.LAST) := c;  -- never closed: leak\n    END;\n  END LOOP;\nEND;\n/\n-- ORA-01000: maximum open cursors exceeded","repro_note":null,"related":["oracle/ora-00018","oracle/ora-00020"],"sqlly":"SQLly closes its own statements after each run, so this error usually points at the open tab's long-running query rather than at the client.","faqs":[{"question":"Do I need to restart anything to recover?","answer":"No. Cursors close when the session closes them or disconnects. Fix the leaking code and the session can carry on; the count resets as cursors are released."},{"question":"Is OPEN_CURSORS a database-wide limit?","answer":"No, it is per session. A thousand sessions at 50 cursors each is fine as long as no single session exceeds its own cap."},{"question":"The JDBC code closes everything. Why do I still hit it?","answer":"Check for early returns and exception paths that skip close(), check the driver's statement cache size, and check code that calls executeQuery without ever reading or closing the ResultSet. Ref Cursors returned to the application also count until the app closes them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01008","corpus":"errors","engine":"oracle","language":"en","title":"not all variables bound","description":"The statement has a bind placeholder such as :id that was given no value, often because a colon in the SQL text was read as a placeholder.","body":{"code":"ORA-01008","slug":"ora-01008","name":null,"message":"not all variables bound","group":"syntax","severity":null,"sql_state":null,"summary":"The statement has a bind placeholder such as :id that was given no value, often because a colon in the SQL text was read as a placeholder.","meaning":"Each placeholder like `:id` or `:1` in a statement needs a value when it runs. ORA-01008 means at least one has none.\n\nRecent releases point at the placeholder: `value for bind variable placeholder variable_name was not provided`.","causes":["Passing fewer values than there are placeholders, or binding by a different name.","A colon-prefixed word in the SQL, such as `:new` in a trigger body, that a client tool or driver treats as a bind placeholder.","Reusing the same placeholder name twice with a driver that binds by position."],"fix":[{"text":"Match every placeholder with a value, by name or by position.","sql":null},{"text":"In SQL*Plus or SQL Developer, declare and set the variable first.","sql":"VARIABLE id NUMBER\nEXEC :id := 100\nSELECT * FROM hr.employees WHERE employee_id = :id;"}],"diagnostic":"-- ORA-01008 happens in the driver or client, not in the database, so look at the statement and the bind list together.\n-- 1. Count placeholders in the failing SQL text (each unique :name or :n counts once).\n-- 2. List what your code actually binds. In SQL*Plus you can see the session's declared variables:\nPRINT\n-- 3. If the statement contains a trigger keyword like :new or :old, it was probably sent as plain SQL\n--    instead of staying inside the trigger body, so the client treats it as a bind.\n-- 4. If you bind by position, the same name used twice counts twice; check the driver docs for\n--    bind-by-name versus bind-by-position behavior.","alternatives":"If you cannot fix the bind list, rewrite the statement to inline safe literal values instead of binds, or split it so each execution binds the full set. Inside tools like SQL Developer, declare the variable with VARIABLE before running the statement.","details":[],"details_title":null,"repro":"-- SQL*Plus, no bind declared:\nSELECT * FROM dual WHERE dummy = :id;\n-- ORA-01008: not all variables bound\n-- The trigger-body trap: :new sent to the server as plain SQL, where the driver\n-- reads it as an ordinary bind:\n--   SELECT :new.id FROM dual;  -- ORA-01008 in any client\n-- Declaring the bind makes it work:\nVARIABLE id VARCHAR2(10)\nEXEC :id := 'x'\nSELECT * FROM dual WHERE dummy = :id;","repro_note":null,"related":["oracle/ora-00936","sqlite/sqlite-range"],"sqlly":"SQLly's error pane shows the statement text beside the error, so the placeholder the driver expected is one glance away; fixing the bind list is an edit in the same tab.","faqs":[{"question":"Why do I get this when my SQL has no binds at all?","answer":"The driver treats any colon-prefixed word as a bind. A string containing something like 'http://x' can trip some drivers, and trigger code with :new or :old fails when it is run outside the trigger. Quote or escape those, or keep trigger code in the trigger."},{"question":"Does the number of placeholders include repeats of the same name?","answer":"It depends on the driver. With bind by name, one value per unique name is enough. With bind by position, a name used twice needs two values. ODBC and JDBC differ here, so check which mode your driver is in."},{"question":"Can I see which variable was missing?","answer":"Newer Oracle releases change the message to name the placeholder, for example 'value for bind variable ID was not provided'. On older releases the message is generic and you have to compare the SQL text with the bind list yourself."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01008","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01017","corpus":"errors","engine":"oracle","language":"en","title":"invalid username/password; logon denied","description":"Oracle rejected the login: wrong user name or password, a case-sensitive password typed in the wrong case, or the wrong database or PDB.","body":{"code":"ORA-01017","slug":"ora-01017","name":null,"message":"invalid username/password; logon denied","group":"connection","severity":null,"sql_state":null,"summary":"Oracle rejected the login: wrong user name or password, a case-sensitive password typed in the wrong case, or the wrong database or PDB.","meaning":"ORA-01017 means the database didn't accept the credentials. Since Oracle 11g passwords are case-sensitive by default, and in a multitenant database a common user and a local PDB user are different accounts, so connecting to the wrong service can look like a wrong password.\n\nLater releases word it `invalid credential or not authorized; logon denied`.","causes":["Wrong password, or the right password in the wrong case.","Connecting to the container database (CDB) instead of the PDB where the user lives, or the reverse.","An older client that can't use the password verifier the account has (for example an account with only 12C verifiers and a very old client).","Special characters in the password mangled by the shell or connection string; quote the password.","Operating-system authentication (`/ as sysdba`) failing because the OS user isn't in the right group."],"fix":[{"text":"Check that the account exists in the database you are connecting to, and its status.","sql":"SELECT username, account_status, authentication_type\nFROM dba_users WHERE username = 'APP_USER';"},{"text":"Reset the password as an administrator. Quote it to keep the exact case and special characters.","sql":"ALTER USER app_user IDENTIFIED BY \"N3w-Strong-Pass\";"},{"text":"Make sure the connect string names the right service: the PDB service, not the CDB, for a local user.","sql":null},{"text":"In SQL*Plus, quote passwords with special characters: `sqlplus app_user/\\\"p@ss\\\"@//db-host:1521/salespdb`.","sql":null}],"diagnostic":"-- As DBA: does the account exist here, and what state is it in?\nSELECT username, account_status FROM dba_users WHERE username = UPPER('scratch_user');\n-- If dba_users is not available to you, all_users at least confirms existence:\nSELECT username FROM all_users WHERE username = UPPER('scratch_user');\n-- No row means you are connected to the wrong database or PDB, or the name is wrong.\n-- OPEN means the credentials themselves are the problem. LOCKED or EXPIRED points at ORA-28000/28001 instead.","alternatives":"If you suspect you are connecting to the wrong database (easy in a multitenant setup where a common user and a PDB-local user share a name), connect with an explicit Easy Connect string to the exact host, port and service instead of an alias. For a forgotten password, any DBA can reset it with ALTER USER ... IDENTIFIED BY, or you can use ALTER USER ... IDENTIFIED BY VALUES to restore a known hash from a backup.","details":[],"details_title":null,"repro":"-- On a scratch database, create a user and try the wrong password.\nCREATE USER scratch_user IDENTIFIED BY \"Correct-Horse-1\";\nGRANT CREATE SESSION TO scratch_user;\n-- Then connect (SQL*Plus, SQLcl or your client) with:\n-- sqlplus scratch_user/WrongPass1@//localhost:1521/YOURPDB\n-- ORA-01017: invalid username/password; logon denied\n-- Since 11g passwords are case-sensitive by default, so correcthorse-1 fails too.\n-- Repeated failures count against FAILED_LOGIN_ATTEMPTS and can lock the account; unlock when done:\n-- ALTER USER scratch_user ACCOUNT UNLOCK;","repro_note":null,"related":["oracle/ora-28000","oracle/ora-28001","oracle/ora-12154","oracle/ora-01031","sql-server/18456","postgresql/28P01","mysql/1045"],"sqlly":"SQLly's connection test reports the exact error the database returned along with the round-trip time, so you can tell a credentials problem from a listener or network one.","faqs":[{"question":"I am sure the password is right. What else causes ORA-01017?","answer":"The usual suspects: connecting to a different database or PDB than you think (a local user with the same name does not exist in the CDB root), a password that was changed or expired elsewhere, quoting problems where special characters in the password need double quotes in the connect string, and case sensitivity introduced in 11g."},{"question":"Does the error tell me whether the user exists?","answer":"No. Oracle returns the same ORA-01017 whether the username or the password is wrong, so an attacker cannot enumerate accounts. That is why the first diagnostic step is checking the account exists in the database you actually reached."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01017","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01031","corpus":"errors","engine":"oracle","language":"en","title":"insufficient privileges","description":"Your user lacks a system or object privilege the statement needs, or holds it only through a role, which doesn't count inside definer-rights PL/SQL or views.","body":{"code":"ORA-01031","slug":"ora-01031","name":null,"message":"insufficient privileges","group":"objects","severity":null,"sql_state":null,"summary":"Your user lacks a system or object privilege the statement needs, or holds it only through a role, which doesn't count inside definer-rights PL/SQL or views.","meaning":"ORA-01031 means the statement needs a privilege the current user doesn't have: a system privilege such as `CREATE TABLE` or `CREATE VIEW`, or an object privilege such as `UPDATE` on another user's table. A classic trap: privileges granted through roles are not used when compiling definer-rights PL/SQL or creating views on other users' tables, so a statement that works interactively fails inside a procedure.","causes":["Missing system privilege, for example `CREATE VIEW`, `CREATE PROCEDURE` or `CREATE SEQUENCE`.","Missing object privilege on another schema's table for the operation (`SELECT` is not enough for `UPDATE`).","The privilege comes from a role, and the statement runs in definer-rights PL/SQL or is a `CREATE VIEW` on another schema's objects.","Connecting `/ as sysdba` with an OS user who isn't in the DBA group."],"fix":[{"text":"See what the user has, directly and through roles.","sql":"SELECT * FROM session_privs ORDER BY privilege;\nSELECT * FROM user_tab_privs WHERE table_name = 'EMPLOYEES';"},{"text":"Grant the missing privilege directly to the user (an administrator or the object's owner runs this).","sql":"GRANT CREATE VIEW TO app_user;\nGRANT SELECT, UPDATE ON hr.employees TO app_user;"},{"text":"For a view over another schema's table that you want to grant on, the owner must grant with the grant option.","sql":"GRANT SELECT ON hr.employees TO app_user WITH GRANT OPTION;"}],"diagnostic":"-- What privileges does the current session actually hold?\nSELECT privilege FROM session_privs ORDER BY privilege;\n-- Which of those come from roles? Role-granted privileges are invisible\n-- to definer-rights PL/SQL and to CREATE VIEW over other schemas:\nSELECT granted_role FROM user_role_privs;\nSELECT privilege FROM role_sys_privs WHERE role = 'CONNECT';\n-- What object grants do you hold on the table in question?\nSELECT privilege, grantor FROM user_tab_privs WHERE table_name = 'EMPLOYEES';","alternatives":"If the statement runs in a stored procedure, ask the DBA for a direct grant instead of a role. If you only need read access to data, a view owned by the table's schema can publish a narrow slice, and you get SELECT on that view instead of broad rights on the base table.","details":[],"details_title":null,"repro":"-- Needs an admin to set up; run against a scratch user.\n-- As a DBA:\n--   CREATE USER rep_user IDENTIFIED BY \"pw\";\n--   GRANT CREATE SESSION TO rep_user;\n--   CREATE ROLE rep_role;\n--   GRANT SELECT ON hr.employees TO rep_role;\n--   GRANT rep_role TO rep_user;\n-- As rep_user, this works (roles count in plain SQL):\n--   SELECT * FROM hr.employees;\n-- But this fails with ORA-01031:\n--   CREATE VIEW my_v AS SELECT * FROM hr.employees;\n-- Views compile with direct grants only, and rep_user's SELECT\n-- comes from a role. A direct grant fixes it:\n--   GRANT SELECT ON hr.employees TO rep_user;","repro_note":null,"related":["oracle/ora-00942","oracle/ora-01950","sql-server/229","mysql/1142","postgresql/42501"],"sqlly":"SQLly's Validate SQL resolves a statement's names against the connection without running it, so a privilege-shaped failure shows up as unknown objects before you ship the query.","faqs":[{"question":"Why does the query work in SQL Developer but fail inside my procedure?","answer":"In a tool your session has role privileges. Inside definer-rights PL/SQL, Oracle uses only privileges granted directly to the owner, and ignores roles. That is a deliberate security rule, so the fix is a direct grant."},{"question":"I have DBA role. Why does it still fail?","answer":"Being an administrator through a role does not help inside definer-rights code or for CREATE VIEW on another schema's objects. The privilege must be granted to your user directly."},{"question":"Can I grant myself out of this in a script?","answer":"Only if you have the admin option. GRANT itself can raise ORA-01031 when you lack it. Run grants as the object owner or a DBA."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01031","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01034","corpus":"errors","engine":"oracle","language":"en","title":"ORACLE not available","description":"The database instance isn't running, or you connected to a different instance than the one you meant. Start the instance or fix ORACLE_SID.","body":{"code":"ORA-01034","slug":"ora-01034","name":null,"message":"ORACLE not available","group":"connection","severity":null,"sql_state":null,"summary":"The database instance isn't running, or you connected to a different instance than the one you meant. Start the instance or fix ORACLE_SID.","meaning":"ORA-01034 means the session reached no running instance. It often appears together with ORA-27101 (shared memory realm does not exist) on a local connection, which tells you the instance's memory isn't there because it isn't started.\n\nLater releases state it plainly: `The Oracle instance is not available for use. Start the instance.`","causes":["The instance is shut down, or failed to start.","`ORACLE_SID` (or `ORACLE_HOME`) in your environment points at a different instance.","The listener has a static registration for an instance that isn't running."],"fix":[{"text":"Check `ORACLE_SID` and `ORACLE_HOME`, then connect as SYSDBA and start the instance.","sql":"-- sqlplus / as sysdba\nSTARTUP;"},{"text":"If startup fails, read the alert log for the reason (parameter file, memory, missing files).","sql":null}],"diagnostic":"-- From the server shell, is a pmon process alive for your SID?\nps -ef | grep pmon\n-- What does your environment point at?\necho $ORACLE_SID $ORACLE_HOME\n-- If the listener fronts the connection, what does it know about?\nlsnrctl status\n-- If the instance is up but unreachable, check the alert log for startup failures:\n-- $ORACLE_BASE/diag/rdbms/<db>/<sid>/trace/alert_<sid>.log","alternatives":"If you cannot start the instance yourself, connect through the listener with a full connect string instead of a local bequeath connection, which sidesteps a wrong ORACLE_SID. On a pluggable setup, confirm which PDB you actually need; a wrong service name gives a different error but the same confusion.","details":[],"details_title":null,"repro":"-- Run on a throwaway instance, never on one people use.\n-- From a shell where ORACLE_SID points at a down instance:\n--   echo $ORACLE_SID\n--   sqlplus scott/tiger\n-- ORA-01034 appears (often with ORA-27101).\n-- To create the state from a running scratch instance:\n--   sqlplus / as sysdba\n--   SHUTDOWN IMMEDIATE;\n-- Then any ordinary login fails with ORA-01034. Restart with STARTUP;","repro_note":null,"related":["oracle/ora-27101","oracle/ora-12514","oracle/ora-12505"],"sqlly":"The connection test fails fast with the server's exact message, so the host you actually reached is on screen next to the news that no instance is running.","faqs":[{"question":"Why do I get ORA-01034 when the database is clearly running?","answer":"Your session is looking at a different instance than the one that is running. Check ORACLE_SID and ORACLE_HOME in the shell you connected from, especially if several instances share the host. On Linux the SID is case-sensitive."},{"question":"Can I fix this with a GRANT or a settings change in my client?","answer":"No. Nothing in the client or your user's privileges matters here. The instance your connection reached is not started, and only starting it (or pointing at a running one) removes the error."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01034","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01400","corpus":"errors","engine":"oracle","language":"en","title":"cannot insert NULL into column","description":"An INSERT left a NOT NULL column empty or set it to NULL. The message names the column as (SCHEMA.TABLE.COLUMN).","body":{"code":"ORA-01400","slug":"ora-01400","name":null,"message":"cannot insert NULL into (string)","group":"constraints","severity":null,"sql_state":null,"summary":"An INSERT left a NOT NULL column empty or set it to NULL. The message names the column as (SCHEMA.TABLE.COLUMN).","meaning":"ORA-01400 means a row would have NULL in a column declared `NOT NULL`, for example `ORA-01400: cannot insert NULL into (\"SALES\".\"ORDERS\".\"CUSTOMER_ID\")`. Leaving a column out of an `INSERT` gives it NULL unless it has a default. Oracle also treats an empty string `''` as NULL, which surprises people coming from other databases. Updating a NOT NULL column to NULL raises the related ORA-01407.","causes":["The `INSERT` column list leaves out a required column that has no default.","An empty string `''` inserted into a NOT NULL `VARCHAR2` column; Oracle stores `''` as NULL.","A primary key column that should be filled by a sequence or identity but isn't."],"fix":[{"text":"Supply a value for the column named in the message, or give it a default.","sql":"ALTER TABLE orders MODIFY (status DEFAULT 'NEW');"},{"text":"Use an identity column (12c and later) or a sequence default for keys.","sql":"CREATE TABLE orders (\n    id          NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,\n    customer_id NUMBER NOT NULL\n);"},{"text":"Store a placeholder such as a single space, or allow NULL, when a value can legitimately be empty.","sql":null}],"diagnostic":"-- Which columns are NOT NULL, and are they nullable through a default?\nSELECT c.column_name, c.nullable, c.data_default, c.identity_column\nFROM all_tab_columns c\nWHERE c.owner = USER AND c.table_name = 'ORDERS'\nORDER BY c.column_id;\n\n-- NOT NULL constraints show up as system-named check constraints too\nSELECT cc.column_name, c.constraint_name, c.search_condition_vc\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nWHERE c.owner = USER AND c.table_name = 'ORDERS'\n  AND c.constraint_type = 'C'\n  AND c.search_condition_vc LIKE '%\"NOT NULL\"%';\n\n-- If the insert selects from another table, find which source rows\n-- carry NULL into the NOT NULL column\nSELECT * FROM stage_orders WHERE customer_id IS NULL;","alternatives":"Give the column a DEFAULT so inserts that omit it still get a value, or an identity column for generated keys (`GENERATED ALWAYS AS IDENTITY`, 12.1+). If NULLs are genuinely valid data, drop the NOT NULL constraint with `ALTER TABLE ... MODIFY (column NULL)`. For bulk loads, filter out or default NULL source rows before the insert instead of catching row-by-row failures.","details":[],"details_title":null,"repro":"-- ORA-01400: cannot insert NULL into\nCREATE TABLE orders (\n  order_id     NUMBER PRIMARY KEY,\n  customer_id  NUMBER NOT NULL,\n  note         VARCHAR2(100)\n);\n\nINSERT INTO orders (order_id, note) VALUES (1, 'no customer');\n-- ORA-01400: cannot insert NULL into (\"SCHEMA\".\"ORDERS\".\"CUSTOMER_ID\")\n\nINSERT INTO orders (order_id, customer_id) VALUES (1, 42);\n-- works","repro_note":null,"related":["oracle/ora-00001","oracle/ora-02291","postgresql/23502","sql-server/515","mysql/1048","sqlite/sqlite-constraint-notnull"],"sqlly":"SQLly's data grid shows the column names, and the server's message names the column that refused the NULL, so the empty cell is findable in the row editor.","faqs":[{"question":"I did not pass NULL. Why the error?","answer":"Any insert that omits a column gives it NULL, including `INSERT INTO t VALUES (...)` with a short value list and `INSERT INTO t SELECT` where the source column is NULL. A column with a DEFAULT is filled only when omitted and no explicit NULL was named; `INSERT INTO t (col) VALUES (NULL)` still fails on a NOT NULL column even with a default defined."},{"question":"Can I find which of many rows failed in a bulk insert?","answer":"Add `LOG ERRORS` (`BEGIN dbms_errlog.create_error_log('ORDERS'); END;` then `INSERT ... LOG ERRORS INTO err$_orders REJECT LIMIT UNLIMITED`). The error log records each rejected row and its ORA-01400, so the load continues and you review failures afterwards."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01400","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01401","corpus":"errors","engine":"oracle","language":"en","title":"inserted value too large for column","description":"An older form of the 'value too large' error: a value was longer than its column. Current releases normally report ORA-12899 with the column name.","body":{"code":"ORA-01401","slug":"ora-01401","name":null,"message":"inserted value too large for column","group":"data","severity":null,"sql_state":null,"summary":"An older form of the 'value too large' error: a value was longer than its column. Current releases normally report ORA-12899 with the column name.","meaning":"ORA-01401 means a value inserted or updated was larger than the column could hold. Modern Oracle releases usually raise ORA-12899 instead, which names the column and the lengths, so ORA-01401 now mostly appears from older versions or specific code paths.","causes":["A string longer than the column's defined length.","Multi-byte characters in a column sized in bytes."],"fix":[{"text":"Compare the data with the column sizes and widen the column, as for ORA-12899.","sql":"ALTER TABLE customers MODIFY (name VARCHAR2(200 CHAR));"}],"diagnostic":"-- ORA-01401 does not name the column, so compare every character column against the values you insert.\n-- List byte-sized text columns and the longest values heading into them:\nSELECT c.column_name, c.data_type, c.data_length, c.char_used,\n       (SELECT MAX(LENGTHB(s.col_val)) FROM stage_data s WHERE s.col_name = c.column_name) AS longest_incoming\nFROM all_tab_columns c\nWHERE c.owner = USER AND c.table_name = 'TARGET'\n  AND c.data_type IN ('VARCHAR2', 'CHAR', 'NVARCHAR2', 'NCHAR');\n-- Any column where longest_incoming exceeds DATA_LENGTH (for CHAR_USED = 'B') is the culprit.\n\n-- A multi-row insert can also be narrowed with an error log, which records the failing row\n-- and the ORA error number per row:\nBEGIN DBMS_ERRLOG.CREATE_ERROR_LOG('TARGET', 'ERR_TARGET'); END;\n/\nINSERT INTO target SELECT * FROM stage_data\nLOG ERRORS INTO err_target ('load1') REJECT LIMIT UNLIMITED;\nSELECT ora_err_number$, ora_err_mesg$, cols FROM err_target WHERE ora_err_tag$ = 'load1';","alternatives":"Widen the offending column with VARCHAR2(n CHAR) so multi-byte text fits. If the data must be shortened instead, truncate deliberately with SUBSTR (characters) or SUBSTRB (bytes) before the insert so the failure becomes a controlled cut rather than an error.","details":[],"details_title":null,"repro":"-- On releases that still raise ORA-01401, a plain overflow shows the older message;\n-- current releases raise ORA-12899 with the column name and lengths instead.\nCREATE TABLE t01401 (name VARCHAR2(5));\nINSERT INTO t01401 VALUES ('abcdef');\n-- ORA-01401: inserted value too large for column  (older releases)\n-- ORA-12899: value too large for column ... (actual: 6, maximum: 5)  (newer releases)\n\nDROP TABLE t01401 PURGE;","repro_note":null,"related":["oracle/ora-12899","oracle/ora-01438"],"sqlly":"SQLly surfaces the server's full message text, so on older releases you still see which insert failed even though the message omits the column.","faqs":[{"question":"Is ORA-01401 deprecated?","answer":"Modern Oracle releases report the same problem as ORA-12899, which names the column and both lengths. ORA-01401 still shows up on older releases and from some code paths, so both errors mean the same fix."},{"question":"How do I find the bad column when the message does not say?","answer":"Two ways: compare the byte length of each incoming value against the column's DATA_LENGTH in ALL_TAB_COLUMNS, or run the insert with LOG ERRORS so the error log records the failing column set and message per rejected row."},{"question":"Can a LOB raise ORA-01401?","answer":"No. Overflow on character columns raises ORA-01401 or ORA-12899; LOB writes size themselves. The error is limited to CHAR, VARCHAR2, NCHAR and NVARCHAR2 style columns."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01401","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01403","corpus":"errors","engine":"oracle","language":"en","title":"no data found","description":"A SELECT INTO in PL/SQL returned no rows, or code read an associative array element that doesn't exist. Handle NO_DATA_FOUND or query in a way that allows zero rows.","body":{"code":"ORA-01403","slug":"ora-01403","name":null,"message":"no data found","group":"plsql","severity":null,"sql_state":null,"summary":"A SELECT INTO in PL/SQL returned no rows, or code read an associative array element that doesn't exist. Handle NO_DATA_FOUND or query in a way that allows zero rows.","meaning":"In PL/SQL, `SELECT ... INTO` must return exactly one row. When it returns none, Oracle raises the predefined exception `NO_DATA_FOUND` (ORA-01403). Reading an element of an associative array that was never assigned raises it too. In plain SQL a query with no rows is not an error.","causes":["A `SELECT ... INTO` for a key that doesn't exist.","A filter that excludes the row, such as a wrong status or date.","Reading `my_array(i)` for an index that was never set."],"fix":[{"text":"Handle the case explicitly.","sql":"BEGIN\n  SELECT email INTO l_email FROM customers WHERE id = p_id;\nEXCEPTION\n  WHEN NO_DATA_FOUND THEN\n    l_email := NULL;\nEND;"},{"text":"Or use an aggregate, which always returns one row.","sql":"SELECT MAX(email) INTO l_email FROM customers WHERE id = p_id;"},{"text":"Check `my_array.EXISTS(i)` before reading an associative array element.","sql":null}],"diagnostic":"-- Run the SELECT ... INTO's query by hand with a row counter to see what it returns.\nSELECT COUNT(*) FROM ndf WHERE id = 999;\n-- Zero means the lookup key or filters are wrong for the data. One means the exception comes from somewhere else in the block; ORA-06512 names the line.","alternatives":"If zero rows is normal, branch on it with an explicit exception handler, or rewrite as a cursor loop, or use an aggregate like MAX so the query always returns one row. For associative arrays, check EXISTS before indexing.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\nCREATE TABLE ndf (id NUMBER, email VARCHAR2(100));\nINSERT INTO ndf VALUES (1, 'a@x.com');\nCOMMIT;\nDECLARE\n  l_email VARCHAR2(100);\nBEGIN\n  SELECT email INTO l_email FROM ndf WHERE id = 999; -- ORA-01403\nEND;\n/","repro_note":null,"related":["oracle/ora-01422","oracle/ora-06512","oracle/ora-06503"],"sqlly":"SQLly's editor shows the failing PL/SQL block with the error position, so an empty SELECT INTO is located without reopening the procedure.","faqs":[{"question":"Why does a FOR loop with a SELECT INTO inside still fail?","answer":"The loop iterates over whatever its cursor returns. A SELECT INTO inside the body runs once per iteration and still needs its own row, so one bad iteration raises ORA-01403."},{"question":"Is ORA-01403 always an error?","answer":"In SQL it is silent: a plain query returning no rows is fine. It becomes an exception only in PL/SQL contexts that demand one row, like SELECT INTO."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01403","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01422","corpus":"errors","engine":"oracle","language":"en","title":"exact fetch returns more than requested rows","description":"A SELECT INTO in PL/SQL returned more than one row. Narrow the query to one row, or fetch into a collection or loop.","body":{"code":"ORA-01422","slug":"ora-01422","name":null,"message":"exact fetch returns more than requested number of rows","group":"plsql","severity":null,"sql_state":null,"summary":"A SELECT INTO in PL/SQL returned more than one row. Narrow the query to one row, or fetch into a collection or loop.","meaning":"`SELECT ... INTO` must return exactly one row; when it returns several, PL/SQL raises the predefined exception `TOO_MANY_ROWS` (ORA-01422). 19c words it `exact fetch returns more than requested number of rows`.","causes":["Looking up by a column that isn't unique.","A missing condition, so the query matches many rows.","Duplicate rows in data that was assumed unique."],"fix":[{"text":"Filter on a unique key, or pick one row on purpose.","sql":"SELECT id INTO l_id FROM customers\nWHERE email = p_email\nORDER BY created_at DESC\nFETCH FIRST 1 ROW ONLY;"},{"text":"If several rows are expected, fetch them into a collection or loop over a cursor.","sql":"SELECT id BULK COLLECT INTO l_ids FROM customers WHERE email = p_email;"}],"diagnostic":"-- Run the SELECT INTO's query with a count to see how many rows actually match.\nSELECT COUNT(*) FROM tmr WHERE email = 'dup@x.com';\n-- More than one means the lookup column is not unique. Check for a missing unique constraint:\nSELECT constraint_name, constraint_type FROM all_constraints\nWHERE table_name = 'TMR' AND owner = USER;","alternatives":"BULK COLLECT into a collection when several rows are legitimate, or add FETCH FIRST 1 ROW ONLY with a deliberate ORDER BY when you want the newest or best match. If the duplicates are bad data, deduplicate and add a unique constraint so it stays clean.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\nCREATE TABLE tmr (id NUMBER, email VARCHAR2(100));\nINSERT INTO tmr VALUES (1, 'dup@x.com');\nINSERT INTO tmr VALUES (2, 'dup@x.com');\nCOMMIT;\nDECLARE\n  l_id NUMBER;\nBEGIN\n  SELECT id INTO l_id FROM tmr WHERE email = 'dup@x.com'; -- ORA-01422\nEND;\n/","repro_note":null,"related":["oracle/ora-01403","oracle/ora-01427","sql-server/512","mysql/1242"],"sqlly":"Copy the SELECT into a second SQLly tab and run it on its own: the row count the INTO didn't expect is right there, one paste away.","faqs":[{"question":"Which row did Oracle fetch before raising the error?","answer":"It stops after fetching one more row than requested. None of the fetched values are assigned, so the INTO variables keep their prior values."},{"question":"Is this the opposite of ORA-01403?","answer":"Yes. ORA-01403 is zero rows, ORA-01422 is more than one. Both come from the exactly-one-row rule of SELECT INTO."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01422","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01427","corpus":"errors","engine":"oracle","language":"en","title":"single-row subquery returns more than one row","description":"A subquery used where one value is expected, after = or in the select list, returned several rows.","body":{"code":"ORA-01427","slug":"ora-01427","name":null,"message":"single-row subquery returns more than one row","group":"syntax","severity":null,"sql_state":null,"summary":"A subquery used where one value is expected, after = or in the select list, returned several rows.","meaning":"A subquery after `=`, `<`, `>` or in a `SET` or select list must return at most one row. ORA-01427 means it returned more, so Oracle can't pick a value.","causes":["A lookup that matches several rows, for example by a non-unique name.","Missing correlation to the outer row, so the subquery returns every row.","Duplicate rows in a table that was assumed to have one row per key."],"fix":[{"text":"Use `IN` if any of the values may match.","sql":"SELECT * FROM hr.employees\nWHERE department_id IN (SELECT department_id FROM hr.departments WHERE location_id = 1700);"},{"text":"Make the subquery return one row: correlate it, filter on a unique key, or aggregate.","sql":"UPDATE orders o\nSET region = (SELECT c.region FROM customers c WHERE c.id = o.customer_id);"},{"text":"Find the keys that have duplicates.","sql":"SELECT name, COUNT(*) FROM customers GROUP BY name HAVING COUNT(*) > 1;"}],"diagnostic":"-- Run the subquery on its own and count what it returns\nSELECT COUNT(*) FROM customers WHERE region = 'WEST';\n\n-- For an UPDATE's SET subquery, find the join keys whose subquery\n-- would return more than one parent row\nSELECT c.customer_id, COUNT(*) AS matches\nFROM orders o JOIN customers c ON c.customer_id = o.customer_id\nGROUP BY c.customer_id\nHAVING COUNT(*) > 1;\n\n-- Duplicate parent keys would also do it; check the constraint actually holds\nSELECT c.customer_id, COUNT(*)\nFROM customers c\nGROUP BY c.customer_id HAVING COUNT(*) > 1;\n\n-- Which session is running the failing statement? (needs v$session privileges)\nSELECT sid, sql_id, event, seconds_in_wait\nFROM v$session WHERE username IS NOT NULL AND sql_id IS NOT NULL;","alternatives":"Add `AND ROWNUM = 1` to force one row, but that picks an arbitrary row unless you also add an ORDER BY in a wrapping subquery, so only do it when any row is acceptable. A join handles the many-to-one mapping properly and is usually faster. In an UPDATE, correlated subqueries can be replaced with `MERGE`, which enforces the one-row-per-target expectation explicitly. `MAX()` or `MIN()` around the subquery also collapses duplicates when you want a deterministic single value.","details":[],"details_title":null,"repro":"-- ORA-01427: single-row subquery returns more than one row\nCREATE TABLE customers (customer_id NUMBER PRIMARY KEY, region VARCHAR2(20));\nCREATE TABLE orders (order_id NUMBER PRIMARY KEY, customer_id NUMBER, region VARCHAR2(20));\nINSERT INTO customers VALUES (1, 'WEST');\nINSERT INTO customers VALUES (2, 'WEST');\nINSERT INTO orders VALUES (100, 1, NULL);\n\nUPDATE orders\nSET region = (SELECT region FROM customers\n              WHERE customers.customer_id = orders.customer_id);\n-- OK so far: each order matches one customer\nINSERT INTO orders VALUES (101, 2, NULL);\n\nSELECT customer_id,\n       (SELECT region FROM customers WHERE region = 'WEST')\nFROM orders WHERE order_id = 100;\n-- ORA-01427: single-row subquery returns more than one row\n-- Two customers live in WEST, so the scalar subquery has two answers.\n\n-- Fix with a join instead:\nSELECT o.customer_id, c.region\nFROM orders o JOIN customers c ON c.customer_id = o.customer_id;","repro_note":null,"related":["oracle/ora-01422","sql-server/512","mysql/1242","postgresql/21000"],"sqlly":"SQLly shows the statement next to the server's full error, so you can copy the inner SELECT into a new tab and count its rows.","faqs":[{"question":"Why did the query work yesterday and fail today?","answer":"The subquery's row count depends on data. It ran fine while the WHERE clause matched at most one row; new data pushed it past one. These failures often appear after a load or an insert into the table the subquery reads. Run the subquery standalone to see the extra rows."},{"question":"Does ORA-01427 roll back my UPDATE?","answer":"The statement fails atomically: no rows it processed are changed. However, in a multi-row UPDATE Oracle may have applied the change to some rows before hitting the failing one; the statement-level rollback undoes those. Earlier committed statements are untouched."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01427","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01438","corpus":"errors","engine":"oracle","language":"en","title":"value larger than specified precision","description":"A number has more digits before the decimal point than the column's NUMBER(precision, scale) allows.","body":{"code":"ORA-01438","slug":"ora-01438","name":null,"message":"value larger than specified precision allowed for this column","group":"data","severity":null,"sql_state":null,"summary":"A number has more digits before the decimal point than the column's NUMBER(precision, scale) allows.","meaning":"A `NUMBER(p, s)` column holds at most `p - s` digits to the left of the decimal point. ORA-01438 means the value needs more. Digits beyond the scale on the right are rounded, not rejected, so the error is always about the integer part. For example `NUMBER(5,2)` accepts up to 999.99.\n\nRecent releases show the value and the limit: `value value greater than specified precision precision_scale for column column`.","causes":["A value too big for the column, such as 1000 in `NUMBER(5,2)`.","Storing a value in the wrong unit, for example cents in a column meant for currency units.","An arithmetic result in an `UPDATE` that grows past the limit."],"fix":[{"text":"Check the column's precision and scale.","sql":"SELECT column_name, data_precision, data_scale\nFROM all_tab_columns WHERE table_name = 'ORDERS' AND column_name = 'TOTAL';"},{"text":"Widen the column.","sql":"ALTER TABLE orders MODIFY (total NUMBER(12,2));"}],"diagnostic":"-- The column whose precision is exceeded: for a single-row insert, test each numeric column.\nSELECT column_name, data_type, data_precision, data_scale\nFROM all_tab_columns\nWHERE owner = USER AND table_name = 'T01438' AND data_type = 'NUMBER';\n-- Max allowed integer digits = data_precision - data_scale.\n\n-- For a multi-row load, an error log names the failing rows and column set:\nBEGIN DBMS_ERRLOG.CREATE_ERROR_LOG('T01438', 'ERR_T01438'); END;\n/\nINSERT INTO t01438 SELECT * FROM stage_amounts\nLOG ERRORS INTO err_t01438 ('load1') REJECT LIMIT UNLIMITED;\nSELECT ora_err_number$, ora_err_mesg$ FROM err_t01438 WHERE ora_err_tag$ = 'load1';","alternatives":"Widen the column with ALTER TABLE ... MODIFY (total NUMBER(12,2)) when the values are legitimate. If the values are in the wrong unit, convert in the load (divide cents by 100) rather than inflating every column. Rounding with ROUND to the column's scale in the INSERT can also keep borderline values inside the limit.","details":[],"details_title":null,"repro":"-- NUMBER(5,2) holds up to 999.99; the integer part is what fails.\nCREATE TABLE t01438 (total NUMBER(5,2));\nINSERT INTO t01438 VALUES (999.99);   -- ok, and 999.994 rounds to 999.99\nINSERT INTO t01438 VALUES (1000);     -- ORA-01438: value larger than specified precision\n\n-- Scale overflow is rounded, not an error:\nINSERT INTO t01438 VALUES (1.234);\nSELECT * FROM t01438;\n\nDROP TABLE t01438 PURGE;","repro_note":null,"related":["oracle/ora-12899","oracle/ora-01722","sql-server/8115","postgresql/22003","mysql/1264"],"sqlly":"SQLly's schema browser shows the column's NUMBER precision beside its name, so an out-of-range value is checkable against the definition before the save.","faqs":[{"question":"Why does 1.234 fit in NUMBER(5,2) but 1000 does not?","answer":"Oracle rounds digits beyond the scale, so extra decimal places are fine. The limit is on digits left of the decimal point: NUMBER(5,2) allows 3 integer digits, so 1000 with 4 digits fails."},{"question":"Does the error tell me the value and the column?","answer":"Later releases include both, for example 'value 1000 greater than specified precision 5,2 for column TOTAL'. Older releases give only the generic message, and you find the column by testing or by using an error log."},{"question":"Can a big NUMBER column overflow on insert?","answer":"A bare NUMBER without precision accepts any value Oracle can represent, so it never raises ORA-01438. The error only comes from NUMBER(p,s) columns with a declared precision."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01438","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01476","corpus":"errors","engine":"oracle","language":"en","title":"divisor is equal to zero","description":"An expression divided a number by zero. Guard the divisor with NULLIF or CASE so a zero gives NULL or a default instead.","body":{"code":"ORA-01476","slug":"ora-01476","name":null,"message":"divisor is equal to zero","group":"data","severity":null,"sql_state":null,"summary":"An expression divided a number by zero. Guard the divisor with NULLIF or CASE so a zero gives NULL or a default instead.","meaning":"ORA-01476 is raised when a numeric expression divides by zero. Note that a query can fail on rows you didn't expect, since Oracle may evaluate the expression for rows before applying every filter.","causes":["Ratios or percentages over rows where the total is zero.","A divisor column that allows zero or a default of 0."],"fix":[{"text":"Turn a zero divisor into NULL.","sql":"SELECT clicks / NULLIF(impressions, 0) AS ctr FROM ad_stats;"},{"text":"Or return a default with `CASE`.","sql":"SELECT CASE WHEN impressions = 0 THEN 0 ELSE clicks / impressions END AS ctr FROM ad_stats;"}],"diagnostic":"-- Find the rows whose divisor is zero; they are the ones the ratio would fail on.\nSELECT * FROM t01476 WHERE impressions = 0;\n\n-- If the divisor is an expression, count its zero outcomes first:\nSELECT COUNT(*) FROM t01476 WHERE NVL(impressions, 0) + NVL(prev_impressions, 0) = 0;\n-- NULL divisors do not raise ORA-01476 (x/NULL is NULL), so only literal or computed\n-- zeros matter; NVL around a nullable column can create zeros that did not exist before.","alternatives":"Wrap every risky divisor in NULLIF(divisor, 0) as a habit in reporting queries, or return a fixed value like 0 with CASE when a zero denominator is meaningful. If zeros in the column are bad data, fix them with an UPDATE or a DEFAULT clause rather than papering over every query.","details":[],"details_title":null,"repro":"CREATE TABLE t01476 (clicks NUMBER, impressions NUMBER);\nINSERT INTO t01476 VALUES (5, 0);\n\nSELECT clicks / impressions FROM t01476;\n-- ORA-01476: divisor is equal to zero\n\n-- NULLIF turns the zero into NULL, and x/NULL is NULL:\nSELECT clicks / NULLIF(impressions, 0) AS ctr FROM t01476;\n\nDROP TABLE t01476 PURGE;","repro_note":null,"related":["sql-server/8134","postgresql/22012","oracle/ora-01722"],"sqlly":"SQLly shows the failed statement's error immediately in the results pane, and you can re-run it with a NULLIF guard in the same tab.","faqs":[{"question":"Why did the query fail when no visible row has a zero divisor?","answer":"Oracle may evaluate the division for rows before every filter is applied, and with an OR-expanded or merged plan the set it evaluates can be wider than the result. Guard the divisor with NULLIF so evaluation order stops mattering."},{"question":"What is the difference between NULLIF and NVL here?","answer":"NULLIF(x, 0) returns NULL when x is 0, which makes the division return NULL. NVL(x, 0) does the opposite: it turns NULL into 0, which can create the very divide-by-zero you were avoiding."},{"question":"Can this happen with integer and decimal division alike?","answer":"Yes. Oracle division is decimal regardless of the operands' scale, but a zero divisor raises ORA-01476 in every case, NUMBER or INTEGER."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01476","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01555","corpus":"errors","engine":"oracle","language":"en","title":"snapshot too old","description":"A long query needed old row versions from undo to stay read-consistent, but they had already been overwritten. Make the query faster or keep undo longer.","body":{"code":"ORA-01555","slug":"ora-01555","name":null,"message":"snapshot too old: rollback segment number string with name \"string\" too small","group":"resources","severity":null,"sql_state":null,"summary":"A long query needed old row versions from undo to stay read-consistent, but they had already been overwritten. Make the query faster or keep undo longer.","meaning":"Oracle gives each query a consistent view of the data as of its start, rebuilding changed rows from undo. If the query runs longer than undo is kept, the undo it needs may be gone and it fails with ORA-01555 (`snapshot too old: rollback segment number string with name \"string\" too small`).","causes":["A long-running query on tables that other sessions update heavily.","`UNDO_RETENTION` shorter than the query's run time, or an undo tablespace too small to honor it.","Fetching across commits: committing inside a loop that reads from a cursor on the same table."],"fix":[{"text":"Speed up the query (better plan, indexes, less data) so it finishes within the undo retention.","sql":null},{"text":"Raise undo retention, and size the undo tablespace to keep it.","sql":"ALTER SYSTEM SET undo_retention = 3600;\nALTER TABLESPACE undotbs1 RETENTION GUARANTEE;"},{"text":"Don't commit inside a loop over a cursor that reads the table being changed; commit after the loop.","sql":null}],"diagnostic":"-- How long is undo being kept vs. what the queries need:\nSELECT name, value FROM v$parameter\nWHERE name IN ('undo_retention','undo_management');\nSELECT tablespace_name, SUM(bytes)/1024/1024 AS free_mb\nFROM dba_free_space WHERE tablespace_name = (SELECT value FROM v$parameter WHERE name = 'undo_tablespace')\nGROUP BY tablespace_name;\n-- Stolen and expired blocks stats (10g+):\nSELECT begin_time, end_time, undoblks, txncount,\n       ssolderrcnt AS ora1555_count, nospaceerrcnt AS no_space_count\nFROM v$undostat ORDER BY begin_time DESC;\n-- v$undostat and the undo parameters need dictionary access on most setups.","alternatives":"Shrink the query's runtime with a better plan or batching so it does not outlive the retention window. Raise UNDO_RETENTION and size the undo tablespace to match (autoextend undo files with a generous MAXSIZE lets Oracle honor retention). For the fetch-across-commit variant, either commit less often, or re-open the cursor per batch so each read is short.","details":[],"details_title":null,"repro":"-- Two SQL*Plus sessions on a scratch schema; small undo (or low undo_retention) makes it fire.\n-- Session A: a table and a cursor that fetches across commits:\nCREATE TABLE snap (id NUMBER, v NUMBER);\nINSERT INTO snap SELECT level, level FROM dual CONNECT BY level <= 100000;\nCOMMIT;\nDECLARE CURSOR c IS SELECT id, v FROM snap; n NUMBER;\nBEGIN\n  FOR r IN c LOOP n := r.v; COMMIT; END LOOP;  -- commit while the cursor is still open\nEND;\n/\n-- Session B, while A's cursor is open, churns the same rows:\nUPDATE snap SET v = v + 1; COMMIT;  -- repeat until A's fetch ends\n-- Once the undo holding A's read-consistent image is overwritten, A's fetch fails:\n-- ORA-01555: snapshot too old: rollback segment number <n> with name \"<name>\" too small\nDROP TABLE snap PURGE;","repro_note":null,"related":["oracle/ora-30036","oracle/ora-01652"],"sqlly":"SQLly keeps the tab connected after the error, so you can raise the retention, shrink the query or batch the fetch and re-run without reconnecting.","faqs":[{"question":"Who is to blame, the reader or the writers?","answer":"Both and neither: the reader ran longer than the undo was kept while writers churned the same data. The fix is usually a mix: faster query plus more undo room."},{"question":"Does raising UNDO_RETENTION alone fix it?","answer":"Only if the undo tablespace is big enough to hold that much undo. With a fixed-size file, Oracle ignores retention when it needs space and reuses expired undo anyway, so the error can persist."},{"question":"Why does my PL/SQL loop get ORA-01555 without other sessions touching the table?","answer":"The fetch-across-commit pattern: the loop commits while the cursor over the same table is still open, so the cursor's own transaction invalidates its read consistency. Reopen the cursor per batch or avoid committing inside the loop."},{"question":"Does this happen in flashback queries too?","answer":"Yes, and worse: flashback query needs undo as far back as its timestamp, so a short retention window fails flashback with ORA-01555 even when ordinary reads are fine."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01555","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01652","corpus":"errors","engine":"oracle","language":"en","title":"unable to extend temp segment","description":"A sort, hash join or temporary table needed more space in the temporary tablespace than it could get. Usually a query that sorts far more data than it should.","body":{"code":"ORA-01652","slug":"ora-01652","name":null,"message":"unable to extend temp segment by string in tablespace string","group":"resources","severity":null,"sql_state":null,"summary":"A sort, hash join or temporary table needed more space in the temporary tablespace than it could get. Usually a query that sorts far more data than it should.","meaning":"Large sorts, hash joins, `GROUP BY`, index builds and global temporary tables spill to the temporary tablespace. ORA-01652 means that tablespace ran out of room for this operation. The 19c wording is `unable to extend temp segment by string in tablespace string`. One runaway query (often a missing join condition producing a Cartesian product) can use all of it.\n\nOn current releases the message also carries the SQL ID and how much temp space the session used.","causes":["A query with a missing or wrong join condition that multiplies rows.","A large sort or hash join on more data than expected, for example due to a bad plan.","The temporary tablespace is simply too small for the workload, or shared by many concurrent big queries.","Temp files with autoextend off or at their maximum size."],"fix":[{"text":"Find who is using temporary space now.","sql":"SELECT s.sid, s.username, s.sql_id, u.tablespace, u.blocks\nFROM v$tempseg_usage u JOIN v$session s ON s.saddr = u.session_addr\nORDER BY u.blocks DESC;"},{"text":"Check the query's plan and join conditions before adding space.","sql":null},{"text":"If the workload genuinely needs more, add a temp file or let it grow.","sql":"ALTER TABLESPACE temp ADD TEMPFILE SIZE 10G AUTOEXTEND ON NEXT 1G MAXSIZE 32G;"}],"diagnostic":"-- Who is using temp right now, for which SQL?\nSELECT s.sid, s.serial#, s.username, u.tablespace,\n       u.blocks * (SELECT block_size FROM v$parameter WHERE name = 'db_block_size') / 1024 / 1024 AS mb,\n       s.sql_id\nFROM v$sort_usage u\nJOIN v$session s ON s.saddr = u.session_addr\nORDER BY mb DESC;\n-- Free and total temp space (dba_free_space covers datafiles, not temp files):\nSELECT tablespace_name, SUM(bytes_free)/1024/1024 AS free_mb\nFROM v$temp_space_header GROUP BY tablespace_name;\nSELECT file_name, bytes/1024/1024 AS size_mb, autoextensible, maxbytes/1024/1024 AS max_mb\nFROM dba_temp_files;\n-- v$sort_usage, v$temp_space_header and dba_temp_files need dictionary access; a plain developer account may lack them.","alternatives":"If the query is genuinely huge, break it into stages with intermediate tables, or process it in batches. If it is a Cartesian product from a missing join condition, fixing the SQL removes the whole problem. Adding a temp file (ALTER TABLESPACE TEMP ADD TEMPFILE ... SIZE 4G AUTOEXTEND ON) buys room but hides a bad plan, so check the plan first with EXPLAIN PLAN or dbms_xplan.","details":[],"details_title":null,"repro":"-- Needs a small TEMP tablespace to be reliable; this fits the sort in memory otherwise.\n-- Force a spill with a big sort on a scratch schema:\nCREATE TABLE big AS\nSELECT level n, rpad('x', 200, 'x') pad\nFROM dual CONNECT BY level <= 2000000;\n-- Under the default automatic PGA management (11g and later) sort_area_size is ignored:\n-- the sort spills to TEMP once it outgrows PGA_AGGREGATE_TARGET, which a small target\n-- makes happen early.\nSELECT n, pad FROM big ORDER BY pad;\n-- ORA-01652: unable to extend temp segment by N in tablespace TEMP","repro_note":null,"related":["oracle/ora-01653","oracle/ora-30036","oracle/ora-04031"],"sqlly":"SQLly reports the tablespace name from the message in the error pane, so a temp-space failure is traceable to a tablespace before you log into the server.","faqs":[{"question":"TEMP segment, so is this about the TEMP tablespace only?","answer":"Almost always, yes: sorts, hash joins, and global temporary tables live there. The same error text can appear for index builds or CTAS using the target tablespace's space, but the tablespace name in the message tells you which one."},{"question":"How do I find the query that ate all the temp?","answer":"v$sort_usage joined to v$session gives the sid and sql_id per consumer while it runs. From 12.2 onward the message itself carries the sql_id and the temp usage."},{"question":"I added a temp file and it filled again. Now what?","answer":"The space is a symptom. Check the plan for a huge row source: a missing join condition, a SORT with no index support, or a HASH JOIN on unfiltered data. Fix the plan or the SQL."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01652","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01653","corpus":"errors","engine":"oracle","language":"en","title":"unable to extend table in tablespace","description":"A table needed a new extent and its tablespace had no free space left. Add a data file, resize one, or enable autoextend.","body":{"code":"ORA-01653","slug":"ora-01653","name":null,"message":"unable to extend table string.string by string in tablespace string","group":"resources","severity":null,"sql_state":null,"summary":"A table needed a new extent and its tablespace had no free space left. Add a data file, resize one, or enable autoextend.","meaning":"When a table fills its allocated extents, Oracle allocates another one in the table's tablespace. ORA-01653 means there was no room, for example `ORA-01653: unable to extend table APP.EVENTS by 1024 in tablespace USERS`. The insert or update that needed the space fails.\n\nLater releases expand it: `unable to increase tablespace tablespace_name by storage_allocated storage_units during insert or update on table schema_name.table_name`.","causes":["The tablespace's data files are full and can't grow (autoextend off or at `MAXSIZE`).","The disk or ASM disk group holding the data files is full.","A big load or a runaway process inserting rows."],"fix":[{"text":"Check free space and autoextend settings.","sql":"SELECT file_name, bytes/1024/1024 AS mb, autoextensible, maxbytes/1024/1024 AS max_mb\nFROM dba_data_files WHERE tablespace_name = 'USERS';"},{"text":"Add a data file or let an existing one grow.","sql":"ALTER TABLESPACE users ADD DATAFILE SIZE 10G AUTOEXTEND ON NEXT 1G MAXSIZE 32G;\nALTER DATABASE DATAFILE '/u01/oradata/ORCL/users01.dbf' AUTOEXTEND ON MAXSIZE UNLIMITED;"},{"text":"Or reclaim space by purging old data and the recycle bin.","sql":"PURGE RECYCLEBIN;"}],"diagnostic":"-- How full is the tablespace, and can its files grow?\nSELECT f.tablespace_name, f.file_name,\n       f.bytes/1024/1024 AS size_mb,\n       f.autoextensible, f.maxbytes/1024/1024 AS max_mb,\n       f.increment_by * (SELECT block_size FROM v$parameter WHERE name = 'db_block_size')/1024/1024 AS inc_mb\nFROM dba_data_files f WHERE f.tablespace_name = 'USERS';\n-- Free space in the same tablespace:\nSELECT tablespace_name, SUM(bytes)/1024/1024 AS free_mb\nFROM dba_free_space WHERE tablespace_name = 'USERS' GROUP BY tablespace_name;\n-- dba_data_files/dba_free_space need DBA-level or dictionary views; developers often lack them.","alternatives":"Enable autoextend or add a data file for an immediate fix. Longer term, check whether the table is bloated: a high-watertable from deleted rows or old partitions can be reclaimed with ALTER TABLE ... SHRINK SPACE (heap tables, needs row movement enabled) or by moving to a new tablespace. Partitioned tables can drop old partitions instead of growing forever.","details":[],"details_title":null,"repro":"-- Scratch tablespace with a small, non-growing data file (absolute path; a bare\n-- relative name only resolves when DB_CREATE_FILE_DEST is set):\nCREATE TABLESPACE tiny DATAFILE '/tmp/tiny01.dbf' SIZE 2M AUTOEXTEND OFF;\nCREATE TABLE tiny_t (id NUMBER, pad VARCHAR2(100)) TABLESPACE tiny;\nINSERT INTO tiny_t\nSELECT level, rpad('x', 100, 'x') FROM dual CONNECT BY level <= 200000;\n-- ORA-01653: unable to extend table SCHEMA.TINY_T by 128 in tablespace TINY\nDROP TABLE tiny_t PURGE;\nDROP TABLESPACE tiny INCLUDING CONTENTS AND DATAFILES;","repro_note":null,"related":["oracle/ora-01652","oracle/ora-01950","sql-server/1105","sqlite/sqlite-full"],"sqlly":"SQLly shows the failed insert with the tablespace named in the message, so the space problem is visible from the tab that hit it.","faqs":[{"question":"ORA-01653 vs ORA-01654 vs ORA-01652, what is the difference?","answer":"Same root cause, different object: 01653 is a table, 01654 an index, 01652 the temp segment for sorts. All mean the named tablespace had no room for the next extent."},{"question":"Why does it say a weird number like 'by 128'?","answer":"That is the block count of the extent Oracle tried to allocate. Multiply by the block size to get the space it wanted."},{"question":"Should I just set MAXSIZE UNLIMITED?","answer":"Autoextend without a sane MAXSIZE can fill the disk and take the database down, which is worse than one failed insert. Pick a cap and monitor it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01653","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01722","corpus":"errors","engine":"oracle","language":"en","title":"invalid number","description":"Oracle tried to convert a string to a number and the string isn't numeric, often through an implicit conversion when a text column is compared with a number.","body":{"code":"ORA-01722","slug":"ora-01722","name":null,"message":"invalid number","group":"data","severity":null,"sql_state":null,"summary":"Oracle tried to convert a string to a number and the string isn't numeric, often through an implicit conversion when a text column is compared with a number.","meaning":"ORA-01722 means a character value couldn't be converted to a number. The conversion is often implicit: comparing a `VARCHAR2` column with a number (`WHERE code = 10`) makes Oracle convert every row's `code` to a number, and fails on the first value that isn't one, even in rows you didn't expect to touch.\n\nNewer builds echo the offending value: `unable to convert string value containing invalid_char to a number: column_or_expression`.","causes":["Comparing a text column to a numeric literal or bind.","Non-numeric data such as `'N/A'`, spaces or a thousands separator in a text column that is converted with `TO_NUMBER`.","Decimal separators that don't match the session's `NLS_NUMERIC_CHARACTERS` (`1,5` versus `1.5`).","Inserting a value into a NUMBER column in the wrong position of a column list."],"fix":[{"text":"Compare text columns with text.","sql":"SELECT * FROM products WHERE code = '10';"},{"text":"Convert safely and find the bad rows with `DEFAULT ... ON CONVERSION ERROR` (12.2 and later) or `VALIDATE_CONVERSION`.","sql":"SELECT code FROM products WHERE VALIDATE_CONVERSION(code AS NUMBER) = 0;\nSELECT TO_NUMBER(code DEFAULT NULL ON CONVERSION ERROR) FROM products;"},{"text":"Give `TO_NUMBER` an explicit format and NLS setting when the text uses other separators.","sql":"SELECT TO_NUMBER('1.234,50', '9G999D99', 'NLS_NUMERIC_CHARACTERS='',.''') FROM dual;"}],"diagnostic":"-- Find the non-numeric values (12.2 and later):\nSELECT code FROM t01722 WHERE VALIDATE_CONVERSION(code AS NUMBER) = 0;\n-- On releases before 12.2, a PL/SQL function with an exception handler does the same job.\n\n-- Check the session's numeric settings when literals use other separators:\nSELECT parameter, value FROM nls_session_parameters\nWHERE parameter IN ('NLS_NUMERIC_CHARACTERS', 'NLS_TERRITORY');\n\n-- If the error appears without an obvious TO_NUMBER, look for a text column compared\n-- to a number or bound to a numeric host variable:\nSELECT column_name, data_type FROM all_tab_columns\nWHERE owner = USER AND table_name = 'T01722';","alternatives":"Compare text columns to text literals so no conversion happens at all. For reads that must tolerate bad data, TO_NUMBER(code DEFAULT NULL ON CONVERSION ERROR) (12.2 and later) returns NULL instead of raising. For user input, validate the format in the application before it reaches SQL.","details":[],"details_title":null,"repro":"-- Implicit conversion: comparing a text column to a number converts every row's value.\nCREATE TABLE t01722 (code VARCHAR2(10));\nINSERT INTO t01722 VALUES ('10');\nINSERT INTO t01722 VALUES ('N/A');\n\nSELECT * FROM t01722 WHERE code = 10;\n-- ORA-01722: invalid number  (fails on the 'N/A' row)\n\n-- Explicit TO_NUMBER fails the same way:\nSELECT TO_NUMBER(code) FROM t01722;\n\n-- Decimal separator depends on the session NLS setting:\nALTER SESSION SET NLS_NUMERIC_CHARACTERS = ',.';\nSELECT TO_NUMBER('1.5') FROM dual;\n-- ORA-01722: invalid number  ('.' is a group separator here)\nALTER SESSION SET NLS_NUMERIC_CHARACTERS = '.,';\n\nDROP TABLE t01722 PURGE;","repro_note":null,"related":["oracle/ora-01438","oracle/ora-06502","oracle/ora-00932","sql-server/245","postgresql/22P02","mysql/1366"],"sqlly":"SQLly shows the failed statement with the server's full error, so you can copy the suspect comparison into a new tab and test it on its own.","faqs":[{"question":"Why did the query fail on a row my WHERE clause should have excluded?","answer":"Oracle can evaluate the conversion for rows before applying every filter, and an implicit conversion from comparing a text column to a number applies to every row it reads. There is no guaranteed evaluation order, so one bad row anywhere in the table can fail the query."},{"question":"Why does TO_NUMBER('1.5') work for a colleague but not me?","answer":"The decimal and group separators come from NLS_NUMERIC_CHARACTERS, which follows the session territory. Under a comma-decimal setting, '1.5' is read as a group separator and fails. Set the parameter explicitly or pass a format model with the third TO_NUMBER argument."},{"question":"How do I clean up a column with mixed numeric and text data?","answer":"First list the bad values with VALIDATE_CONVERSION on 12.2 and later, then either fix them with an UPDATE or read them with DEFAULT NULL ON CONVERSION ERROR. Before 12.2, a small PL/SQL function that traps VALUE_ERROR and returns NULL is the usual tool."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01722","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01747","corpus":"errors","engine":"oracle","language":"en","title":"invalid user.table.column specification","description":"A column name in the statement is badly formed, most often because it is a reserved word such as DATE, LEVEL or COMMENT used without quotes.","body":{"code":"ORA-01747","slug":"ora-01747","name":null,"message":"invalid user.table.column, table.column, or column specification","group":"syntax","severity":null,"sql_state":null,"summary":"A column name in the statement is badly formed, most often because it is a reserved word such as DATE, LEVEL or COMMENT used without quotes.","meaning":"ORA-01747 means a column reference doesn't follow the `user.table.column` form Oracle expects, typically because a reserved word was used as a column name.\n\nLater releases name the column: `invalid column specification: column_name`.","causes":["A column called `DATE`, `LEVEL`, `COMMENT`, `SIZE` or another reserved word, unquoted.","A trailing comma or dot in a column list, as in `SET a = 1, WHERE`."],"fix":[{"text":"Quote reserved-word columns exactly as created (usually upper case), or rename them.","sql":"UPDATE events SET \"COMMENT\" = 'checked' WHERE id = 1;\nALTER TABLE events RENAME COLUMN \"COMMENT\" TO note;"},{"text":"Check the reserved words list in `V$RESERVED_WORDS` when naming columns.","sql":"SELECT keyword FROM v$reserved_words WHERE reserved = 'Y' ORDER BY keyword;"}],"diagnostic":"-- If the column name is a reserved word, quoting or renaming is the issue.\nSELECT keyword, reserved FROM v$reserved_words WHERE UPPER(keyword) = UPPER('&column_name');\n-- RESERVED = 'Y' means it cannot be used unquoted.\n\n-- If you suspect stray punctuation in generated SQL, list the column names Oracle knows\n-- and compare them with what the statement uses:\nSELECT column_name FROM all_tab_columns WHERE table_name = 'T01747' ORDER BY column_id;","alternatives":"Rename the column to something that is not a reserved word, which fixes every future query instead of each one. If the name must stay, always write it quoted and as \"SCHEMA\".\"TABLE\".\"COLUMN\" in generated SQL.","details":[],"details_title":null,"repro":"-- A qualified reference to a quoted reserved-word column, unquoted, raises ORA-01747.\nCREATE TABLE t01747 (id NUMBER, \"COMMENT\" VARCHAR2(20));\nINSERT INTO t01747 VALUES (1, 'x');\n\nSELECT t.comment FROM t01747 t;\n-- ORA-01747: invalid user.table.column, table.column, or column specification\n\n-- A trailing dot in a column list does the same:\nSELECT id. FROM t01747;\n\nDROP TABLE t01747 PURGE;","repro_note":null,"related":["oracle/ora-00904","oracle/ora-00933"],"sqlly":"SQLly's editor jumps to the reported column reference, and Validate SQL marks the reserved word it couldn't resolve.","faqs":[{"question":"Why does SELECT comment FROM t give a different error than t.comment?","answer":"An unqualified reserved word usually fails earlier with ORA-00904 or a syntax error. Once you qualify it as table.comment, the parser reaches the column-reference rule and that path raises ORA-01747."},{"question":"Is COMMENT actually reserved?","answer":"Yes, COMMENT is on Oracle's reserved words list, along with DATE, LEVEL, SIZE and others. V$RESERVED_WORDS shows the full list; the RESERVED column tells you whether unquoted use is blocked."},{"question":"Can I query v$reserved_words in any edition?","answer":"It is a real v$ view available to any user with access to v$ views, which most developer and DBA accounts have. If you cannot see it, Oracle publishes the reserved words list in the SQL Language Reference for your release."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01747","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01756","corpus":"errors","engine":"oracle","language":"en","title":"quoted string not properly terminated","description":"A string literal has an opening single quote but no matching closing quote, usually because a quote inside the text wasn't doubled.","body":{"code":"ORA-01756","slug":"ora-01756","name":null,"message":"quoted string not properly terminated","group":"syntax","severity":null,"sql_state":null,"summary":"A string literal has an opening single quote but no matching closing quote, usually because a quote inside the text wasn't doubled.","meaning":"Oracle reads a string literal from one single quote to the next. If the text contains an apostrophe, such as `O'Brien`, the literal ends early and the rest of the statement no longer parses; when no closing quote is found at all, Oracle raises ORA-01756.","causes":["An apostrophe inside a string that wasn't doubled: `'O'Brien'`.","A missing closing quote at the end of a literal.","Curly quotes pasted from a document, which Oracle doesn't treat as quotes.","SQL built by concatenating user input into the statement text."],"fix":[{"text":"Double each single quote inside a literal.","sql":"INSERT INTO customers (last_name) VALUES ('O''Brien');"},{"text":"Or use Oracle's alternative quoting syntax, which lets the text contain single quotes as-is.","sql":"SELECT q'[It's O'Brien's order]' FROM dual;"},{"text":"In application code, pass values as bind variables instead of concatenating them into SQL. That also prevents SQL injection.","sql":null}],"diagnostic":"-- This is a client-side parse error: the statement never reaches a running\n-- plan, so there is nothing to query in the database. Echo the exact text the\n-- application sent. In a script file, look at the flagged line and its quote\n-- balance: count single quotes per line to find the odd one.\n-- Also check for curly quotes (U+2018/U+2019) pasted from editors, which are\n-- ordinary characters, not delimiters:\n--   grep -n $'\\u2018\\|\\u2019' bad.sql","alternatives":"In application code, bind variables remove the whole problem: the driver sends the value separately from the SQL text, apostrophes included. Oracle's alternative quoting q'[...]' lets the text contain single quotes as-is; pick a delimiter like [ ] that does not appear in the text.","details":[],"details_title":null,"repro":"-- Runs on any schema.\nSELECT 'O'Brien' FROM dual;\n-- ORA-01756: quoted string not properly terminated\n-- Oracle ends the literal at the quote inside O'Brien; the rest Brien' is\n-- unparseable.\n\n-- Correct forms:\nSELECT 'O''Brien' FROM dual;\nSELECT q'[O'Brien]' FROM dual;","repro_note":null,"related":["oracle/ora-00917","oracle/ora-00911","sql-server/105"],"sqlly":"SQLly's editor highlights string literals, so an unterminated quote is visible as a colored run that never closes.","faqs":[{"question":"Why does doubling quotes work?","answer":"Inside a string literal, two single quotes in a row stand for one literal quote character. 'O''Brien' is the six characters O'Brien. That is standard SQL, not an Oracle quirk."},{"question":"The SQL looks fine on screen. Why does Oracle complain?","answer":"Two common traps: a curly quote from a word processor or chat paste looks like an apostrophe but is a different character, and an invisible trailing character after the final quote makes the parser expect more. Re-type the quotes in your editor and check the raw bytes if it still fails."},{"question":"Is this a sign of SQL injection?","answer":"It can be. SQL built by concatenating user input breaks exactly this way when a value contains an apostrophe, and the same construction is what attackers exploit. Switch those statements to bind variables; it fixes the error and the vulnerability at once."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01756","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01830","corpus":"errors","engine":"oracle","language":"en","title":"date format picture ends before end of input","description":"The string being converted to a date has more characters than the format model describes, typically a time part the format leaves out.","body":{"code":"ORA-01830","slug":"ora-01830","name":null,"message":"date format picture ends before converting entire input string","group":"data","severity":null,"sql_state":null,"summary":"The string being converted to a date has more characters than the format model describes, typically a time part the format leaves out.","meaning":"ORA-01830 means Oracle finished applying the format model while there was still input left, for example converting `'2026-11-09 14:30:00'` with `'YYYY-MM-DD'`.","causes":["A timestamp string converted with a date-only format.","Implicit conversion of a string with a time part, using an `NLS_DATE_FORMAT` without one.","Fractional seconds passed to `TO_DATE`, which doesn't support them."],"fix":[{"text":"Include every part of the string in the format.","sql":"SELECT TO_DATE('2026-11-09 14:30:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual;"},{"text":"Use `TO_TIMESTAMP` for fractional seconds.","sql":"SELECT TO_TIMESTAMP('2026-11-09 14:30:00.123', 'YYYY-MM-DD HH24:MI:SS.FF3') FROM dual;"}],"diagnostic":"-- Check what the incoming strings actually contain.\nSELECT raw_value FROM staging\nWHERE REGEXP_LIKE(raw_value, '[0-9]{2}:[0-9]{2}')\n  AND LENGTH(raw_value) > 10;\n-- Any hit is a value with a time part that a date-only format will not absorb.","alternatives":"TRUNCATE the string to the date part when you really do not care about the time, or convert with TO_TIMESTAMP when you do. If the value comes from an app, have the app send a clean date-only string or a bind of type TIMESTAMP.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\n-- The format runs out before the time part.\nSELECT TO_DATE('2026-11-09 14:30:00', 'YYYY-MM-DD') FROM dual;","repro_note":null,"related":["oracle/ora-01861","oracle/ora-01843"],"sqlly":"SQLly's editor jumps to the reported position, so the extra time part in the string is visible against the format model.","faqs":[{"question":"Why not just add HH24:MI:SS to the format?","answer":"That works, but TO_DATE throws the fractional seconds away and cannot handle them at all. If the string has .123 style fractions, use TO_TIMESTAMP with FF."},{"question":"Can an implicit conversion raise this?","answer":"Yes. If NLS_DATE_FORMAT has no time part and the string does, the format ends before the input does."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01830","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01843","corpus":"errors","engine":"oracle","language":"en","title":"not a valid month","description":"A string converted to a date has a month Oracle doesn't accept for the format in use, often because the session's NLS_DATE_FORMAT or language differs from the data.","body":{"code":"ORA-01843","slug":"ora-01843","name":null,"message":"not a valid month","group":"data","severity":null,"sql_state":null,"summary":"A string converted to a date has a month Oracle doesn't accept for the format in use, often because the session's NLS_DATE_FORMAT or language differs from the data.","meaning":"ORA-01843 means the month part of a date string didn't match the format model. Without an explicit format, `TO_DATE` and implicit conversions use the session's `NLS_DATE_FORMAT` and `NLS_DATE_LANGUAGE`, so the same SQL can work for one user and fail for another.\n\nLater releases word it `An invalid month was specified.`","causes":["Relying on implicit conversion: `WHERE order_date = '2026-11-09'` with a session format of `DD-MON-RR`.","Day and month swapped between formats such as `MM/DD` and `DD/MM`.","Month names in a language other than the session's `NLS_DATE_LANGUAGE`."],"fix":[{"text":"Always give an explicit format, or use an ANSI date literal.","sql":"SELECT * FROM orders WHERE order_date >= DATE '2026-11-09';\nSELECT TO_DATE('09/11/2026', 'DD/MM/YYYY') FROM dual;"},{"text":"Pin the language for month names when needed.","sql":"SELECT TO_DATE('09-NOV-2026', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=ENGLISH') FROM dual;"}],"diagnostic":"-- What format does this session use for implicit conversions?\nSELECT parameter, value FROM nls_session_parameters\nWHERE parameter IN ('NLS_DATE_FORMAT', 'NLS_DATE_LANGUAGE');","alternatives":"ANSI date literals like DATE '2026-11-09' skip the format model entirely and always mean November 9. Passing a real DATE or bind variable instead of a string removes the conversion from the picture.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\nALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-RR';\n-- '13' is not a month name in English, so the MON slot fails:\nSELECT TO_DATE('26-13-09', 'DD-MON-RR') FROM dual;\n-- ORA-01843: not a valid month","repro_note":null,"related":["oracle/ora-01861","oracle/ora-01830","sql-server/241","postgresql/22007","mysql/1292"],"sqlly":"SQLly shows the server's message with the statement that failed, so a date-format mismatch is visible next to the query; an explicit TO_DATE format in the re-run settles it.","faqs":[{"question":"The same query works on one machine and fails on another. Why?","answer":"The two sessions have different NLS_DATE_FORMAT or NLS_DATE_LANGUAGE settings, often set by the client tool. The SQL is identical; the implicit format is not."},{"question":"Does this error mean the data is bad?","answer":"No. It means the string could not be read with the format Oracle was told to use. The month may be perfectly valid under a different format."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01843","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01861","corpus":"errors","engine":"oracle","language":"en","title":"literal does not match format string","description":"A string given to TO_DATE or an implicit date conversion doesn't match the format model, for example a different separator or field order.","body":{"code":"ORA-01861","slug":"ora-01861","name":null,"message":"literal does not match format string","group":"data","severity":null,"sql_state":null,"summary":"A string given to TO_DATE or an implicit date conversion doesn't match the format model, for example a different separator or field order.","meaning":"ORA-01861 means the characters in a date string don't line up with the format model, such as `TO_DATE('2026-11-09', 'DD/MM/YYYY')`. Implicit conversions use the session's `NLS_DATE_FORMAT`, which is why this often appears when a string is compared with a DATE column.","causes":["A format model that doesn't match the string's layout.","Comparing a DATE column with a string and relying on the session's date format.","Mixed data in a text column that stores dates in several layouts."],"fix":[{"text":"Use a format model that matches the string exactly.","sql":"SELECT TO_DATE('2026-11-09 14:30', 'YYYY-MM-DD HH24:MI') FROM dual;"},{"text":"Use date and timestamp literals for constants.","sql":"SELECT * FROM orders WHERE created_at >= TIMESTAMP '2026-11-09 00:00:00';"},{"text":"Find rows that don't parse, on 12.2 and later.","sql":"SELECT raw_date FROM staging WHERE VALIDATE_CONVERSION(raw_date AS DATE, 'YYYY-MM-DD') = 0;"}],"diagnostic":"-- Which rows in a staging column will not parse? 12.2 and later.\nSELECT raw_date FROM staging\nWHERE VALIDATE_CONVERSION(raw_date AS DATE, 'YYYY-MM-DD') = 0;","alternatives":"For columns that may hold several layouts, try each format in order with VALIDATE_CONVERSION, or clean the data on load with an external table and a rejection clause. Storing dates in DATE columns instead of VARCHAR2 avoids the whole class of problem.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\nALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YYYY';\n-- The string layout does not match the session format.\nSELECT TO_DATE('2026-11-09') FROM dual;","repro_note":null,"related":["oracle/ora-01843","oracle/ora-01830","sql-server/241","postgresql/22007"],"sqlly":"SQLly's editor jumps to the reported position, and re-running with an explicit TO_DATE format is a one-line change in the same tab.","faqs":[{"question":"Is this the same as ORA-01843?","answer":"They are cousins. ORA-01861 is about the overall layout of the string versus the format model. ORA-01843 is specifically about the month part not making sense."},{"question":"Why does it fail in production but not in my dev session?","answer":"Because NLS_DATE_FORMAT differs between sessions. Code that relies on the session format is timing-dependent by nature."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01861","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-01950","corpus":"errors","engine":"oracle","language":"en","title":"no privileges on tablespace","description":"The user has no space quota on the tablespace where it is trying to create or grow a table or index. Grant a quota.","body":{"code":"ORA-01950","slug":"ora-01950","name":null,"message":"no privileges on tablespace 'string'","group":"resources","severity":null,"sql_state":null,"summary":"The user has no space quota on the tablespace where it is trying to create or grow a table or index. Grant a quota.","meaning":"Creating segments (tables, indexes, LOBs) uses space in a tablespace, and users need a quota there. ORA-01950 means the owner of the object has no quota, or none left, on that tablespace. Since 12c the `RESOURCE` role no longer grants `UNLIMITED TABLESPACE`, which is why new users often hit this on their first insert.\n\nRecent releases say it outright: `The user user_name has insufficient quota on tablespace tablespace_name.`","causes":["A new user with no quota on its default tablespace.","A quota that was set and has been used up.","Creating an object in a tablespace other than the user's default one."],"fix":[{"text":"Grant a quota on the tablespace (an administrator runs this).","sql":"ALTER USER app_user QUOTA 10G ON users;\n-- or\nALTER USER app_user QUOTA UNLIMITED ON users;"},{"text":"Check current quotas.","sql":"SELECT tablespace_name, bytes, max_bytes FROM dba_ts_quotas WHERE username = 'APP_USER';"}],"diagnostic":"-- Quota per user per tablespace:\nSELECT username, tablespace_name, bytes/1024/1024 AS used_mb,\n       max_bytes/1024/1024 AS max_quota_mb\nFROM dba_ts_quotas WHERE username = 'APP_OWNER';\n-- A missing row means no quota at all on that tablespace. -1 in MAX_BYTES means unlimited.\n-- dba_ts_quotas needs DBA or SELECT_CATALOG_ROLE access.","alternatives":"Grant a quota on the user's default tablespace (ALTER USER x QUOTA UNLIMITED ON users, or a fixed amount). If the table is meant to live elsewhere, either move it or grant quota on that tablespace. Creating the table as a privileged schema owner and granting access to the app user sidesteps the quota but mixes ownership models.","details":[],"details_title":null,"repro":"-- As a DBA account:\nCREATE USER quota_test IDENTIFIED BY pw DEFAULT TABLESPACE users;\nGRANT CREATE SESSION, CREATE TABLE TO quota_test;\n-- As quota_test:\nCREATE TABLE t (id NUMBER);\nINSERT INTO t VALUES (1);\n-- ORA-01950: no privileges on tablespace 'USERS'\n-- Note: CREATE TABLE succeeds; the first INSERT fails, when the segment is actually created.","repro_note":null,"related":["oracle/ora-01031","oracle/ora-01653"],"sqlly":"SQLly surfaces the exact no-quota message with the user it connected as, so a missing tablespace quota is obvious on the first failed insert.","faqs":[{"question":"Why does the CREATE TABLE succeed and the INSERT fail?","answer":"Oracle creates the segment lazily, on the first insert (or deferred segment creation since 11.2, the default since 12c for heap tables). The quota check happens when the segment is built, so the error lands on the INSERT."},{"question":"Didn't the RESOURCE role cover this?","answer":"Before 12c, RESOURCE granted UNLIMITED TABLESPACE. That stopped in 12c, which is why users that worked before now hit ORA-01950 on first insert."},{"question":"How do I give unlimited quota safely?","answer":"Per tablespace: ALTER USER x QUOTA UNLIMITED ON users. The global UNLIMITED TABLESPACE privilege covers every tablespace including SYSTEM, which is rarely what you want; prefer the targeted grant."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-01950","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-02266","corpus":"errors","engine":"oracle","language":"en","title":"keys referenced by enabled foreign keys","description":"TRUNCATE (or a similar operation) was refused because enabled foreign keys in other tables reference this table's primary or unique key.","body":{"code":"ORA-02266","slug":"ora-02266","name":null,"message":"unique/primary keys in table referenced by enabled foreign keys","group":"constraints","severity":null,"sql_state":null,"summary":"TRUNCATE (or a similar operation) was refused because enabled foreign keys in other tables reference this table's primary or unique key.","meaning":"`TRUNCATE TABLE` removes all rows without checking each one, so Oracle refuses it while an enabled foreign key in another table references the table, even if the child table is empty. A self-referencing foreign key doesn't block it.","causes":["Truncating a parent table that other tables reference.","Clearing test data in parent-first order."],"fix":[{"text":"Find the referencing constraints.","sql":"SELECT c.owner, c.table_name, c.constraint_name\nFROM all_constraints c\nJOIN all_constraints p ON p.owner = c.r_owner AND p.constraint_name = c.r_constraint_name\nWHERE c.constraint_type = 'R' AND p.table_name = 'CUSTOMERS';"},{"text":"Disable them, truncate, and enable them again (after emptying or fixing the child tables).","sql":"ALTER TABLE orders DISABLE CONSTRAINT orders_customer_fk;\nTRUNCATE TABLE customers;\nALTER TABLE orders ENABLE CONSTRAINT orders_customer_fk;"},{"text":"On 12c and later, `TRUNCATE TABLE customers CASCADE` also truncates the child tables, but only when the foreign keys are defined with `ON DELETE CASCADE`.","sql":null},{"text":"Or use `DELETE`, which checks each row against the foreign keys.","sql":null}],"diagnostic":"-- List the enabled foreign keys pointing at the table, and whether the child\n-- tables actually hold rows. An empty child still blocks the truncate; that is\n-- by design, not a bug.\nSELECT c.owner, c.table_name AS child_table, c.constraint_name,\n       c.delete_rule\nFROM all_constraints c\nJOIN all_constraints p\n  ON p.owner = c.r_owner AND p.constraint_name = c.r_constraint_name\nWHERE c.constraint_type = 'R'\n  AND c.status = 'ENABLED'\n  AND p.owner = USER\n  AND p.table_name = 'PARENT_DEMO';\n\n-- Rows in each child table:\nSELECT table_name,\n       (SELECT TO_NUMBER(extractvalue(xmltype(dbms_xmlgen.getxml(\n          'SELECT COUNT(*) c FROM ' || table_name)), '/ROWSET/ROW/C'))\n        FROM dual) AS row_count\nFROM user_tables\nWHERE table_name = 'CHILD_DEMO';","alternatives":"TRUNCATE TABLE ... CASCADE on 12c and later truncates the children too, but only when the foreign keys were declared ON DELETE CASCADE. DELETE FROM parent works whenever the children are empty or the rows they point at are gone first, and it respects the constraints the whole time.","details":[],"details_title":null,"repro":"-- Runs on any schema.\nCREATE TABLE parent_demo (id NUMBER PRIMARY KEY);\nCREATE TABLE child_demo (\n  id NUMBER PRIMARY KEY,\n  parent_id NUMBER REFERENCES parent_demo(id)\n);\n\n-- Even with zero rows in child_demo:\nTRUNCATE TABLE parent_demo;\n-- ORA-02266: unique/primary keys in table referenced by enabled foreign keys\n\nDROP TABLE child_demo;\nDROP TABLE parent_demo;","repro_note":null,"related":["oracle/ora-02449","oracle/ora-02292","mysql/1701"],"sqlly":"SQLly's ER diagram shows the enabled foreign keys into a table, so a refused TRUNCATE is predictable before you run it.","faqs":[{"question":"The child table is empty. Why is the truncate still refused?","answer":"TRUNCATE skips per-row checks by design, so Oracle cannot confirm the children are empty at truncate time in the same cheap pass. The rule is on the constraint, not the data: any enabled foreign key referencing the table blocks it until you disable the key or use CASCADE."},{"question":"I disabled the constraint and re-enabled it. Is that safe?","answer":"Only if the child tables were emptied or had no rows referencing the truncated data. ENABLE does validate the data, so an orphaned child row makes the enable fail with ORA-02298. Disable, truncate children if needed, truncate parent, then enable."},{"question":"Does DROP TABLE hit the same error?","answer":"No, it raises a different one: ORA-02449, keys referenced by enabled foreign keys. DROP TABLE parent CASCADE CONSTRAINTS gets past it, but that silently drops the child foreign key constraints, so check what will disappear before you use it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-02266","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-02291","corpus":"errors","engine":"oracle","language":"en","title":"integrity constraint violated - no parent key","description":"An INSERT or UPDATE set a foreign key to a value that doesn't exist in the parent table. Insert the parent first or fix the value.","body":{"code":"ORA-02291","slug":"ora-02291","name":null,"message":"integrity constraint (string.string) violated - parent key not found","group":"constraints","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE set a foreign key to a value that doesn't exist in the parent table. Insert the parent first or fix the value.","meaning":"A foreign key requires every non-null value in the child column to exist in the referenced parent key. ORA-02291 means the new or changed child row points at a parent that isn't there. The message names the foreign key constraint.","causes":["Inserting child rows before their parent rows, for example loading tables in the wrong order.","A typo or wrong id in the foreign key column.","The parent row exists but hasn't been committed by another session, so this session can't see it.","Data copied from another environment where the parent ids differ."],"fix":[{"text":"Find the parent table and columns of the constraint.","sql":"SELECT c.constraint_name, c.table_name, p.table_name AS parent_table, pc.column_name\nFROM all_constraints c\nJOIN all_constraints p ON p.owner = c.r_owner AND p.constraint_name = c.r_constraint_name\nJOIN all_cons_columns pc ON pc.owner = p.owner AND pc.constraint_name = p.constraint_name\nWHERE c.constraint_name = 'ORDERS_CUSTOMER_FK';"},{"text":"Insert the parent row first, then the child.","sql":null},{"text":"For loads where order is hard to control, make the constraint deferrable so it is checked at commit.","sql":"ALTER TABLE orders DROP CONSTRAINT orders_customer_fk;\nALTER TABLE orders ADD CONSTRAINT orders_customer_fk\n    FOREIGN KEY (customer_id) REFERENCES customers (id)\n    DEFERRABLE INITIALLY DEFERRED;"}],"diagnostic":"-- Confirm the constraint named in the error and what it references\nSELECT c.constraint_name, cc.column_name,\n       c.r_constraint_name AS parent_constraint,\n       rc.table_name AS parent_table, rcc.column_name AS parent_column\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nJOIN all_constraints rc ON rc.owner = c.r_owner AND rc.constraint_name = c.r_constraint_name\nJOIN all_cons_columns rcc ON rcc.owner = rc.owner AND rcc.constraint_name = rc.constraint_name\nWHERE c.constraint_name = 'SYS_C0012345';\n\n-- Does the parent value exist? Case and whitespace count\nSELECT * FROM customers WHERE customer_id = 42;\n\n-- Find every child row already orphaned by earlier loads\nSELECT o.* FROM orders o\nLEFT JOIN customers c ON c.customer_id = o.customer_id\nWHERE c.customer_id IS NULL;","alternatives":"Load data in dependency order: parents first, then children. For bulk loads, consider disabling the constraint during the load and validating afterwards, but run the orphan query above before re-enabling, since enable fails if orphans remain. `ON DELETE CASCADE` on the parent does not help inserts; it only affects deletes. Data loading tools can also defer constraint checks to commit with deferrable constraints.","details":[],"details_title":null,"repro":"-- ORA-02291: integrity constraint violated - parent key not found\nCREATE TABLE customers (customer_id NUMBER PRIMARY KEY);\nCREATE TABLE orders (order_id NUMBER PRIMARY KEY, customer_id NUMBER\n  REFERENCES customers(customer_id));\n\nINSERT INTO orders VALUES (1, 42);\n-- ORA-02291: integrity constraint (SCHEMA.SYS_C0012345) violated -\n-- parent key not found\n\nINSERT INTO customers VALUES (42);\nINSERT INTO orders VALUES (1, 42);\n-- works","repro_note":null,"related":["oracle/ora-02292","oracle/ora-00001","postgresql/23503","mysql/1452","sql-server/547","sqlite/sqlite-constraint-foreignkey"],"sqlly":"SQLly's ER diagram shows the foreign keys between your tables, so you can see which parent table a failing insert depends on.","faqs":[{"question":"The parent row exists. Why does the insert still fail?","answer":"Check that the session inserting into the child can see the parent. If another session inserted the parent without committing yet, your session does not see it and the foreign key check fails. Also compare exact values: trailing spaces, different case, or a wrong data type conversion all look equal to the eye and unequal to Oracle."},{"question":"Can I get the constraint name without the system-generated SYS_C name being useless?","answer":"Yes, query all_constraints with that name to get the child and parent table, as in the diagnostic above. Going forward, name your foreign keys explicitly (`CONSTRAINT fk_orders_customer FOREIGN KEY ...`) so error messages are readable."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-02291","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-02292","corpus":"errors","engine":"oracle","language":"en","title":"integrity constraint violated - child record found","description":"A DELETE or key UPDATE on a parent row was blocked because child rows still reference it through a foreign key.","body":{"code":"ORA-02292","slug":"ora-02292","name":null,"message":"integrity constraint (string.string) violated - child record found","group":"constraints","severity":null,"sql_state":null,"summary":"A DELETE or key UPDATE on a parent row was blocked because child rows still reference it through a foreign key.","meaning":"ORA-02292 is the other side of a foreign key: you tried to delete a parent row, or change its key, while rows in a child table still point at it. The message names the child's foreign key constraint.","causes":["Deleting a customer, order or other parent that still has dependent rows.","Updating a primary key value that child rows use.","Cleaning up test data in the wrong order."],"fix":[{"text":"Find the child table and delete or reassign the child rows first.","sql":"SELECT owner, table_name FROM all_constraints\nWHERE constraint_name = 'ORDERS_CUSTOMER_FK';\nDELETE FROM orders WHERE customer_id = 42;\nDELETE FROM customers WHERE id = 42;"},{"text":"If children should go with the parent, recreate the foreign key with `ON DELETE CASCADE` (or `ON DELETE SET NULL`).","sql":"ALTER TABLE orders ADD CONSTRAINT orders_customer_fk\n    FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;"}],"diagnostic":"-- Resolve the constraint name from the error to its child table and column\nSELECT c.table_name AS child_table, cc.column_name AS child_column,\n       rc.table_name AS parent_table\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nJOIN all_constraints rc ON rc.owner = c.r_owner AND rc.constraint_name = c.r_constraint_name\nWHERE c.constraint_name = 'SYS_C0012345';\n\n-- Which child rows block this delete?\nSELECT * FROM orders WHERE customer_id = 42;\n\n-- Find every foreign key pointing at this table, not just the one in the error\nSELECT c.constraint_name, c.table_name, cc.column_name\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nWHERE c.constraint_type = 'R'\n  AND c.r_constraint_name IN (\n    SELECT constraint_name FROM all_constraints\n    WHERE owner = USER AND table_name = 'CUSTOMERS' AND constraint_type IN ('P','U'))\n  AND c.owner = USER;","alternatives":"Delete children first, then the parent, in one transaction. If children should vanish with the parent, add `ON DELETE CASCADE` when creating or modifying the constraint. If children should stay but lose the reference, add `ON DELETE SET NULL` (the child column must allow NULL). Deleting or updating the parent key through a view still hits the same constraints.","details":[],"details_title":null,"repro":"-- ORA-02292: integrity constraint violated - child record found\nCREATE TABLE customers (customer_id NUMBER PRIMARY KEY);\nCREATE TABLE orders (order_id NUMBER PRIMARY KEY, customer_id NUMBER\n  REFERENCES customers(customer_id));\n\nINSERT INTO customers VALUES (42);\nINSERT INTO orders VALUES (1, 42);\n\nDELETE FROM customers WHERE customer_id = 42;\n-- ORA-02292: integrity constraint (SCHEMA.SYS_C0012345) violated -\n-- child record found","repro_note":null,"related":["oracle/ora-02291","oracle/ora-02449","mysql/1451","postgresql/23503","sql-server/547"],"sqlly":"The ER diagram draws the foreign keys between your tables, so you can see which child rows block a delete before running it.","faqs":[{"question":"How is ORA-02292 different from ORA-02291?","answer":"ORA-02291 happens on insert or update in the child, when the parent is missing. ORA-02292 happens on delete or key update in the parent, when children still reference the row. Same constraint system, opposite direction."},{"question":"Why did the delete fail when the child table is empty as far as I can see?","answer":"You may be looking at the wrong table or schema. The constraint name in the error identifies the real child table; resolve it with the diagnostic query. Uncommitted rows from another session also block the delete even though you cannot see them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-02292","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-02449","corpus":"errors","engine":"oracle","language":"en","title":"unique/primary keys referenced by foreign keys","description":"DROP TABLE failed because foreign keys in other tables reference this table's primary or unique key. Drop those constraints first or use CASCADE CONSTRAINTS.","body":{"code":"ORA-02449","slug":"ora-02449","name":null,"message":"unique/primary keys in table referenced by foreign keys","group":"constraints","severity":null,"sql_state":null,"summary":"DROP TABLE failed because foreign keys in other tables reference this table's primary or unique key. Drop those constraints first or use CASCADE CONSTRAINTS.","meaning":"Oracle won't drop a table while other tables have foreign keys pointing at it, since those constraints would be left referring to nothing. ORA-02449 tells you such constraints exist.","causes":["Dropping a parent table that other tables reference.","Rebuilding a schema in the wrong order."],"fix":[{"text":"See which constraints reference the table.","sql":"SELECT c.owner, c.table_name, c.constraint_name\nFROM all_constraints c\nJOIN all_constraints p ON p.owner = c.r_owner AND p.constraint_name = c.r_constraint_name\nWHERE c.constraint_type = 'R' AND p.table_name = 'CUSTOMERS';"},{"text":"Drop the table together with the foreign keys that reference it (the child tables and their data stay).","sql":"DROP TABLE customers CASCADE CONSTRAINTS;"}],"diagnostic":"-- List every foreign key that points at this table before dropping it\nSELECT c.owner, c.constraint_name, c.table_name AS child_table,\n       cc.column_name, c.delete_rule\nFROM all_constraints c\nJOIN all_cons_columns cc ON cc.owner = c.owner AND cc.constraint_name = c.constraint_name\nWHERE c.constraint_type = 'R'\n  AND c.r_constraint_name IN (\n    SELECT constraint_name FROM all_constraints\n    WHERE owner = USER AND table_name = 'CUSTOMERS' AND constraint_type IN ('P','U'));\n\n-- Any orphaned recyclebin objects or other-schema references? Widen the\n-- owner filter above or query dba_constraints if you have privileges.","alternatives":"Drop the child constraints first (`ALTER TABLE orders DROP CONSTRAINT fk_orders_customer`), or drop the child tables, then the parent. `DROP TABLE customers CASCADE CONSTRAINTS` drops the referencing foreign keys in the same statement, which is faster but silently removes those constraints, so only use it when you know the children can live without them. `TRUNCATE` is not affected; ORA-02449 applies to `DROP`.","details":[],"details_title":null,"repro":"-- ORA-02449: unique/primary keys in table referenced by foreign keys\nCREATE TABLE customers (customer_id NUMBER PRIMARY KEY);\nCREATE TABLE orders (order_id NUMBER PRIMARY KEY, customer_id NUMBER\n  REFERENCES customers(customer_id));\n\nDROP TABLE customers;\n-- ORA-02449: unique/primary keys in table referenced by foreign keys\n\nDROP TABLE orders;\nDROP TABLE customers;\n-- works: child dropped first","repro_note":null,"related":["oracle/ora-02292","oracle/ora-02291","sql-server/3726","mysql/1451"],"sqlly":"SQLly's ER diagram shows every foreign key pointing at a table, so a DROP that will refuse is predictable from the diagram.","faqs":[{"question":"Does CASCADE CONSTRAINTS delete the child rows?","answer":"No. It drops the foreign key constraints themselves, not any data. Child tables keep their rows; they just no longer reference the parent. Any application logic depending on those constraints now has nothing enforcing it."},{"question":"How do I drop and recreate a parent table without losing the children's constraints?","answer":"There is no clean way; foreign keys cannot survive the parent being dropped. The usual pattern is: capture the FK definitions from all_constraints, drop the constraints, replace the parent table, recreate the FKs with `ALTER TABLE ... ADD CONSTRAINT ...`."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-02449","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-03113","corpus":"errors","engine":"oracle","language":"en","title":"end-of-file on communication channel","description":"The connection to the database ended unexpectedly: the server process died, the instance went down, or the network dropped the connection.","body":{"code":"ORA-03113","slug":"ora-03113","name":null,"message":"end-of-file on communication channel","group":"connection","severity":null,"sql_state":null,"summary":"The connection to the database ended unexpectedly: the server process died, the instance went down, or the network dropped the connection.","meaning":"ORA-03113 means the client was talking to its server process and the connection closed without warning. It is a symptom; the cause is on the server or the network. If the server process crashed, the database alert log and trace files usually show an ORA-00600 or ORA-07445 at the same moment.","causes":["The server process serving the session crashed, often logged as ORA-00600 or ORA-07445.","The instance was shut down or crashed.","A firewall or load balancer dropped an idle connection.","The session was killed by an administrator or resource limit."],"fix":[{"text":"Check the alert log and trace files on the server for errors at the time of the disconnect. The `V$DIAG_INFO` view shows where they are.","sql":"SELECT name, value FROM v$diag_info;"},{"text":"Reconnect. If the same statement kills the connection each time, it has hit a server bug; search My Oracle Support for the ORA-00600 arguments.","sql":null},{"text":"For idle disconnects, enable dead connection detection with `SQLNET.EXPIRE_TIME` in the server's `sqlnet.ora`, or keep connections from sitting idle behind firewalls.","sql":null}],"diagnostic":"-- Where are the diagnostics?\nSELECT name, value FROM v$diag_info;\n-- On the server, read the alert log around the disconnect time and search for ORA-00600/ORA-07445-class entries\n-- and check whether the PMON/SMON background processes or the instance itself died:\nSELECT instance_name, status, startup_time FROM v$instance;\n-- If the instance is up and the alert log is clean, the disconnect was in the network layer or the session was killed.","alternatives":"If a genuine ORA-00600/ORA-07445 is in the alert log, search My Oracle Support for the first argument of that error; hitting a known bug often has a patch or workaround, and raising a service request with the trace file is the normal path. For client-side patterns (one tool drops, another survives), rule out the middle layer: connection pools, VPNs and NAT firewalls each can close sessions the database never ended.","details":[],"details_title":null,"repro":"-- A full repro needs a server-side failure; from SQL alone you can simulate the symptom\n-- by killing your own session's server process from a second session.\n-- Session 1 (as scratch_user):\n--   SELECT SYS_CONTEXT('USERENV','SID') FROM dual;  -- note the SID\n-- Session 2 (as DBA):\nSELECT sid, serial#, paddr FROM v$session WHERE username = 'SCRATCH_USER';\nALTER SYSTEM KILL SESSION '<sid>,<serial#>' IMMEDIATE;   -- session 1's next call then fails\n-- with ORA-00028 (session killed) or ORA-03113 (process gone), depending on client and timing\n-- In a real crash, the alert log usually shows ORA-00600 or ORA-07445 at the same timestamp; V$DIAG_INFO locates it.","repro_note":null,"related":["oracle/ora-03135","oracle/ora-12170","mysql/2013","mysql/2006","postgresql/08006"],"sqlly":"When a connection dies mid-query, SQLly marks the tab disconnected instead of leaving stale results, so the next run can't silently hit a dead session.","faqs":[{"question":"Is ORA-03113 always a crash?","answer":"No. It means the server process your session was talking to is gone. That can be an instance crash, a killed session, a resource-killer like the OS OOM killer taking the process, or the network closing the path. The alert log tells you which."},{"question":"Why do I see it during a big sort or export?","answer":"Long-running operations are the ones that expose resource exhaustion: temp space, PGA limits or the OOM killer can take the server process down mid-run. Check the alert log at the failure time and watch memory and temp usage while it runs."},{"question":"Can a client version mismatch cause ORA-03113?","answer":"Rarely on its own; version mismatches usually produce ORA-03134 or character-set errors instead. A dropped connection during handshake more often means a firewall or proxy is in the path, or the listener handed you to a server process that died immediately, which again shows in the alert log."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-03113","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-03135","corpus":"errors","engine":"oracle","language":"en","title":"connection lost contact","description":"The client lost its connection to the database, typically after a firewall or timeout cut an idle session, or the server process ended.","body":{"code":"ORA-03135","slug":"ora-03135","name":null,"message":"connection lost contact","group":"connection","severity":null,"sql_state":null,"summary":"The client lost its connection to the database, typically after a firewall or timeout cut an idle session, or the server process ended.","meaning":"ORA-03135 is reported when the connection to the server is gone, often when the client next tries to use a session that a firewall, a timeout or the server silently ended while it was idle.","causes":["A firewall or NAT device timing out an idle connection.","A profile limit such as `IDLE_TIME` or a server-side timeout ending the session.","The server process or instance stopping."],"fix":[{"text":"Reconnect, and have long-lived applications validate pooled connections before use.","sql":null},{"text":"Set `SQLNET.EXPIRE_TIME` (in minutes) in the server's `sqlnet.ora` so the database probes idle connections and firewalls see traffic.","sql":null},{"text":"Check the user's profile for idle limits.","sql":"SELECT p.resource_name, p.limit\nFROM dba_users u JOIN dba_profiles p ON p.profile = u.profile\nWHERE u.username = 'APP_USER' AND p.resource_name IN ('IDLE_TIME', 'CONNECT_TIME');"}],"diagnostic":"-- Which sessions are idle long enough to be dropped by a firewall?\nSELECT sid, serial#, username, status, last_call_et AS seconds_idle, machine, program\nFROM v$session WHERE type = 'USER' ORDER BY last_call_et DESC;\n-- Server-side keepalive setting (minutes; 0 = off):\nSELECT value FROM v$parameter WHERE name = 'sqlnet_expire_time';\n-- On the network side, ask what idle timeout the firewalls between client and server apply; compare with your idle duration.","alternatives":"Set SQLNET.EXPIRE_TIME in sqlnet.ora on the server (and client, in newer releases DIED inherits it) to a value below the firewall idle timeout so probe packets keep the path alive. In the application, configure the pool to validate or test connections on borrow and to discard dead ones instead of handing them out. Resource Manager's MAX_IDLE_TIME can also end idle sessions deliberately; check it if drops correlate with idle time.","details":[],"details_title":null,"repro":"-- Needs a firewall or TCP keepalive setting that kills idle connections; SQL alone cannot drop a live session,\n-- but you can reproduce the client-side symptom by killing an idle session from another session:\n-- Session 1: connect as scratch_user and let it sit idle\n-- Session 2 (DBA):\nSELECT sid, serial# FROM v$session WHERE username = 'SCRATCH_USER' AND status = 'INACTIVE';\nALTER SYSTEM DISCONNECT SESSION '<sid>,<serial#>' POST_TRANSACTION;   -- or IMMEDIATE\n-- When session 1 next runs something it reports ORA-03135, or ORA-00028 first, depending on\n-- client and timing (SQL*Plus; other clients word it differently).","repro_note":null,"related":["oracle/ora-03113","mysql/2013","mysql/4031"],"sqlly":"SQLly surfaces the exact server error when a saved connection's session has been dropped, so an idle-timeout kill shows up on the next query instead of staying mysterious.","faqs":[{"question":"ORA-03113 versus ORA-03135: what is the difference?","answer":"ORA-03113 usually lands while the session is active and means the process or connection died under you. ORA-03135 is the typical error when a session that sat idle comes back to find the connection silently gone, most often killed by a firewall or NAT idle timeout."},{"question":"What does SQLNET.EXPIRE_TIME actually do?","answer":"It makes Oracle send a small probe packet every N minutes so the connection never looks idle to firewalls and NAT devices. It is set in sqlnet.ora in minutes; a value like 10 is common. It adds negligible traffic and is the standard fix for mid-morning dead-connection reports."},{"question":"Why do only some of our offices see this?","answer":"Different network paths have different middleboxes. Sites that traverse a VPN or a stateful firewall with a short idle timeout drop connections; direct paths survive. Compare the network route of a failing site with a working one."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-03135","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-04021","corpus":"errors","engine":"oracle","language":"en","title":"timeout waiting to lock object","description":"A session waited too long for a library cache lock on an object, typically while recompiling a package or altering a table that other sessions are using.","body":{"code":"ORA-04021","slug":"ora-04021","name":null,"message":"timeout occurred while waiting to lock object string string string string string","group":"locking","severity":null,"sql_state":null,"summary":"A session waited too long for a library cache lock on an object, typically while recompiling a package or altering a table that other sessions are using.","meaning":"ORA-04021 means a session couldn't get a library cache lock or pin on an object within the timeout. It is common when compiling or replacing a PL/SQL package, procedure or view while other sessions are running it.","causes":["`CREATE OR REPLACE` or `ALTER ... COMPILE` on a package that other sessions are executing.","DDL on a table while long-running statements are using it."],"fix":[{"text":"Find who is using the object.","sql":"SELECT sid, serial#, username, program FROM v$session\nWHERE sid IN (SELECT sid FROM v$access WHERE object = 'BILLING_PKG');"},{"text":"Deploy the change when the object is idle, or ask the sessions using it to finish first.","sql":null},{"text":"For zero-downtime PL/SQL changes, look at edition-based redefinition.","sql":null}],"diagnostic":"-- Who is in the package right now? Needs read access to v$access and v$session.\nSELECT s.sid, s.serial#, s.username, s.program\nFROM v$access a\nJOIN v$session s ON s.sid = a.sid\nWHERE a.object = 'SLOW_P';\n-- DBA_DDL_LOCKS (needs privileges) shows the exact library cache lock held.","alternatives":"Compile with a shorter timeout so the deploy fails fast and retries instead of hanging a pipeline. Edition-based redefinition (11gR2 and later) lets new code compile and run in a new edition while old sessions keep the old one.","details":[],"details_title":null,"repro":"-- Two SQL*Plus sessions on a scratch schema.\n-- Session A creates a long-running call. DBMS_LOCK.SLEEP needs EXECUTE on DBMS_LOCK,\n-- which is usually DBA-only; DBMS_SESSION.SLEEP (18c and later) needs no extra grant:\nCREATE OR REPLACE PROCEDURE slow_p IS BEGIN DBMS_SESSION.SLEEP(300); END;\n/\n-- Session A:\nEXEC slow_p; -- still running\n-- Session B:\nALTER PROCEDURE slow_p COMPILE; -- ORA-04021 after the timeout","repro_note":null,"related":["oracle/ora-00054","oracle/ora-04068"],"sqlly":"SQLly surfaces the server's exact timeout message with the object name, so the blocked recompile is attributable before you hunt sessions.","faqs":[{"question":"Why does replacing a harmless procedure block?","answer":"CREATE OR REPLACE takes an exclusive library cache lock on the object. Anyone currently executing it pins it, so the replace waits, and ORA-04021 is the wait timing out."},{"question":"The sessions show INACTIVE. Are they holding it?","answer":"Check v$access, not session status. An inactive session that called the package earlier can still be mid-call if it is blocked on a network write or a lock of its own."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-04021","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-04031","corpus":"errors","engine":"oracle","language":"en","title":"unable to allocate bytes of shared memory","description":"Oracle couldn't find a large enough piece of memory in the shared pool or another SGA pool, often from heavy hard parsing of SQL without bind variables.","body":{"code":"ORA-04031","slug":"ora-04031","name":null,"message":"unable to allocate string bytes of shared memory (\"string\",\"string\",\"string\",\"string\")","group":"resources","severity":null,"sql_state":null,"summary":"Oracle couldn't find a large enough piece of memory in the shared pool or another SGA pool, often from heavy hard parsing of SQL without bind variables.","meaning":"ORA-04031 means an allocation in the SGA (usually the shared pool, sometimes the large or Java pool) failed. The message names the pool and what was being allocated. Shared pool fragmentation from many unique SQL statements, typically SQL built with literal values instead of bind variables, is a classic cause.\n\nLater releases name the heap: `out of shared memory in heap_name`.","causes":["Applications concatenating values into SQL text, so every statement is new and must be hard parsed and cached.","A shared pool (or SGA) sized too small for the workload.","Large allocations for parallel query or RMAN in a too-small large pool."],"fix":[{"text":"Use bind variables in application SQL so statements are shared.","sql":"SELECT * FROM orders WHERE customer_id = :customer_id;"},{"text":"Check pool sizes and free memory, and enlarge the SGA if needed.","sql":"SELECT pool, name, bytes FROM v$sgastat WHERE name = 'free memory';\nALTER SYSTEM SET sga_target = 8G SCOPE = SPFILE;"},{"text":"As a short-term relief only, flushing the shared pool frees fragments, at the cost of re-parsing everything.","sql":"ALTER SYSTEM FLUSH SHARED_POOL;"}],"diagnostic":"-- Needs SELECT on v$ views. The ORA-04031 message itself names the pool and\n-- allocation size; start there.\nSELECT pool, name, bytes\nFROM v$sgastat\nWHERE name = 'free memory'\nORDER BY pool;\n\n-- Is the workload sharing SQL? A ratio near 1 means statements are reused.\nSELECT SUM(sharable_mem) AS shared_sql_bytes, COUNT(*) AS sql_statements\nFROM v$sqlarea;\n\n-- Literal-heavy SQL (no binds) is the usual cause. Look for statements executed\n-- once with distinct text:\nSELECT sql_id, SUBSTR(sql_text, 1, 60) AS sql_text, executions\nFROM v$sqlarea\nWHERE executions = 1\nORDER BY sharable_mem DESC\nFETCH FIRST 20 ROWS ONLY;","alternatives":"If you can't change the application to use binds quickly, increasing the shared pool or SGA target buys room. CURSOR_SHARING = FORCE makes Oracle rewrite literals to binds automatically; it helps with 4031 but can change execution plans, so test it before relying on it.","details":[],"details_title":null,"repro":"-- Difficult to reproduce on demand because it depends on pool fragmentation.\n-- Closest safe approximation: saturate the shared pool with thousands of distinct\n-- unshared statements, each a new parse entry.\nBEGIN\n  FOR i IN 1 .. 20000 LOOP\n    EXECUTE IMMEDIATE 'SELECT ' || i || ' FROM dual';\n  END LOOP;\nEND;\n/\n-- On a small SGA this drives up shared-pool usage and may surface ORA-04031.\n-- Check the damage afterwards:\nSELECT name, bytes FROM v$sgastat WHERE pool = 'shared pool' AND name = 'free memory';","repro_note":null,"related":["oracle/ora-01652","sql-server/701","sqlite/sqlite-nomem"],"sqlly":"SQLly's connection test reports the server's exact error text, so a shared-pool allocation failure is distinguishable from a network problem by the message alone.","faqs":[{"question":"Is flushing the shared pool a fix?","answer":"No. It coalesces free space for a while but throws out every cached plan and cursor, so the whole instance re-parses and often runs slower right after. Treat it as an emergency valve while you fix the real cause, usually unshared SQL or a too-small pool."},{"question":"How do I read the error message?","answer":"It names the pool, the byte size of the failed allocation and the shared-pool object it came from. 'shared pool', 'unknown object' with a small size like 4K usually means fragmentation or too little free memory; large allocations usually point at the large pool for parallel query or RMAN."},{"question":"Does ASMM or AMM make this impossible?","answer":"No. Automatic memory management moves memory between pools, but a workload that hard-parses everything can still fragment the shared pool or outgrow the SGA. Fix the SQL first, then size memory."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-04031","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-04068","corpus":"errors","engine":"oracle","language":"en","title":"existing state of packages has been discarded","description":"A package this session had already used was recompiled or changed, so its package-level variables were reset. The next call usually works.","body":{"code":"ORA-04068","slug":"ora-04068","name":null,"message":"existing state of packages string string string has been discarded","group":"plsql","severity":null,"sql_state":null,"summary":"A package this session had already used was recompiled or changed, so its package-level variables were reset. The next call usually works.","meaning":"Package-level variables keep their values for the life of a session. When a package (or something it depends on) is recompiled, sessions that had used it lose that state, and their next call raises ORA-04068, often followed by ORA-04061 and ORA-04065 or ORA-06508. Calling again in the same session normally succeeds, with the state re-initialized.","causes":["Deploying a new version of a package while application sessions are connected.","A change to a table, type or other object the package depends on, which invalidated it.","Packages with global variables (stateful packages) used from connection pools."],"fix":[{"text":"Retry the call once in the application when this error is caught, then continue.","sql":null},{"text":"Recompile invalid objects after deployments.","sql":"SELECT object_name, object_type FROM user_objects WHERE status = 'INVALID';\nEXEC DBMS_UTILITY.COMPILE_SCHEMA(schema => USER, compile_all => FALSE);"},{"text":"Keep packages stateless where you can (no package-level variables), or mark them `PRAGMA SERIALLY_REUSABLE`, so recompiling them doesn't discard session state.","sql":null}],"diagnostic":"-- Did a recompile or invalidation happen around the error time? Timestamps\n-- show it. Needs SELECT on the dictionary views.\nSELECT object_name, object_type, status,\n       TO_CHAR(last_ddl_time, 'YYYY-MM-DD HH24:MI:SS') AS last_ddl\nFROM user_objects\nWHERE object_type IN ('PACKAGE', 'PACKAGE BODY')\nORDER BY last_ddl_time DESC;\n\n-- Does the package have session state? Any package-level variable (except\n-- constants) means recompiles discard state. Check the package spec and body\n-- source for declarations outside procedures:\nSELECT text FROM user_source\nWHERE name = 'STATE_DEMO' AND type = 'PACKAGE'\n  AND text NOT LIKE '%constant%'\n  AND REGEXP_LIKE(text, '^\\s*[a-z_]+\\s+[a-z_]+\\s*(:=|;)', 'i');","alternatives":"For deployments, recompile everything immediately after the change so the invalidation window is short, and schedule it when pools are idle. Where a stateful package can't be avoided, have the application catch ORA-04068 and retry once, since the very next call after the error succeeds.","details":[],"details_title":null,"repro":"-- Session A (SQL*Plus #1):\nCREATE OR REPLACE PACKAGE state_demo AS\n  g_calls NUMBER := 0;\n  FUNCTION bump RETURN NUMBER;\nEND;\n/\nCREATE OR REPLACE PACKAGE BODY state_demo AS\n  FUNCTION bump RETURN NUMBER IS BEGIN g_calls := g_calls + 1; RETURN g_calls; END;\nEND;\n/\n\n-- Session B (SQL*Plus #2), while A is connected:\nSELECT state_demo.bump FROM dual;   -- works, initializes state\n\n-- Back in session A:\nCREATE OR REPLACE PACKAGE state_demo AS\n  g_calls NUMBER := 0;\n  FUNCTION bump RETURN NUMBER;\n  PROCEDURE noop;\nEND;\n/\nCREATE OR REPLACE PACKAGE BODY state_demo AS\n  FUNCTION bump RETURN NUMBER IS BEGIN g_calls := g_calls + 1; RETURN g_calls; END;\n  PROCEDURE noop IS BEGIN NULL; END;\nEND;\n/\n\n-- Session B again:\nSELECT state_demo.bump FROM dual;\n-- ORA-04068: existing state of packages has been discarded\n-- The next call after this one succeeds.","repro_note":null,"related":["oracle/ora-06508","oracle/ora-04021","oracle/ora-06512"],"sqlly":"SQLly surfaces the ORA-04068/ORA-06508 stack with the package name, and a plain re-run of the statement from the tab succeeds after the discard.","faqs":[{"question":"The next call works fine. Is the error harmless?","answer":"The call that failed was rolled back and its effects lost, so it is not harmless, but the package itself is fine: after one ORA-04068 the session reloads the new version and continues. The risk is application code that treats the error as fatal or doesn't retry."},{"question":"Why doesn't this happen with procedures and functions?","answer":"It does not happen for stateless code because there is no session state to lose. A standalone procedure with no package-level variables recompiles and the next call just runs the new version. Only packages carrying state raise ORA-04068 in other sessions."},{"question":"Does PRAGMA SERIALLY_REUSABLE fix it?","answer":"It avoids ORA-04068 because serially reusable packages don't keep state across calls, so there is nothing to discard. The tradeoff: package variables reset on every call, and cursor state behaves differently. Only use it where per-call reset semantics fit the code."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-04068","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-04088","corpus":"errors","engine":"oracle","language":"en","title":"error during execution of trigger","description":"A trigger raised an error while running. The real error is listed with it in the stack; this one names the trigger as SCHEMA.TRIGGER.","body":{"code":"ORA-04088","slug":"ora-04088","name":null,"message":"error during execution of trigger ' string.string '","group":"plsql","severity":null,"sql_state":null,"summary":"A trigger raised an error while running. The real error is listed with it in the stack; this one names the trigger as SCHEMA.TRIGGER.","meaning":"ORA-04088 wraps an error that happened inside a trigger, telling you which trigger it was, for example `ORA-04088: error during execution of trigger 'APP.ORDERS_BIU'`. The error above or below it in the stack (an ORA-06512 line and the original error) says what went wrong.","causes":["Any error inside the trigger body, such as ORA-01403, ORA-04091 or a `RAISE_APPLICATION_ERROR` the trigger uses to enforce a rule.","An invalid trigger after a change to an object it uses."],"fix":[{"text":"Read the accompanying errors and look at the trigger's code.","sql":"SELECT trigger_body FROM all_triggers WHERE owner = 'APP' AND trigger_name = 'ORDERS_BIU';"},{"text":"Fix the data or the trigger. To test whether the trigger is the cause, an administrator can disable it temporarily.","sql":"ALTER TRIGGER app.orders_biu DISABLE;"}],"diagnostic":"-- Pull the trigger's code and find the failing path:\nSELECT trigger_name, triggering_event, status FROM all_triggers\nWHERE table_name = 'T2' AND owner = 'APP';\nSELECT line, text FROM user_source\nWHERE name = 'T2_CHECK' AND type = 'TRIGGER' ORDER BY line;","alternatives":"If the trigger enforces a data rule, a CHECK constraint is usually better: it cannot raise ORA-04088, it is declarative, and it survives rewrites. If the trigger only fails because it is invalid (an object it uses was dropped), fix the dependency and recompile the trigger; nothing about the DML itself is wrong.","details":[],"details_title":null,"repro":"CREATE TABLE t2 (id NUMBER, price NUMBER);\nCREATE OR REPLACE TRIGGER t2_check\nBEFORE INSERT ON t2 FOR EACH ROW\nBEGIN\n  IF :new.price < 0 THEN\n    RAISE_APPLICATION_ERROR(-20001, 'negative price');\n  END IF;\nEND;\n/\nINSERT INTO t2 VALUES (1, -5);\n-- ORA-20001: negative price\n-- ORA-04088: error during execution of trigger 'SCHEMA.T2_CHECK'","repro_note":null,"related":["oracle/ora-04091","oracle/ora-06512","sqlite/sqlite-constraint-trigger"],"sqlly":"The error pane shows the full stack: your error, ORA-04088, ORA-06512. The trigger that wrapped the failure is identified in one place.","faqs":[{"question":"Is ORA-04088 the real error?","answer":"No, it names the trigger. Read up or down the stack for the original error, commonly an ORA-20xxx user error, ORA-01403, or ORA-04091."},{"question":"My DML statement did not change, why does it now fail?","answer":"Someone added or changed a trigger on the table. Check all_triggers for the table's triggers and their status; the trigger raises during your statement even though your own SQL is fine."},{"question":"Does the trigger's error roll back my statement?","answer":"Yes. The statement fails and its changes are rolled back, as with any error raised mid-statement."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-04088","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-04091","corpus":"errors","engine":"oracle","language":"en","title":"table is mutating, trigger may not see it","description":"A row-level trigger (or a function it calls) queried or changed the table the triggering statement is modifying, which Oracle forbids.","body":{"code":"ORA-04091","slug":"ora-04091","name":null,"message":"table string.string is mutating, trigger/function may not see it","group":"plsql","severity":null,"sql_state":null,"summary":"A row-level trigger (or a function it calls) queried or changed the table the triggering statement is modifying, which Oracle forbids.","meaning":"While a statement is changing a table, its rows are in flux, so Oracle doesn't let a row-level trigger on that table read or modify it. In 19c that message is `table string.string is mutating, trigger/function may not see it`. Statement-level triggers and compound triggers don't have this restriction for the statement-level parts.","causes":["A `FOR EACH ROW` trigger that runs `SELECT COUNT(*)` or `UPDATE` on its own table.","A function called from the trigger, or from the DML itself, that queries the table.","Cascading foreign key actions that reach a table with such a trigger."],"fix":[{"text":"Use the `:NEW` and `:OLD` values instead of re-querying the row.","sql":null},{"text":"Move checks that need the whole table into a compound trigger: collect ids in the row section and query the table in `AFTER STATEMENT`.","sql":"CREATE OR REPLACE TRIGGER orders_limit\nFOR INSERT ON orders COMPOUND TRIGGER\n  AFTER STATEMENT IS\n    l_count NUMBER;\n  BEGIN\n    SELECT COUNT(*) INTO l_count FROM orders WHERE status = 'OPEN';\n    IF l_count > 1000 THEN\n      RAISE_APPLICATION_ERROR(-20001, 'Too many open orders');\n    END IF;\n  END AFTER STATEMENT;\nEND;"},{"text":"Or enforce the rule with a constraint or in the application instead of a trigger.","sql":null}],"diagnostic":"-- Which row-level triggers exist on the table, and do they read or write it?\nSELECT t.trigger_name, t.triggering_event, t.base_table_name\nFROM all_triggers t\nWHERE t.table_name = 'TLOG' AND t.owner = 'APP';\n-- Then check each trigger body for its own table's name:\nSELECT name, line, text FROM user_source\nWHERE name = 'T_COUNT' AND LOWER(text) LIKE '%tlog%';","alternatives":"A compound trigger (11g onward) is the standard workaround: buffer the changed keys in its row-level section, then process them in the AFTER STATEMENT section where reading the table is legal. For simple totals, an aggregated materialized view with fast refresh can replace the trigger. If the trigger only validates the new row against others in the set, restate the rule as a constraint or move it to an application-level check that runs after commit.","details":[],"details_title":null,"repro":"CREATE TABLE tlog (id NUMBER);\nCREATE OR REPLACE TRIGGER t_count\nAFTER INSERT ON tlog FOR EACH ROW\nDECLARE\n  n NUMBER;\nBEGIN\n  SELECT COUNT(*) INTO n FROM tlog; -- mutating-table read\nEND;\n/\nINSERT INTO tlog VALUES (1);\n-- ORA-04091: table SCHEMA.TLOG is mutating, trigger/function may not see it","repro_note":null,"related":["oracle/ora-04088","oracle/ora-06512"],"sqlly":"SQLly shows the mutating-table error with the trigger name from the stack, and the schema browser lists that table's triggers one click away.","faqs":[{"question":"Why is the restriction there at all?","answer":"The rows the statement is changing have no settled state mid-statement, so reading the table could see a mixture of before and after values that no one ever committed."},{"question":"Does a SELECT in a row trigger always fail?","answer":"Only when it targets the same table the DML is touching, or a table that cascade-deletes into it. Reads of other tables are fine."},{"question":"Is a statement-level trigger also forbidden from reading the table?","answer":"No. The AFTER STATEMENT (and BEFORE STATEMENT) parts of a compound trigger, and plain statement-level triggers, may read the table; the restriction applies to the row-level sections."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-04091","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-06502","corpus":"errors","engine":"oracle","language":"en","title":"PL/SQL: numeric or value error","description":"A PL/SQL assignment or conversion failed: a value too long for a variable, a string that isn't a number, or a NULL into a NOT NULL variable.","body":{"code":"ORA-06502","slug":"ora-06502","name":null,"message":"PL/SQL: numeric or value error string","group":"plsql","severity":null,"sql_state":null,"summary":"A PL/SQL assignment or conversion failed: a value too long for a variable, a string that isn't a number, or a NULL into a NOT NULL variable.","meaning":"ORA-06502 is raised in PL/SQL when a value can't be stored or converted, and the text after the message says how, for example `character string buffer too small` or `character to number conversion error`.\n\nIn newer releases the message is `PL/SQL: value or conversion error`.","causes":["`character string buffer too small`: assigning a string longer than a `VARCHAR2(n)` variable, often a local variable smaller than the column it receives.","`character to number conversion error`: assigning non-numeric text to a NUMBER variable.","`number precision too large`: a number that doesn't fit a constrained NUMBER variable.","Assigning NULL to a variable declared `NOT NULL`."],"fix":[{"text":"Declare variables with `%TYPE` so they match the column they hold.","sql":"DECLARE\n  l_name customers.name%TYPE;\nBEGIN\n  SELECT name INTO l_name FROM customers WHERE id = 1;\nEND;"},{"text":"Read the line number in the accompanying ORA-06512 and check the assignment there; convert explicitly with `TO_NUMBER(... DEFAULT NULL ON CONVERSION ERROR)` when input may be bad.","sql":null}],"diagnostic":"-- Compare the variable size with the column it receives; %TYPE removes the guesswork.\nSELECT column_name, data_type, data_length, char_length\nFROM all_tab_columns\nWHERE owner = USER AND table_name = 'YOUR_TABLE'\n  AND column_name = 'YOUR_COLUMN';\n-- Then read the ORA-06512 that accompanies the 06502: it names the exact line where the assignment or conversion failed.","alternatives":"Where input can be dirty, convert with TO_NUMBER(expr DEFAULT NULL ON CONVERSION ERROR) (12.2 and later) instead of a bare assignment, and validate lengths in the app before insert. Declaring with %TYPE or %ROWTYPE keeps PL/SQL variables in step with column definitions when the schema changes.","details":[],"details_title":null,"repro":"-- Run on a scratch schema.\nDECLARE\n  l_name VARCHAR2(5);\nBEGIN\n  l_name := 'abcdef'; -- character string buffer too small\nEND;\n/\nDECLARE\n  l_num NUMBER;\nBEGIN\n  l_num := '12x3'; -- character to number conversion error\nEND;\n/","repro_note":null,"related":["oracle/ora-06512","oracle/ora-01722","oracle/ora-12899"],"sqlly":"SQLly shows the full PL/SQL error stack including the ORA-06512 lines, so the failing line of the block is readable in the error pane.","faqs":[{"question":"Why does the error mention a line in a package I did not change?","answer":"The data changed, not the code. A value that used to fit the declared VARCHAR2 no longer does. The ORA-06512 backtrace points at the assignment."},{"question":"Does VARCHAR2(5) mean 5 bytes or 5 characters?","answer":"Bytes by default. With character-length semantics it is 5 characters, which matters for multibyte text. A 'buffer too small' error on short-looking strings is often a multibyte value exceeding the byte limit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-06502","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-06503","corpus":"errors","engine":"oracle","language":"en","title":"PL/SQL: function returned without value","description":"A PL/SQL function reached its end, or an exception handler finished, without executing a RETURN statement.","body":{"code":"ORA-06503","slug":"ora-06503","name":null,"message":"PL/SQL: Function returned without value","group":"plsql","severity":null,"sql_state":null,"summary":"A PL/SQL function reached its end, or an exception handler finished, without executing a RETURN statement.","meaning":"Every path through a PL/SQL function must end in `RETURN value`. ORA-06503 means the function ran off its end, typically through an `IF` branch or an exception handler that has no `RETURN`.","causes":["An `IF` or `CASE` without a branch for every case.","An exception handler that logs the error but doesn't return or re-raise."],"fix":[{"text":"Make sure every path returns, including exception handlers.","sql":"CREATE OR REPLACE FUNCTION grade (p_score NUMBER) RETURN VARCHAR2 IS\nBEGIN\n  IF p_score >= 90 THEN RETURN 'A';\n  ELSIF p_score >= 75 THEN RETURN 'B';\n  END IF;\n  RETURN 'C';\nEXCEPTION\n  WHEN OTHERS THEN\n    RAISE;\nEND;"}],"diagnostic":"-- Read every path through the function and find the ones without RETURN.\n-- all_source gives the stored text; scan the IF/ELSIF branches and EXCEPTION handlers:\nSELECT line, text FROM user_source\nWHERE name = 'GRADE' AND type = 'FUNCTION'\nORDER BY line;","alternatives":"If you cannot touch the function, a wrapper can defend the caller: call it inside a block with an exception handler for ORA-06503, though that treats the symptom. The real fix is a final RETURN before EXCEPTION, or re-raising from handlers so the caller sees the original error instead of a silent null.","details":[],"details_title":null,"repro":"CREATE OR REPLACE FUNCTION no_return (p NUMBER) RETURN NUMBER IS\nBEGIN\n  IF p > 0 THEN RETURN p; END IF;\n  -- no RETURN when p <= 0\nEND;\n/\nSELECT no_return(-1) FROM dual;\n-- ORA-06503: PL/SQL: Function returned without value\n-- ORA-06512: at \"SCHEMA.NO_RETURN\", line 5","repro_note":null,"related":["oracle/ora-06512","oracle/ora-01403"],"sqlly":"SQLly's error pane shows the ORA-06512 line that names the function and line, so the missing RETURN path is findable from the error alone.","faqs":[{"question":"Why didn't the compiler catch the missing RETURN?","answer":"PL/SQL checks for a RETURN on the last executable path but cannot prove a value on every branch through complex IF logic. A branch that ends without RETURN compiles and fails at runtime."},{"question":"What does the caller get when this happens?","answer":"ORA-06503 is raised to the caller, so the query or statement fails. The function does not silently return NULL; a NO_DATA_NEEDED exception is the only related case that is not an error."},{"question":"What about NO_DATA_NEEDED?","answer":"Since 12c you can raise that exception in pipelined table functions to stop producing rows early. It is related to return semantics but is not an error and must not be caught by a WHEN OTHERS handler."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-06503","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-06508","corpus":"errors","engine":"oracle","language":"en","title":"PL/SQL: could not find program unit being called","description":"PL/SQL called a procedure or package that is missing, invalid or not accessible at run time, often after it was dropped or failed to recompile.","body":{"code":"ORA-06508","slug":"ora-06508","name":null,"message":"PL/SQL: could not find program unit being called string","group":"plsql","severity":null,"sql_state":null,"summary":"PL/SQL called a procedure or package that is missing, invalid or not accessible at run time, often after it was dropped or failed to recompile.","meaning":"ORA-06508 means a called program unit couldn't be found or loaded when the call ran. It frequently follows ORA-04068 (existing state of packages has been discarded) after a package was recompiled while sessions were using it.","causes":["The called package or procedure was dropped or is invalid after a change it depends on.","The calling session had package state discarded by a recompilation.","Missing privilege on the called unit."],"fix":[{"text":"Find invalid objects and recompile them.","sql":"SELECT object_name, object_type FROM user_objects WHERE status = 'INVALID';\nALTER PACKAGE billing_pkg COMPILE BODY;"},{"text":"Reconnect sessions that held old package state, or retry the call once.","sql":null}],"diagnostic":"-- Is the unit there and valid? Do you have the privilege?\nSELECT owner, object_name, object_type, status\nFROM all_objects\nWHERE object_name = 'MY_PKG' AND object_type IN ('PACKAGE','PACKAGE BODY');\n-- Any compile errors after the change:\nSELECT line, position, text FROM all_errors\nWHERE owner = 'APP' AND name = 'MY_PKG';","alternatives":"If the error follows a deployment, the fix is often just reconnecting: the session's cached state is stale. If it repeats without any recompiles, check DDL jobs or an IDE auto-recompiling under you. Setting the package's statelessness helps long term: SERIALLY_REUSABLE pragma or moving state into tables avoids ORA-04068 entirely.","details":[],"details_title":null,"repro":"-- Recompile a package while another session holds it open:\n-- Session A: runs the package (keeps instance state cached)\n-- Session B:\nALTER PACKAGE app.my_pkg COMPILE;\n-- Session A, next call:\n-- ORA-04068: existing state of packages has been discarded\n-- ORA-06508: PL/SQL: could not find program unit being called","repro_note":null,"related":["oracle/ora-04068","oracle/ora-06550","oracle/ora-04021"],"sqlly":"SQLly surfaces the whole error stack (ORA-04068 plus ORA-06508), so a discarded package state reads as a retry, not a bug.","faqs":[{"question":"ORA-06508 right after ORA-04068, do I have a real problem?","answer":"Often no. ORA-04068 means the session's cached package state was discarded by a recompile. Reconnect or re-invoke; the package was recompiled, so the next call usually works."},{"question":"It happens every call, no recompiles happening. What then?","answer":"Check the unit still exists and is valid, and that your role or grant survived. A revoked EXECUTE privilege or an invalid body that fails recompile gives ORA-06508 on every call."},{"question":"Does this happen to stateless packages?","answer":"The discard happens for packages with state (variables at package level or in the body). Purely stateless packages can be recompiled without invalidating sessions' calls."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-06508","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-06512","corpus":"errors","engine":"oracle","language":"en","title":"at line (PL/SQL error stack)","description":"Not an error by itself: a line in the error stack showing which PL/SQL unit and line raised or passed on the real error listed above it.","body":{"code":"ORA-06512","slug":"ora-06512","name":null,"message":"at string line string","group":"plsql","severity":null,"sql_state":null,"summary":"Not an error by itself: a line in the error stack showing which PL/SQL unit and line raised or passed on the real error listed above it.","meaning":"ORA-06512 entries form a backtrace: `ORA-06512: at \"APP.BILLING_PKG\", line 42`. The first error in the stack (above the ORA-06512 lines) is the real problem; each ORA-06512 shows a PL/SQL unit and line it passed through, innermost first.\n\nThe 19c text is `at string line string`.","causes":["Any unhandled error inside PL/SQL, such as ORA-01403, ORA-06502 or a `RAISE_APPLICATION_ERROR`."],"fix":[{"text":"Fix the first error in the stack. Open the unit and line named by the first ORA-06512 to see where it was raised.","sql":"SELECT line, text FROM all_source\nWHERE owner = 'APP' AND name = 'BILLING_PKG' AND type = 'PACKAGE BODY'\nAND line BETWEEN 35 AND 45;"},{"text":"When you log errors in exception handlers, include `DBMS_UTILITY.FORMAT_ERROR_BACKTRACE` so the line numbers aren't lost.","sql":"EXCEPTION\n  WHEN OTHERS THEN\n    log_error(SQLERRM || ' ' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);\n    RAISE;"}],"diagnostic":"-- Show the source around the line the first ORA-06512 names:\nSELECT line, text FROM all_source\nWHERE owner = 'APP' AND name = 'BILLING_PKG'\n  AND line BETWEEN 37 AND 47\nORDER BY line;\n-- all_source holds the stored text of every unit you can see, so the named\n-- line matches what was compiled (recompile if the file on disk has drifted).","alternatives":"If the stack is long, work innermost out: the first error is the real one and the ORA-06512 lines are just the call path. SQL*Plus and SQLcl show the same stack; SQL Developer formats it in the message tab.","details":[],"details_title":null,"repro":"-- ORA-06512 is just the backtrace line; this block reproduces a full stack:\nCREATE OR REPLACE FUNCTION boom RETURN NUMBER IS\nBEGIN\n  RETURN TO_NUMBER('not-a-number'); -- raises ORA-06502\nEND;\n/\nSELECT boom FROM dual;\n-- ORA-06502: PL/SQL: numeric or value error ...\n-- ORA-06512: at \"SCHEMA.BOOM\", line 3","repro_note":null,"related":["oracle/ora-01403","oracle/ora-06502","oracle/ora-06550"],"sqlly":"SQLly's error pane lists the complete ORA-06512 backtrace, so the unit and line named first is readable without re-running anything.","faqs":[{"question":"Why do I get ORA-06512 when my error is ORA-01403?","answer":"The stack lists every frame the error passed through. ORA-01403 is what failed; each ORA-06512 line names a PL/SQL unit and line it traveled through on the way out. Fix the top error, not the 06512 lines."},{"question":"Does the line number match my source file?","answer":"It matches the text Oracle has stored for that unit, which is what all_source returns. If you edited the file but never recompiled, the line number points at the compiled version, not your editor's."},{"question":"Can ORA-06512 appear without a real error above it?","answer":"No. It is always a frame in the stack of some other error. If you see it alone, something above it was cut off or swallowed by logging."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-06512","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-06550","corpus":"errors","engine":"oracle","language":"en","title":"PL/SQL compilation error at line, column","description":"A PL/SQL block failed to compile. The message gives the line and column, and the PLS- error after it says what's wrong.","body":{"code":"ORA-06550","slug":"ora-06550","name":null,"message":"line string, column string: string","group":"plsql","severity":null,"sql_state":null,"summary":"A PL/SQL block failed to compile. The message gives the line and column, and the PLS- error after it says what's wrong.","meaning":"ORA-06550 reports a compilation error in an anonymous block or a call, as `ORA-06550: line 3, column 5:` followed by the actual problem, usually a `PLS-` error such as `PLS-00201: identifier 'X' must be declared` or `PLS-00103: Encountered the symbol ...`.","causes":["A syntax error, such as a missing `;` or `END`.","Referencing an undeclared variable or an object you can't access (PLS-00201).","Calling a procedure with the wrong number or types of arguments (PLS-00306)."],"fix":[{"text":"Read the PLS- error that follows and go to the line and column given.","sql":null},{"text":"For stored code, list the compile errors.","sql":"SELECT line, position, text FROM user_errors\nWHERE name = 'BILLING_PKG' ORDER BY sequence;"},{"text":"If the identifier is another schema's object, qualify it and get the privilege granted directly (not through a role).","sql":null}],"diagnostic":"SHOW ERRORS FUNCTION APP.MY_FUNC; -- SQL*Plus / SQLcl, right after compiling\n-- or, for any stored unit:\nSELECT line, position, text FROM all_errors\nWHERE owner = 'APP' AND name = 'MY_FUNC'\nORDER BY sequence;","alternatives":"For an anonymous block there is no stored unit, so the ORA-06550 line and column are the only pointers you get. Paste the exact block into the client and count to the reported position; the PLS- error usually names the symbol that confused the parser.","details":[],"details_title":null,"repro":"BEGIN\n  x := 1; -- undeclared: PLS-00201 under ORA-06550\nEND;\n/\n-- ORA-06550: line 2, column 3:\n-- PLS-00201: identifier 'X' must be declared","repro_note":null,"related":["oracle/ora-06512","oracle/ora-06508","oracle/ora-00904"],"sqlly":"SQLly's editor jumps to the line and column ORA-06550 reports and shows the PLS- error beneath it in the results pane.","faqs":[{"question":"Is ORA-06550 the actual problem?","answer":"Rarely. It is the wrapper that carries the line and column. The PLS- or ORA- error printed under it says what is wrong."},{"question":"Why does it say an identifier must be declared when the table exists?","answer":"PLS-00201 is about PL/SQL names, not SQL tables. A missing DECLARE section, a typo, or an object you have no privilege on all produce it."},{"question":"Does the block still run partially?","answer":"No. If compilation fails, nothing in the block executes. Stored units can stay compiled with errors and fail at call time instead, which shows up as ORA-04068 or PLS- errors on invocation."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-06550","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-08177","corpus":"errors","engine":"oracle","language":"en","title":"can't serialize access for this transaction","description":"A SERIALIZABLE transaction tried to change a row that another transaction changed and committed after this one began. Roll back and retry.","body":{"code":"ORA-08177","slug":"ora-08177","name":null,"message":"can't serialize access for this transaction","group":"locking","severity":null,"sql_state":null,"summary":"A SERIALIZABLE transaction tried to change a row that another transaction changed and committed after this one began. Roll back and retry.","meaning":"In `SERIALIZABLE` isolation, a transaction sees the database as of its start. If it tries to update or delete a row that another transaction modified and committed after that point, Oracle can't make the result look serial and raises ORA-08177. The transaction should be rolled back and run again.","causes":["Concurrent updates to the same rows under `ISOLATION LEVEL SERIALIZABLE`.","Long serializable transactions on busy tables."],"fix":[{"text":"Roll back and retry the transaction in the application.","sql":"ROLLBACK;"},{"text":"Use the default `READ COMMITTED` isolation unless the transaction really needs serializable behavior, and keep serializable transactions short.","sql":"SET TRANSACTION ISOLATION LEVEL READ COMMITTED;"}],"diagnostic":"-- Isolation level of your own session (READCOMMITTED or SERIALIZABLE):\nSELECT SYS_CONTEXT('USERENV', 'TRANSACTION_ISOLATION') AS isolation_level FROM dual;\n-- Your session's in-flight transaction, if any (v$transaction has no isolation column):\nSELECT t.xidusn, t.xidslot, t.xidsqn, t.start_time, s.sid, s.username\nFROM v$transaction t JOIN v$session s ON s.taddr = t.addr\nWHERE s.sid = SYS_CONTEXT('USERENV','SID');\n-- READCOMMITTED here means the session is not serializable; SERIALIZABLE plus a\n-- conflicting writer is the scenario from the causes.","alternatives":"READ COMMITTED with explicit SELECT FOR UPDATE on the rows you depend on gives most workloads the guarantee they want without aborts. For report-grade consistency without writes, a read-only transaction (SET TRANSACTION READ ONLY) never hits ORA-08177.","details":[],"details_title":null,"repro":"-- Two SQL*Plus sessions on a scratch schema.\n-- Both:\nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n-- Session A:\nCREATE TABLE ser (id NUMBER, v NUMBER);\nINSERT INTO ser VALUES (1, 0);\nCOMMIT;\nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\nUPDATE ser SET v = 1 WHERE id = 1;\n-- Session B:\nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\nUPDATE ser SET v = 2 WHERE id = 1;\nCOMMIT;\n-- Session A:\nUPDATE ser SET v = 3 WHERE id = 1; -- ORA-08177 on commit or on the next conflicting write","repro_note":null,"related":["oracle/ora-00060","postgresql/40001","sql-server/3960","sqlite/sqlite-busy-snapshot"],"sqlly":"SQLly shows the failed statement with its error in the results pane, so a serializable conflict is visible at the statement that lost the race.","faqs":[{"question":"Is this a bug in my code?","answer":"Under serializable isolation it is expected behavior, not corruption. The transaction's snapshot is stale relative to a committed change, and Oracle refuses to overwrite it. Your code decides whether to retry or move to a weaker isolation level."},{"question":"Does undo retention matter here?","answer":"Yes. Serializable transactions read from undo, and a long one can also hit ORA-01555 if the undo it needs is gone."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-08177","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12154","corpus":"errors","engine":"oracle","language":"en","title":"TNS: could not resolve the connect identifier","description":"The Oracle client couldn't turn the name you connected with into a database address: the alias isn't in tnsnames.ora, or the client is reading a different file.","body":{"code":"ORA-12154","slug":"ora-12154","name":null,"message":"TNS:could not resolve the connect identifier specified","group":"connection","severity":null,"sql_state":null,"summary":"The Oracle client couldn't turn the name you connected with into a database address: the alias isn't in tnsnames.ora, or the client is reading a different file.","meaning":"When you connect with a net service name such as `SALES`, the Oracle client looks it up with its naming methods, usually `tnsnames.ora`. ORA-12154 means it couldn't find that name. The database is never contacted, so the server isn't the problem.\n\nRecent releases spell the answer out, including where the client looked: `Cannot connect to database. Cannot find alias alias_value in repository_loc.`","causes":["The alias isn't defined in the `tnsnames.ora` the client actually reads, or it's misspelled.","`TNS_ADMIN` points at another directory, or several Oracle homes each have their own `tnsnames.ora`.","A syntax error in `tnsnames.ora`, such as unbalanced parentheses, that makes the entry unreadable.","`sqlnet.ora` restricts naming methods (`NAMES.DIRECTORY_PATH`) so `tnsnames.ora` isn't consulted.","A domain is appended to the name from `NAMES.DEFAULT_DOMAIN` and the entry doesn't have it."],"fix":[{"text":"Skip the alias and connect with Easy Connect, which needs no `tnsnames.ora`: `sqlplus app_user@//db-host:1521/salespdb`.","sql":null},{"text":"Check which file the client uses: run `tnsping SALES`, which prints the parameter file it read and how it resolved the name.","sql":null},{"text":"Add or fix the entry in that file.","sql":"SALES =\n  (DESCRIPTION =\n    (ADDRESS = (PROTOCOL = TCP)(HOST = db-host)(PORT = 1521))\n    (CONNECT_DATA = (SERVICE_NAME = salespdb)))"},{"text":"Set `TNS_ADMIN` to the directory that holds the right `tnsnames.ora` and `sqlnet.ora`.","sql":null}],"diagnostic":"-- Check where the client is looking and what it finds. In a shell:\n-- echo $TNS_ADMIN / echo %TNS_ADMIN%   (set? pointing where?)\n-- tnsping NO_SUCH_ALIAS_XYZ   -> shows the parameter file(s) used and fails the same way\n-- Inside SQL*Plus, once connected by another route:\nSELECT SYS_CONTEXT('USERENV', 'DB_NAME') FROM dual;  -- which DB did you actually land on?\n-- If tnsping resolves the name but the connection fails, the problem moved past ORA-12154 to the listener (ORA-12514/12541).","alternatives":"Skip tnsnames.ora entirely and use Easy Connect (host:port/service_name) or a full connect descriptor inline. If an application requires the alias, set TNS_ADMIN to a directory you control, or add the entry to the local tnsnames.ora, and remember to copy it when the Oracle client is upgraded or replaced.","details":[],"details_title":null,"repro":"-- Reproduced entirely on the client; no database is ever contacted.\n-- 1. Make sure no net service name with this name exists in tnsnames.ora\n--    (check $ORACLE_HOME/network/admin/tnsnames.ora and $TNS_ADMIN).\n-- 2. Connect using an alias that is not defined:\n-- sqlplus app_user@NO_SUCH_ALIAS_XYZ\n-- ORA-12154: TNS:could not resolve the connect identifier specified\n-- You can prove it is name resolution, not the network, by connecting directly:\n-- sqlplus app_user@//localhost:1521/YOURSERVICE   (Easy Connect, no tnsnames needed)","repro_note":null,"related":["oracle/ora-12514","oracle/ora-12541","oracle/ora-12505","oracle/ora-12170","oracle/ora-01017"],"sqlly":"Before you save an alias, test it: SQLly's connection dialog runs the connection and reports the client's exact message, so a name that doesn't resolve fails in the dialog instead of at first use.","faqs":[{"question":"tnsping works but my application gets ORA-12154. How?","answer":"tnsping and the application may be using different Oracle homes, different TNS_ADMIN values, or the application may pass the value in a form that gets mangled, such as an unescaped parentheses or equals sign in a JDBC or .NET connection string. Make the application's environment explicit and try the same alias there."},{"question":"I just installed a new Oracle client and everything broke with ORA-12154.","answer":"A new Oracle home brings its own empty network/admin directory. Your tnsnames.ora stayed behind in the old home. Copy it over or set TNS_ADMIN to the old location."},{"question":"Can this happen with localhost connections?","answer":"Yes. ORA-12154 is only about resolving the name to a connect descriptor. Connecting to localhost with a bad alias fails the same way as a remote host, because the listener is never contacted."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12154","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12170","corpus":"errors","engine":"oracle","language":"en","title":"TNS: connect timeout occurred","description":"The client gave up waiting to connect: the host is unreachable, a firewall silently drops the traffic, or the server was too slow to respond.","body":{"code":"ORA-12170","slug":"ora-12170","name":null,"message":"TNS:Connect timeout occurred","group":"connection","severity":null,"sql_state":null,"summary":"The client gave up waiting to connect: the host is unreachable, a firewall silently drops the traffic, or the server was too slow to respond.","meaning":"ORA-12170 means the connection attempt didn't complete in time. Unlike ORA-12541, nothing refused the connection; the packets went unanswered. That points at the network: a wrong IP address, routing, or a firewall that drops rather than rejects.\n\nRecent releases name the timeout that fired: `Cannot connect. timeout_type timeout of timeout for host_port.`","causes":["A firewall or security group dropping traffic to the listener port.","A wrong or unreachable host address, for example a private IP from outside the network.","A very slow or overloaded server or network, with a short `SQLNET.OUTBOUND_CONNECT_TIMEOUT` or `CONNECT_TIMEOUT`."],"fix":[{"text":"Test reachability from the client machine: `nc -vz db-host 1521` or `tnsping`. If it hangs, it's the network path.","sql":null},{"text":"Open the listener port in every firewall between client and server, including cloud security groups.","sql":null},{"text":"If the network is just slow, raise the connect timeout in the client's `sqlnet.ora` (`SQLNET.OUTBOUND_CONNECT_TIMEOUT`) or the descriptor's `CONNECT_TIMEOUT`.","sql":null}],"diagnostic":"-- From the client machine, separate DNS, routing and port reachability:\n-- ping db-host            (does the name resolve and the host respond at all?)\n-- nc -vz db-host 1521     (hangs -> packets dropped; refused -> that is ORA-12541 instead)\n-- tnsping ALIAS           (shows which descriptor is used and how far the connection gets)\n-- If nc succeeds but sqlplus times out, look at a firewall in the path inspecting or throttling port 1521 traffic.","alternatives":"Raise the client timeout for slow but working paths with CONNECT_TIMEOUT or TRANSPORT_CONNECT_TIMEOUT in the connect descriptor. For links that quietly drop idle sessions, ask the network team about the firewall's idle timeout, or set SQLNET.EXPIRE_TIME on the server so keepalive packets keep the path alive.","details":[],"details_title":null,"repro":"-- Needs a host that drops packets to the chosen port. A firewalled address or a non-routable IP works:\n-- sqlplus app_user@//10.255.255.1:1521/ANYTHING   (if your network drops this, it hangs)\n-- ORA-12170: TNS:Connect timeout occurred\n-- The default connect timeout is controlled by the client; in tnsnames.ora:\n-- (CONNECT_DATA=...) (CONNECT_TIMEOUT=10) or, per address, (TRANSPORT_CONNECT_TIMEOUT=3000 ms)\n-- If nothing on your network drops packets, pointing at an unroutable RFC1918 address reproduces the hang.","repro_note":null,"related":["oracle/ora-12541","oracle/ora-03113","oracle/ora-12154","mysql/2003"],"sqlly":"In the connection test, SQLly shows where the attempt stopped and how long it waited, which separates a slow network from a dropped port.","faqs":[{"question":"It works with tnsping but sqlplus gives ORA-12170. Why?","answer":"tnsping only checks name resolution and a lightweight listener contact; the actual session handshake goes further. A firewall or load balancer that allows the initial packet but drops the session, or a listener queue problem, can behave this way. Compare a full sqlplus login with tnsping from the same machine."},{"question":"Why do connections fail only after they sit idle for a while?","answer":"That pattern is usually a firewall with an idle-session timeout dropping the state entry, and the next packet is silently discarded. It typically shows up as ORA-03135 on an existing session rather than ORA-12170 on a new connect, and the fix is keepalives via SQLNET.EXPIRE_TIME."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12170","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12505","corpus":"errors","engine":"oracle","language":"en","title":"TNS: listener doesn't know the SID","description":"The connect string names a SID the listener doesn't know. Often a service name passed as a SID, especially in JDBC URLs with host:port:SID.","body":{"code":"ORA-12505","slug":"ora-12505","name":null,"message":"TNS:listener does not currently know of SID given in connect descriptor","group":"connection","severity":null,"sql_state":null,"summary":"The connect string names a SID the listener doesn't know. Often a service name passed as a SID, especially in JDBC URLs with host:port:SID.","meaning":"A connect descriptor can name an instance by `SID` or a database by `SERVICE_NAME`. ORA-12505 means it used a SID and the listener has no instance by that name. With multitenant databases, PDBs are reached by service name only, so a PDB name used as a SID fails this way.\n\nCurrent releases say `Cannot connect to database. SID SID_value is not registered with the listener at host_port.`","causes":["A JDBC URL in the `jdbc:oracle:thin:@host:port:NAME` form (SID) where `NAME` is really a service name.","Using a PDB name as a SID.","The instance is down, so it isn't registered."],"fix":[{"text":"Connect by service name instead. In JDBC, use the slash form.","sql":"-- SID form (fails for a PDB):     jdbc:oracle:thin:@db-host:1521:salespdb\n-- service name form:              jdbc:oracle:thin:@//db-host:1521/salespdb"},{"text":"Check what the listener knows with `lsnrctl status`, and that the instance is started.","sql":null}],"diagnostic":"-- On the server, list the SIDs and services the listener actually knows:\n-- lsnrctl status\n-- In the database, check the instance name and registered services:\nSELECT instance_name, status FROM v$instance;\nSELECT value FROM v$parameter WHERE name = 'service_names';\n-- If the instance name matches your SID but the listener still rejects it, look at registration: LOCAL_LISTENER and ALTER SYSTEM REGISTER.","alternatives":"Switch the connect descriptor to SERVICE_NAME form, which works for both single instances and PDBs and is the form Oracle recommends. In JDBC that means the //host:port/service URL. Only a genuine pre-multitenant-style SID connection needs SID syntax.","details":[],"details_title":null,"repro":"-- Needs a running database and listener. Send a descriptor that names a SID the listener has no instance for:\n-- sqlplus app_user@'(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=BOGUS_SID_XYZ)))'\n-- ORA-12505: TNS:listener does not currently know of SID given in connect descriptor\n-- Easy Connect (`//host:port/name`) carries a service name and cannot express a SID;\n-- an unknown name in that form raises ORA-12514 instead.\n-- In JDBC the SID form is the colon one:\n-- jdbc:oracle:thin:@localhost:1521:ORCL    (SID form)\n-- jdbc:oracle:thin:@//localhost:1521/ORCLPDB  (service form, what a PDB needs)","repro_note":null,"related":["oracle/ora-12514","oracle/ora-12541","oracle/ora-01034"],"sqlly":"SQLly's Oracle connection form keeps SID and service name in separate fields, so the colon/slash mix-up can't hide in a saved connection string.","faqs":[{"question":"Why does my PDB name fail as a SID?","answer":"PDBs register services with the listener, not instances. A PDB has no listener-visible SID, so SID syntax can never reach it. Use the service form: //host:port/pdb_service_name."},{"question":"How do I tell SID syntax from service syntax in a URL?","answer":"A single colon before the name (host:port:ORCL) is SID syntax. A slash after the port (host:port//service or host:port/service) is service syntax. In tnsnames.ora, look for SID= versus SERVICE_NAME= in the CONNECT_DATA section."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12505","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12514","corpus":"errors","engine":"oracle","language":"en","title":"TNS: listener doesn't know the requested service","description":"The listener answered, but no database has registered the service name you asked for. Usually a wrong service name, a closed PDB or a database that is down.","body":{"code":"ORA-12514","slug":"ora-12514","name":null,"message":"TNS:listener does not currently know of service requested in connect descriptor","group":"connection","severity":null,"sql_state":null,"summary":"The listener answered, but no database has registered the service name you asked for. Usually a wrong service name, a closed PDB or a database that is down.","meaning":"The client reached the listener, so host and port are right, but the listener has no service by the name in your connect descriptor. Databases register their services with the listener dynamically; until a database (or PDB) is open and registered, the listener can't hand connections to it.\n\nThe current wording names the service: `Cannot connect to database. Service service_name is not registered with the listener at host_port.`","causes":["A typo in the service name, or using the SID or database name where the service name is required.","The database or PDB is down or not open, so its service isn't registered.","The database registers with a different listener (`LOCAL_LISTENER` points elsewhere) or registration hasn't happened yet after a listener restart.","Connecting to the CDB's name when the service you need belongs to a PDB."],"fix":[{"text":"On the server, list the services the listener knows: `lsnrctl status` (or `lsnrctl services`).","sql":null},{"text":"In the database, check the service names and open the PDB if it is mounted.","sql":"SELECT name FROM v$services;\nSELECT name, open_mode FROM v$pdbs;\nALTER PLUGGABLE DATABASE salespdb OPEN;"},{"text":"Ask the database to register with the listener now.","sql":"ALTER SYSTEM REGISTER;"},{"text":"Fix the client's connect string to use a service name the listener lists.","sql":null}],"diagnostic":"-- On the server, ask the listener what it knows:\n-- lsnrctl status       (or: lsnrctl services)\n-- In the database, compare registered services and PDB state:\nSELECT name, open_mode FROM v$pdbs;\nSELECT value FROM v$parameter WHERE name = 'service_names';\n-- If the service is missing from lsnrctl output, the database has not registered it:\n-- check LOCAL_LISTENER, and use ALTER SYSTEM REGISTER; to force immediate registration.","alternatives":"If the PDB is closed, open it (ALTER PLUGGABLE DATABASE salespdb OPEN;). If registration is slow after a bounce, ALTER SYSTEM REGISTER forces it right away. As a client-side workaround, connect to the CDB root service and, from there, issue an ALTER SESSION SET CONTAINER if your environment supports it.","details":[],"details_title":null,"repro":"-- Needs a running database and listener. Connect asking for a service the listener has not registered:\n-- sqlplus app_user@//localhost:1521/NO_SUCH_SERVICE_XYZ\n-- ORA-12514: TNS:listener does not currently know of service requested in connect descriptor\n-- Compare with lsnrctl status on the server, which lists the services it actually knows.\n-- A fresh, still-closed PDB reproduces the same error under its own service name:\n-- (as DBA) SELECT name, open_mode FROM v$pdbs;   -- a PDB in MOUNTED is not registered","repro_note":null,"related":["oracle/ora-12505","oracle/ora-12541","oracle/ora-12154","oracle/ora-01034"],"sqlly":"The connection test reports the server's exact message and round-trip time, so you can see the listener answered but the service name is wrong.","faqs":[{"question":"Why did this start right after I restarted the database?","answer":"Dynamic registration takes a minute or so after instance startup, and a PDB is only registered once it is open. Connecting in that window gives ORA-12514. Wait for registration or run ALTER SYSTEM REGISTER as DBA."},{"question":"What is the difference between ORA-12514 and ORA-12505?","answer":"12514 means the listener does not know the SERVICE_NAME you asked for. 12505 means it does not know the SID you asked for. The fix is usually the same: use a service name that appears in lsnrctl status."},{"question":"The service shows in lsnrctl status but I still get ORA-12514.","answer":"Check for multiple listeners on different ports: the database may be registered with listener A while your connect string points at listener B. Also confirm the exact service spelling, since registration uses SERVICE_NAMES, which can differ from the DB name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12514","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12519","corpus":"errors","engine":"oracle","language":"en","title":"TNS: no appropriate service handler found","description":"The listener has no handler ready to take a new connection for the service, very often because the database has reached its PROCESSES limit.","body":{"code":"ORA-12519","slug":"ora-12519","name":null,"message":"TNS:no appropriate service handler found","group":"connection","severity":null,"sql_state":null,"summary":"The listener has no handler ready to take a new connection for the service, very often because the database has reached its PROCESSES limit.","meaning":"The listener hands each new connection to a service handler. ORA-12519 means none was available, and a common reason is that the instance is at its `PROCESSES` limit, so the listener marks the dedicated handler as blocked. The listener's view can lag a little behind the database, so the error can also appear in bursts when many connections arrive at once.","causes":["The database is at or near `PROCESSES` (see ORA-00020).","A burst of new connections from an application pool starting up.","The service isn't fully registered with the listener."],"fix":[{"text":"Check process usage and raise `PROCESSES` if needed.","sql":"SELECT resource_name, current_utilization, limit_value\nFROM v$resource_limit WHERE resource_name = 'processes';"},{"text":"Limit how many connections pools open, and how fast they open them.","sql":null},{"text":"Run `lsnrctl services` to see each handler's state (`ready` or `blocked`).","sql":null}],"diagnostic":"-- On the database host, ask the listener what state the handlers are in.\n-- 'blocked: 2' means the instance told the listener it is at its limit.\n--   lsnrctl services\n\n-- From the database, needs SELECT on v$ views:\nSELECT resource_name, current_utilization, limit_value\nFROM v$resource_limit\nWHERE resource_name = 'processes';\n\n-- If processes are NOT at the limit, suspect service registration instead:\n-- check that the service you connect to is registered and ready.\nSELECT name, NULL FROM v$services;\n-- and compare with the listener output for the same service name.","alternatives":"If the workload needs connection bursts, configure the pool to open connections gradually (min pool size, incremental growth) instead of all at once. A separate service for administrative connections can also keep monitoring traffic from consuming the handler capacity the application needs.","details":[],"details_title":null,"repro":"-- No clean safe repro: it needs the instance at its process limit while the\n-- listener is contacted. Approximate on a scratch instance with SYSDBA:\nALTER SYSTEM SET processes = 10 SCOPE = SPFILE;\nSHUTDOWN IMMEDIATE;\nSTARTUP;\n-- Saturate the 10 processes with connections, then try one more through the\n-- listener (not a local bequeath connection). The listener sees no ready\n-- handler and returns ORA-12519.\n-- Restore:\nALTER SYSTEM SET processes = 300 SCOPE = SPFILE;\nSHUTDOWN IMMEDIATE;\nSTARTUP;","repro_note":null,"related":["oracle/ora-00020","oracle/ora-00018","oracle/ora-12514","oracle/ora-12541"],"sqlly":"SQLly's connection test shows the server's exact message and timing, so a burst of pool startups shows as 12519 from the listener rather than a timeout.","faqs":[{"question":"Is ORA-12519 the same as the database being down?","answer":"No. The listener answered you, which means the network path works. It just had no handler to hand the connection to. If the database were unreachable you would get ORA-12541 (no listener) or ORA-12514 (service unknown)."},{"question":"It happens in bursts, then recovers. Why?","answer":"That pattern fits a connection pool opening many connections at once, or short-lived scripts connecting in parallel. The instance briefly sits at its PROCESSES limit; as sessions drop off, the listener marks handlers ready again."},{"question":"The instance was just restarted and now every connection fails with 12519. Why?","answer":"The listener still has stale registration state, or the instance has not re-registered yet. Wait about a minute for registration, or from the database run ALTER SYSTEM REGISTER to prompt it. If processes came back with a lower limit than before, that is the real cause."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12519","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12541","corpus":"errors","engine":"oracle","language":"en","title":"TNS: no listener","description":"Nothing is listening at the host and port the client tried: the listener isn't running, or the address or port is wrong or blocked.","body":{"code":"ORA-12541","slug":"ora-12541","name":null,"message":"TNS:no listener","group":"connection","severity":null,"sql_state":null,"summary":"Nothing is listening at the host and port the client tried: the listener isn't running, or the address or port is wrong or blocked.","meaning":"The client opened a connection to the address in the connect descriptor and nothing answered as an Oracle listener. Either the listener process isn't running on that host and port, or the client is aiming at the wrong place.\n\nIn newer releases the message is simply `Cannot connect. No listener at host_port.`","causes":["The listener is stopped, for example after a server reboot.","Wrong host or port in the connect string; the default port is 1521 but many installations change it.","The listener listens only on `localhost` or another interface.","A firewall rejects the port."],"fix":[{"text":"On the database server, check and start the listener: `lsnrctl status`, then `lsnrctl start`.","sql":null},{"text":"Compare the host and port in the client's connect string with the addresses `lsnrctl status` reports.","sql":null},{"text":"From the client, test the port with `tnsping` or a TCP check such as `nc -vz db-host 1521`, and open it in any firewall in between.","sql":null}],"diagnostic":"-- From the client, check whether anything answers on the port:\n-- nc -vz db-host 1521     (connection refused -> no listener; timeout -> see ORA-12170)\n-- On the server, check the listener process and what it listens on:\n-- lsnrctl status\n-- ps -ef | grep tnslsnr\n-- If lsnrctl status fails, the listener is down; lsnrctl start brings it back.","alternatives":"If the listener is intentionally on a different port or host, fix the connect descriptor or tnsnames entry to match (lsnrctl status shows the actual endpoints). In RAC or Data Guard setups, connecting to a node whose listener is down while others are up can be worked around with a failover connect descriptor that lists several addresses.","details":[],"details_title":null,"repro":"-- Needs a machine where nothing listens on the port. Any unused port works:\n-- sqlplus app_user@//localhost:15299/ANYTHING\n-- ORA-12541: TNS:no listener\n-- To reproduce against a real server, stop the listener (server side):\n-- lsnrctl stop\n-- ... run the connection attempt, then restore it with lsnrctl start.\n-- nc -vz localhost 15299   shows the port refused the connection outright.","repro_note":null,"related":["oracle/ora-12514","oracle/ora-12170","oracle/ora-12154","mysql/2003","postgresql/08001"],"sqlly":"SQLly's connection test shows whether a connection attempt reached the server and how long it took, which separates a missing listener from a login problem.","faqs":[{"question":"ORA-12541 versus ORA-12170: which one means what?","answer":"ORA-12541 means the machine answered and refused: nothing listens on that port, so the listener is down or the port is wrong. ORA-12170 means nothing answered at all: routing or a firewall is in the way. Refused is a listener problem; timeout is a network problem."},{"question":"The listener is running per lsnrctl status, but clients get ORA-12541.","answer":"Check which host and port the listener actually bound. It may listen on a specific IP that DNS resolves differently for clients, or on a different port than the connect descriptor uses. Also check host firewalls on the server: a firewall can reject instead of drop, which looks identical to no listener."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12541","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-12899","corpus":"errors","engine":"oracle","language":"en","title":"value too large for column","description":"A value is longer than the column allows. The message names the column and gives the actual and maximum length, often in bytes rather than characters.","body":{"code":"ORA-12899","slug":"ora-12899","name":null,"message":"value too large for column string (actual: string, maximum: string)","group":"data","severity":null,"sql_state":null,"summary":"A value is longer than the column allows. The message names the column and gives the actual and maximum length, often in bytes rather than characters.","meaning":"ORA-12899 means a string doesn't fit its column, for example `ORA-12899: value too large for column \"SALES\".\"CUSTOMERS\".\"NAME\" (actual: 61, maximum: 50)`. A `VARCHAR2(50)` column is 50 bytes by default (`NLS_LENGTH_SEMANTICS = BYTE`), so text with accented or non-Latin characters, which take 2 to 4 bytes each in AL32UTF8, can overflow a column that looks long enough.","causes":["The data is longer than the column definition.","Multi-byte characters in a column sized in bytes.","Migrating to a Unicode database character set, which makes some strings longer in bytes."],"fix":[{"text":"Find the longest values that would go into the column, and compare with its definition.","sql":"SELECT column_name, data_type, data_length, char_length, char_used\nFROM all_tab_columns WHERE table_name = 'CUSTOMERS' AND column_name = 'NAME';"},{"text":"Widen the column, and size it in characters if it holds text in many languages.","sql":"ALTER TABLE customers MODIFY (name VARCHAR2(200 CHAR));"},{"text":"Or truncate deliberately before inserting, if losing the tail is acceptable.","sql":"INSERT INTO customers (name) VALUES (SUBSTR(:name, 1, 50));"}],"diagnostic":"-- The message already names the column and both lengths; confirm the column's semantics next.\nSELECT column_name, data_type, data_length, char_length, char_used\nFROM all_tab_columns\nWHERE owner = USER AND table_name = 'T12899' AND column_name = 'NAME';\n-- CHAR_USED = 'B' means bytes, 'C' means chars.\n\n-- To find which rows you are trying to load are too long, measure in bytes (LENGTHB):\nSELECT id, LENGTHB(name) AS bytes FROM stage_customers WHERE LENGTHB(name) > 5;","alternatives":"Set NLS_LENGTH_SEMANTICS = CHAR for the session or in the spfile so new VARCHAR2 declarations default to characters, which prevents the class of problem on Unicode databases. Truncating with SUBSTR or SUBSTRB before insert also works when losing the tail is acceptable, and 12.2 and later can widen a column online.","details":[],"details_title":null,"repro":"-- Byte semantics are the default, so accented text overflows quickly in AL32UTF8.\nCREATE TABLE t12899 (name VARCHAR2(5));\n-- é is 2 bytes in AL32UTF8, so this is 8 bytes against a 5-byte limit:\nINSERT INTO t12899 VALUES ('éééé');\n-- ORA-12899: value too large for column \"...\".\"T12899\".\"NAME\" (actual: 8, maximum: 5)\n\n-- CHAR semantics counts characters instead:\nCREATE TABLE t12899c (name VARCHAR2(5 CHAR));\nINSERT INTO t12899c VALUES ('éééé');\nSELECT * FROM t12899c;\n\nDROP TABLE t12899 PURGE;\nDROP TABLE t12899c PURGE;","repro_note":null,"related":["oracle/ora-01401","oracle/ora-01438","sql-server/8152","sql-server/2628","postgresql/22001","mysql/1406"],"sqlly":"SQLly's schema browser shows the column's data type and length, so a value that's too long in bytes is checkable before the insert.","faqs":[{"question":"Why did the column fit before the database was migrated to AL32UTF8?","answer":"In a single-byte character set each character was one byte. In AL32UTF8, accented Latin characters take 2 bytes and CJK takes 3, so the same text is longer in bytes while the column size in bytes stayed fixed."},{"question":"Does VARCHAR2(50) mean 50 characters or 50 bytes?","answer":"Bytes, unless the column was declared with CHAR semantics or the session default NLS_LENGTH_SEMANTICS was CHAR when the table was created. Check CHAR_USED in ALL_TAB_COLUMNS to see which one a given column actually has."},{"question":"Can I change the default semantics for the whole database?","answer":"Yes, with ALTER SYSTEM SET NLS_LENGTH_SEMANTICS = CHAR. It only affects tables created afterwards, not existing columns, and it does not apply to dictionary objects like the data dictionary itself."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-12899","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-27101","corpus":"errors","engine":"oracle","language":"en","title":"shared memory realm does not exist","description":"A local connection found no shared memory for the instance named by ORACLE_SID: the instance isn't started, or ORACLE_SID or ORACLE_HOME is wrong.","body":{"code":"ORA-27101","slug":"ora-27101","name":null,"message":"shared memory realm does not exist","group":"connection","severity":null,"sql_state":null,"summary":"A local connection found no shared memory for the instance named by ORACLE_SID: the instance isn't started, or ORACLE_SID or ORACLE_HOME is wrong.","meaning":"On a local (bequeath) connection, the client attaches to the instance's shared memory directly. ORA-27101 means there is no shared memory for the instance named by `ORACLE_SID` in that `ORACLE_HOME`. It usually comes paired with ORA-01034.","causes":["The instance isn't running.","`ORACLE_SID` is wrong or in the wrong case (it is case-sensitive on Linux and Unix).","`ORACLE_HOME` differs from the one the instance was started from."],"fix":[{"text":"Check the environment: `echo $ORACLE_SID $ORACLE_HOME` on Linux, and compare with the running instance (`ps -ef | grep pmon`).","sql":null},{"text":"Start the instance if it is down.","sql":"-- sqlplus / as sysdba\nSTARTUP;"}],"diagnostic":"-- Is the instance up? Look for pmon_<SID> in the process list.\nps -ef | grep pmon\n-- Does the shell's SID match the running one, byte for byte?\necho $ORACLE_SID\n-- If shared memory exists but attach fails, check the environment\n-- and whether ORACLE_HOME matches the home the instance was started from:\nls -l $ORACLE_HOME/dbs/spfile*.ora","alternatives":"Connect over the listener with a full connect string (sqlplus user/pass@//host:1521/service) instead of a local connection; then the SID of your shell stops mattering. If multiple ORACLE_HOMEs exist, run . oraenv and pick the right one rather than exporting variables by hand.","details":[],"details_title":null,"repro":"-- On a scratch instance only.\n--   sqlplus / as sysdba\n--   SHUTDOWN IMMEDIATE;\n--   exit\n-- Then, from the same shell (same ORACLE_SID):\n--   sqlplus scott/tiger\n-- ORA-01034 plus ORA-27101: the client found no shared memory to attach to.\n-- Restart with STARTUP; to clean up.","repro_note":null,"related":["oracle/ora-01034"],"sqlly":"SQLly's connection manager stores the service name or SID each saved connection uses, so a wrong-SID local connection stands out against the entry that used to work.","faqs":[{"question":"ORA-27101 shows up together with ORA-01034. Which one do I fix?","answer":"Treat them as one problem. ORA-01034 says the instance is not available, ORA-27101 explains why on a local connection: there is no shared memory to attach to. Start the instance or fix ORACLE_SID and both go away."},{"question":"The instance is running. Why do I still see it?","answer":"Your ORACLE_SID or ORACLE_HOME does not match the running instance. The client computes a shared-memory key from those two values, and a mismatch means it looks for memory that belongs to nobody."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-27101","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-28000","corpus":"errors","engine":"oracle","language":"en","title":"the account is locked","description":"The account was locked, by an administrator or automatically after too many failed logins, so Oracle refuses to log it in until it is unlocked.","body":{"code":"ORA-28000","slug":"ora-28000","name":null,"message":"the account is locked","group":"connection","severity":null,"sql_state":null,"summary":"The account was locked, by an administrator or automatically after too many failed logins, so Oracle refuses to log it in until it is unlocked.","meaning":"Oracle locks an account when an administrator runs `ALTER USER ... ACCOUNT LOCK` or when failed login attempts exceed the profile's `FAILED_LOGIN_ATTEMPTS` limit (10 in the default profile). The account then can't log in until it is unlocked or, if the profile sets `PASSWORD_LOCK_TIME`, until that time has passed.","causes":["Too many failed logins, often an application or job still using an old password.","An administrator locked the account.","Sample or system accounts that are locked by default after installation."],"fix":[{"text":"Check the status and when it was locked.","sql":"SELECT username, account_status, lock_date, profile\nFROM dba_users WHERE username = 'APP_USER';"},{"text":"Unlock it (and reset the password if that was the reason for the failures).","sql":"ALTER USER app_user ACCOUNT UNLOCK;\nALTER USER app_user IDENTIFIED BY \"N3w-Strong-Pass\" ACCOUNT UNLOCK;"},{"text":"Find and fix whatever keeps logging in with the old password, or it will lock again.","sql":null}],"diagnostic":"-- As DBA, see the status and when it was locked:\nSELECT username, account_status, lock_date, profile FROM dba_users WHERE username = 'LOCK_TEST';\n-- What are the profile limits that govern locking?\nSELECT p.profile, p.resource_name, p.limit FROM dba_profiles p\nWHERE p.resource_name IN ('FAILED_LOGIN_ATTEMPTS','PASSWORD_LOCK_TIME') ORDER BY p.profile;\n-- OPEN means the account is not locked and the login failure is ORA-01017 territory.\n-- 'LOCKED(TIMED)' means the profile will unlock it automatically after PASSWORD_LOCK_TIME days.","alternatives":"If the account should stay locked but you need its data, connect as another user with the right grants instead of unlocking it. If the account locks itself repeatedly overnight, look for a scheduled job or monitoring tool retrying an old password; each cycle of failures re-locks it. Setting PASSWORD_LOCK_TIME to a small value, or FAILED_LOGIN_ATTEMPTS higher for service accounts via a dedicated profile, reduces the blast radius without disabling locking.","details":[],"details_title":null,"repro":"-- Reproduced with SQL on a scratch database.\n-- As DBA:\nCREATE USER lock_test IDENTIFIED BY \"Lock-Me-1\";\nGRANT CREATE SESSION TO lock_test;\nALTER USER lock_test ACCOUNT LOCK;\n-- Now, as lock_test:\n-- sqlplus lock_test/Lock-Me-1@//localhost:1521/YOURPDB\n-- ORA-28000: The account is locked.\n-- Clean up:\n-- ALTER USER lock_test ACCOUNT UNLOCK;\n-- DROP USER lock_test CASCADE;   -- when done\n-- The profile-driven path also reproduces it: set FAILED_LOGIN_ATTEMPTS low, then enter bad passwords until it locks.","repro_note":null,"related":["oracle/ora-01017","oracle/ora-28001","sql-server/18486"],"sqlly":"SQLly's connection test surfaces the server's account-locked message verbatim, with the host and user it tried, so the lockout is obvious before you retype the password.","faqs":[{"question":"Will the account unlock itself?","answer":"Only if the profile sets PASSWORD_LOCK_TIME to a number of days; the status then shows LOCKED(TIMED) and the account opens when the time passes. PASSWORD_LOCK_TIME UNLIMITED or an administrator-issued ACCOUNT LOCK keeps it locked until someone runs ALTER USER ... ACCOUNT UNLOCK."},{"question":"Nobody is typing the password. Why does it keep locking?","answer":"Something is retrying stale credentials: a monitoring probe, a connection pool that never picked up the new password, a scheduled job, or a client that cached the old password. Check the database audit log or the listener log for a source IP around each lock time; that tells you which machine to fix."},{"question":"How do I find out who or what locked the account?","answer":"The lock_date in dba_users tells you when. Unified auditing (AUDIT USER management or a policy auditing ALTER USER) records the administrator who issued ACCOUNT LOCK, and failed-login auditing records the source of lockout-by-attempts."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-28000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-28001","corpus":"errors","engine":"oracle","language":"en","title":"the password has expired","description":"The account's password reached the end of its PASSWORD_LIFE_TIME, so the user must change it before logging in again.","body":{"code":"ORA-28001","slug":"ora-28001","name":null,"message":"the password has expired","group":"connection","severity":null,"sql_state":null,"summary":"The account's password reached the end of its PASSWORD_LIFE_TIME, so the user must change it before logging in again.","meaning":"Oracle profiles can limit how long a password lasts (`PASSWORD_LIFE_TIME`, 180 days in the default profile of many releases). When it runs out, and any grace period has passed, logins fail with ORA-28001 until the password is changed. Interactive tools like SQL*Plus prompt for a new password; most applications just fail.","causes":["The password is older than the profile allows, common for application and service accounts.","An administrator expired it with `ALTER USER ... PASSWORD EXPIRE`."],"fix":[{"text":"Set a new password.","sql":"ALTER USER app_user IDENTIFIED BY \"N3w-Strong-Pass\";"},{"text":"For service accounts, assign a profile with a password life time that suits your rotation policy.","sql":"CREATE PROFILE app_service LIMIT PASSWORD_LIFE_TIME UNLIMITED;\nALTER USER app_user PROFILE app_service;"}],"diagnostic":"-- As DBA: confirm the status and profile.\nSELECT username, account_status, expiry_date, profile FROM dba_users WHERE username = 'EXPIRE_TEST';\n-- How long does this profile allow, and how much grace?\nSELECT resource_name, limit FROM dba_profiles\nWHERE profile = (SELECT profile FROM dba_users WHERE username = 'EXPIRE_TEST')\nAND resource_name IN ('PASSWORD_LIFE_TIME','PASSWORD_GRACE_TIME');\n-- 'EXPIRED' means a password change fixes it; 'EXPIRED(GRACE)' means logins still work but a warning is showing,\n-- so an application that ignores warnings will break only when grace ends.","alternatives":"For service accounts, the usual pattern is a dedicated profile with PASSWORD_LIFE_TIME UNLIMITED so the password never ages out, accepting the tradeoff that it must be rotated manually. Applications can also be given the new password ahead of time while the account is still in the grace window. Note 12c's separate PASSWORD_ROLLOVER_TIME setting allows old and new passwords in parallel during a rotation, but only for accounts authenticated by password verification, and only when the profile sets it.","details":[],"details_title":null,"repro":"-- Reproduced with SQL on a scratch database.\n-- As DBA: build a profile with a tiny lifetime and no grace, then apply it.\nCREATE PROFILE expire_fast LIMIT PASSWORD_LIFE_TIME 1 PASSWORD_GRACE_TIME 0;\nCREATE USER expire_test IDENTIFIED BY \"Expire-Me-1\" PROFILE expire_fast;\nGRANT CREATE SESSION TO expire_test;\n-- Force expiry immediately (11g and later):\nALTER USER expire_test PASSWORD EXPIRE;\n-- As expire_test:\n-- sqlplus expire_test/Expire-Me-1@//localhost:1521/YOURPDB\n-- ORA-28001: The password has expired\n-- SQL*Plus offers to change it on the spot; APIs and drivers just fail.\n-- Cleanup: DROP USER expire_test CASCADE; DROP PROFILE expire_fast;","repro_note":null,"related":["oracle/ora-28000","oracle/ora-01017","sql-server/18487"],"sqlly":"When a login fails with an expired password, SQLly shows the server's message in the connection test result, so you know a reset is needed before opening the schema.","faqs":[{"question":"Why did my app break exactly 180 days after setup?","answer":"The default profile in many releases sets PASSWORD_LIFE_TIME to 180 days. After that comes PASSWORD_GRACE_TIME, during which logins still work with a warning most applications ignore. When grace ends, logins fail with ORA-28001. Service accounts created with the default profile hit this on schedule."},{"question":"Can the application change the password itself?","answer":"Yes. Most drivers and OCI support changing the password at connect time (OCI's password-change mode; JDBC via OracleDataSource with the new password). If you set a grace period and rotate proactively, the app can switch before the hard stop."},{"question":"I reset the password but still get ORA-28001. Why?","answer":"The reset must reach the database you connect to: in a multitenant setup a same-named user may exist in both the CDB root and a PDB. Also confirm the account_status shows OPEN after the change; if it shows EXPIRED, you altered a different user or the profile immediately re-expired it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-28001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/oracle/ora-30036","corpus":"errors","engine":"oracle","language":"en","title":"unable to extend segment in undo tablespace","description":"A transaction needed more undo space than the undo tablespace could give, usually a single huge UPDATE or DELETE.","body":{"code":"ORA-30036","slug":"ora-30036","name":null,"message":"unable to extend segment by string in undo tablespace 'string'","group":"resources","severity":null,"sql_state":null,"summary":"A transaction needed more undo space than the undo tablespace could give, usually a single huge UPDATE or DELETE.","meaning":"Every change a transaction makes is recorded in undo until it commits. ORA-30036 means the undo tablespace couldn't grow to hold more for this transaction. The failing statement is rolled back.","causes":["One very large `UPDATE` or `DELETE` in a single transaction.","An undo tablespace that is too small or can't autoextend.","Long-running transactions that hold undo for a long time."],"fix":[{"text":"Change the data in batches with commits between them, or use `CREATE TABLE AS SELECT` and swap tables for very large rewrites.","sql":null},{"text":"Let the undo tablespace grow.","sql":"ALTER DATABASE DATAFILE '/u01/oradata/ORCL/undotbs01.dbf' AUTOEXTEND ON MAXSIZE 32G;"},{"text":"Look for old open transactions holding undo.","sql":"SELECT s.sid, s.username, t.start_time, t.used_ublk\nFROM v$transaction t JOIN v$session s ON s.taddr = t.addr\nORDER BY t.start_time;"}],"diagnostic":"-- Which transaction was growing undo when it failed? v$transaction shows active ones.\n-- Needs SELECT on the v$ views (SELECT_CATALOG_ROLE or DBA).\nSELECT s.sid, s.serial#, s.username, s.sql_id, t.start_time,\n       t.used_ublk * (SELECT TO_NUMBER(value) FROM v$parameter WHERE name = 'db_block_size') AS undo_bytes\nFROM v$transaction t\nJOIN v$session s ON s.taddr = t.addr\nORDER BY t.start_time;\n\n-- Can the undo tablespace still grow? Check free space and autoextend.\nSELECT file_name, bytes/1024/1024 AS size_mb,\n       autoextensible, maxbytes/1024/1024 AS max_mb\nFROM dba_data_files\nWHERE tablespace_name = (SELECT value FROM v$parameter WHERE name = 'undo_tablespace');","alternatives":"Split the work into batches of a few thousand rows with a commit between them so each transaction's undo stays small. For a full-table rewrite, CREATE TABLE AS SELECT plus a rename avoids generating row-by-row undo entirely.","details":[],"details_title":null,"repro":"-- Needs a small undo tablespace and privilege to create one.\nCREATE UNDO TABLESPACE undo_demo\n  DATAFILE '/tmp/undo_demo.dbf' SIZE 2M AUTOEXTEND OFF;\nALTER SYSTEM SET undo_tablespace = undo_demo;\n\nCREATE TABLE big_demo AS SELECT ROWNUM AS id FROM all_objects;\n\n-- One huge uncommitted change forces undo to grow past 2M.\nUPDATE big_demo SET id = id + 1000000;\n-- ORA-30036: unable to extend segment by 8 in undo tablespace 'UNDO_DEMO'\n\nROLLBACK;\nALTER SYSTEM SET undo_tablespace = undotbs1; -- restore the undo tablespace you noted before switching\nDROP TABLESPACE undo_demo INCLUDING CONTENTS AND DATAFILES;\nDROP TABLE big_demo;","repro_note":null,"related":["oracle/ora-01555","oracle/ora-01652","sql-server/9002"],"sqlly":"SQLly shows the failed statement with the undo tablespace named, and the tab stays connected so you can split the UPDATE into batches immediately.","faqs":[{"question":"Does my UPDATE get rolled back automatically?","answer":"Yes. The statement that failed is rolled back, undo included. Anything you committed earlier in the session stays committed. Run ROLLBACK anyway to release any remaining locks and undo held by the surrounding transaction."},{"question":"Will raising UNDO_RETENTION fix this?","answer":"No. UNDO_RETENTION controls how long committed undo is kept for read consistency. ORA-30036 happens while a transaction is still running and writing undo, before any commit. You need more undo space or smaller transactions."},{"question":"Why did this start happening after months with no changes?","answer":"The usual suspects: the table grew past what the undo tablespace can absorb in one transaction, someone turned off autoextend, or a long-running report now runs at the same time and pins old undo. Check v$transaction for transactions that started before yours."}],"aliases":[]},"source_url":"https://sqlly.app/errors/oracle/ora-30036","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/08001","corpus":"errors","engine":"postgresql","language":"en","title":"unable to establish connection","description":"The client couldn't open a connection to the server at all: nothing listening on that host and port, a firewall, DNS, or a timeout.","body":{"code":"08001","slug":"08001","name":"sqlclient_unable_to_establish_sqlconnection","message":"connection to server at \"db.example.com\" (10.0.0.5), port 5432 failed: Connection refused\n\tIs the server running on that host and accepting TCP/IP connections?","group":"08","severity":null,"sql_state":null,"summary":"The client couldn't open a connection to the server at all: nothing listening on that host and port, a firewall, DNS, or a timeout.","meaning":"08001 is a client-side SQLSTATE: drivers such as PgJDBC and Npgsql report it when they can't establish a connection, and libpq-based tools print messages like the one above. The server never saw a login attempt, so the problem is the network path or the server not listening, not credentials.\n\nThe operating-system error at the end says which: `Connection refused` means the host answered but nothing listens on that port; `timeout expired` or `Operation timed out` usually means a firewall dropped the packets; `could not translate host name` is DNS.","causes":["The PostgreSQL server isn't running, or is listening on another port.","`listen_addresses` is `localhost` (the default), so the server only accepts local connections.","A firewall, security group or Docker port mapping blocks port 5432.","Wrong host name, or a host name that doesn't resolve from the client.","Connecting to `localhost` from inside a container, which refers to the container itself."],"fix":[{"text":"On the server, check that PostgreSQL is running and which addresses and port it listens on.","sql":"SHOW listen_addresses;\nSHOW port;"},{"text":"Allow network connections: set `listen_addresses = '*'` (or the server's address) in `postgresql.conf` and restart, then add a `pg_hba.conf` rule for the clients.","sql":null},{"text":"Test the network path from the client, for example `pg_isready -h db.example.com -p 5432`, and open the port in the firewall or security group.","sql":null},{"text":"From a container, connect to the database container's service name or the host's address instead of `localhost`.","sql":null}],"diagnostic":"-- From the client machine, in order:\n-- 1. Does the name resolve?\npg_isready -h db.example.com -p 5432\n\n-- 2. On the server, is PostgreSQL running and what is it listening on?\nSHOW listen_addresses;\nSHOW port;\nSELECT pg_is_in_recovery();\n\n-- 3. On the server host, what is actually bound to 5432?\n-- ss -ltnp | grep 5432\n\n-- 4. pg_isready prints accepting, rejecting, no response, or no attempt (exit 0, 1, 2, 3).\n-- A refused TCP connect and a firewall drop both show up as 'no response';\n-- the 'Connection refused' wording in psql is the OS-level error, which is\n-- how you tell the two apart.","alternatives":"If you cannot open the port right now, an SSH tunnel gets you in without touching the firewall: ssh -L 5432:localhost:5432 user@server, then connect to localhost on the client. For containers, use the service name from the compose file instead of localhost.","details":[],"details_title":null,"repro":"-- From the client machine, point at a port nothing listens on:\n-- $ psql -h 127.0.0.1 -p 1 -c 'SELECT 1'\n-- psql: error: connection to server at \"127.0.0.1\", port 1 failed: Connection refused\n-- No server was reached; libpq reports the failure client-side as SQLSTATE 08001.","repro_note":"Safe to run anywhere: it targets an unused port, so no server or data is touched.","related":["postgresql/08006","postgresql/28000","postgresql/57P03","mysql/2003","mysql/2002","oracle/ora-12541"],"sqlly":"SQLly's connection test shows whether the server answered, the round-trip time and the last error, so a refused or timed-out connection is easy to tell apart from a login problem. SSH tunnels are supported for servers that aren't reachable directly.","faqs":[{"question":"Could this be a wrong password?","answer":"No. A wrong password produces 28P01, and a rejected host produces 28000 with a pg_hba.conf message. 08001 means the TCP connection itself never got established, so PostgreSQL never saw your credentials."},{"question":"It works from psql on the server but not from my laptop. What differs?","answer":"The network path. On the server you connect over a Unix socket, which ignores listen_addresses. From your laptop you need TCP: the server must listen on a non-localhost address, pg_hba.conf must allow your address, and nothing between you and the server may block port 5432."},{"question":"My app connects fine sometimes and fails other times. Ideas?","answer":"That points at something between app and database rather than the database itself: the server reaching max_connections, which makes it reject new connections with 53300 too_many_connections rather than 08001, a load balancer with a stale target, or DNS that intermittently resolves to the wrong host. Log the resolved host and port on failure to pin it down."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/08001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/08006","corpus":"errors","engine":"postgresql","language":"en","title":"connection failure","description":"The connection to the server broke during use. The server process ended, restarted or was killed, or the network dropped an idle connection.","body":{"code":"08006","slug":"08006","name":"connection_failure","message":"server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.","group":"08","severity":null,"sql_state":null,"summary":"The connection to the server broke during use. The server process ended, restarted or was killed, or the network dropped an idle connection.","meaning":"08006 is a client-side code: drivers report it when an established connection fails mid-conversation. When the server can still send one, it sends a FATAL first (for example 57P01 or 57P05). The message above comes from the client library when the connection is gone, and the 08006 code is assigned by the driver, not by libpq. libpq-based tools such as psql print the message above, and PgJDBC reports SQLSTATE 08006 with `An I/O error occurred while sending to the backend.`\n\nThe server log usually explains it: a backend crash and restart, an out-of-memory kill, an administrator terminating the session, or nothing at all when a firewall or load balancer silently dropped an idle TCP connection.","causes":["The server process for the session crashed or was killed, often by the operating system's out-of-memory killer, which makes PostgreSQL restart all sessions.","The server was restarted or failed over.","A firewall, NAT gateway or cloud load balancer dropped a connection that was idle longer than its timeout.","The session was terminated by `pg_terminate_backend()` or an idle timeout, and the client only noticed on its next query."],"fix":[{"text":"Check the server log around the time of the failure for `terminated by signal`, `server process ... was terminated`, or a restart.","sql":null},{"text":"If an idle connection was dropped by the network, enable TCP keepalives on the server (or the client) so the connection never looks idle.","sql":"ALTER SYSTEM SET tcp_keepalives_idle = 60;\nALTER SYSTEM SET tcp_keepalives_interval = 10;\nALTER SYSTEM SET tcp_keepalives_count = 6;\nSELECT pg_reload_conf();"},{"text":"Configure the connection pool to validate or recycle connections before handing them out, and retry the operation once on a fresh connection when it is safe to do so.","sql":null},{"text":"If the server ran out of memory, find the query that used it and lower `work_mem` or the number of concurrent connections.","sql":null}],"diagnostic":"-- Did the server restart, and when?\nSELECT pg_postmaster_start_time();\n\n-- Crashes leave a trail in the log. On the server, grep the window\n-- around the failure for 'terminated' or 'server process'.\n-- A backend killed by the OOM killer also shows up in dmesg / journalctl.\n\n-- Which of my sessions are still alive from here?\nSELECT pid, application_name, backend_start, state, query\nFROM pg_stat_activity\nWHERE usename = current_user;\n\n-- Check the keepalive settings that decide whether idle\n-- connections get dropped by middleboxes.\nSHOW tcp_keepalives_idle;\nSHOW tcp_keepalives_interval;","alternatives":"If you cannot change server settings, set keepalives on the client instead (libpq's keepalives_idle and friends in the connection string) and configure the pooler to test a connection with a cheap query before handing it out. A read-only retry with a fresh connection covers the restart case for idempotent queries.","details":[],"details_title":null,"repro":"-- Needs shell on the server host. In the SQL session, note the pid:\nSELECT pg_backend_pid();\n-- Terminate that one backend from a second session (safe on a shared server; kill -9 restarts every session):\n--   SELECT pg_terminate_backend(<pid>);\n-- The next statement in the SQL session fails with:\n--   FATAL: terminating connection due to administrator command\n--   server closed the connection unexpectedly\n--   connection to server was lost","repro_note":"Needs a second session. Use pg_terminate_backend on your own scratch session. Do not use kill -9: a SIGKILL'd backend makes the server reset every session.","related":["postgresql/57P01","postgresql/08001","postgresql/53200","mysql/2013","mysql/2006","oracle/ora-03113"],"sqlly":"SQLly's connection test shows the status, round-trip time and the last error for a connection, which helps separate a dropped network path from a server that is down.","faqs":[{"question":"Is my data corrupted after this error?","answer":"Almost always no. PostgreSQL is crash-safe: committed transactions are on disk before the client hears back, and a backend that crashes forces the server to reset every session, with uncommitted work rolled back as part of that crash recovery. The message is scary but the database comes back consistent."},{"question":"Why did only one connection die while others kept working?","answer":"A full server crash takes every connection down. If only one session dropped, someone ran pg_terminate_backend on it or an idle timeout ended it. An OOM-killed or signal-killed backend resets all sessions, so it looks like a full crash. The log tells you which."},{"question":"The error happens every morning at the same time. What should I look for?","answer":"That pattern usually means an idle timeout: a firewall, NAT gateway or managed-provider proxy drops connections idle longer than its limit, and the client notices on its first query of the day. Enable keepalives or have the pool recycle idle connections below that threshold."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/08006","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/0A000","corpus":"errors","engine":"postgresql","language":"en","title":"feature not supported","description":"The statement asks for something PostgreSQL doesn't support in that form, such as a cross-database reference or an unsupported combination of options.","body":{"code":"0A000","slug":"0A000","name":"feature_not_supported","message":"cross-database references are not implemented: \"otherdb.public.orders\"","group":"0A","severity":null,"sql_state":null,"summary":"The statement asks for something PostgreSQL doesn't support in that form, such as a cross-database reference or an unsupported combination of options.","meaning":"0A000 is a catch-all for valid-looking SQL that PostgreSQL doesn't implement. The message says what isn't supported. Common ones are a three-part name referring to another database, `FOR UPDATE` combined with `GROUP BY`, `DISTINCT` or aggregates (`FOR UPDATE is not allowed with aggregate functions`), and altering a column type used by a view or rule.\n\nThe fix is to express the same thing another way; there is no setting that enables the feature.","causes":["A name like `otherdb.public.orders`: each connection can only see its own database.","Row locking (`FOR UPDATE`) on a query with `GROUP BY`, `DISTINCT`, aggregates or window functions.","`ALTER TABLE ... ALTER COLUMN TYPE` on a column a view depends on.","Syntax from another database or a newer PostgreSQL version than the server."],"fix":[{"text":"For cross-database queries, use the `postgres_fdw` extension (or `dblink`), or keep the data in schemas of one database.","sql":"CREATE EXTENSION postgres_fdw;\nCREATE SERVER otherdb FOREIGN DATA WRAPPER postgres_fdw OPTIONS (dbname 'otherdb');\nCREATE USER MAPPING FOR CURRENT_USER SERVER otherdb OPTIONS (user 'app', password 'secret');\nIMPORT FOREIGN SCHEMA public LIMIT TO (orders) FROM SERVER otherdb INTO public;"},{"text":"Lock rows in a subquery, then aggregate outside it.","sql":"SELECT customer_id, count(*)\nFROM (SELECT * FROM orders WHERE status = 'new' FOR UPDATE) o\nGROUP BY customer_id;"},{"text":"To change the type of a column a view uses, drop the view, alter the column, and recreate the view, in one transaction.","sql":null}],"diagnostic":"-- For the cross-database case: is the name really another database?\nSELECT datname FROM pg_database;\n\n-- For the FOR UPDATE case: does the query lock rows directly,\n-- or through an aggregate, DISTINCT or window function?\n-- PostgreSQL rejects locking whenever the locked row would not\n-- correspond one-to-one with an output row.\n\n-- ALTER COLUMN TYPE on a column a view uses is rejected outright, so list\n-- the directly dependent views before you plan the change. This does not list\n-- views built on those views; check those too:\nSELECT DISTINCT dependent_ns.nspname AS schema_name,\n       dependent_view.relname AS view_name\nFROM pg_depend d\nJOIN pg_rewrite r ON r.oid = d.objid AND d.classid = 'pg_rewrite'::regclass\nJOIN pg_class dependent_view ON dependent_view.oid = r.ev_class\nJOIN pg_namespace dependent_ns ON dependent_ns.oid = dependent_view.relnamespace\nJOIN pg_class source_table ON source_table.oid = d.refobjid\nWHERE source_table.relname = 'orders'\n  AND dependent_view.oid <> source_table.oid;","alternatives":"For cross-database data, moving the tables into schemas of one database is usually better than postgres_fdw: no per-query overhead and real transactions across tables. When a feature exists only in a newer PostgreSQL release, upgrading the server is the only real option; check the release notes to confirm which version added it.","details":[],"details_title":null,"repro":"SELECT * FROM otherdb.public.t;  -- ERROR: cross-database references are not implemented","repro_note":null,"related":["postgresql/42P01","postgresql/3D000","postgresql/42601"],"sqlly":null,"faqs":[{"question":"MySQL does cross-database queries with db.table. Why not PostgreSQL?","answer":"In MySQL the two names are schemas under one server, and PostgreSQL schemas work the same way with schema.table. A PostgreSQL database is a separate universe: one connection sees one database, and cross-database access only exists through foreign data wrappers like postgres_fdw or dblink."},{"question":"My SQL runs on Postgres 16 but fails on 14. Is that this error?","answer":"Possibly, but not for the reason usually given. 0A000 means the server recognises the feature and does not implement it. Syntax the server does not know is reported as 42601 (syntax_error), and an unknown function as 42883. A newer feature used on an older server is therefore more often a syntax error than 0A000. Check the release notes for the feature to find the minimum version, and run SELECT version(); to see what you are actually talking to."},{"question":"Can a setting or extension turn on the missing feature?","answer":"Rarely. Most 0A000 cases are hard design boundaries, not configuration. The exceptions are the foreign data wrappers for cross-database access, which do need CREATE EXTENSION first. For everything else the answer is rewriting the query."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/0A000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/0LP01","corpus":"errors","engine":"postgresql","language":"en","title":"invalid grant operation","description":"A GRANT or REVOKE asked for something PostgreSQL doesn't allow, such as WITH GRANT OPTION to PUBLIC or granting a role to itself.","body":{"code":"0LP01","slug":"0LP01","name":"invalid_grant_operation","message":"grant options can only be granted to roles","group":"0L","severity":null,"sql_state":null,"summary":"A GRANT or REVOKE asked for something PostgreSQL doesn't allow, such as WITH GRANT OPTION to PUBLIC or granting a role to itself.","meaning":"0LP01 (`invalid_grant_operation`) is raised when the shape of a `GRANT` or `REVOKE` is invalid, not when you lack the privilege (that is 42501). The common messages are `grant options can only be granted to roles` (for `WITH GRANT OPTION` to `PUBLIC`) and errors about circular role membership, such as granting a role to itself or granting a role back to a member of its own membership chain. Re-granting an existing membership is not an error; PostgreSQL only sends a NOTICE.","causes":["`GRANT ... TO PUBLIC WITH GRANT OPTION`.","Granting a role to itself, or creating a membership loop (`GRANT a TO b` when `a` is already a member of `b`).","Scripts generated for another database's privilege model."],"fix":[{"text":"Grant with grant option to a specific role instead of `PUBLIC`.","sql":"GRANT SELECT ON orders TO reporting WITH GRANT OPTION;"},{"text":"Check existing role memberships before adding one, to avoid loops.","sql":"SELECT r.rolname AS role, m.rolname AS member\nFROM pg_auth_members am\nJOIN pg_roles r ON r.oid = am.roleid\nJOIN pg_roles m ON m.oid = am.member;"}],"diagnostic":"-- Who already holds grant options on the object, and who can grant what?\nSELECT grantee, grantor,\n       privilege_type,\n       is_grantable\nFROM information_schema.role_table_grants\nWHERE table_name = 'orders';\n\n-- Show current role memberships to spot a loop before GRANT creates one.\nSELECT r.rolname AS role, m.rolname AS member\nFROM pg_auth_members am\nJOIN pg_roles r ON r.oid = am.roleid\nJOIN pg_roles m ON m.oid = am.member\nORDER BY 1, 2;","alternatives":"If the goal is to let users pass a privilege along, creating one role that owns the grant and making people members of it is easier to audit than a chain of WITH GRANT OPTION. In PostgreSQL 16 and later, GRANT ... WITH SET FALSE and scoped membership options (admin, inherit) give finer control over how memberships propagate.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE t (id int);\nGRANT SELECT ON t TO PUBLIC WITH GRANT OPTION;  -- ERROR: grant options can only be granted to roles","repro_note":null,"related":["postgresql/42501","postgresql/42704"],"sqlly":null,"faqs":[{"question":"What is the difference between this and 42501?","answer":"42501 means you lack the privilege you are trying to grant. 0LP01 means the GRANT statement itself is shaped wrong, like giving grant options to PUBLIC or creating a role membership loop. Fixing 0LP01 is a rewrite of the statement, not a request for more rights."},{"question":"Why can't PUBLIC hold WITH GRANT OPTION?","answer":"PUBLIC is the implicit group of every role, so a grant option on it would let anyone who ever connects hand the privilege to anyone else, with no accountable grantor trail. PostgreSQL rejects the combination outright; name a real role instead."},{"question":"How did a role membership loop get into my database?","answer":"Usually from generated migrations that grant roles blindly without checking existing membership. The pg_auth_members query above shows the current graph; run it before scripted GRANT statements so you can skip pairs that already exist."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/0LP01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/21000","corpus":"errors","engine":"postgresql","language":"en","title":"more than one row returned by a subquery","description":"A scalar subquery, used where a single value is expected, returned several rows. Add a filter, an aggregate, LIMIT 1, or use IN or a join.","body":{"code":"21000","slug":"21000","name":"cardinality_violation","message":"more than one row returned by a subquery used as an expression","group":"21","severity":null,"sql_state":null,"summary":"A scalar subquery, used where a single value is expected, returned several rows. Add a filter, an aggregate, LIMIT 1, or use IN or a join.","meaning":"A subquery in the select list, in a comparison (`= (SELECT ...)`) or in a `SET` clause must produce at most one row. PostgreSQL only finds out at run time, when the subquery returns a second row, and then fails with 21000 (`cardinality_violation`).\n\nThe same code is used by `ON CONFLICT DO UPDATE command cannot affect row a second time`, when one `INSERT` proposes the same key twice.","causes":["A lookup subquery on a column that isn't unique, such as matching customers by name.","A correlated subquery missing part of its join condition.","Data that used to be unique and no longer is.","An `INSERT ... ON CONFLICT DO UPDATE` whose input contains duplicate keys."],"fix":[{"text":"If any of several values will do, or you want one of them deterministically, pick it explicitly.","sql":"SELECT o.id,\n       (SELECT c.email FROM contacts c\n        WHERE c.customer_id = o.customer_id\n        ORDER BY c.is_primary DESC, c.id\n        LIMIT 1) AS email\nFROM orders o;"},{"text":"If all matching rows count, use `IN`, `ANY` or a join instead of `=`.","sql":"SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE name = 'Ada');"},{"text":"Find the keys that return more than one row.","sql":"SELECT customer_id, count(*) FROM contacts GROUP BY customer_id HAVING count(*) > 1;"},{"text":"For `ON CONFLICT`, remove duplicate keys from the input first.","sql":"INSERT INTO prices (sku, price)\nSELECT DISTINCT ON (sku) sku, price FROM staging ORDER BY sku, updated_at DESC\nON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price;"}],"diagnostic":"-- Which keys feed the subquery more than one row?\nSELECT customer_id, count(*)\nFROM contacts\nGROUP BY customer_id\nHAVING count(*) > 1;\n\n-- Is the column the subquery filters on unique?\n-- If a primary key or unique constraint backs it, the error must come from data, not schema.\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'contacts'::regclass AND contype IN ('p', 'u');\n\n-- For ON CONFLICT DO UPDATE, find duplicate keys in the input set\n-- before the INSERT runs.\nSELECT sku, count(*)\nFROM staging\nGROUP BY sku\nHAVING count(*) > 1;","alternatives":"If several rows matching is legitimate business meaning, a join expresses it without the scalar constraint and usually plans better. If you want any single row and do not care which, FETCH FIRST 1 ROWS ONLY (or LIMIT 1) on the subquery works, but say which with an ORDER BY so results stay stable.","details":[],"details_title":null,"repro":"SELECT (SELECT x FROM (VALUES (1), (2)) v(x));  -- ERROR: more than one row returned by a subquery used as an expression","repro_note":null,"related":["postgresql/42803","postgresql/23505","sql-server/512","mysql/1242","oracle/ora-01427"],"sqlly":null,"faqs":[{"question":"Why did this query work yesterday and fail today?","answer":"The subquery's second row arrived. Scalar subqueries only fail when the data actually has a duplicate, so the schema was already able to produce this. Someone added a row, a uniqueness constraint was dropped, or the query's filter changed and now matches more."},{"question":"Does MAX() around the subquery fix it?","answer":"It silences the error but hides a decision. Put the aggregate inside the subquery, as in `(SELECT max(c.email) FROM contacts c WHERE ...)`. An aggregate wrapped around the whole subquery, as in `MAX((SELECT ...))`, still raises this error. The inner aggregate picks one value arbitrarily; that may be fine for genuinely interchangeable values and silently wrong for prices or addresses. An ORDER BY plus LIMIT 1 states the choice instead of burying it."},{"question":"The error message mentions ON CONFLICT but my INSERT looks fine. Where is the duplicate?","answer":"The INSERT's input has two rows with the same conflict key, so the second proposal would update the row the first one already touched. The staging-table query in the diagnostic finds the offenders; DISTINCT ON in the statement deduplicates inline."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/21000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22001","corpus":"errors","engine":"postgresql","language":"en","title":"value too long for type","description":"A string is longer than the column's varchar(n) or char(n) limit. PostgreSQL rejects it rather than silently truncating.","body":{"code":"22001","slug":"22001","name":"string_data_right_truncation","message":"value too long for type character varying(20)","group":"22","severity":null,"sql_state":null,"summary":"A string is longer than the column's varchar(n) or char(n) limit. PostgreSQL rejects it rather than silently truncating.","meaning":"A `varchar(n)` or `char(n)` column holds at most n characters. Inserting or updating a longer value fails with 22001 (`string_data_right_truncation`), unless the excess characters are all spaces, in which case PostgreSQL truncates silently. An explicit cast also truncates silently, as in `'abcdef'::varchar(3)`.\n\nThe message names the type but not the column, so with several limited columns you need to check which value is too long.","causes":["User input or imported data longer than the column definition.","A multi-column `INSERT` where values are in a different order than the column list, putting a long value in a short column.","A schema migrated from another database with tight limits."],"fix":[{"text":"Find which column overflowed by comparing value lengths with the limits.","sql":"SELECT column_name, character_maximum_length\nFROM information_schema.columns\nWHERE table_name = 'customers' AND character_maximum_length IS NOT NULL;"},{"text":"Widen the column, or use `text`, which has no length limit and performs the same as `varchar`.","sql":"ALTER TABLE customers ALTER COLUMN name TYPE varchar(200);\n-- or\nALTER TABLE customers ALTER COLUMN name TYPE text;"},{"text":"If truncation is acceptable, do it explicitly.","sql":"INSERT INTO customers (name) VALUES (left('a very long name ...', 20));"}],"diagnostic":"-- The message names the type but not the column. List the table's length-limited\n-- columns and compare each limit against the value you tried to write.\nSELECT column_name, data_type, character_maximum_length\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND table_name = 'customers'\n  AND character_maximum_length IS NOT NULL\nORDER BY character_maximum_length;\n-- The first column whose limit is shorter than your incoming value is the culprit.\n-- If every limit is longer than your value, the overflow happened in an explicit\n-- cast like 'abcdef'::varchar(3) somewhere in the query text.","alternatives":"If the limit is a business rule, store the column as text and enforce it with a CHECK so the error names the constraint that failed (for example `v139_code_rule`), though not the column. Or truncate in the application before the insert, where you control what gets cut.","details":[],"details_title":null,"repro":"SELECT CAST('abc' AS varchar(2)) AS silently_truncated;\nCREATE TEMP TABLE t (code varchar(2));\nINSERT INTO t VALUES ('abc');  -- ERROR: value too long for type character varying(2)","repro_note":null,"related":["postgresql/22003","postgresql/22P02","sql-server/8152","sql-server/2628","mysql/1406","oracle/ora-12899"],"sqlly":null,"faqs":[{"question":"Is text slower than varchar in PostgreSQL?","answer":"No. text and varchar use the same storage. A length limit is a constraint on the data, not a performance feature."},{"question":"Why did my value get cut off in one place and error in another?","answer":"An explicit cast like `::varchar(3)` truncates silently. Writing a longer value into a `varchar(3)` column errors. Same limit, different behavior: the cast truncates and the write raises the error."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22003","corpus":"errors","engine":"postgresql","language":"en","title":"numeric value out of range","description":"A number doesn't fit its type: an integer overflow, a value too big for numeric(p,s), or an id column that hit the int4 limit.","body":{"code":"22003","slug":"22003","name":"numeric_value_out_of_range","message":"integer out of range","group":"22","severity":null,"sql_state":null,"summary":"A number doesn't fit its type: an integer overflow, a value too big for numeric(p,s), or an id column that hit the int4 limit.","meaning":"Each numeric type has a range: `smallint` up to 32767, `integer` up to 2147483647, `bigint` up to about 9.2 × 10^18, and `numeric(p, s)` up to p digits with s after the point. A value or a calculation result outside the range fails with 22003. The message names the type: `integer out of range`, `bigint out of range`, `smallint out of range`, or `numeric field overflow` for `numeric(p, s)`.\n\nArithmetic on two integers is done in integer, so `count * price_in_cents` can overflow even when the final answer is stored in a `bigint` column.","causes":["A `serial` (integer) primary key reached 2147483647. `nextval` then fails with SQLSTATE 2200H, `nextval: reached maximum value of sequence ... (2147483647)`. Error 22003 `integer out of range` appears on insert only when the sequence is bigint-typed while the column is integer.","Multiplying or summing integers whose result exceeds the integer range before it is cast.","A value with more digits than `numeric(p, s)` allows, for example 1000.00 in a `numeric(5,2)` column.","Casting a large text or float value to `integer` or `smallint`."],"fix":[{"text":"Widen the column; for an integer id that is running out, move to `bigint` (this rewrites the table, so plan it).","sql":"ALTER TABLE events ALTER COLUMN id TYPE bigint;\nALTER SEQUENCE events_id_seq AS bigint;"},{"text":"Cast to a wider type before the arithmetic, not after.","sql":"SELECT qty::bigint * unit_price_cents FROM order_lines;"},{"text":"Increase the precision of a `numeric(p, s)` column.","sql":"ALTER TABLE invoices ALTER COLUMN total TYPE numeric(12, 2);"},{"text":"Check how close a sequence is to its limit.","sql":"SELECT last_value, max_value FROM pg_sequences WHERE sequencename = 'events_id_seq';"}],"diagnostic":"-- Which sequences are close to their integer limit?\nSELECT sequencename, last_value, max_value,\n       round(100.0 * last_value / max_value, 2) AS pct_used\nFROM pg_sequences\nWHERE data_type <> 'bigint'::regtype\nORDER BY pct_used DESC;\n\n-- How wide are the columns in the table that failed?\nSELECT column_name, data_type, numeric_precision, numeric_scale\nFROM information_schema.columns\nWHERE table_name = 'events';\n\n-- Find the largest value already stored, to size the new type:\nSELECT max(id) FROM events;\n\n-- Reproduce the arithmetic overflow in isolation:\nSELECT 2147483647 + 1;","alternatives":"If widening the column is too disruptive right now, a CHECK-free intermediate measure is casting reads to bigint at the query level, which fixes arithmetic overflow but not the storage limit. For numeric columns, choosing the precision once with headroom (numeric(14,2) for money) avoids repeated ALTER TYPE rewrites; numeric without precision has no practical overflow (up to 131072 digits before the decimal point and 16383 after, https://www.postgresql.org/docs/current/datatype-numeric.html), at the cost of less schema documentation.","details":[],"details_title":null,"repro":"SELECT 2147483647 + 1;      -- ERROR: integer out of range\nSELECT 1000::numeric(5, 2);  -- ERROR: numeric field overflow","repro_note":null,"related":["postgresql/22001","postgresql/22P02","postgresql/22012","sql-server/8115","mysql/1264","oracle/ora-01438"],"sqlly":null,"faqs":[{"question":"How urgent is a serial primary key hitting 2147483647?","answer":"Stop-and-plan urgent. Once the sequence reaches the integer ceiling, nextval fails with 2200H and every insert that needs a new id fails, so the window is the number of ids left, not time on a calendar. The pg_sequences query shows the percentage used; plan the bigint migration while you still have room, and remember the rewrite locks the table."},{"question":"Why did 3000000 * 2000 overflow when the result fits in bigint?","answer":"PostgreSQL types the operands first: integer times integer is computed as integer, and only the result is considered. Both operands fit in integer, so the multiplication runs in integer and 6,000,000,000 exceeds the integer range. 1000 * 1000 does not overflow. Cast one operand to bigint before the operator."},{"question":"Does altering a column to bigint rewrite the whole table?","answer":"Yes, increasing integer to bigint requires a table rewrite with an ACCESS EXCLUSIVE lock, so on large tables plan a maintenance window or use a migration tool that does it in batches. The sequence must be altered to bigint separately, otherwise nextval keeps producing 32-bit values."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22003","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22007","corpus":"errors","engine":"postgresql","language":"en","title":"invalid datetime format","description":"A string couldn't be read as a date, time or timestamp: an unknown format, impossible field, or ambiguous day/month order.","body":{"code":"22007","slug":"22007","name":"invalid_datetime_format","message":"invalid input syntax for type date: \"not a date\"","group":"22","severity":null,"sql_state":null,"summary":"A string couldn't be read as a date, time or timestamp: an unknown format, impossible field, or ambiguous day/month order.","meaning":"PostgreSQL parses date and time input in ISO 8601 (`2026-12-31 23:59:00`) and several other formats, using the `DateStyle` setting to decide whether `01/02/2026` is January 2 or February 1. Text it can't parse at all fails with 22007; text that parses but has an out-of-range field (month 13, hour 25) usually fails with 22008 instead.\n\n`to_date` and `to_timestamp` with an explicit format string avoid guessing.","causes":["A date in a regional format that doesn't match `DateStyle`.","Empty strings or placeholder text such as `'N/A'` in a date column of an import file.","Extra text, such as a weekday name or a time zone abbreviation PostgreSQL doesn't know.","A format string in `to_date` or `to_timestamp` that doesn't match the input."],"fix":[{"text":"Send dates in ISO 8601 format, which works with every `DateStyle`.","sql":"INSERT INTO events (at) VALUES ('2026-12-31 23:59:00+00');"},{"text":"Parse other formats explicitly.","sql":"SELECT to_timestamp('31/12/2026 23:59', 'DD/MM/YYYY HH24:MI');"},{"text":"Clean placeholders to `NULL` before converting.","sql":"SELECT NULLIF(NULLIF(trim(raw_date), ''), 'N/A')::date FROM staging;"},{"text":"Check the session's `DateStyle` if numeric dates are read in the wrong order.","sql":"SHOW DateStyle;\nSET DateStyle = 'ISO, DMY';"}],"diagnostic":"-- Isolate the failing cast and read the exact value back:\nSELECT 'not a date'::date;\n\n-- What does the session accept for numeric dates?\nSHOW DateStyle;\n\n-- Find unconvertible values in a staging column (PostgreSQL 16+).\nSELECT raw_date\nFROM staging\nWHERE raw_date IS NOT NULL\n  AND NOT pg_input_is_valid(raw_date, 'date');\n\n-- Check which placeholders you actually have in the data:\nSELECT raw_date, count(*)\nFROM staging\nGROUP BY raw_date\nORDER BY count(*) DESC\nLIMIT 20;","alternatives":"When inputs arrive in several formats, normalizing in a staging column with to_date per known format, tried in order, beats widening the session settings. If the column legitimately holds non-dates, store the raw text alongside the parsed value so failures are data you can query rather than errors you must chase.","details":[],"details_title":null,"repro":"SELECT 'not a date'::date;  -- ERROR: invalid input syntax for type date: \"not a date\"","repro_note":null,"related":["postgresql/22008","postgresql/22P02","sql-server/241","mysql/1292","oracle/ora-01861","oracle/ora-01843"],"sqlly":null,"faqs":[{"question":"How is this different from 22008?","answer":"22007 means the text cannot be parsed as a date or time at all: wrong shape, unknown text, garbage. 22008 means the text parsed fine but a field is out of range, like month 13. Same family, different stage of the parse."},{"question":"Why does '01/02/2026' work in one environment and fail in another?","answer":"DateStyle. In MDY sessions it is January 2; in DMY sessions February 1; a value like '13/01/2026' parses in DMY and fails in MDY. Environments with different DateStyle settings accept different literals, which is why ISO 8601 input is the safe default."},{"question":"My format string in to_timestamp looks right but the cast fails. What should I check?","answer":"Every character of the input must be consumed or matched. Text the format does not expect, in the middle or at the start, breaks the match, such as a time zone abbreviation before the time: '2026-12-31 PST 23:59' fails with invalid value \"PS\" for \"HH24\". Text left over after the format is fully applied is ignored: to_timestamp('31/12/2026 23:59 XYZ', 'DD/MM/YYYY HH24:MI') returns 2026-12-31 23:59:00+00. Unpadded numbers parse ('3:59' for HH24) and a two-digit year under YYYY gives year 0026. to_timestamp is lenient about separators and field width, so when a value is wrong, echo the input and the format side by side and compare the parts that land in each field."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22007","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22008","corpus":"errors","engine":"postgresql","language":"en","title":"date/time field value out of range","description":"A date or time had a field outside its valid range, such as month 13 or day 31 in a 30-day month, or a day/month order mix-up.","body":{"code":"22008","slug":"22008","name":"datetime_field_overflow","message":"date/time field value out of range: \"2026-13-01\"","group":"22","severity":null,"sql_state":null,"summary":"A date or time had a field outside its valid range, such as month 13 or day 31 in a 30-day month, or a day/month order mix-up.","meaning":"The input looked like a date or time, but one of its fields is impossible: a month above 12, a day that doesn't exist in that month, an hour above 24. 22008 (`datetime_field_overflow`) also covers results outside the representable range, such as `timestamp out of range`.\n\nWhen the value is a numeric date like `13/01/2026`, PostgreSQL adds a hint that you may need a different `DateStyle`, because it read 13 as the month.","causes":["Day and month swapped relative to the session's `DateStyle`.","Invalid calendar dates in source data, such as February 30.","Date arithmetic that produces a value beyond the supported range."],"fix":[{"text":"Use ISO 8601 dates (`YYYY-MM-DD`), which are never ambiguous.","sql":null},{"text":"If the data is day-first, say so, or parse it with an explicit format.","sql":"SET DateStyle = 'ISO, DMY';\nSELECT '13/01/2026'::date;\n-- or\nSELECT to_date('13/01/2026', 'DD/MM/YYYY');"},{"text":"Find bad rows in a staging table before converting them (PostgreSQL 16 and later).","sql":"SELECT raw_date FROM staging WHERE NOT pg_input_is_valid(raw_date, 'date');"}],"diagnostic":"-- Reproduce the parse in isolation to see which value fails:\nSELECT '2026-02-30'::date;\n\n-- What order is the session reading numeric dates in?\nSHOW DateStyle;\n\n-- Scan a staging column for unconvertible values before the real\n-- INSERT (PostgreSQL 16+; earlier versions need a function with\n-- an exception handler).\nSELECT raw_date\nFROM staging\nWHERE NOT pg_input_is_valid(raw_date, 'date');\n\n-- Check the arithmetic end of the range: the boundaries of the types.\nSELECT 'infinity'::timestamp, '4714-11-24 BC'::date, '294276-12-31'::timestamp;","alternatives":"When the source format is fixed but ugly, to_date or to_timestamp with an explicit format string is safer than flipping DateStyle for the whole session, because it affects only that expression. Date arithmetic does not clamp: a date + interval that runs past 294276 AD raises timestamp out of range (SQLSTATE 22008). Check the operands against the limits before adding.","details":[],"details_title":null,"repro":"SELECT '2026-02-30'::date;  -- ERROR: date/time field value out of range: \"2026-02-30\"","repro_note":null,"related":["postgresql/22007","postgresql/22003","sql-server/242","mysql/1292","oracle/ora-01843"],"sqlly":null,"faqs":[{"question":"February 30 is obviously wrong, but '13/01/2026' looks like a valid date. Why the error?","answer":"It depends on DateStyle. In the default ISO, MDY setting, PostgreSQL reads the first number as the month, so 13 is month 13 and the value is out of range. The hint PostgreSQL adds to the error suggests DateStyle for exactly this reason."},{"question":"What are the actual limits of timestamp?","answer":"timestamp runs from 4713 BC to 294276 AD, both inclusive, at microsecond resolution. Values beyond that, or arithmetic that lands outside it, raise 'timestamp out of range'. If you are anywhere near those bounds, the input data is wrong rather than the type being too small."},{"question":"Is there a way to get NULL instead of an error for bad dates?","answer":"On PostgreSQL 16 and later, pg_input_is_valid(value, 'date') returns a boolean you can test first. Wrap it in a CASE to return NULL for the failures, for example: SELECT CASE WHEN pg_input_is_valid(raw_date, 'date') THEN raw_date::date END FROM staging; On older versions, wrap the cast in a small SQL function with an exception clause, or clean the data in a staging pass."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22008","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22012","corpus":"errors","engine":"postgresql","language":"en","title":"division by zero","description":"An expression divided a number by zero. PostgreSQL raises an error instead of returning NULL or infinity for integer and numeric division.","body":{"code":"22012","slug":"22012","name":"division_by_zero","message":"division by zero","group":"22","severity":null,"sql_state":null,"summary":"An expression divided a number by zero. PostgreSQL raises an error instead of returning NULL or infinity for integer and numeric division.","meaning":"Dividing an integer or `numeric` value by zero, or taking a modulo by zero, is an error in PostgreSQL. It usually appears in reports and ratios where some groups have a zero denominator. Floating-point division by zero is an error too.\n\nBecause PostgreSQL may evaluate expressions in any order, a `WHERE x <> 0` filter does not always protect an expression in the select list of the same query; guard the expression itself.","causes":["A ratio such as `revenue / orders` where some rows have zero orders.","An average computed by hand as `coalesce(sum(x), 0) / count(*)` over an empty group. A bare `sum(x) / count(*)` returns NULL there and does not raise.","Relying on a `WHERE` or `CASE` elsewhere in the query to filter zero rows out before the division runs."],"fix":[{"text":"Turn a zero divisor into `NULL` with `NULLIF`; the result is then `NULL` instead of an error.","sql":"SELECT region, revenue / NULLIF(order_count, 0) AS avg_order\nFROM region_totals;"},{"text":"Use `CASE` when zero should produce a specific value.","sql":"SELECT CASE WHEN order_count = 0 THEN 0 ELSE revenue / order_count END\nFROM region_totals;"},{"text":"For averages, use `avg()`, which ignores `NULL` and returns `NULL` for an empty set.","sql":"SELECT customer_id, avg(amount) FROM payments GROUP BY customer_id;"}],"diagnostic":"-- Find which column actually carries zeros in the data:\nSELECT count(*) FILTER (WHERE order_count = 0) AS zero_denominators,\n       count(*) AS total\nFROM region_totals;\n\n-- Hunt every division in a view or query once you suspect one:\n-- search your SQL for '/' and check each right-hand side against\n-- the data above. There is no catalog view that lists expressions,\n-- so this is a read-the-query step.\n\n-- Confirm the behavior with three separate statements: the first error\n-- aborts the statement, so one combined select list never shows the rest.\nSELECT 1 / 0;               -- ERROR: division by zero\nSELECT 1.0 / 0::numeric;    -- ERROR: division by zero\nSELECT 'NaN'::float8 / 0;   -- NaN","alternatives":"For dashboards where a missing ratio should show as a dash, COALESCE(revenue / NULLIF(order_count, 0), 0) turns the NULL into 0. For a text placeholder such as 'n/a', cast the division to text first: COALESCE((revenue / NULLIF(order_count, 0))::text, 'n/a'). Passing 'n/a' into a COALESCE over a numeric result raises invalid input syntax for type numeric. In window-function-heavy reports, computing sums and counts with aggregate functions instead of hand-rolled sum/count division sidesteps the empty-group case entirely.","details":[],"details_title":null,"repro":"SELECT 1 / 0;  -- ERROR: division by zero","repro_note":null,"related":["postgresql/22003","postgresql/25P02","sql-server/8134","oracle/ora-01476"],"sqlly":null,"faqs":[{"question":"Why didn't my WHERE clause prevent this?","answer":"PostgreSQL does not promise evaluation order between the WHERE list and the select list. The optimizer may compute the select-list expression before applying the filter, so a zero row can reach the division even though the WHERE would have removed it. Guard inside the expression with NULLIF or CASE."},{"question":"Should I return NULL or 0 for a zero denominator?","answer":"NULL is the honest answer: an average of nothing is undefined. 0 reads as a real measurement of zero and skews further math built on it. Use 0 only when the consumer genuinely needs a number and zero is a safe default."},{"question":"Does this apply to float division too?","answer":"Yes. Unlike some databases, PostgreSQL raises division by zero for float8 and float4 as well as integer and numeric. Only NaN propagates: NaN / 0 returns NaN, and Infinity / Infinity returns NaN too. A zero divisor with a non-NaN numerator raises for every numeric type. The same NULLIF guard works for all of them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22012","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22021","corpus":"errors","engine":"postgresql","language":"en","title":"invalid byte sequence for encoding","description":"Text contains bytes that aren't valid in the database or client encoding: a Latin-1 or Windows-1252 file loaded as UTF-8, or a NUL byte in text.","body":{"code":"22021","slug":"22021","name":"character_not_in_repertoire","message":"invalid byte sequence for encoding \"UTF8\": 0xff","group":"22","severity":null,"sql_state":null,"summary":"Text contains bytes that aren't valid in the database or client encoding: a Latin-1 or Windows-1252 file loaded as UTF-8, or a NUL byte in text.","meaning":"PostgreSQL checks that every text value is valid in the encoding it arrives in. 22021 (`character_not_in_repertoire`) means a byte sequence isn't a valid character there. With a UTF-8 database it usually means the data was really in another encoding, such as Latin-1 or Windows-1252, where bytes like `0xe9` (é) are single bytes that aren't valid UTF-8 on their own.\n\nPostgreSQL text types can never contain the NUL byte, so `invalid byte sequence for encoding \"UTF8\": 0x00` means binary or C-string data reached a text column.","causes":["Loading a CSV exported by a tool that wrote Windows-1252 or Latin-1, with `COPY` or `\\copy` assuming UTF-8.","`client_encoding` set to `UTF8` while the client actually sends another encoding.","Binary data, or strings with embedded NUL bytes, inserted into a `text` or `varchar` column.","Data truncated in the middle of a multi-byte character by an application."],"fix":[{"text":"Tell `COPY` the file's real encoding; PostgreSQL converts it.","sql":"\\copy customers FROM 'customers.csv' WITH (FORMAT csv, HEADER true, ENCODING 'WIN1252')"},{"text":"Or set the client encoding for the session to match what the client sends.","sql":"SET client_encoding = 'LATIN1';"},{"text":"Convert the file before loading, for example `iconv -f WINDOWS-1252 -t UTF-8 in.csv > out.csv`.","sql":null},{"text":"Store binary data in `bytea`, and strip NUL bytes from text in the application before inserting.","sql":null}],"diagnostic":"-- What encoding does the database and this session use?\nSELECT datname, pg_encoding_to_char(encoding) FROM pg_database;\nSHOW client_encoding;\n\n-- A value that fails the encoding check never reaches a text column; the\n-- error fires on input, so there are no broken rows to filter afterwards.\n-- To find the offending lines, stage the bytes in a bytea column and test\n-- each one:\nCREATE TABLE raw_import (id int, raw bytea);\nINSERT INTO raw_import VALUES (1, convert_to('ok', 'UTF8')), (2, '\\xe9'::bytea);\nDO $$\nDECLARE r record;\nBEGIN\n  FOR r IN SELECT id, raw FROM raw_import LOOP\n    BEGIN\n      PERFORM convert_from(r.raw, 'UTF8');\n    EXCEPTION WHEN character_not_in_repertoire THEN\n      RAISE NOTICE 'row % fails the encoding check', r.id;\n    END;\n  END LOOP;\nEND $$;\n\n-- On the file itself, before loading:\n-- file -I customers.csv    (shows charset, e.g. iso-8859-1)","alternatives":"If the whole file is one known encoding, loading it into a scratch table with the text columns typed as bytea and converting per column with convert_from(col, 'WIN1252') gives you per-row control and error messages that name the row. For repeated loads, fixing the producer to write UTF-8 is cheaper than converting on every import.","details":[],"details_title":null,"repro":"-- Produce an invalid UTF-8 byte sequence from within one session:\nSELECT convert_from(decode('e9', 'hex'), 'UTF8');\n-- ERROR:  invalid byte sequence for encoding \"UTF8\": 0xe9\n-- The NUL-byte case:\nSELECT convert_from(decode('410042', 'hex'), 'UTF8');\n-- ERROR:  invalid byte sequence for encoding \"UTF8\": 0x00","repro_note":null,"related":["postgresql/22P02","postgresql/22001","mysql/1366"],"sqlly":"SQLly's CSV import previews the parsed rows before inserting anything, so garbled characters from a wrong encoding show up in the preview instead of in your table.","faqs":[{"question":"The file opens fine in my editor. Why does PostgreSQL reject it?","answer":"Editors detect encodings and render them for you. PostgreSQL does not guess: it checks every byte against the session encoding. A Windows-1252 file looks right in the editor and fails on the first accented character, because that byte is not valid UTF-8 alone."},{"question":"Where did a 0x00 byte come from?","answer":"Usually binary data: a hash, an encryption output, a protobuf blob, or a C string read from a file. PostgreSQL text types cannot store NUL at all, in any encoding. Store such data in bytea, or strip the NULs in the application before insert."},{"question":"Can I change the database encoding to fix this?","answer":"That treats the symptom. The database encoding should match what the application really sends. If the data is Latin-1 and stays Latin-1, a LATIN1 database works, but converting an existing database means dump and restore. Setting client_encoding so PostgreSQL converts on the way in is almost always the smaller change."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22021","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22023","corpus":"errors","engine":"postgresql","language":"en","title":"invalid parameter value","description":"A setting or function argument has a value outside what it accepts: an unknown time zone, a bad unit in a memory setting, a zero step in generate_series.","body":{"code":"22023","slug":"22023","name":"invalid_parameter_value","message":"invalid value for parameter \"TimeZone\": \"Mars/Olympus\"","group":"22","severity":null,"sql_state":null,"summary":"A setting or function argument has a value outside what it accepts: an unknown time zone, a bad unit in a memory setting, a zero step in generate_series.","meaning":"22023 (`invalid_parameter_value`) means the value is the right type but not an allowed value. For configuration parameters the message is `invalid value for parameter \"name\": \"value\"`, often with a hint listing the valid units or values. Many built-in functions use the same code for bad arguments, such as `step size cannot equal zero` from `generate_series`.\n\nRead the message and hint closely: they name the parameter and, usually, what is allowed.","causes":["A time zone name PostgreSQL doesn't know (the valid names are in `pg_timezone_names`).","A memory or time setting with a wrong unit, such as `work_mem = '64mb'` instead of `'64MB'` (units are case-sensitive).","A function argument out of its allowed range or set, such as a zero step or an unknown option keyword."],"fix":[{"text":"Check the valid values for a setting.","sql":"SELECT name, unit, vartype, min_val, max_val, enumvals\nFROM pg_settings WHERE name = 'work_mem';"},{"text":"Pick a time zone from the list PostgreSQL knows.","sql":"SELECT name FROM pg_timezone_names WHERE name ILIKE '%new_york%';\nSET TimeZone = 'America/New_York';"},{"text":"Use units as PostgreSQL spells them: `B`, `kB`, `MB`, `GB`, `TB` for memory and `us`, `ms`, `s`, `min`, `h`, `d` for time.","sql":"SET work_mem = '64MB';\nSET statement_timeout = '30s';"}],"diagnostic":"-- Which parameter failed, and what does the server allow?\nSELECT name, setting, unit, vartype, min_val, max_val, enumvals, source\nFROM pg_settings\nWHERE name = 'TimeZone';   -- substitute the named parameter\n\n-- For a time zone, search the catalog of names PostgreSQL knows:\nSELECT name, abbrev, utc_offset\nFROM pg_timezone_names\nWHERE name ILIKE '%york%';\n\n-- For generate_series and similar functions, check the arguments\n-- against the documented contract; a zero step is the usual offender.\n-- A reversed integer step returns no rows rather than an error.\nSELECT generate_series(1, 10, 0);","alternatives":"When a setting keeps getting wrong values from application code, setting it at the role level (ALTER ROLE app SET work_mem = '64MB') takes it out of the application's hands. For time zones, accepting an IANA name and validating against pg_timezone_names before SET turns a runtime error into a form-validation error.","details":[],"details_title":null,"repro":"SET TimeZone = 'Mars/Olympus';  -- ERROR: invalid value for parameter \"TimeZone\": \"Mars/Olympus\"","repro_note":null,"related":["postgresql/42704","postgresql/22P02","postgresql/22003"],"sqlly":null,"faqs":[{"question":"Are memory units really case-sensitive?","answer":"Yes. PostgreSQL accepts kB, MB, GB and TB, and lowercase mb is rejected with 22023, and so is kb. '64mb' fails where '64MB' works. The unit column in pg_settings shows the exact spelling the server expects."},{"question":"How is this different from 22P02?","answer":"22P02 is about text that should have been a value of a type, like 'abc' as an integer. 22023 is a value of the right type that a parameter or function rejects, like work_mem = -1 or an unknown time zone name. The message wording tells you which: invalid input syntax versus invalid value for parameter."},{"question":"Why does the same time zone name work on one server and fail on another?","answer":"Time zone names come from the server's tzdata, installed with the operating system or bundled with PostgreSQL. Old or minimal servers miss newer zone names and some abbreviations. Compare SELECT count(*) FROM pg_timezone_names; across servers to confirm."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22023","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/22P02","corpus":"errors","engine":"postgresql","language":"en","title":"invalid input syntax for type","description":"A text value couldn't be converted to the target type: letters into an integer, a malformed UUID, bad JSON, an empty string into a number.","body":{"code":"22P02","slug":"22P02","name":"invalid_text_representation","message":"invalid input syntax for type integer: \"abc\"","group":"22","severity":null,"sql_state":null,"summary":"A text value couldn't be converted to the target type: letters into an integer, a malformed UUID, bad JSON, an empty string into a number.","meaning":"PostgreSQL converts literals and text to typed values with each type's input function. When the text isn't a valid representation of the type, the conversion fails with 22P02 and the message quotes the offending value.\n\nThe value can come from a literal in the query, a bound parameter, a `CAST`, or a column of text being compared with or inserted into a typed column.","causes":["Comparing a numeric or UUID column with a string that isn't a number or UUID, for example `WHERE id = 'abc'` or an empty string `''`.","Passing an empty string where a number is expected. PostgreSQL does not turn `''` into `NULL` or 0.","Malformed input for `uuid`, `json`/`jsonb`, `boolean`, `inet` or an array literal.","Bulk `COPY` or CSV loads where one row has text in a numeric column."],"fix":[{"text":"Find rows that wouldn't convert before casting them (PostgreSQL 16 and later have `pg_input_is_valid`).","sql":"SELECT raw_value\nFROM staging\nWHERE NOT pg_input_is_valid(raw_value, 'integer');"},{"text":"On older versions, filter with a pattern and a range check before casting.","sql":"SELECT raw_value::int\nFROM staging\nWHERE raw_value ~ '^-?[0-9]+$'\n  AND raw_value::numeric BETWEEN -2147483648 AND 2147483647;"},{"text":"Turn empty strings into `NULL` explicitly.","sql":"SELECT NULLIF(trim(raw_value), '')::int FROM staging;"},{"text":"In application code, bind parameters with the right type instead of building SQL strings, and validate input before it reaches the database.","sql":null}],"diagnostic":"-- Which values in the text column cannot convert? PostgreSQL 16 and later:\nSELECT raw_value, count(*)\nFROM staging\nWHERE raw_value IS NOT NULL\n  AND NOT pg_input_is_valid(raw_value, 'integer')\nGROUP BY raw_value\nORDER BY 2 DESC\nLIMIT 20;\n-- Empty strings show up here too. On versions before 16, filter with\n-- raw_value !~ '^-?[0-9]+$' instead. The grouped counts tell you whether this is\n-- one repeated bad value (likely an app bug) or scattered rows (likely dirty data).","alternatives":"For bulk loads, PostgreSQL 17 and later have COPY with the ON_ERROR option to skip rows whose values fail conversion, logging them so you can clean up after. Otherwise load into an all-text staging table, fix the values there, then cast.","details":[],"details_title":null,"repro":"SELECT 'abc'::int;  -- ERROR: invalid input syntax for type integer: \"abc\"","repro_note":null,"related":["postgresql/22003","postgresql/22007","postgresql/42804","postgresql/22021","sql-server/245","mysql/1366","oracle/ora-01722"],"sqlly":"SQLly's CSV import previews the parsed rows and lists the values that won't convert to the target column type, with row and column, before anything is inserted.","faqs":[{"question":"Why does WHERE id = '' fail here but work in MySQL?","answer":"MySQL coerces '' to 0 in numeric context. PostgreSQL never does: an empty string is not a valid integer, so the input function rejects it. Use NULL explicitly if you mean missing."},{"question":"Why does the query fail only sometimes?","answer":"The bad value arrives with some rows and not others, often an empty string from an unset form field or a non-numeric id from a stale link. The error message quotes the value; that is your clue about which caller sends it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/22P02","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/23502","corpus":"errors","engine":"postgresql","language":"en","title":"null value violates not-null constraint","description":"An INSERT or UPDATE left a NOT NULL column empty, often because the column was omitted and has no default.","body":{"code":"23502","slug":"23502","name":"not_null_violation","message":"null value in column \"email\" of relation \"users\" violates not-null constraint\nDETAIL:  Failing row contains (7, Ada, null).","group":"23","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE left a NOT NULL column empty, often because the column was omitted and has no default.","meaning":"A `NOT NULL` column must have a value in every row. 23502 means the new or updated row had `NULL` there, either explicitly or because the column was left out of an `INSERT` and its default is `NULL`.\n\nThe `DETAIL` line shows the whole failing row. PostgreSQL 13 and later name the table in the message; older versions say only `null value in column \"email\" violates not-null constraint`.","causes":["The `INSERT` doesn't list the column and the column has no `DEFAULT`.","The application sent `NULL`, for example an unset field or a failed lookup.","`INSERT ... SELECT` or an `UPDATE` with a subquery that returned no row, producing `NULL`.","A column added with `NOT NULL` that existing code doesn't know about."],"fix":[{"text":"Supply the value, or give the column a default.","sql":"ALTER TABLE users ALTER COLUMN created_at SET DEFAULT now();\nINSERT INTO users (id, name, email) VALUES (7, 'Ada', 'ada@example.com');"},{"text":"Use `COALESCE` when a lookup or expression can return `NULL`.","sql":"UPDATE orders o\nSET region = COALESCE((SELECT region FROM customers c WHERE c.id = o.customer_id), 'unknown');"},{"text":"If the column should allow missing values, drop the constraint.","sql":"ALTER TABLE users ALTER COLUMN phone DROP NOT NULL;"}],"diagnostic":"-- Which NOT NULL columns have no default? Those fail any INSERT that omits them.\nSELECT column_name, is_nullable, column_default\nFROM information_schema.columns\nWHERE table_schema = 'public' AND table_name = 'users'\nORDER BY ordinal_position;\n-- A row with is_nullable = 'NO' and column_default IS NULL is the one your\n-- statement skipped. If the column is listed in your INSERT, the application\n-- sent NULL itself, so trace that value in the client code.","alternatives":"For bulk loads with patchy data, load into an unconstrained staging table first, fill or reject the missing values there, then insert into the real table. A BEFORE INSERT trigger can also supply computed defaults, though a plain column DEFAULT is cheaper and easier to read.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE u (id int, email text NOT NULL);\nINSERT INTO u (id) VALUES (1);  -- ERROR: null value in column \"email\" of relation \"u\" violates not-null constraint","repro_note":null,"related":["postgresql/23505","postgresql/23503","postgresql/23514","sql-server/515","mysql/1048","mysql/1364","oracle/ora-01400","sqlite/sqlite-constraint-notnull"],"sqlly":null,"faqs":[{"question":"Why does the error mention a column I never included in the INSERT?","answer":"An omitted column gets its DEFAULT, and if there is none the value is NULL. The message is about the row as constructed, so an unnamed column can still be the one that failed."},{"question":"Can I turn NOT NULL checks off for one load?","answer":"No, NOT NULL has no deferrable or per-session switch. Load into a staging table, or drop NOT NULL and re-add it after cleaning, which takes a full-table scan either way. On PostgreSQL 18 and later, ADD CONSTRAINT ... NOT NULL ... NOT VALID defers the scan to VALIDATE CONSTRAINT."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/23502","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/23503","corpus":"errors","engine":"postgresql","language":"en","title":"foreign key constraint violation","description":"A row references a parent key that doesn't exist, or you deleted or changed a parent row that child rows still reference.","body":{"code":"23503","slug":"23503","name":"foreign_key_violation","message":"insert or update on table \"orders\" violates foreign key constraint \"orders_customer_id_fkey\"\nDETAIL:  Key (customer_id)=(42) is not present in table \"customers\".","group":"23","severity":null,"sql_state":null,"summary":"A row references a parent key that doesn't exist, or you deleted or changed a parent row that child rows still reference.","meaning":"A foreign key says every value in the child column must exist in the referenced (parent) column. PostgreSQL raises 23503 in two directions: when you insert or update a child row whose key has no parent (`is not present in table`), and when you delete or update a parent row that child rows still point to (`is still referenced from table`).\n\nThe `DETAIL` line gives the key value and the other table, so you know which rows to look at.","causes":["Inserting child rows before their parent rows, for example loading `orders` before `customers`.","A typo or stale id in the child row.","Deleting a parent row that still has children, without `ON DELETE CASCADE` or `SET NULL` on the foreign key.","Updating a parent's primary key while children reference the old value.","Two transactions: one inserts a child for a parent another just deleted."],"fix":[{"text":"Find the missing parent or the remaining children.","sql":"SELECT * FROM customers WHERE id = 42;\nSELECT * FROM orders WHERE customer_id = 42;"},{"text":"Insert parents first, or load both tables in one transaction with the constraint deferred (it must be declared `DEFERRABLE`).","sql":"ALTER TABLE orders ALTER CONSTRAINT orders_customer_id_fkey DEFERRABLE INITIALLY IMMEDIATE;\nBEGIN;\nSET CONSTRAINTS orders_customer_id_fkey DEFERRED;\nINSERT INTO orders (id, customer_id) VALUES (1, 42);\nINSERT INTO customers (id, name) VALUES (42, 'Ada');\nCOMMIT;  -- checked here"},{"text":"When deleting a parent, delete or reassign its children first, or change the foreign key's delete rule if that is the behavior you want.","sql":"ALTER TABLE orders\n    DROP CONSTRAINT orders_customer_id_fkey,\n    ADD CONSTRAINT orders_customer_id_fkey FOREIGN KEY (customer_id)\n        REFERENCES customers (id) ON DELETE CASCADE;"},{"text":"Find orphans before adding a foreign key to existing data.","sql":"SELECT o.*\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL AND c.id IS NULL;"}],"diagnostic":"-- The message text splits the causes in two. \"is not present in table\" means a\n-- missing parent; confirm and see whether it ever existed:\nSELECT * FROM customers WHERE id = 42;\n-- \"is still referenced from table\" means a delete hit a parent with children:\nSELECT * FROM orders WHERE customer_id = 42;\n-- To survey all broken references at once, list every child whose parent is gone:\nSELECT o.*\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL AND c.id IS NULL;","alternatives":"For a big load, add the foreign key as NOT VALID (existing rows unchecked), load, clean up orphans, then VALIDATE CONSTRAINT. Ordering the load by dependency, parents before children, avoids the problem without deferring anything.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE p (id int PRIMARY KEY);\nCREATE TEMP TABLE c (p_id int REFERENCES p (id));\nINSERT INTO c VALUES (1);  -- ERROR: ... violates foreign key constraint \"c_p_id_fkey\"","repro_note":null,"related":["postgresql/23505","postgresql/23502","postgresql/42830","postgresql/2BP01","sql-server/547","mysql/1452","mysql/1451","oracle/ora-02291","oracle/ora-02292","sqlite/sqlite-constraint-foreignkey"],"sqlly":"SQLly's ER diagram draws the foreign keys between tables, so you can see which parent table a constraint points at and load or delete in the right order.","faqs":[{"question":"Why did the same insert work in my test database?","answer":"The test data was probably loaded in a different order, or the gap was never tested. Adding the constraint to data that already has orphans fails with 23503 unless you add it NOT VALID. After that, the constraint checks each inserted or updated row, whatever order the data arrived in."},{"question":"Can I disable the foreign key for a one-off import?","answer":"As a superuser you can run SET session_replication_role = replica for the session, which skips foreign key triggers for that session only; set it back to origin afterwards, and note that rows loaded this way are not checked. Otherwise, drop the constraint, import, then re-add it NOT VALID and VALIDATE CONSTRAINT afterwards, or declare it DEFERRABLE and defer the checks within the import transaction."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/23503","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/23505","corpus":"errors","engine":"postgresql","language":"en","title":"duplicate key violates unique constraint","description":"An INSERT or UPDATE would create a second row with the same value in a column covered by a primary key, unique constraint or unique index.","body":{"code":"23505","slug":"23505","name":"unique_violation","message":"duplicate key value violates unique constraint \"users_email_key\"\nDETAIL:  Key (email)=(ada@example.com) already exists.","group":"23","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE would create a second row with the same value in a column covered by a primary key, unique constraint or unique index.","meaning":"PostgreSQL enforces every primary key, `UNIQUE` constraint and unique index at the moment a row is written. If the new or changed row has the same key as a row that already exists (or one another transaction has written but not yet committed), the statement fails with 23505 and nothing it changed is kept.\n\nThe `DETAIL` line names the column and the duplicate value, and the message names the constraint or index, which tells you exactly which rule was broken.","causes":["Inserting a row whose key already exists, for example re-running an import or a seed script.","A `serial` or identity sequence that has fallen behind the data, usually after rows were loaded with explicit ids. The next default id collides with an existing row: the classic `Key (id)=(1) already exists`.","Two sessions inserting the same key at the same time; the second one waits for the first and fails as soon as the first commits.","An `UPDATE` that sets a unique column to a value another row already has."],"fix":[{"text":"Find the existing row named in the `DETAIL` line and decide whether the new data is a duplicate or a different record.","sql":"SELECT * FROM users WHERE email = 'ada@example.com';"},{"text":"If the write should update the existing row instead, make it an upsert with `ON CONFLICT`.","sql":"INSERT INTO users (email, name)\nVALUES ('ada@example.com', 'Ada')\nON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;"},{"text":"If duplicates should simply be skipped, use `ON CONFLICT DO NOTHING`.","sql":"INSERT INTO users (email, name)\nVALUES ('ada@example.com', 'Ada')\nON CONFLICT (email) DO NOTHING;"},{"text":"If the duplicate is on a `serial` or identity id, move the sequence past the highest existing value.","sql":"SELECT setval(pg_get_serial_sequence('users', 'id'),\n              (SELECT COALESCE(MAX(id), 0) + 1 FROM users), false);"}],"diagnostic":"-- Two checks cover the usual causes. Is the sequence behind the data?\nSELECT CASE WHEN s.is_called THEN s.last_value + 1 ELSE s.last_value END AS next_default_id,\n       (SELECT COALESCE(MAX(id), 0) FROM users) AS max_id FROM users_id_seq s;\n-- If next_default_id <= max_id, the next default id collides with an existing row.\n-- Otherwise, is the duplicate on a unique column you chose?\nSELECT email, count(*)\nFROM users\nGROUP BY email\nHAVING count(*) > 1\nLIMIT 20;","alternatives":"MERGE, available since PostgreSQL 15, handles insert-or-update logic with more conditions than ON CONFLICT, which requires a matching unique index. For imports, deduplicate the staging table first with DISTINCT ON so the batch has no repeated keys of its own. Rows whose key already exists in the target still conflict and still need ON CONFLICT or an anti-join.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE t (id int PRIMARY KEY);\nINSERT INTO t VALUES (1);\nINSERT INTO t VALUES (1);  -- ERROR: duplicate key value violates unique constraint \"t_pkey\"","repro_note":null,"related":["postgresql/23503","postgresql/23502","postgresql/25P02","sql-server/2627","sql-server/2601","mysql/1062","oracle/ora-00001","sqlite/sqlite-constraint-unique"],"sqlly":null,"faqs":[{"question":"Why does the insert fail with duplicate key on the id column when I never set the id?","answer":"The table's sequence is behind the data, usually because rows were inserted with explicit ids or restored without the sequence value. Reset it with `setval` to one past `MAX(id)`."},{"question":"Does ON CONFLICT work with any unique index?","answer":"It works with the columns of a unique index or constraint, or with `ON CONFLICT ON CONSTRAINT name`. A partial unique index needs its `WHERE` predicate repeated in the conflict target, as in `ON CONFLICT (email) WHERE name <> 'deleted'`, or PostgreSQL raises 42P10. It needs PostgreSQL 9.5 or later."},{"question":"Why does ON CONFLICT say there is no unique constraint matching my columns?","answer":"ON CONFLICT needs a unique index or constraint over exactly those columns. A plain index, or a unique index on a different column list, cannot prove the rows conflict, so PostgreSQL refuses the guess."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/23505","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/23514","corpus":"errors","engine":"postgresql","language":"en","title":"check constraint violation","description":"A row failed a CHECK constraint on the table, or a domain's check, so the INSERT or UPDATE was rejected.","body":{"code":"23514","slug":"23514","name":"check_violation","message":"new row for relation \"orders\" violates check constraint \"orders_qty_check\"\nDETAIL:  Failing row contains (12, -1).","group":"23","severity":null,"sql_state":null,"summary":"A row failed a CHECK constraint on the table, or a domain's check, so the INSERT or UPDATE was rejected.","meaning":"A `CHECK` constraint is a condition every row must satisfy, such as `qty > 0`. 23514 means the new or updated row made the condition false. A condition that evaluates to `NULL` passes, so checks don't reject `NULL` values on their own.\n\nThe message names the constraint; `\\d table_name` in psql or `pg_get_constraintdef` shows its condition. Adding a check to a table with existing bad rows fails the same way, with `check constraint ... of relation ... is violated by some row`.","causes":["Data outside the allowed range or set, for example a negative quantity or an unknown status.","Application validation that differs from the database's rules.","Adding a `CHECK` constraint to a table that already has rows breaking it.","A domain type with a `CHECK` (`value for domain ... violates check constraint`)."],"fix":[{"text":"Read the constraint's condition.","sql":"SELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'orders'::regclass AND contype = 'c';"},{"text":"Fix the data being written so it meets the condition.","sql":null},{"text":"To add a check to a table with old bad rows, add it `NOT VALID` (enforced for new rows only), clean up, then validate.","sql":"ALTER TABLE orders ADD CONSTRAINT orders_qty_check CHECK (qty > 0) NOT VALID;\nUPDATE orders SET qty = 1 WHERE qty <= 0;\nALTER TABLE orders VALIDATE CONSTRAINT orders_qty_check;"}],"diagnostic":"-- Read the constraint's condition first, then hunt for rows that break it.\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'orders'::regclass AND contype = 'c';\n-- Substitute the condition you just read. Rows shown here would also have\n-- blocked adding the constraint, which points at dirty legacy data:\nSELECT * FROM orders WHERE NOT (qty > 0) LIMIT 50;\n-- If the failure came from a domain instead, the constraint lives on the\n-- domain, not on a table (conrelid is 0):\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE contype = 'c' AND contypid = 'positive_qty'::regtype::oid;","alternatives":"If the same rule applies across several tables, define it once in a domain type and use that type for the columns. For rules involving other tables, a CHECK cannot see them; use a trigger or a deferred constraint trigger instead.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE o (qty int CHECK (qty > 0));\nINSERT INTO o VALUES (-1);  -- ERROR: new row for relation \"o\" violates check constraint \"o_qty_check\"","repro_note":null,"related":["postgresql/23502","postgresql/23505","postgresql/23P01","mysql/3819","sqlite/sqlite-constraint-check"],"sqlly":null,"faqs":[{"question":"Does a CHECK constraint reject NULL?","answer":"No. If the condition evaluates to NULL, the row passes. Add an explicit IS NOT NULL check to the condition if NULL should fail."},{"question":"Can a CHECK query another table?","answer":"No. The condition must only reference the current row. Cross-row or cross-table rules need a trigger. PostgreSQL does not enforce immutability of CHECK expressions, but a non-immutable function can make a dump and restore fail or behave differently, so keep check expressions immutable."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/23514","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/23P01","corpus":"errors","engine":"postgresql","language":"en","title":"exclusion constraint violation","description":"A row conflicts with an existing row under an EXCLUDE constraint, typically an overlapping time range for the same room, resource or person.","body":{"code":"23P01","slug":"23P01","name":"exclusion_violation","message":"conflicting key value violates exclusion constraint \"bookings_room_during_excl\"\nDETAIL:  Key (room_id, during)=(4, [\"2026-05-01 10:00:00\",\"2026-05-01 11:00:00\")) conflicts with existing key (room_id, during)=(4, [\"2026-05-01 10:30:00\",\"2026-05-01 12:00:00\")).","group":"23","severity":null,"sql_state":null,"summary":"A row conflicts with an existing row under an EXCLUDE constraint, typically an overlapping time range for the same room, resource or person.","meaning":"An exclusion constraint generalizes uniqueness: no two rows may satisfy all the listed comparisons at once. The classic use is `EXCLUDE USING gist (room_id WITH =, during WITH &&)`, meaning no two bookings for the same room may have overlapping ranges.\n\n23P01 means the new or updated row conflicts with the existing row shown in the `DETAIL` line.","causes":["A double booking: the new range overlaps an existing one for the same key.","Ranges with inclusive upper bounds (`[a,b]`) that touch: `[10:00,11:00]` and `[11:00,12:00]` overlap at 11:00. The default half-open form `[a,b)` avoids this.","Two concurrent transactions inserting overlapping ranges; the second fails when the first commits."],"fix":[{"text":"Find the conflicting rows before writing, or show the user which booking is in the way.","sql":"SELECT * FROM bookings\nWHERE room_id = 4\n  AND during && tstzrange('2026-05-01 10:00', '2026-05-01 11:00');"},{"text":"Use half-open ranges so back-to-back bookings don't overlap.","sql":"INSERT INTO bookings (room_id, during)\nVALUES (4, tstzrange('2026-05-01 11:00', '2026-05-01 12:00', '[)'));"},{"text":"Skip conflicting rows with `ON CONFLICT DO NOTHING`, which works with exclusion constraints (`DO UPDATE` does not).","sql":"INSERT INTO bookings (room_id, during)\nVALUES (4, tstzrange('2026-05-01 10:00', '2026-05-01 11:00'))\nON CONFLICT ON CONSTRAINT bookings_room_during_excl DO NOTHING;"}],"diagnostic":"-- Read the constraint to see which operators it combines and on which indexes.\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'bookings'::regclass AND contype = 'x';\n-- A && on ranges means overlap, so check whether the range values you insert use\n-- inclusive upper bounds: '[10:00,11:00]' and '[11:00,12:00]' overlap at 11:00,\n-- while half-open '[10:00,11:00)' and '[11:00,12:00)' do not. For the failed row,\n-- list exactly which stored row it collides with:\nSELECT *\nFROM bookings\nWHERE room_id = 4\n  AND during && tstzrange('2026-05-01 10:00', '2026-05-01 11:00');","alternatives":"The constraint is checked at write time and holds under concurrency: if two transactions insert overlapping ranges, the second waits for the first to finish, then fails with 23P01 if the first committed, or succeeds if the first rolled back. If the range type does not fit the rule, a plain UNIQUE constraint or a SERIALIZABLE transaction covers simpler cases.","details":[],"details_title":null,"repro":"CREATE EXTENSION IF NOT EXISTS btree_gist;\nCREATE TEMP TABLE b (room_id int, during tstzrange,\n    EXCLUDE USING gist (room_id WITH =, during WITH &&));\nINSERT INTO b VALUES (1, tstzrange('2026-01-01 10:00', '2026-01-01 11:00'));\nINSERT INTO b VALUES (1, tstzrange('2026-01-01 10:30', '2026-01-01 12:00'));  -- ERROR: conflicting key value violates exclusion constraint","repro_note":"The `btree_gist` extension lets a GiST index compare plain integers with `=`.","related":["postgresql/23505","postgresql/23514","postgresql/42P10"],"sqlly":null,"faqs":[{"question":"Why do two bookings that merely touch each other fail?","answer":"The ranges overlap at the shared endpoint, which happens with inclusive upper bounds like [a,b]. Build ranges with tstzrange(start, end, '[)') so back-to-back bookings do not count as overlapping."},{"question":"Does ON CONFLICT DO UPDATE work with exclusion constraints?","answer":"No, only DO NOTHING. There is no sensible single \"the\" conflicting row to update when a range can overlap several."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/23P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/25001","corpus":"errors","engine":"postgresql","language":"en","title":"cannot run inside a transaction block","description":"Some commands (VACUUM, CREATE DATABASE, CREATE INDEX CONCURRENTLY, ALTER SYSTEM) must run on their own, outside BEGIN ... COMMIT.","body":{"code":"25001","slug":"25001","name":"active_sql_transaction","message":"CREATE INDEX CONCURRENTLY cannot run inside a transaction block","group":"25","severity":null,"sql_state":null,"summary":"Some commands (VACUUM, CREATE DATABASE, CREATE INDEX CONCURRENTLY, ALTER SYSTEM) must run on their own, outside BEGIN ... COMMIT.","meaning":"A handful of PostgreSQL commands manage their own transactions or can't be rolled back, so they refuse to run inside an explicit transaction block: `VACUUM`, `CREATE DATABASE`, `DROP DATABASE`, `CREATE INDEX CONCURRENTLY`, `REINDEX ... CONCURRENTLY`, `ALTER SYSTEM`, `CREATE TABLESPACE` and others. Running one after `BEGIN` fails with 25001 (`active_sql_transaction`).\n\nThe catch is that many tools and drivers open a transaction for you: migration frameworks wrap each migration in one, and clients with autocommit turned off start one implicitly.","causes":["A migration framework runs every migration inside a transaction.","The client or driver has autocommit off (psycopg2's default, JDBC with `setAutoCommit(false)`), so every statement is inside a transaction.","A script sends several statements as one multi-statement query string, which PostgreSQL runs as a single implicit transaction.","Calling the command from a function or `DO` block, which always runs inside a transaction."],"fix":[{"text":"Run the command on its own with autocommit on. In psql that is the default; just don't put it between `BEGIN` and `COMMIT`.","sql":"CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);"},{"text":"In your driver, switch autocommit on for this statement (psycopg: `conn.autocommit = True`).","sql":null},{"text":"In migration tools, mark the migration as non-transactional; most frameworks have an option for this.","sql":null},{"text":"Send each such command as a separate query, not combined with others in one string.","sql":null}],"diagnostic":"-- If a transaction is already open for your session, xact_start is set.\n-- Run this before the failing command:\nSELECT pid, state, xact_start, now() - xact_start AS in_txn_for\nFROM pg_stat_activity\nWHERE pid = pg_backend_pid();\n-- xact_start IS NOT NULL when a transaction is open: an explicit BEGIN, the\n-- driver's autocommit being off, or the tool wrapping statements.\n-- Caution: this SELECT is itself a statement, so xact_start is also set with\n-- autocommit on (tested on PostgreSQL 18). A NULL result does not identify a\n-- bundled command. Look for a multi-statement string or a DO block in the script\n-- instead.","alternatives":"If the migration framework offers no non-transactional mode, fall back to a plain CREATE INDEX in the migration and accept the write lock, or apply the command manually on each environment and record it as applied. There is no server setting to relax this restriction.","details":[],"details_title":null,"repro":"BEGIN;\nVACUUM;  -- ERROR: VACUUM cannot run inside a transaction block\nROLLBACK;","repro_note":null,"related":["postgresql/25P02","postgresql/2D000","postgresql/55006"],"sqlly":null,"faqs":[{"question":"Which commands refuse to run inside a transaction block?","answer":"The ones that manage their own transactions or cannot roll back: VACUUM, CREATE DATABASE, DROP DATABASE, CREATE INDEX CONCURRENTLY, REINDEX CONCURRENTLY, ALTER SYSTEM, CREATE TABLESPACE and a few others."},{"question":"Why does the same script work in psql but fail in my migration tool?","answer":"psql runs each statement with autocommit on unless you type BEGIN. Migration frameworks typically wrap every migration file in one transaction, so a statement that is fine alone becomes illegal inside it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/25001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/25006","corpus":"errors","engine":"postgresql","language":"en","title":"read-only SQL transaction","description":"A write was attempted in a read-only transaction: on a hot-standby replica, with default_transaction_read_only on, or after SET TRANSACTION READ ONLY.","body":{"code":"25006","slug":"25006","name":"read_only_sql_transaction","message":"cannot execute INSERT in a read-only transaction","group":"25","severity":null,"sql_state":null,"summary":"A write was attempted in a read-only transaction: on a hot-standby replica, with default_transaction_read_only on, or after SET TRANSACTION READ ONLY.","meaning":"PostgreSQL refuses `INSERT`, `UPDATE`, `DELETE`, DDL and other writes when the transaction is read-only. That happens when you are connected to a streaming-replication standby (all transactions there are read-only), when `default_transaction_read_only` is on for the server, database or role, or when the transaction was started `READ ONLY`.\n\nThe message names the command that was refused.","causes":["The connection went to a read replica, for example through a load balancer or a DNS name that points at a standby after a failover.","`default_transaction_read_only = on` set on the database or role, sometimes deliberately for reporting users.","`BEGIN READ ONLY` or `SET TRANSACTION READ ONLY` earlier in the transaction.","A managed database switched to read-only because it ran out of storage."],"fix":[{"text":"Check whether you are on a standby and whether read-only is set.","sql":"SELECT pg_is_in_recovery();\nSHOW default_transaction_read_only;\nSHOW transaction_read_only;"},{"text":"Send writes to the primary. With Use `target_session_attrs=read-write` in a multi-host connection string (libpq supports this since PostgreSQL 10) to pick the writable host from a list.","sql":null},{"text":"If read-only was set on the role or database by mistake, turn it off.","sql":"ALTER ROLE app SET default_transaction_read_only = off;\nALTER DATABASE shop SET default_transaction_read_only = off;"}],"diagnostic":"-- One call per cause. Run this in the failing session:\nSELECT pg_is_in_recovery() AS on_standby,\n       current_setting('transaction_read_only') AS this_txn,\n       current_setting('default_transaction_read_only') AS server_default;\n-- on_standby = true: you are on a replica; find out why the connection landed\n--   there (load balancer, DNS, failover).\n-- server_default = on: a role or database setting; check with\nSELECT rolname, rolconfig FROM pg_roles WHERE rolconfig IS NOT NULL;\n-- this_txn = on with server_default = off: your own code ran BEGIN READ ONLY.","alternatives":"Routing is usually the real fix: connect to the primary by name rather than through a balancer that can pick a standby, or use libpq 14+ with target_session_attrs=read-write to pick the writable host automatically. Deliberate read-only roles for reporting users are worth keeping; scope the write access instead of lifting the restriction.","details":[],"details_title":null,"repro":"BEGIN READ ONLY;\nCREATE TEMP TABLE t (id int);  -- ERROR: cannot execute CREATE TABLE in a read-only transaction\nROLLBACK;","repro_note":null,"related":["postgresql/42501","postgresql/57P03","postgresql/25001","mysql/1792","mysql/1290","sqlite/sqlite-readonly"],"sqlly":"SQLly can mark a connection read-only itself, so writes are blocked in the app before they reach the server, and production connections can ask for confirmation before risky statements run.","faqs":[{"question":"How do I tell a standby from the primary?","answer":"Run SELECT pg_is_in_recovery(). It returns true on a standby in recovery and false on a writable primary. pg_stat_replication on the primary shows who is streaming from it."},{"question":"Writes worked yesterday and fail today. What changed?","answer":"Common causes: a failover or DNS change now points the connection string at a standby, someone set default_transaction_read_only on the role or database, or a managed provider flipped the instance to read-only because it ran out of storage."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/25006","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/25P02","corpus":"errors","engine":"postgresql","language":"en","title":"current transaction is aborted","description":"An earlier statement in this transaction failed, so PostgreSQL refuses everything else until you ROLLBACK (or roll back to a savepoint).","body":{"code":"25P02","slug":"25P02","name":"in_failed_sql_transaction","message":"current transaction is aborted, commands ignored until end of transaction block","group":"25","severity":null,"sql_state":null,"summary":"An earlier statement in this transaction failed, so PostgreSQL refuses everything else until you ROLLBACK (or roll back to a savepoint).","meaning":"In PostgreSQL, any error inside a transaction block puts the whole transaction into a failed state. From then on every statement except `ROLLBACK` and `ROLLBACK TO SAVEPOINT` fails with 25P02 without running. `COMMIT` raises no error here: it does not commit, it ends the transaction and reports `ROLLBACK`.\n\n25P02 is never the real problem. It is the echo of an error that happened earlier in the same transaction.","causes":["A statement failed earlier in the transaction (a constraint violation, a typo, a bad cast) and the code kept going without rolling back.","An application catches an exception from one query and reuses the same connection, still inside the failed transaction.","A connection pool hands out a connection that was left in a failed transaction by its previous user."],"fix":[{"text":"Look for the first error in the transaction, in your application log or the server log, and fix that.","sql":null},{"text":"End the failed transaction with `ROLLBACK`, then start again.","sql":"ROLLBACK;"},{"text":"If some statements are allowed to fail without losing the rest of the transaction, wrap each one in a savepoint.","sql":"BEGIN;\nINSERT INTO audit_log (msg) VALUES ('start');\nSAVEPOINT try_insert;\nINSERT INTO users (id, email) VALUES (1, 'dup@example.com');  -- may fail\n-- on error:\nROLLBACK TO SAVEPOINT try_insert;\nCOMMIT;  -- audit_log row is kept"},{"text":"In `psql`, `\\set ON_ERROR_ROLLBACK interactive` in an interactive terminal makes psql set an implicit savepoint before each statement, so one typo doesn't abort the transaction. The `interactive` value does nothing for script or piped input; use `on` there.","sql":null}],"diagnostic":"-- The server log has the original error, tagged with your backend's pid:\nSELECT pid FROM pg_stat_activity WHERE pid = pg_backend_pid();\n-- Search the log for that pid's\n-- first ERROR since the transaction began; every later line is just the 25P02\n-- echo. In application code the driver's exception for the first statement\n-- already carried the real error, so check what your catch block swallowed.","alternatives":"If individual statements may legitimately fail, use driver-level autocommit instead of one long transaction. Some poolers and ORMs can reset connections that return to the pool in a failed state, which stops one request's mistake from breaking the next user of the connection.","details":[],"details_title":null,"repro":"BEGIN;\nSELECT 1/0;          -- ERROR: division by zero\nSELECT 1;            -- ERROR: current transaction is aborted ...\nROLLBACK;","repro_note":null,"related":["postgresql/40P01","postgresql/23505","postgresql/22012","sql-server/3930"],"sqlly":null,"faqs":[{"question":"Why does COMMIT say ROLLBACK?","answer":"The transaction had already failed, so there is nothing valid to commit. PostgreSQL ends it and reports `ROLLBACK` to make that clear."},{"question":"I only see 25P02 in my logs. Where is the real error?","answer":"One statement earlier, from the same backend. The server log records the original ERROR with its statement; application logs usually have it too unless the code caught and discarded the first exception."},{"question":"Can I keep running statements after ROLLBACK TO SAVEPOINT?","answer":"Yes, that is the point of a savepoint: it rewinds to a point inside the transaction, and the statements after it run normally. ROLLBACK without a savepoint name ends the whole transaction instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/25P02","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/25P03","corpus":"errors","engine":"postgresql","language":"en","title":"idle-in-transaction session timeout","description":"The session sat inside an open transaction doing nothing for longer than idle_in_transaction_session_timeout, so the server closed it.","body":{"code":"25P03","slug":"25P03","name":"idle_in_transaction_session_timeout","message":"terminating connection due to idle-in-transaction timeout","group":"25","severity":null,"sql_state":null,"summary":"The session sat inside an open transaction doing nothing for longer than idle_in_transaction_session_timeout, so the server closed it.","meaning":"A session that has started a transaction and then goes quiet is `idle in transaction`. It still holds its locks and keeps old row versions from being vacuumed. `idle_in_transaction_session_timeout` makes the server end such sessions after a time limit; when it fires, the client gets this `FATAL` error and the connection is closed, rolling the transaction back.\n\nThe usual root cause is application code that opens a transaction and then waits on something else, such as a network call or user input, before committing.","causes":["Code that does slow work (HTTP calls, file processing) between `BEGIN` and `COMMIT`.","A client or GUI with autocommit off, left open after a `SELECT`, so a transaction stays open.","An exception path that never commits or rolls back, leaving the pooled connection idle in a transaction."],"fix":[{"text":"Find sessions idle in a transaction and how long they have been idle.","sql":"SELECT pid, usename, application_name, now() - state_change AS idle_for, query\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\nORDER BY idle_for DESC;"},{"text":"Do slow non-database work before opening the transaction or after committing it, and always commit or roll back in a `finally` block.","sql":null},{"text":"Keep the timeout as a safety net; set it per role if some jobs legitimately need longer.","sql":"-- Replace app with a role that exists.\nALTER ROLE app SET idle_in_transaction_session_timeout = '5min';"}],"diagnostic":"-- Who is idle in a transaction right now, and which client left them there?\nSELECT pid, usename, application_name, client_addr,\n       xact_start, now() - state_change AS idle_for, left(query, 80) AS last_query\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\nORDER BY idle_for DESC;\n-- application_name and last_query point at the code that opened the transaction\n-- and never finished it. Wait_event is usually 'ClientRead', meaning the server\n-- is waiting on the client, not on a lock or a slow query.","alternatives":"If the problem is long-running queries rather than quiet sessions, statement_timeout is the better lever since it cancels a query without touching the connection. Connection pools can also be configured to roll back or recycle connections that sit idle in a transaction, which catches the exception-path leaks without a timeout on every session.","details":[],"details_title":null,"repro":"-- Two psql sessions. Session 1:\nSET idle_in_transaction_session_timeout = '2s';\nBEGIN;\nSELECT 1;  -- then stop typing: the session is idle in transaction\n-- Wait 2 seconds. The next statement in session 1 fails and the connection\n-- is closed:\nSELECT 1;  -- FATAL: terminating connection due to idle-in-transaction timeout","repro_note":null,"related":["postgresql/57P01","postgresql/53300","postgresql/55P03","postgresql/08006"],"sqlly":"SQLly shows a pending-changes count in the status bar while a tab is in manual-commit mode, asks before closing a tab with an open transaction, and rolls back a manual transaction with uncommitted changes that has been idle for too long (five minutes by default).","faqs":[{"question":"Does the timeout roll back my uncommitted changes?","answer":"Yes. The server closes the connection, and closing a connection rolls back its open transaction. Any work that was not committed is gone."},{"question":"Why is idle in transaction harmful even without a timeout?","answer":"The session holds its locks and its snapshot, which keeps old row versions alive so vacuum cannot clean them. A long-idle transaction can bloat tables across the whole database until it ends."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/25P03","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/28000","corpus":"errors","engine":"postgresql","language":"en","title":"invalid authorization specification","description":"The server refused the login before checking a password: no pg_hba.conf rule matches, the role doesn't exist, or it can't log in.","body":{"code":"28000","slug":"28000","name":"invalid_authorization_specification","message":"no pg_hba.conf entry for host \"10.0.0.5\", user \"app\", database \"shop\", no encryption","group":"28","severity":null,"sql_state":null,"summary":"The server refused the login before checking a password: no pg_hba.conf rule matches, the role doesn't exist, or it can't log in.","meaning":"28000 covers login failures other than a wrong password (28P01). The most common is `no pg_hba.conf entry`: the server's host-based authentication file has no line that matches this client's address, user, database and encryption. Others with this code are `role \"app\" does not exist` and `role \"app\" is not permitted to log in` (the role lacks the `LOGIN` attribute). Those two messages appear only when the matching rule does not ask for a password (trust, peer or ident). Over a password rule such as `scram-sha-256`, an unknown role gets `password authentication failed for user \"app\"` (28P01) instead.\n\nThe message lists exactly what the server saw, which is what you need to match in `pg_hba.conf`. The last part says whether the connection was encrypted: a rule of type `hostssl` only matches SSL connections.","causes":["Connecting from a new IP address or network that no `pg_hba.conf` line covers.","The client connects without SSL but the only matching rule is `hostssl` (or with SSL when the rule is `hostnossl`).","A rule that lists specific users or databases that don't include this one.","The role doesn't exist on this server, or was created with `CREATE ROLE` (which defaults to `NOLOGIN`) instead of `CREATE USER`."],"fix":[{"text":"Add a `pg_hba.conf` line for the client, above any broader `reject` line, then reload. For example `hostssl  shop  app  10.0.0.0/24  scram-sha-256`.","sql":"SELECT pg_reload_conf();\nSELECT line_number, type, database, user_name, address, auth_method, error\nFROM pg_hba_file_rules;"},{"text":"Allow the role to log in, or create it.","sql":"ALTER ROLE app WITH LOGIN;\nCREATE ROLE app WITH LOGIN PASSWORD 'strong-password';"},{"text":"Make sure the server listens on the network at all (`listen_addresses`), and that the client uses SSL if the rule needs it, for example `sslmode=require`.","sql":null}],"diagnostic":"-- Which pg_hba.conf line (if any) matches this connection? The error column flags broken lines in the file.\nSELECT line_number, type, database, user_name, address, auth_method, error\nFROM pg_hba_file_rules\nORDER BY line_number;\n\n-- Does the role exist and is it allowed to log in at all?\nSELECT rolname, rolcanlogin\nFROM pg_roles\nWHERE rolname = 'app';","alternatives":"Instead of widening pg_hba.conf, route the client through an SSH tunnel or pgbouncer on a host the file already allows. If the role only needs read access from this network, a dedicated restricted role keeps the new rule narrow.","details":[],"details_title":null,"repro":"-- On the server, add a rule that only covers one network, then try to connect from outside it.\n-- pg_hba.conf:\n--   hostssl  shop  app  10.0.0.0/24  scram-sha-256\n-- $ psql \"host=db.example.com dbname=shop user=app\"\n-- psql: error: FATAL:  no pg_hba.conf entry for host \"203.0.113.9\", user \"app\", database \"shop\", no encryption","repro_note":null,"related":["postgresql/28P01","postgresql/08001","postgresql/3D000","postgresql/42501","mysql/1130","sql-server/18456"],"sqlly":"SQLly's connection test reports the server's exact message, which for this error lists the host, user, database and encryption the server saw.","faqs":[{"question":"I edited pg_hba.conf but the error stays the same. Why?","answer":"The file is only read at startup or on reload. Run SELECT pg_reload_conf(); as a superuser, or pg_ctl reload. New rules apply to new connections only; existing sessions are unaffected."},{"question":"Does rule order in pg_hba.conf matter?","answer":"Yes. The first matching line wins and later lines are never consulted. If a reject line or a trust line for a broader address range sits above your new rule, your rule never fires."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/28000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/28P01","corpus":"errors","engine":"postgresql","language":"en","title":"password authentication failed","description":"PostgreSQL rejected the password for this user. A wrong password, a role without a password, or a password hashed in a format the server no longer accepts.","body":{"code":"28P01","slug":"28P01","name":"invalid_password","message":"password authentication failed for user \"app\"","group":"28","severity":null,"sql_state":null,"summary":"PostgreSQL rejected the password for this user. A wrong password, a role without a password, or a password hashed in a format the server no longer accepts.","meaning":"The server found a `pg_hba.conf` rule that asks for a password (`scram-sha-256`, `md5` or `password`) for this connection, and the password the client sent didn't match the role's stored password.\n\nFor security the client is only told the password failed. The server log has the reason, for example `User \"app\" has no password assigned` or `Role \"app\" does not exist`.","causes":["Wrong password, or a password with special characters mangled in a connection URL (they must be percent-encoded).","The role doesn't exist or has no password set; the client still sees `password authentication failed`.","The role's password is stored as an MD5 hash but `pg_hba.conf` requires `scram-sha-256`, after an upgrade to a default of SCRAM.","The client picked up a different password from `PGPASSWORD` or a `.pgpass` file."],"fix":[{"text":"Read the server log entry for the failed login; it states the real reason.","sql":null},{"text":"Set a new password as a superuser (in psql, `\\password app` prompts without echoing it).","sql":"ALTER ROLE app WITH LOGIN PASSWORD 'new-strong-password';"},{"text":"Check how the password is stored. A value starting with `md5` must be reset after switching `password_encryption` to `scram-sha-256`.","sql":"SHOW password_encryption;\nSELECT rolname, left(rolpassword, 14) AS hash_type\nFROM pg_authid WHERE rolname = 'app';"},{"text":"Check which `pg_hba.conf` line matched; the view shows the file as the server loaded it. By default only superusers can read it.","sql":"SELECT line_number, type, database, user_name, address, auth_method\nFROM pg_hba_file_rules;"},{"text":"Percent-encode special characters in connection URLs, for example `@` as `%40`: `postgresql://app:p%40ss@db:5432/shop`.","sql":null}],"diagnostic":"-- How is the password stored? A prefix of SCRAM-SHA-256$ or md5 tells you the hash format.\n-- Reading pg_authid needs superuser or pg_read_all_data.\nSELECT rolname, left(rolpassword, 14) AS hash_type\nFROM pg_authid\nWHERE rolname = 'probe';\n\n-- Which auth method does the matching pg_hba.conf line use?\nSELECT line_number, user_name, address, auth_method\nFROM pg_hba_file_rules\nWHERE auth_method IN ('scram-sha-256', 'md5', 'password');","alternatives":"Use a .pgpass file or the PGPASSWORD environment variable for interactive work instead of embedding the password in scripts, so a stale value in one place is the only thing to fix. For services, a pg_service.conf entry or connection pooler keeps credentials in one file.","details":[],"details_title":null,"repro":"-- In psql, against a scratch database:\nCREATE ROLE probe WITH LOGIN PASSWORD 'correct-horse';\n-- From another shell:\n-- $ PGPASSWORD=wrong psql -h localhost -U probe -d postgres -c 'SELECT 1'\n-- psql: error: connection to server at \"db\", port 5432 failed: FATAL:  password authentication failed for user \"probe\"","repro_note":null,"related":["postgresql/28000","postgresql/3D000","postgresql/53300","sql-server/18456","mysql/1045","oracle/ora-01017"],"sqlly":"SQLly stores connection passwords in the operating system's credential store and its connection test shows the server's exact error and the round-trip time, so you can tell an authentication failure from a network problem.","faqs":[{"question":"The password is definitely right. Why does it still fail?","answer":"The server log says the real reason: often the role has no password at all, doesn't exist, or its stored hash is md5 while pg_hba.conf demands scram-sha-256. Reset the password with password_encryption set to scram-sha-256."},{"question":"Can I turn off password checks for my dev database?","answer":"You can set trust for localhost in pg_hba.conf, which lets anyone connecting from that host in as any role. Only do this on a machine and network nobody else can reach."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/28P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/2BP01","corpus":"errors","engine":"postgresql","language":"en","title":"dependent objects still exist","description":"DROP refused because views, foreign keys, SQL-standard (BEGIN ATOMIC) functions or other objects depend on it. Drop or change those first, or use CASCADE with care.","body":{"code":"2BP01","slug":"2BP01","name":"dependent_objects_still_exist","message":"cannot drop table customers because other objects depend on it\nDETAIL:  constraint orders_customer_id_fkey on table orders depends on table customers\nHINT:  Use DROP ... CASCADE to drop the dependent objects too.","group":"2B","severity":null,"sql_state":null,"summary":"DROP refused because views, foreign keys, SQL-standard (BEGIN ATOMIC) functions or other objects depend on it. Drop or change those first, or use CASCADE with care.","meaning":"PostgreSQL tracks dependencies between objects. Dropping a table, column, type, function or role that something else uses fails with 2BP01 and lists the dependents in the `DETAIL` lines. `DROP ... CASCADE` would drop all of them too, which is rarely what you want on a shared database.\n\nFor roles the related message is `role \"app\" cannot be dropped because some objects depend on it`, which lists objects the role owns or has privileges on.","causes":["A view, materialized view, or SQL-standard function (CREATE FUNCTION ... BEGIN ATOMIC ... END) uses the table or column. PL/pgSQL and string-body SQL functions are not tracked and do not block the drop.","Another table has a foreign key that references this table.","A column type is a custom type or enum that columns still use.","A role still owns objects or holds privileges."],"fix":[{"text":"Read the `DETAIL` lines to see every dependent, then drop or change them deliberately.","sql":"ALTER TABLE orders DROP CONSTRAINT orders_customer_id_fkey;\nDROP TABLE customers;"},{"text":"List the views that depend directly on a table. Views built on those views are not listed; query again for each one found.","sql":"SELECT DISTINCT v.relname AS view_name\nFROM pg_depend d\nJOIN pg_rewrite r ON r.oid = d.objid\nJOIN pg_class v ON v.oid = r.ev_class\nWHERE d.refobjid = 'customers'::regclass AND v.oid <> 'customers'::regclass;"},{"text":"To drop a role, hand its objects to another role and remove its privileges in the current database. Repeat the same commands in each other database that holds objects it owns or has privileges on, because DROP OWNED only affects the current database.","sql":"REASSIGN OWNED BY old_role TO new_owner;\nDROP OWNED BY old_role;\nDROP ROLE old_role;"},{"text":"Use `CASCADE` only when you have read the list of dependents and want them all gone.","sql":"DROP TABLE customers CASCADE;"}],"diagnostic":"-- List every object that depends on a table, with its type, before dropping it.\n-- A view depends through its rewrite rule: pg_rewrite carries the edge, and\n-- pg_depend points at the table through refclassid and refobjid.\nSELECT d.deptype, c.relkind AS dependent_kind,\n       n.nspname || '.' || c.relname AS dependent_object\nFROM pg_depend d\nJOIN pg_rewrite r ON r.oid = d.objid\nJOIN pg_class c ON c.oid = r.ev_class\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE d.refclassid = 'pg_class'::regclass\n  AND d.refobjid = 'public.customers'::regclass\n  AND d.deptype = 'n'\n  AND c.oid <> 'public.customers'::regclass\nUNION\nSELECT 'f', 'f', conname\nFROM pg_constraint\nWHERE confrelid = 'public.customers'::regclass AND contype = 'f';","alternatives":"If the goal is to replace a table without losing its views, create the new table, point the views at it with CREATE OR REPLACE VIEW, then drop the old one. For a one-off cleanup, run the DROP inside a transaction and inspect the DETAIL output before deciding on CASCADE.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE p (id int);\nCREATE TEMP VIEW pv AS SELECT * FROM p;\nDROP TABLE p;  -- ERROR: cannot drop table p because other objects depend on it","repro_note":null,"related":["postgresql/23503","postgresql/55006","sql-server/3726","sql-server/5074","oracle/ora-02449","mysql/1701"],"sqlly":"SQLly's ER diagram and dependency browser show what references a table before you drop it.","faqs":[{"question":"Is DROP ... CASCADE safe?","answer":"It is safe only if you already know what CASCADE will drop. It recursively drops every dependent, including views that took work to build and foreign keys other tables rely on. Read the DETAIL lines or query pg_depend first, and run it inside a transaction so you can roll back."},{"question":"Why does dropping a column fail the same way?","answer":"Views and generated columns that reference the column are dependents of the column itself. The fix is the same shape: drop or rewrite the dependents, or use CASCADE knowing they go too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/2BP01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/2D000","corpus":"errors","engine":"postgresql","language":"en","title":"invalid transaction termination","description":"COMMIT or ROLLBACK ran inside a procedure or DO block that can't control transactions, for example one called inside an explicit transaction or from a function.","body":{"code":"2D000","slug":"2D000","name":"invalid_transaction_termination","message":"invalid transaction termination","group":"2D","severity":null,"sql_state":null,"summary":"COMMIT or ROLLBACK ran inside a procedure or DO block that can't control transactions, for example one called inside an explicit transaction or from a function.","meaning":"Since PostgreSQL 11, procedures (`CALL`) and `DO` blocks may run `COMMIT` and `ROLLBACK`. That only works when they are called at the top level, not inside a transaction the caller opened. If a procedure is called after `BEGIN`, from a function, from a trigger, or through a path that wraps it in a transaction, its `COMMIT` fails with 2D000.\n\nFunctions can never commit or roll back; their work is always part of the caller's transaction.","causes":["Calling the procedure inside `BEGIN ... COMMIT`, or from a client with autocommit off.","Calling it from a function or a trigger, including a `SELECT` that calls such a function. A plain `SELECT` of a procedure fails with 42809 instead.","A `COMMIT` inside a function body rather than a procedure.","A `COMMIT` inside a block that has an `EXCEPTION` clause, which runs as a subtransaction."],"fix":[{"text":"Call the procedure on its own, with autocommit on.","sql":"CALL archive_old_orders();"},{"text":"If you need transaction control, make it a procedure, not a function, and keep `COMMIT` out of blocks with exception handlers.","sql":"CREATE PROCEDURE archive_old_orders()\nLANGUAGE plpgsql AS $$\nBEGIN\n    LOOP\n        DELETE FROM orders WHERE id IN (\n            SELECT id FROM orders WHERE created_at < now() - interval '2 years' LIMIT 1000);\n        EXIT WHEN NOT FOUND;\n        COMMIT;\n    END LOOP;\nEND;\n$$;"}],"diagnostic":"-- The COMMIT came from inside a routine's body. Is it a procedure or a\n-- function? prokind 'p' is a procedure, 'f' a function; functions can never\n-- commit.\nSELECT n.nspname, p.proname, p.prokind\nFROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.proname = 'wipe';\n\n-- Does the body contain transaction control, and is the routine safe to call top-level only?\nSELECT pg_get_functiondef('wipe()'::regprocedure);\n\n-- Who is calling it right now? pg_stat_activity shows statement text, not the PL/pgSQL call stack; the CONTEXT lines of the error show the nesting.\nSELECT pid, query FROM pg_stat_activity WHERE datname = current_database() AND state <> 'idle';","alternatives":"If the caller must own the transaction, move the COMMIT out of the routine: return a status and let the caller commit. For batch deletes inside one transaction, keep the batches small enough that a single commit at the end is acceptable.","details":[],"details_title":null,"repro":"-- Top level works (PostgreSQL 11+):\nCREATE TABLE chunk (id int);\nCREATE PROCEDURE wipe() LANGUAGE plpgsql AS $$\nBEGIN\n    DELETE FROM chunk;\n    COMMIT;\nEND $$;\nCALL wipe();  -- fine\n\n-- Same call inside a transaction fails:\nBEGIN;\nCALL wipe();  -- ERROR: invalid transaction termination\nROLLBACK;","repro_note":null,"related":["postgresql/25001","postgresql/25P02","postgresql/3B001"],"sqlly":null,"faqs":[{"question":"Why can a procedure commit but a function can't?","answer":"Functions run inside the statement that calls them, often as part of a larger query, so there is no boundary for them to commit at. Procedures are invoked with CALL as their own statement, which is why PostgreSQL 11 and later let them manage transactions when called at top level."},{"question":"Can a procedure commit inside a block with an EXCEPTION clause?","answer":"No. The block with an EXCEPTION handler runs as a subtransaction, and COMMIT inside it fails the same way. Move the COMMIT outside that block, or drop the handler for the loop that commits."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/2D000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/3B001","corpus":"errors","engine":"postgresql","language":"en","title":"invalid savepoint specification","description":"ROLLBACK TO SAVEPOINT or RELEASE named a savepoint that doesn't exist in the current transaction, often because it was already released or never set.","body":{"code":"3B001","slug":"3B001","name":"invalid_savepoint_specification","message":"savepoint \"before_update\" does not exist","group":"3B","severity":null,"sql_state":null,"summary":"ROLLBACK TO SAVEPOINT or RELEASE named a savepoint that doesn't exist in the current transaction, often because it was already released or never set.","meaning":"Savepoints mark a point inside a transaction you can roll back to. 3B001 means the name in `ROLLBACK TO SAVEPOINT` or `RELEASE SAVEPOINT` doesn't match an active savepoint: it was never created, it was released, or a rollback to an earlier savepoint discarded it.\n\nSavepoints only exist inside a transaction block. Outside one, the command fails with a different error (`can only be used in transaction blocks`, 25P01).","causes":["A typo in the savepoint name.","`RELEASE SAVEPOINT` already ran, which removes that savepoint and any created after it.","`ROLLBACK TO` an earlier savepoint, which destroys the savepoints created after it.","Autocommit is on, so each statement is its own transaction. SAVEPOINT then fails at once with 25P01 (`SAVEPOINT can only be used in transaction blocks`), and no savepoint is created, so you see 25P01 rather than 3B001."],"fix":[{"text":"Run the whole sequence inside one transaction, with matching names.","sql":"BEGIN;\nSAVEPOINT before_update;\nUPDATE accounts SET balance = balance - 100 WHERE id = 1;\nROLLBACK TO SAVEPOINT before_update;\nCOMMIT;"},{"text":"`ROLLBACK TO SAVEPOINT` keeps the savepoint, so you can roll back to it again. `RELEASE SAVEPOINT` removes it, and after that a rollback to that name fails with 3B001.","sql":null}],"diagnostic":"-- No catalog lists active savepoints; they are session-internal. Confirm you are inside a transaction\n-- and which savepoint names your client actually issued, from the earliest:\nBEGIN;\nSAVEPOINT a;\nSAVEPOINT b;\nROLLBACK TO SAVEPOINT a;  -- discards b\nROLLBACK TO SAVEPOINT b;  -- ERROR here proves b was destroyed by the earlier rollback\nROLLBACK;","alternatives":"If you keep rolling back to the same point, you do not need to re-issue SAVEPOINT, because ROLLBACK TO keeps it. Rolling back to an earlier savepoint destroys every later one whatever its name, so per-step names do not prevent that. If you need step 3 after a step 2 rollback, do not roll back to step 2 first. Reusing a name is safe: ROLLBACK TO uses the most recent savepoint with that name.","details":[],"details_title":null,"repro":"BEGIN;\nROLLBACK TO SAVEPOINT nope;  -- ERROR: savepoint \"nope\" does not exist\nROLLBACK;","repro_note":null,"related":["postgresql/25P02","postgresql/2D000","sql-server/6401"],"sqlly":null,"faqs":[{"question":"What is the difference between RELEASE and ROLLBACK TO for savepoints?","answer":"ROLLBACK TO undoes work after the savepoint but keeps the savepoint itself alive. RELEASE SAVEPOINT removes the savepoint and keeps its work. Both destroy any savepoints created after the one named."},{"question":"Why did my savepoint disappear without any RELEASE?","answer":"Either the transaction committed or rolled back, ending its lifetime, or a ROLLBACK TO an earlier savepoint ran, which discards every savepoint created after that point."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/3B001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/3D000","corpus":"errors","engine":"postgresql","language":"en","title":"database does not exist","description":"The connection names a database that isn't on this server. Often a typo, a case mismatch, or a client defaulting the database name to the user name.","body":{"code":"3D000","slug":"3D000","name":"invalid_catalog_name","message":"database \"shop\" does not exist","group":"3D","severity":null,"sql_state":null,"summary":"The connection names a database that isn't on this server. Often a typo, a case mismatch, or a client defaulting the database name to the user name.","meaning":"Every PostgreSQL connection is to one database, named in the connection string. If no database by that name exists on the server you reached, login stops with 3D000.\n\nDatabase names are case-sensitive once created with quotes, and many clients fill in a default: `psql` and libpq use the user name as the database name when none is given, so `psql -U app` tries to open a database called `app`.","causes":["A typo, or a database created with a quoted mixed-case name such as `\"Shop\"`.","No database given, so the client used the user name as the database name.","Connecting to the wrong server or port (another instance, a different container) where the database was never created.","The database was dropped or hasn't been created yet by setup scripts."],"fix":[{"text":"Connect to a database that always exists, such as `postgres`, and list the databases.","sql":"-- psql -h db -U app -d postgres\nSELECT datname FROM pg_database ORDER BY datname;"},{"text":"Create the database if it should exist.","sql":"CREATE DATABASE shop OWNER app;"},{"text":"Pass the database name explicitly in the connection string, for example `postgresql://app@db:5432/shop` or `psql -d shop`.","sql":null},{"text":"If it was created with capitals, use the exact name. In a URL or `-d` option no quotes are needed: `psql -d Shop`.","sql":null}],"diagnostic":"-- Connect to the always-present postgres database, then check what actually exists and how the name is stored:\n-- $ psql -d postgres\nSELECT datname, pg_encoding_to_char(encoding) AS encoding\nFROM pg_database\nORDER BY datname;\n-- A mixed-case name stored as Shop must be requested exactly; datname shows the exact spelling.","alternatives":"For local development, a setup script that runs CREATE DATABASE only when missing (query pg_database first, since CREATE DATABASE has no IF NOT EXISTS) avoids the error on re-runs. CREATE DATABASE cannot run inside a transaction block, so a script that wraps its statements in BEGIN or psql -1 must run that statement outside the transaction. If names drift between environments, pin the database name in the connection string rather than relying on client defaults.","details":[],"details_title":null,"repro":"-- In psql against a scratch cluster:\n-- $ psql -d no_such_db\n-- psql: error: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: FATAL:  database \"no_such_db\" does not exist\n-- The client-default case: psql uses your OS user name as the database name when -d is omitted.\n-- $ psql\n-- psql: error: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: FATAL:  database \"matt\" does not exist","repro_note":null,"related":["postgresql/28P01","postgresql/42P01","postgresql/3F000","postgresql/42P04","sql-server/4060","mysql/1049"],"sqlly":null,"faqs":[{"question":"Why does psql say database does not exist when I only gave a user name?","answer":"When no database is specified, psql connects to a database with the same name as the user. Add -d postgres or the database you want."},{"question":"How do I create a database only if it does not exist?","answer":"CREATE DATABASE has no IF NOT EXISTS. From a script, connect to postgres and check first: SELECT 1 FROM pg_database WHERE datname = 'shop'; and run CREATE DATABASE shop only when that returns no rows."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/3D000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/3F000","corpus":"errors","engine":"postgresql","language":"en","title":"schema does not exist","description":"A statement names a schema that isn't in the current database, or creates an object when no schema on the search_path exists.","body":{"code":"3F000","slug":"3F000","name":"invalid_schema_name","message":"schema \"sales\" does not exist","group":"3F","severity":null,"sql_state":null,"summary":"A statement names a schema that isn't in the current database, or creates an object when no schema on the search_path exists.","meaning":"Schemas are namespaces inside one database. 3F000 means the schema named in a qualified name (`sales.orders`) or in a CREATE statement's qualified name doesn't exist in the database you're connected to. `SET search_path` accepts schema names that do not exist without error; the 3F000 appears later, when a CREATE needs a schema and none on the path exists.. Schema names follow the same case rules as other identifiers: unquoted names fold to lower case.\n\nA related case is `no schema has been selected to create in`, when `CREATE TABLE` runs with a `search_path` that contains no existing schema.","causes":["The schema hasn't been created in this database (each database has its own schemas).","A quoted mixed-case schema name such as `\"Sales\"` referenced without quotes.","Connected to the wrong database.","A `search_path` that names only schemas that don't exist."],"fix":[{"text":"List the schemas in this database.","sql":"SELECT nspname FROM pg_namespace ORDER BY nspname;"},{"text":"Create the schema, optionally owned by the application role. This needs the role app to exist; if it does not, run CREATE ROLE app; first.","sql":"CREATE SCHEMA IF NOT EXISTS sales AUTHORIZATION app;"},{"text":"Point the search path at schemas that exist.","sql":"SET search_path TO sales, public;"}],"diagnostic":"-- Does the schema exist in the database you are connected to, and what is the current search_path?\nSELECT current_database(), current_schema(),\n       to_regnamespace('sales') IS NOT NULL AS schema_exists;\n\nSELECT nspname\nFROM pg_namespace\nWHERE nspname NOT LIKE 'pg_%' AND nspname <> 'information_schema'\nORDER BY nspname;","alternatives":"If the schema belongs to a different database, connect to that database rather than creating a duplicate schema here. For tools that hardcode one schema, set the role's persistent search_path with ALTER ROLE app SET search_path = sales, public;  -- role app must exist instead of chasing per-session SET commands.","details":[],"details_title":null,"repro":"CREATE TABLE no_such_schema.t (id int);  -- ERROR: schema \"no_such_schema\" does not exist","repro_note":null,"related":["postgresql/42P01","postgresql/3D000","postgresql/42P06","postgresql/42501"],"sqlly":null,"faqs":[{"question":"Schemas exist in other databases on this server. Why doesn't mine show up?","answer":"Schemas live inside one database. A schema named sales in the reporting database has nothing to do with a sales schema in the shop database. Connect to the database that holds the schema you need."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/3F000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/40001","corpus":"errors","engine":"postgresql","language":"en","title":"could not serialize access","description":"Under REPEATABLE READ or SERIALIZABLE, a concurrent transaction changed data this one depends on. PostgreSQL rolled it back; retry the whole transaction.","body":{"code":"40001","slug":"40001","name":"serialization_failure","message":"could not serialize access due to concurrent update","group":"40","severity":null,"sql_state":null,"summary":"Under REPEATABLE READ or SERIALIZABLE, a concurrent transaction changed data this one depends on. PostgreSQL rolled it back; retry the whole transaction.","meaning":"PostgreSQL's higher isolation levels promise that a transaction sees a consistent snapshot. When keeping that promise is impossible because another transaction committed a conflicting change, PostgreSQL aborts one of them with 40001 rather than return a result that couldn't happen in a serial order.\n\nThe messages vary with the cause: `could not serialize access due to concurrent update` or `concurrent delete` (a row you tried to change was changed by someone else after your snapshot), and `could not serialize access due to read/write dependencies among transactions` (SERIALIZABLE detected a dangerous pattern). The cure is the same: run the transaction again from the start.","causes":["Two `REPEATABLE READ` or `SERIALIZABLE` transactions update the same row; the second one to update it fails once the first has committed (while the first is still open, the second waits for it).","A `SERIALIZABLE` transaction read rows that another transaction then changed, in a pattern that could produce an anomaly.","Hot rows, such as a counter or a balance, updated by many concurrent serializable transactions."],"fix":[{"text":"Retry. Code that uses `REPEATABLE READ` or `SERIALIZABLE` must catch SQLSTATE `40001` and rerun the whole transaction, including its reads, a few times with a short backoff.","sql":null},{"text":"Keep serializable transactions short and touch as few rows as possible.","sql":null},{"text":"If you don't need serializability for this work, the default `READ COMMITTED` level re-reads the latest row version on update instead of failing.","sql":"BEGIN ISOLATION LEVEL READ COMMITTED;\nUPDATE counters SET n = n + 1 WHERE name = 'visits';\nCOMMIT;"},{"text":"Under `SERIALIZABLE`, declare read-only transactions as such; `SERIALIZABLE READ ONLY DEFERRABLE` never fails with a serialization error.","sql":"BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE;"}],"diagnostic":"-- At the moment of a failure, see who is running serializable transactions and what they touch.\nSELECT pid, xact_start, state, wait_event_type, wait_event, left(query, 80) AS query\nFROM pg_stat_activity\nWHERE datname = current_database()\n  AND xact_start IS NOT NULL\nORDER BY xact_start;\n\n-- Which relations hold locks from which transaction, to spot the hot table:\nSELECT l.pid, l.locktype, n.nspname || '.' || c.relname AS relation, l.mode, l.granted\nFROM pg_locks l\nLEFT JOIN pg_class c ON c.oid = l.relation\nLEFT JOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE l.locktype = 'relation'\nORDER BY l.pid, granted;","alternatives":"For read-mostly serializable workloads, SERIALIZABLE READ ONLY DEFERRABLE transactions wait for a gap in conflicts instead of failing, which suits reporting queries. If correctness only needs row-level compare-and-swap, plain READ COMMITTED with explicit WHERE checks (UPDATE ... WHERE bal >= 100) avoids the retry machinery.","details":[],"details_title":null,"repro":"-- Session 1:\nCREATE TABLE acct (id int PRIMARY KEY, bal int);\nINSERT INTO acct VALUES (1, 100);\nBEGIN ISOLATION LEVEL REPEATABLE READ;\nSELECT bal FROM acct WHERE id = 1;\n-- Session 2:\nUPDATE acct SET bal = 50 WHERE id = 1;\n-- Session 1:\nUPDATE acct SET bal = bal - 10 WHERE id = 1;  -- ERROR: could not serialize access due to concurrent update\nROLLBACK;","repro_note":"Run in two separate connections on a scratch database.","related":["postgresql/40P01","postgresql/25P02","postgresql/55P03","sql-server/3960","oracle/ora-08177","mysql/1213"],"sqlly":null,"faqs":[{"question":"Do I really have to retry the whole transaction, including the reads?","answer":"Yes. The transaction was aborted, its snapshot is gone, and a partial retry could miss the exact conflict that caused the failure. Re-run all statements from the BEGIN."},{"question":"Why does REPEATABLE READ also throw 40001?","answer":"REPEATABLE READ in PostgreSQL guarantees that a row your transaction updated still looks the way you read it when you commit. If another transaction changed that row in the meantime, the second transaction's UPDATE fails with could not serialize access due to concurrent update once the other transaction has committed (while that transaction is still open, the UPDATE waits for it first); the commit is never reached."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/40001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/40P01","corpus":"errors","engine":"postgresql","language":"en","title":"deadlock detected","description":"Two or more transactions were waiting on each other's locks. PostgreSQL rolled one back so the other could finish; retry the one that failed.","body":{"code":"40P01","slug":"40P01","name":"deadlock_detected","message":"deadlock detected\nDETAIL:  Process 1234 waits for ShareLock on transaction 5678; blocked by process 4321.\nProcess 4321 waits for ShareLock on transaction 8765; blocked by process 1234.","group":"40","severity":null,"sql_state":null,"summary":"Two or more transactions were waiting on each other's locks. PostgreSQL rolled one back so the other could finish; retry the one that failed.","meaning":"A deadlock is a cycle of lock waits: transaction A holds a lock B needs while waiting for a lock B holds. Neither can ever proceed, so when a lock wait has lasted `deadlock_timeout` (1 second by default) PostgreSQL checks for a cycle and, if it finds one, aborts one of the transactions with 40P01.\n\nThe aborted transaction is rolled back completely. The other one carries on. The `DETAIL` lines show which processes were involved and the `CONTEXT` line names the table and row being updated. The statement text is in the server log, which the `HINT` line points to.","causes":["Two transactions update the same rows in a different order, for example one transfers money from account 1 to 2 while another goes from 2 to 1.","Foreign keys: inserting child rows takes a `FOR KEY SHARE` lock on the parent row, which conflicts with another transaction that changes the parent's key columns or deletes the parent. A non-key `UPDATE` of the parent does not conflict.","Long transactions that touch many rows, which widen the window for an overlapping lock order.","Explicit `LOCK TABLE` or `SELECT ... FOR UPDATE` taken in different orders in different code paths."],"fix":[{"text":"Retry the failed transaction. A deadlock is a normal concurrency outcome, and the application should catch SQLSTATE `40P01` (and `40001`) and run the whole transaction again.","sql":null},{"text":"Take locks in a consistent order everywhere, for example always lock the lower id first.","sql":"BEGIN;\nSELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;\nUPDATE accounts SET balance = balance - 100 WHERE id = 1;\nUPDATE accounts SET balance = balance + 100 WHERE id = 2;\nCOMMIT;"},{"text":"Keep transactions short: do the reads and computation first, then the writes, and commit promptly.","sql":null},{"text":"Turn on `log_lock_waits` so waits longer than `deadlock_timeout` are logged with the waiting statement and the PID holding the lock, then look at the server log. The holder's statement is not logged.","sql":"ALTER SYSTEM SET log_lock_waits = on;\nSELECT pg_reload_conf();"}],"diagnostic":"-- Find sessions currently blocked on locks and what they wait for:\nSELECT blocked.pid AS blocked_pid,\n       left(blocked.query, 60) AS blocked_query,\n       blocking.pid AS blocking_pid,\n       left(blocking.query, 60) AS blocking_query\nFROM pg_stat_activity blocked\nJOIN pg_locks bl ON bl.pid = blocked.pid AND NOT bl.granted\nJOIN pg_locks gl ON gl.locktype = bl.locktype\n   AND gl.relation IS NOT DISTINCT FROM bl.relation\n   AND gl.transactionid IS NOT DISTINCT FROM bl.transactionid\n   AND gl.granted\nJOIN pg_stat_activity blocking ON blocking.pid = gl.pid\nWHERE blocked.wait_event_type = 'Lock';\n\n-- Confirm the deadlock detector's settings: it fires after deadlock_timeout (1s default).\nSHOW deadlock_timeout;","alternatives":"For a known hot-row pattern such as a queue or counter table, an advisory lock around the whole job serializes workers cheaply and avoids lock-order games. Advisory locks (pg_advisory_lock with a stable key) also give a single, predictable ordering point instead of many row locks.","details":[],"details_title":null,"repro":"-- Session 1:\nCREATE TABLE dl (id int PRIMARY KEY, v int);\nINSERT INTO dl VALUES (1, 0), (2, 0);\nBEGIN; UPDATE dl SET v = 1 WHERE id = 1;\n-- Session 2:\nBEGIN; UPDATE dl SET v = 2 WHERE id = 2;\nUPDATE dl SET v = 2 WHERE id = 1;   -- waits\n-- Session 1:\nUPDATE dl SET v = 1 WHERE id = 2;   -- one session gets ERROR: deadlock detected","repro_note":"Run the steps in two separate connections, in order, on a scratch database.","related":["postgresql/40001","postgresql/55P03","postgresql/25P02","sql-server/1205","mysql/1213","oracle/ora-00060"],"sqlly":"SQLly's activity monitor lists PostgreSQL sessions with blocking chains, so you can see which backend holds the lock others are waiting for and cancel or terminate it.","faqs":[{"question":"Which transaction does PostgreSQL abort in a deadlock?","answer":"The one whose deadlock check found the cycle, which is not predictable in general. Write every transaction so that it can be retried."},{"question":"Does 40P01 roll back only the last statement?","answer":"No. PostgreSQL aborts the whole transaction that took part in the cycle. Your application must run the entire transaction again from the start."},{"question":"Can I make deadlocks less likely without changing code?","answer":"Only a little. Lowering deadlock_timeout detects cycles faster but does not prevent them, and keeping idle_in_transaction_session_timeout short stops idle transactions from holding locks. Real prevention needs a consistent lock order and short transactions."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/40P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42501","corpus":"errors","engine":"postgresql","language":"en","title":"permission denied","description":"The current role lacks a privilege the statement needs: on a table, schema, sequence, function or database. Grant it, or connect as a role that has it.","body":{"code":"42501","slug":"42501","name":"insufficient_privilege","message":"permission denied for table orders","group":"42","severity":null,"sql_state":null,"summary":"The current role lacks a privilege the statement needs: on a table, schema, sequence, function or database. Grant it, or connect as a role that has it.","meaning":"PostgreSQL checks privileges on every object a statement touches. 42501 (`insufficient_privilege`) names the object type and name, for example `permission denied for table orders`, `permission denied for schema app` or `permission denied for sequence orders_id_seq`. Older versions say `relation` instead of `table`.\n\nPrivileges are needed at each level: `USAGE` on the schema, then `SELECT`, `INSERT`, `UPDATE` or `DELETE` on the table, and `USAGE` on the sequence behind a `serial` column for inserts.","causes":["The role was never granted the privilege, or the grant was on other tables than the one in use.","Tables created after a `GRANT ... ON ALL TABLES IN SCHEMA`, which only covers tables that existed at the time.","No `USAGE` on the schema, or since PostgreSQL 15 no `CREATE` on the `public` schema for ordinary roles.","Inserting into a table with a `serial` column without `USAGE` on its sequence.","Altering or dropping an object you don't own (`must be owner of table orders`, same code)."],"fix":[{"text":"Grant the table and schema privileges the role needs.","sql":"GRANT USAGE ON SCHEMA app TO app_user;\nGRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA app TO app_user;\nGRANT USAGE ON ALL SEQUENCES IN SCHEMA app TO app_user;"},{"text":"Cover tables created later with default privileges (set by the role that creates the tables).","sql":"ALTER DEFAULT PRIVILEGES IN SCHEMA app\n    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;"},{"text":"Check what a role has.","sql":"SELECT has_table_privilege('app_user', 'app.orders', 'INSERT'),\n       has_schema_privilege('app_user', 'app', 'USAGE');"},{"text":"On PostgreSQL 15 and later, grant `CREATE` on `public` explicitly if a role must create objects there.","sql":"GRANT CREATE ON SCHEMA public TO app_user;"}],"diagnostic":"-- Privilege checks per level: schema USAGE, table privileges, and who owns the table.\nSELECT has_schema_privilege('reader', 'public', 'USAGE') AS schema_usage,\n       has_table_privilege('reader', 'secret', 'SELECT') AS table_select;\n\nSELECT c.relname, r.rolname AS owner,\n       has_table_privilege('reader', c.oid, 'SELECT,INSERT,UPDATE,DELETE') AS any_dml\nFROM pg_class c\nJOIN pg_roles r ON r.oid = c.relowner\nWHERE c.oid = 'secret'::regclass;\n\n-- Is the session role itself restricted? A superuser skips these privilege checks. BYPASSRLS only skips row-level security policies, not table privileges.\nSELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user;","alternatives":"If the role only needs a slice of the data, a view owned by the table owner with security_invoker = false (the default) exposes just that slice without granting table access. For row-level restrictions, keep a SELECT grant on the table and enable RLS with a policy: the grant is checked first, then the policy filters rows. Without the grant the query still fails with this error.","details":[],"details_title":null,"repro":"-- In psql against a scratch database, as the owner:\nCREATE ROLE reader LOGIN;\nCREATE TABLE secret (id int);\nGRANT USAGE ON SCHEMA public TO reader;\nSET ROLE reader;\nSELECT * FROM secret;  -- ERROR: permission denied for table secret\nRESET ROLE;","repro_note":null,"related":["postgresql/28000","postgresql/42P01","postgresql/0LP01","postgresql/25006","sql-server/229","mysql/1142","oracle/ora-01031"],"sqlly":null,"faqs":[{"question":"I granted SELECT but the app still gets permission denied. What did I miss?","answer":"Check each level: USAGE on the schema, privileges on the exact table, and USAGE on the sequence behind any serial column. Also confirm the app connects as the role you granted to, and that the table wasn't created after your ALTER DEFAULT PRIVILEGES was set by a different role."},{"question":"Why do my default privileges not apply to new tables?","answer":"ALTER DEFAULT PRIVILEGES only applies to objects created by the role named in FOR ROLE, or by the role running the statement when FOR ROLE is omitted. If a migration tool creates tables as postgres but your defaults were set for app_owner, set the defaults again with FOR ROLE postgres."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42501","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42601","corpus":"errors","engine":"postgresql","language":"en","title":"syntax error at or near","description":"PostgreSQL couldn't parse the statement. The token it names, and the caret under it, mark where parsing failed; the real mistake is often just before it.","body":{"code":"42601","slug":"42601","name":"syntax_error","message":"syntax error at or near \"FROM\"\nLINE 1: SELECT id, name, FROM users;\n                         ^","group":"42","severity":null,"sql_state":null,"summary":"PostgreSQL couldn't parse the statement. The token it names, and the caret under it, mark where parsing failed; the real mistake is often just before it.","meaning":"The parser read the statement up to the token in the message and found something that can't come next. `syntax error at end of input` means the statement stopped where more was expected, such as a missing closing parenthesis.\n\nThe position is where PostgreSQL noticed the problem, which is often one token after the actual mistake: a trailing comma before `FROM`, a missing comma between columns, or a reserved word used as a name.","causes":["A trailing comma before `FROM`, `)` or `WHERE`, or a missing comma between items.","A reserved word used as a column or table name without quotes, such as `user`, `order` or `group` (a bare `SELECT user` is accepted as CURRENT_USER, so the error shows up in column lists instead).","Syntax from another database: `TOP`, `[brackets]`, backticks, `LIMIT x, y`. (`IFNULL` is not a syntax error here; it raises 42883 undefined function, see postgresql/42883.)","Unbalanced parentheses or quotes, which shows up as an error at end of input.","Client-side placeholders (`?`, `:name`, `%s`) sent to the server without the driver replacing them; PostgreSQL itself uses `$1`, `$2`."],"fix":[{"text":"Look at the token named in the message and the one just before it; remove the stray comma or add the missing one.","sql":"SELECT id, name FROM users;"},{"text":"Quote reserved words used as identifiers, or rename them.","sql":"SELECT \"user\", \"order\" FROM audit_log;"},{"text":"Rewrite other dialects' syntax in PostgreSQL form.","sql":"-- SQL Server: SELECT TOP 10 * FROM [orders]\nSELECT * FROM orders LIMIT 10;\n-- MySQL: LIMIT 20, 10\nSELECT * FROM orders LIMIT 10 OFFSET 20;"},{"text":"For PL/pgSQL bodies, use dollar quoting so quotes inside the body don't end the string.","sql":"CREATE FUNCTION greet(name text) RETURNS text\nLANGUAGE plpgsql AS $$\nBEGIN\n    RETURN 'Hello, ' || name;\nEND;\n$$;"}],"diagnostic":"-- Is the identifier a reserved word? Reserved words (catcode 'R') need double quotes as identifiers.\nSELECT word, catdesc\nFROM pg_get_keywords()\nWHERE word IN ('order', 'user', 'group', 'from')\nORDER BY word;\n\n-- Test parsing without running the statement: EXPLAIN fails on the same syntax error but has no side effects.\nEXPLAIN SELECT id, name, FROM users;","alternatives":"When porting queries from another database, run them through a migration linter or rewrite them by hand before they reach the server, since the parser error names only the first breaking token. For identifiers that must keep reserved names, a schema-wide rename (order to orders) beats quoting forever in every query.","details":[],"details_title":null,"repro":"SELECT id, FROM (VALUES (1)) v(id);  -- ERROR: syntax error at or near \"FROM\"","repro_note":null,"related":["postgresql/42703","postgresql/42P01","postgresql/42883","sql-server/102","mysql/1064","oracle/ora-00933"],"sqlly":"SQLly highlights the token PostgreSQL rejected and jumps the editor to it, even inside a long script, and its formatter lays a query out clause by clause so a stray comma or missing parenthesis is easy to see.","faqs":[{"question":"Why does the error point at a word that looks fine?","answer":"The parser reports where it got stuck, usually one token after the real mistake. A trailing comma, missing comma, or missing parenthesis just before the named token is the usual culprit."},{"question":"My query works in psql but fails from the app. Why?","answer":"Check what the driver actually sends: placeholders like ? or :name are client-side and some drivers pass them through untouched, which PostgreSQL reports as a 42601 syntax error. The named token is the one after the placeholder, such as \")\" or \";\", not the placeholder itself. Use the driver's placeholder style or PostgreSQL's $1 form."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42601","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42702","corpus":"errors","engine":"postgresql","language":"en","title":"column reference is ambiguous","description":"A column name exists in more than one table of the query (or matches a PL/pgSQL variable), so PostgreSQL can't tell which one you mean.","body":{"code":"42702","slug":"42702","name":"ambiguous_column","message":"column reference \"id\" is ambiguous\nLINE 1: SELECT id FROM orders JOIN customers ON customers.id = orders.customer_id;\n               ^","group":"42","severity":null,"sql_state":null,"summary":"A column name exists in more than one table of the query (or matches a PL/pgSQL variable), so PostgreSQL can't tell which one you mean.","meaning":"When two tables in the `FROM` clause both have a column called `id`, an unqualified `id` could refer to either, so PostgreSQL refuses the query with 42702. Qualifying the column with its table name or alias removes the ambiguity.\n\nIn PL/pgSQL functions the same error appears when a column name matches a variable or parameter name, for example a function parameter `id` used in a query on a table that also has `id`.","causes":["Joined tables share a column name, often `id`, `name`, `created_at` or `status`.","`USING` merges only the columns you list, so other shared names stay ambiguous. A `NATURAL` join merges every shared name, so it avoids this error but joins on columns you may not have intended.","In PL/pgSQL, a parameter or variable has the same name as a column, including `RETURNS TABLE` output columns."],"fix":[{"text":"Qualify the column with its table or alias.","sql":"SELECT o.id, c.name\nFROM orders o\nJOIN customers c ON c.id = o.customer_id;"},{"text":"In PL/pgSQL, give parameters a prefix, or qualify them with the function name.","sql":"CREATE FUNCTION order_total(p_id int) RETURNS numeric\nLANGUAGE plpgsql AS $$\nBEGIN\n    RETURN (SELECT total FROM orders WHERE orders.id = p_id);\nEND;\n$$;"},{"text":"Or tell PL/pgSQL to prefer the column: add `#variable_conflict use_column` at the top of the function body.","sql":null}],"diagnostic":"-- Which tables in the query share the column name? Replace the table list:\nSELECT table_name, column_name\nFROM information_schema.columns\nWHERE column_name = 'id'\n  AND table_name IN ('a_users', 'a_orders')\n  AND table_schema = 'public'\nORDER BY table_name;\n\n-- For the PL/pgSQL variant: compare the function's parameter and output column names with the table's columns\nSELECT proname, pg_get_function_arguments(oid) AS args\nFROM pg_proc\nWHERE proname = 'your_function_name';","alternatives":"In plain SQL, alias the tables (JOIN a_orders o ON ...) and qualify every column; some teams make that a style rule. In PL/pgSQL, rename the parameter or variable, or use a per-function #variable_conflict use_column pragma. Setting plpgsql.variable_conflict globally changes behavior for every function in the session, which is riskier.","details":[],"details_title":null,"repro":"SELECT id FROM (VALUES (1)) a(id), (VALUES (2)) b(id);  -- ERROR: column reference \"id\" is ambiguous","repro_note":null,"related":["postgresql/42703","postgresql/42803","sql-server/209","mysql/1052","oracle/ora-00918"],"sqlly":"SQLly highlights the ambiguous column in the editor, and IntelliSense completes columns with their table alias.","faqs":[{"question":"Why doesn't USING cause this for the join column?","answer":"USING (id) merges the two columns into one output column, so a bare id resolves to it. Any other column name shared by the joined tables is still ambiguous and needs qualification."},{"question":"The query worked before someone added a column. Why?","answer":"The new column duplicated a name the other table already had, and the query relied on only one table having it. Qualifying columns makes the query immune to that."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42702","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42703","corpus":"errors","engine":"postgresql","language":"en","title":"column does not exist","description":"A column name in the query doesn't exist in the tables it can see. Often a typo, a mixed-case name, or double quotes used for a string value.","body":{"code":"42703","slug":"42703","name":"undefined_column","message":"column \"emial\" does not exist\nLINE 1: SELECT emial FROM users;\n               ^\nHINT:  Perhaps you meant to reference the column \"users.email\".","group":"42","severity":null,"sql_state":null,"summary":"A column name in the query doesn't exist in the tables it can see. Often a typo, a mixed-case name, or double quotes used for a string value.","meaning":"PostgreSQL couldn't match a column reference to any column of the tables in the `FROM` clause. When a similar name exists, recent versions add a `HINT` suggesting it.\n\nTwo PostgreSQL rules cause most of these errors. Unquoted identifiers fold to lower case, so a column created as `\"createdAt\"` must be written with the quotes. And double quotes always mean an identifier, never a string, so `WHERE status = \"active\"` looks for a column named `active`.","causes":["A typo, or a column that was renamed or not added yet.","A column created with quoted mixed-case letters (`\"userId\"`) referenced without quotes.","A string value written in double quotes: `WHERE name = \"Ada\"` instead of `'Ada'`.","Referencing a select-list alias in `WHERE` or `GROUP BY` expressions where it isn't visible: aliases are only usable in `ORDER BY` (and as a bare name in `GROUP BY`).","Using the column of a table alias that isn't the right table, or a column from a subquery that wasn't selected in it."],"fix":[{"text":"List the table's real column names.","sql":"SELECT column_name, data_type\nFROM information_schema.columns\nWHERE table_schema = 'public' AND table_name = 'users'\nORDER BY ordinal_position;"},{"text":"Use single quotes for values and double quotes only for identifiers.","sql":"SELECT * FROM users WHERE status = 'active';"},{"text":"Quote mixed-case column names exactly as created.","sql":"SELECT \"userId\", \"createdAt\" FROM events;"},{"text":"Repeat the expression, or wrap the query, instead of using an alias in `WHERE`.","sql":"SELECT * FROM (\n    SELECT id, price * qty AS total FROM order_lines\n) t\nWHERE total > 100;"}],"diagnostic":"-- The HINT usually names the closest real column, but verify directly:\nSELECT column_name, data_type\nFROM information_schema.columns\nWHERE table_name = 'users' ORDER BY ordinal_position;\n\n-- Check schema-qualified truth: search every schema, since a column can exist\n-- on a same-named table in another schema.\nSELECT table_schema, table_name, column_name\nFROM information_schema.columns\nWHERE column_name ILIKE 'emial';\n\n-- Quoting problems: see the exact stored spelling.\nSELECT quote_ident(attname)\nFROM pg_attribute\nWHERE attrelid = 'users'::regclass AND attnum > 0 AND NOT attisdropped;\n-- If the output shows \"userId\" in mixed case, every reference needs the same quotes.","alternatives":"If the column was dropped or renamed and old code still references it, add a compatibility view that exposes the old name, or fix the callers. For mixed-case identifiers, the cheaper long-term fix is renaming the column to snake_case so unquoted references work everywhere.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE users (id int, email text);\nSELECT emial FROM users;  -- ERROR: column \"emial\" does not exist","repro_note":null,"related":["postgresql/42P01","postgresql/42702","postgresql/42803","sql-server/207","mysql/1054","oracle/ora-00904"],"sqlly":"SQLly marks the column PostgreSQL rejected and jumps to it. Validate SQL (Cmd+Shift+V / Ctrl+Shift+V) checks the query against the connection's schema without running it and flags unknown columns, and IntelliSense completes real column names as you type.","faqs":[{"question":"Why does WHERE name = \"Ada\" say column Ada does not exist?","answer":"In PostgreSQL double quotes mark an identifier such as a column or table name. String values take single quotes: WHERE name = 'Ada'."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42703","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42704","corpus":"errors","engine":"postgresql","language":"en","title":"undefined object","description":"A named object that isn't a table or column doesn't exist: a type, role, index, constraint, extension, collation or configuration parameter.","body":{"code":"42704","slug":"42704","name":"undefined_object","message":"type \"jsonbb\" does not exist","group":"42","severity":null,"sql_state":null,"summary":"A named object that isn't a table or column doesn't exist: a type, role, index, constraint, extension, collation or configuration parameter.","meaning":"42704 (`undefined_object`) is PostgreSQL's code for a missing object other than relations (42P01), columns (42703), functions (42883) and schemas (3F000). The message says which kind: `type \"...\" does not exist`, `role \"...\" does not exist`, `index \"...\" does not exist`, `constraint \"...\" of relation \"...\" does not exist`, `extension \"...\" does not exist`, `unrecognized configuration parameter \"...\"`.\n\nThe usual causes are a typo, an object in another schema or database, or an extension that defines the type and isn't installed.","causes":["A typo in a type name, or a type from an extension that isn't installed in this database (`citext`, `hstore`, `geometry`).","A role referenced in `GRANT` or `ALTER ... OWNER TO` that hasn't been created on this server, common when restoring a dump from another server. `SET ROLE` to a missing role is different: it fails with `22023` (`invalid_parameter_value`), not `42704`.","Dropping an index or constraint by a name that differs from the one PostgreSQL generated.","Setting a configuration parameter that doesn't exist in this version, or an extension's parameter before the extension is loaded."],"fix":[{"text":"Install the extension that provides the type.","sql":"CREATE EXTENSION IF NOT EXISTS citext;"},{"text":"Create missing roles before restoring a dump, or restore without ownership and privileges (`pg_restore --no-owner --no-privileges`).","sql":"CREATE ROLE reporting NOLOGIN;"},{"text":"Look up the real name of an index or constraint.","sql":"SELECT conname FROM pg_constraint WHERE conrelid = 'orders'::regclass;\nSELECT indexname FROM pg_indexes WHERE tablename = 'orders';"},{"text":"Use `IF EXISTS` in cleanup scripts.","sql":"DROP INDEX IF EXISTS orders_old_idx;\nALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_old_check;"}],"diagnostic":"-- Which object kind is missing? Search the relevant catalogs by exact name.\nSELECT typname, n.nspname FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE typname = 'jsonbb';\nSELECT rolname FROM pg_roles WHERE rolname = 'app_user';\nSELECT indexname FROM pg_indexes WHERE indexname ILIKE '%orders%';\n\n-- Extension types: is the extension available, and is it installed in THIS database?\nSELECT name, default_version, installed_version\nFROM pg_available_extensions\nWHERE name IN ('citext', 'hstore', 'postgis');\n\n-- Roles and enums are per-cluster vs per-database: roles live at cluster level,\n-- types live per database. A restore from another server commonly fails on\n-- roles that were never created here:\nSELECT rolname FROM pg_roles ORDER BY rolname;\n\n-- Generated index and constraint names differ from what you assumed; list them:\nSELECT indexdef FROM pg_indexes WHERE tablename = 'orders';","alternatives":"For missing roles on restore, create them first (`CREATE ROLE app_user LOGIN;`) or dump with `--no-owner --no-privileges` and reassign afterward. For missing extension types, `CREATE EXTENSION IF NOT EXISTS citext;` in the target database, and note that extensions must be installed per database, not per cluster. For generated names, look them up in pg_indexes or pg_constraint instead of guessing.","details":[],"details_title":null,"repro":"SELECT '{}'::jsonbb;  -- ERROR: type \"jsonbb\" does not exist","repro_note":null,"related":["postgresql/42P01","postgresql/42883","postgresql/3F000","postgresql/58P01","postgresql/42710"],"sqlly":null,"faqs":[{"question":"Why does my dump restore fail on roles that exist on the old server?","answer":"Roles live at the cluster level and pg_dump does not include them in a database-only dump. Create the roles on the target first, or restore with --no-owner --no-privileges and fix ownership separately."},{"question":"I installed the extension but the type still doesn't exist. Why?","answer":"CREATE EXTENSION installs into the database you ran it in, and usually into the first schema of search_path. If your session connects to a different database, or the type is in a schema outside your path, you get 42704. Check pg_extension and current_schemas()."},{"question":"Can SET have this error too?","answer":"Yes. SET app.some_flag = 1 fails with unrecognized configuration parameter when neither PostgreSQL nor a loaded extension defines it. Custom parameters need a dot in the name and are accepted once set, but a plain misspelling fails."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42704","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42710","corpus":"errors","engine":"postgresql","language":"en","title":"duplicate object","description":"A CREATE statement used a name already taken by a role, constraint, extension, trigger, type or other non-table object.","body":{"code":"42710","slug":"42710","name":"duplicate_object","message":"role \"app\" already exists","group":"42","severity":null,"sql_state":null,"summary":"A CREATE statement used a name already taken by a role, constraint, extension, trigger, type or other non-table object.","meaning":"42710 (`duplicate_object`) is the \"already exists\" error for objects other than tables and other relations (42P07), databases (42P04), schemas (42P06) and functions (42723). Typical messages are `role \"app\" already exists`, `constraint \"orders_ck\" for relation \"orders\" already exists (a CHECK or other non-index constraint; a primary key name clash returns 42P07 `relation ... already exists` instead)`, `extension \"pgcrypto\" already exists` and `trigger \"set_updated_at\" for relation \"orders\" already exists`.\n\nIt nearly always means a setup or migration script is running a second time.","causes":["Re-running a setup script that creates roles, extensions or types.","A migration adding a constraint or trigger that an earlier migration or a manual change already added.","Restoring a dump into a database or cluster where the objects already exist."],"fix":[{"text":"Use `IF NOT EXISTS` where the command supports it.","sql":"CREATE EXTENSION IF NOT EXISTS pgcrypto;\nCREATE TABLE IF NOT EXISTS t (id int);"},{"text":"Roles, constraints and types have no `IF NOT EXISTS`; check first in a `DO` block.","sql":"DO $$\nBEGIN\n    IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app') THEN\n        CREATE ROLE app LOGIN;\n    END IF;\nEND;\n$$;"},{"text":"For triggers, replace them in place (PostgreSQL 14 and later).","sql":"CREATE OR REPLACE TRIGGER set_updated_at\n    BEFORE UPDATE ON orders\n    FOR EACH ROW EXECUTE FUNCTION touch_updated_at();"}],"diagnostic":"-- Roles\nSELECT rolname FROM pg_roles WHERE rolname = 'your_role_name';\n\n-- Extensions\nSELECT extname, extversion FROM pg_extension WHERE extname = 'your_extension';\n\n-- Constraints on a table\nSELECT conname, contype, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'your_table'::regclass AND conname = 'your_constraint_name';\n\n-- Triggers on a table\nSELECT tgname FROM pg_trigger\nWHERE tgrelid = 'your_table'::regclass AND tgname = 'your_trigger_name' AND NOT tgisinternal;\n\n-- Types and domains\nSELECT typname, typtype FROM pg_type WHERE typname = 'your_type_name';","alternatives":"CREATE EXTENSION IF NOT EXISTS covers extensions. CREATE ROLE has no IF NOT EXISTS, so wrap it in a DO block that checks pg_roles. Constraints have no ADD CONSTRAINT IF NOT EXISTS either: check pg_constraint in a DO block, or run DROP CONSTRAINT IF EXISTS before adding. pg_restore has no --if-not-exists option. --if-exists only changes how --clean drops objects, so restoring over objects that already exist needs a clean target or --clean --if-exists.","details":[],"details_title":null,"repro":"CREATE EXTENSION plpgsql;  -- ERROR: extension \"plpgsql\" already exists","repro_note":null,"related":["postgresql/42P07","postgresql/42P04","postgresql/42P06","postgresql/42704"],"sqlly":null,"faqs":[{"question":"How do I make CREATE ROLE re-runnable?","answer":"DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app') THEN CREATE ROLE app LOGIN; END IF; END $$; works inside normal scripts and migrations."},{"question":"My migration adds a constraint that already exists. What now?","answer":"Check pg_constraint in a DO block before adding, or run ALTER TABLE ... DROP CONSTRAINT IF EXISTS name; then add it. The second is fine when the existing constraint already matches what you would create."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42710","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42803","corpus":"errors","engine":"postgresql","language":"en","title":"column must appear in the GROUP BY clause","description":"A query with GROUP BY or an aggregate selects a column that is neither grouped nor aggregated, so there is no single value to show per group.","body":{"code":"42803","slug":"42803","name":"grouping_error","message":"column \"o.customer_id\" must appear in the GROUP BY clause or be used in an aggregate function","group":"42","severity":null,"sql_state":null,"summary":"A query with GROUP BY or an aggregate selects a column that is neither grouped nor aggregated, so there is no single value to show per group.","meaning":"With `GROUP BY` (or any aggregate such as `count(*)`), each output row stands for a group of input rows. Every selected column must then be one of the grouping columns, be inside an aggregate, or be functionally dependent on the grouped primary key. Otherwise its value would differ within the group and PostgreSQL won't pick one arbitrarily, so it raises 42803 (`grouping_error`).\n\nMySQL with `ONLY_FULL_GROUP_BY` turned off allows such queries, so this often appears when moving queries to PostgreSQL. The same code covers aggregates in the wrong place, such as `aggregate functions are not allowed in WHERE`.","causes":["A selected column missing from `GROUP BY`.","Grouping by an expression but selecting the underlying column.","An aggregate used in `WHERE` instead of `HAVING`.","Queries written for MySQL's permissive grouping mode."],"fix":[{"text":"Add the column to `GROUP BY`, or aggregate it.","sql":"SELECT o.customer_id, count(*) AS orders, max(o.created_at) AS last_order\nFROM orders o\nGROUP BY o.customer_id;"},{"text":"Group by the table's primary key; its other columns are then allowed in the select list.","sql":"SELECT c.id, c.name, count(o.id)\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.id;"},{"text":"To keep one whole row per group, use `DISTINCT ON` or a window function instead of `GROUP BY`.","sql":"SELECT DISTINCT ON (customer_id) *\nFROM orders\nORDER BY customer_id, created_at DESC;"},{"text":"Filter on aggregates with `HAVING`.","sql":"SELECT customer_id FROM orders GROUP BY customer_id HAVING count(*) > 5;"}],"diagnostic":"-- Reproduce the planner's view of the group: run the SELECT list against the\n-- GROUP BY expression and find columns that fall outside it.\n-- A column is legal if it appears in GROUP BY, is inside an aggregate,\n-- or is functionally dependent on the grouped columns (only for a primary key\n-- of the same table).\n\n-- Confirm the primary key, since grouping by it makes other columns of that\n-- table legal without listing them:\nSELECT conkey, conindid::regclass\nFROM pg_constraint\nWHERE conrelid = 'orders'::regclass AND contype = 'p';\n\n-- If you were counting on a permissive mode such as MySQL with\n-- ONLY_FULL_GROUP_BY off: PostgreSQL has no such toggle and always enforces\n-- this. Rewrite the query.","alternatives":"Group by the primary key instead of a name or code, and other columns of that table become usable without appearing in GROUP BY. If you want one row per group with some non-grouped column's value, say which one: an aggregate such as `min(col)`, `max(col)`, or an ordered `array_agg` makes the intent explicit.","details":[],"details_title":null,"repro":"SELECT x, count(*) FROM (VALUES (1, 'a')) v(x, y) GROUP BY y;  -- ERROR: column \"v.x\" must appear in the GROUP BY clause ...","repro_note":null,"related":["postgresql/42702","postgresql/21000","sql-server/8120","mysql/1055","oracle/ora-00979","oracle/ora-00937"],"sqlly":null,"faqs":[{"question":"Why does grouping by id work but grouping by customer_name doesn't?","answer":"When you group by a table's primary key, PostgreSQL knows every other column of that row is determined by it, so it lets them through. Functional dependency only applies to primary keys, not to other unique columns or to columns of joined tables."},{"question":"Is there a setting like MySQL's ONLY_FULL_GROUP_BY I can turn off?","answer":"No. PostgreSQL always requires that non-aggregated select columns be in GROUP BY or functionally dependent on it. The rewrite is the fix."},{"question":"Can I use a column alias in GROUP BY?","answer":"PostgreSQL accepts a bare alias as a GROUP BY item, but not an expression built from one, and aliases are never visible in WHERE. When in doubt, repeat the expression."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42803","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42804","corpus":"errors","engine":"postgresql","language":"en","title":"datatype mismatch","description":"A value's type doesn't match what the column or context expects and there is no implicit conversion: integer into timestamp, text into boolean, and so on.","body":{"code":"42804","slug":"42804","name":"datatype_mismatch","message":"column \"created_at\" is of type timestamp with time zone but expression is of type integer\nHINT:  You will need to rewrite or cast the expression.","group":"42","severity":null,"sql_state":null,"summary":"A value's type doesn't match what the column or context expects and there is no implicit conversion: integer into timestamp, text into boolean, and so on.","meaning":"PostgreSQL is strict about types. Assigning a value to a column, comparing values, or combining the branches of a `CASE` or `UNION` requires compatible types. When no implicit or assignment cast exists between them, it raises 42804 and usually suggests a cast.\n\nTypical variants are `argument of WHERE must be type boolean, not type integer` and `CASE types integer and text cannot be matched`.","causes":["Inserting a Unix timestamp integer into a `timestamptz` column, or a number into a `boolean`.","A `WHERE` clause that is a number or string rather than a condition (`WHERE 1`).","`CASE` branches or `UNION` columns returning different types, such as an integer in one branch and text in another.","Changing a column's type with `ALTER TABLE` without a `USING` clause."],"fix":[{"text":"Convert the value explicitly.","sql":"INSERT INTO events (created_at) VALUES (to_timestamp(1700000000));\nSELECT * FROM t WHERE flag = (1 = 1);"},{"text":"Make `CASE` or `UNION` branches return the same type.","sql":"SELECT CASE WHEN qty > 0 THEN qty::text ELSE 'none' END FROM stock;"},{"text":"Give `ALTER COLUMN ... TYPE` a `USING` expression for the conversion.","sql":"ALTER TABLE events\n    ALTER COLUMN created_at TYPE timestamptz\n    USING to_timestamp(created_at);"}],"diagnostic":"-- Compare the column type with the type the expression actually produces.\nSELECT column_name, data_type\nFROM information_schema.columns\nWHERE table_name = 'your_table' AND column_name = 'created_at';\n\n-- What does the planner think your expression is? Ask it, without touching data:\nSELECT pg_typeof(1700000000);        -- integer\nSELECT pg_typeof(to_timestamp(1700000000));  -- timestamp with time zone\nSELECT pg_typeof('2024-01-01'::timestamptz);\n\n-- CASE and UNION mismatches: every branch must have a common type. Test the\n-- suspect branch types one by one with pg_typeof until you find the odd one.\n\n-- For ALTER TABLE type changes, check for a USING clause need:\nSELECT attname, format_type(atttypid, atttypmod)\nFROM pg_attribute\nWHERE attrelid = 'your_table'::regclass AND attnum > 0 AND NOT attisdropped;","alternatives":"Convert at the boundary instead of in the query: store Unix epoch integers as bigint and render timestamps in the app, or convert once with `to_timestamp(epoch_col)` in a generated column. For CASE and UNION, cast the odd branch explicitly to the common type, e.g. `branch::text`, so the result type is stated rather than inferred.","details":[],"details_title":null,"repro":"SELECT 1 WHERE 1;  -- ERROR: argument of WHERE must be type boolean, not type integer","repro_note":null,"related":["postgresql/42846","postgresql/42883","postgresql/22P02","sql-server/245","oracle/ora-00932"],"sqlly":null,"faqs":[{"question":"Why does inserting a Unix timestamp integer into timestamptz fail?","answer":"PostgreSQL will not guess that an integer means seconds since 1970. Wrap it: `to_timestamp(1700000000)` for seconds, or `to_timestamp(1700000000000 / 1000.0)` for milliseconds. The explicit call also documents the unit."},{"question":"What is the USING clause for in ALTER TABLE ... TYPE?","answer":"It tells PostgreSQL how to convert existing values when there is no automatic assignment cast, e.g. `ALTER TABLE t ALTER COLUMN c TYPE boolean USING c <> 0;` Without it the ALTER fails with this same 42804 error."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42804","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42830","corpus":"errors","engine":"postgresql","language":"en","title":"invalid foreign key","description":"A foreign key points at columns that aren't covered by a primary key or unique constraint on the referenced table.","body":{"code":"42830","slug":"42830","name":"invalid_foreign_key","message":"there is no unique constraint matching given keys for referenced table \"customers\"","group":"42","severity":null,"sql_state":null,"summary":"A foreign key points at columns that aren't covered by a primary key or unique constraint on the referenced table.","meaning":"A foreign key must reference columns that are guaranteed unique in the parent table, through its primary key or a `UNIQUE` constraint (or a unique index without a predicate) on exactly those columns. Otherwise PostgreSQL can't tell which parent row a child refers to, and creating the foreign key fails with 42830.\n\nThe columns must match as a set: a unique constraint on `(tenant_id, id)` doesn't let a foreign key reference `id` alone.","causes":["The referenced column has no primary key or unique constraint at all.","The foreign key references a subset or superset of the columns of the unique constraint.","The unique index on the parent is partial (has a `WHERE` clause), which can't back a foreign key."],"fix":[{"text":"Add a primary key or unique constraint on the referenced columns, then create the foreign key.","sql":"ALTER TABLE customers ADD CONSTRAINT customers_email_key UNIQUE (email);\nALTER TABLE orders ADD FOREIGN KEY (customer_email) REFERENCES customers (email);"},{"text":"Or reference the existing key, using the same column list.","sql":"ALTER TABLE orders\n    ADD FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id);"}],"diagnostic":"-- What constraints actually exist on the referenced table?\nSELECT conname, contype, pg_get_constraintdef(oid) AS def\nFROM pg_constraint\nWHERE conrelid = 'customers'::regclass;\n\n-- Is there a unique constraint on exactly the referenced columns? A unique\n-- INDEX is not enough on its own; it must be attached to a constraint OR be\n-- a plain unique index that is not partial and not expression-based.\n-- List the indexes backing the columns:\nSELECT i.relname AS index_name, idx.indisunique, idx.indpred IS NOT NULL AS is_partial,\n       pg_get_indexdef(idx.indexrelid) AS def\nFROM pg_index idx\nJOIN pg_class i ON i.oid = idx.indexrelid\nWHERE idx.indrelid = 'customers'::regclass;\n-- Requirements for a foreign key target: indisunique is true, is_partial is\n-- false, and the indexed expression is exactly the plain column list.\n\n-- Compare the column list and order on both sides:\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'orders'::regclass AND contype = 'f';","alternatives":"If the parent columns have a unique index but no constraint, attach it with `ALTER TABLE customers ADD CONSTRAINT customers_email_key UNIQUE USING INDEX customers_email_idx;`. A plain `ADD CONSTRAINT ... UNIQUE (email)` builds a second index next to the existing one. If the referenced column genuinely has no uniqueness, decide whether the foreign key should target the primary key instead. A partial unique index can never back a foreign key; enforce that rule with a trigger if you need both.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE p (id int);\nCREATE TEMP TABLE c (p_id int REFERENCES p (id));  -- ERROR: there is no unique constraint matching given keys for referenced table \"p\"","repro_note":null,"related":["postgresql/23503","postgresql/42P10","mysql/1822","mysql/1215"],"sqlly":"SQLly's table designer and ER diagram show each table's keys and foreign keys, so you can check which columns a foreign key may reference.","faqs":[{"question":"I created a unique index. Why does the foreign key still fail?","answer":"The target must be a unique constraint, or a plain unique index that covers exactly the referenced columns with no WHERE clause and no expressions. ALTER TABLE ... ADD CONSTRAINT UNIQUE is the reliable form because it states the intent in the constraint catalog."},{"question":"Does column order matter for a multi-column foreign key?","answer":"Order does not matter: a foreign key on (a, b) matches a unique constraint on (b, a). The column set must match exactly, though: a unique constraint on (a) alone does not back a foreign key on (a, b)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42830","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42846","corpus":"errors","engine":"postgresql","language":"en","title":"cannot coerce","description":"An explicit cast between two types that have no conversion defined, such as integer to uuid or boolean to date.","body":{"code":"42846","slug":"42846","name":"cannot_coerce","message":"cannot cast type integer to uuid","group":"42","severity":null,"sql_state":null,"summary":"An explicit cast between two types that have no conversion defined, such as integer to uuid or boolean to date.","meaning":"PostgreSQL only casts between types when a cast is defined for that pair. 42846 (`cannot_coerce`) means you asked for one with `::type` or `CAST` and none exists, so PostgreSQL can't convert the value no matter what it contains.\n\nThis differs from 22P02, where a cast exists but the particular text value is invalid. Often the fix is to go through text, or to use a function that builds the target type properly.","causes":["Casting between unrelated types, such as `integer` to `uuid`, `boolean` to `date` or `jsonb` to `integer[]`.","Casting a composite or array value to a scalar type.","Code ported from another database that allows the conversion."],"fix":[{"text":"Convert through text when the text form is valid input for the target type.","sql":"SELECT 42::text::numeric;\nSELECT ('{\"n\": 7}'::jsonb ->> 'n')::int;"},{"text":"Use a conversion function that builds the target type.","sql":"SELECT to_timestamp(1700000000);\nSELECT ARRAY(SELECT jsonb_array_elements_text('[1,2,3]'::jsonb)::int);"},{"text":"List the casts that do exist from a type.","sql":"SELECT castsource::regtype, casttarget::regtype, castcontext\nFROM pg_cast WHERE castsource = 'integer'::regtype;"}],"diagnostic":"-- What type is the source column, and does a cast path exist?\nSELECT column_name, data_type\nFROM information_schema.columns\nWHERE table_name = 'your_table' AND column_name = 'your_column';\n\n-- List every cast between the two types, including ones usable implicitly or via assignment.\nSELECT castsource::regtype, casttarget::regtype, castcontext\nFROM pg_cast\nWHERE castsource = 'integer'::regtype AND casttarget = 'uuid'::regtype;\n-- castcontext: 'i' implicit, 'a' assignment, 'e' explicit only. No rows means no direct\n-- cast from integer to uuid; also run the query with castsource and casttarget swapped, then use an intermediate type such as text.\n\n-- For other type pairs, substitute the regtypes you actually have.","alternatives":"An integer cannot hold a UUID, so `col::text::uuid` only works when the column's text form is already UUID-formatted, such as a text column holding `00000000-0000-0000-0000-000000000042`. Otherwise it fails with 22P02 because it validates the format. For whole-column type changes, `ALTER TABLE ... ALTER COLUMN ... TYPE uuid USING col::text::uuid` converts once instead of casting at every use site, but it fails with 22P02 on an integer column holding values such as 1.","details":[],"details_title":null,"repro":"SELECT 1::uuid;  -- ERROR: cannot cast type integer to uuid","repro_note":null,"related":["postgresql/42804","postgresql/22P02","postgresql/42883"],"sqlly":null,"faqs":[{"question":"Why does `integer::text::uuid` compile when `integer::uuid` doesn't?","answer":"PostgreSQL has a cast from integer to text and from text to uuid, but no direct cast between integer and uuid. Chaining through text gives each step a defined conversion, so the chain compiles. The text-to-uuid step still validates the string, so `SELECT 42::text::uuid;` fails with `22P02 invalid input syntax for type uuid: \"42\"`. The chain only succeeds when the text is a UUID, such as `'00000000-0000-0000-0000-000000000042'::text::uuid`."},{"question":"Does adding a cast with CREATE CAST fix this permanently?","answer":"You can define one, e.g. `CREATE CAST (integer AS uuid) WITH INOUT AS IMPLICIT;` but making it implicit changes how the planner resolves every expression involving those two types, including function overloads. A cast created this way still parses the text form, so `SELECT 1::uuid;` fails with `22P02 invalid input syntax for type uuid: \"1\"` rather than converting. The text round-trip at the few call sites that need it is safer."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42846","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42883","corpus":"errors","engine":"postgresql","language":"en","title":"function does not exist","description":"No function or operator matches that name with those argument types. Usually a missing cast, a missing extension, or a function in another schema.","body":{"code":"42883","slug":"42883","name":"undefined_function","message":"function lower(integer) does not exist\nLINE 1: SELECT lower(42);\n               ^\nHINT:  No function matches the given name and argument types. You might need to add explicit type casts.","group":"42","severity":null,"sql_state":null,"summary":"No function or operator matches that name with those argument types. Usually a missing cast, a missing extension, or a function in another schema.","meaning":"PostgreSQL picks a function by its name and the types of its arguments. 42883 means no function on the `search_path` accepts the types you passed, even with implicit casts. The same code covers operators, as in `operator does not exist: integer = text`.\n\nSince PostgreSQL 8.3, most types are no longer cast to text implicitly, so code written for older versions or for other databases often hits this.","causes":["Argument types don't match: passing an integer to a text function, or comparing `integer = text`.","Calling a function from an extension that isn't installed in this database (`uuid_generate_v4()`, `crypt()`, `similarity()`).","The function lives in a schema that isn't on the `search_path`.","Calling a function from another database, such as MySQL's `IFNULL` or `DATE_FORMAT`.","Typed parameters from a driver: a bound `$1` declared as `integer` and passed to a text function, such as `PREPARE p(int) AS SELECT lower($1)`. An untyped `$1` resolves to text and runs."],"fix":[{"text":"Cast the argument to the type the function expects.","sql":"SELECT lower(42::text);\nSELECT * FROM orders WHERE id = '42'::int;"},{"text":"Install the extension that provides the function, in this database.","sql":"CREATE EXTENSION IF NOT EXISTS pgcrypto;\nSELECT gen_random_uuid();  -- built in since PostgreSQL 13"},{"text":"Find the function and its argument types, then call it schema-qualified.","sql":"SELECT n.nspname, p.proname, pg_get_function_identity_arguments(p.oid)\nFROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.proname = 'my_func';"},{"text":"Replace other databases' functions with PostgreSQL ones: `IFNULL` becomes `COALESCE`, `DATE_FORMAT(d, '%Y')` becomes `to_char(d, 'YYYY')` (PostgreSQL uses its own format patterns, so `'%Y'` returns `%6`), and `NOW()` works as is.","sql":null}],"diagnostic":"-- Does any visible function match the name and argument types? List every\n-- candidate the name resolves to in the schemas on your search path.\nSELECT p.oid::regprocedure AS signature\nFROM pg_proc p\nJOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.proname = 'lower' AND n.nspname = ANY (current_schemas(true));\n\n-- Is it an extension function that was never installed? pg_depend records\n-- the ownership (d.objid is the function, d.refobjid the extension), and an\n-- extension's schema is often not on search_path.\nSELECT e.extname, n.nspname, p.oid::regprocedure\nFROM pg_proc p\nJOIN pg_depend d ON d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e'\nJOIN pg_extension e ON e.oid = d.refobjid\nJOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.proname IN ('uuid_generate_v4', 'crypt', 'similarity');\n\n-- What is the actual type of your argument? pg_typeof(42) beats guessing.\nSELECT pg_typeof(42);\n\n-- Which extension provides a function you may be missing:\nSELECT name, default_version, installed_version\nFROM pg_available_extensions\nWHERE name IN ('uuid-ossp', 'pgcrypto', 'pg_trgm');","alternatives":"Prefer built-in equivalents: `gen_random_uuid()` (built in since PostgreSQL 13) replaces uuid-ossp's `uuid_generate_v4()`, `gen_random_bytes()` in pgcrypto covers some crypt uses, and `lower(col::text)` fixes the integer-to-text-function case. If the function is in a non-public schema, add that schema to `search_path` or schema-qualify the call.","details":[],"details_title":null,"repro":"SELECT lower(42);  -- ERROR: function lower(integer) does not exist","repro_note":null,"related":["postgresql/42804","postgresql/42P18","postgresql/42601","postgresql/42704","mysql/1305","oracle/ora-00904"],"sqlly":null,"faqs":[{"question":"The function exists. Why does psql find it but my app doesn't?","answer":"They usually have different search_path settings. Run `SHOW search_path;` in both and compare; a function in a schema outside the app's path needs qualification or a path change."},{"question":"Why does the error say the function doesn't exist when it's a cast problem?","answer":"PostgreSQL resolves functions by exact name plus argument types. There is no lower(integer), so it reports the nearest failure: no matching function. Casting the argument, `lower(42::text)`, resolves it."},{"question":"Is gen_random_uuid() available in every version?","answer":"It is built in from PostgreSQL 13. On 12 and earlier you need the uuid-ossp extension or pgcrypto for it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42883","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P01","corpus":"errors","engine":"postgresql","language":"en","title":"relation does not exist","description":"PostgreSQL can't find the table, view or sequence. Usually the wrong schema on the search_path, a quoted mixed-case name, or the wrong database.","body":{"code":"42P01","slug":"42P01","name":"undefined_table","message":"relation \"orders\" does not exist\nLINE 1: SELECT * FROM orders;\n                      ^","group":"42","severity":null,"sql_state":null,"summary":"PostgreSQL can't find the table, view or sequence. Usually the wrong schema on the search_path, a quoted mixed-case name, or the wrong database.","meaning":"In PostgreSQL a relation is any table-like object: a table, view, materialized view, sequence, index or foreign table. 42P01 means the name you used doesn't resolve to one, in the schemas listed on your `search_path` (or in the schema you named explicitly).\n\nPostgreSQL folds unquoted names to lower case. A table created as `\"Orders\"` (quoted, capital O) can only be referred to as `\"Orders\"`, so `SELECT * FROM Orders` looks for `orders` and fails.","causes":["The table is in a schema that isn't on the `search_path`, for example `sales.orders` while the path is `\"$user\", public`.","The table was created with a quoted mixed-case name (common with ORMs and GUI tools) and the query doesn't quote it.","You're connected to a different database than the one that has the table. PostgreSQL can't query across databases with a plain name.","The table hasn't been created yet, or a migration failed or ran in another database.","A typo in the table name."],"fix":[{"text":"Check where you are and what your search path is.","sql":"SELECT current_database(), current_schema();\nSHOW search_path;"},{"text":"Find the table, whatever its schema or casing.","sql":"SELECT table_schema, table_name\nFROM information_schema.tables\nWHERE lower(table_name) = 'orders';"},{"text":"Qualify the name with its schema, or add the schema to the search path.","sql":"SELECT * FROM sales.orders;\nSET search_path TO sales, public;\n-- permanently for a role:\nALTER ROLE app SET search_path TO sales, public;"},{"text":"If the table was created with capitals, quote it exactly, or rename it to lower case once so it never needs quotes.","sql":"SELECT * FROM \"Orders\";\nALTER TABLE \"Orders\" RENAME TO orders;"}],"diagnostic":"-- What tables and views actually exist in the search_path you are using:\nSELECT table_schema, table_name, table_type FROM information_schema.tables\nWHERE table_name = 'my_table';\n-- Which schema your search_path resolves first:\nSHOW search_path;","alternatives":"If the table belongs to another schema, schema-qualify the name or set search_path for the session rather than moving the table. If the name is only sometimes missing, check for a drop-and-recreate migration that runs between deployments.","details":[],"details_title":null,"repro":"SELECT * FROM table_that_does_not_exist;  -- ERROR: relation \"table_that_does_not_exist\" does not exist","repro_note":null,"related":["postgresql/42703","postgresql/3F000","postgresql/3D000","postgresql/42501","sql-server/208","mysql/1146","oracle/ora-00942"],"sqlly":"SQLly highlights the token PostgreSQL complained about and moves the editor to it. Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V on Windows and Linux) checks a query against the connection's schema without running it and marks unknown tables and columns.","faqs":[{"question":"The table exists, so why does PostgreSQL say relation does not exist?","answer":"Almost always the schema or the case. Either the table's schema isn't on your search_path, or it was created with a quoted mixed-case name and must be quoted the same way. Querying information_schema.tables with lower(table_name) shows its real schema and spelling."},{"question":"Can I select from a table in another database?","answer":"Not directly. Each PostgreSQL connection is to one database. Use the postgres_fdw or dblink extensions, or connect to the other database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P02","corpus":"errors","engine":"postgresql","language":"en","title":"there is no parameter","description":"The SQL contains a $1-style placeholder but no parameter value was bound, often from running driver SQL directly or from placeholders inside quotes.","body":{"code":"42P02","slug":"42P02","name":"undefined_parameter","message":"there is no parameter $1","group":"42","severity":null,"sql_state":null,"summary":"The SQL contains a $1-style placeholder but no parameter value was bound, often from running driver SQL directly or from placeholders inside quotes.","meaning":"PostgreSQL's own placeholders are `$1`, `$2` and so on, filled in when a statement is prepared or executed with bound parameters. If the text contains `$1` but the statement was sent without parameters, PostgreSQL has nothing to substitute and fails with 42P02 (`undefined_parameter`).\n\nThis usually means SQL copied from application code or a log was run by hand, or a driver sent a query string with placeholders through a path that doesn't bind them.","causes":["Running a parameterized query copied from code or logs in psql or a SQL editor.","A `$1` inside a dollar-quoted DO block or a string passed to `EXECUTE` without `USING`. A `$1` inside an ordinary string literal is just text and does not raise this error.","A `DO` block or dynamic SQL using `$1` without `EXECUTE ... USING`.","Mixing driver placeholder styles. A raw `?` or `%s` in SQL gives 42601 `syntax_error`; a `$1` that the driver did not bind gives 42P02."],"fix":[{"text":"When running it by hand, replace the placeholders with literal values, or use `PREPARE` and `EXECUTE`.","sql":"PREPARE find_order(int) AS SELECT * FROM orders WHERE id = $1;\nEXECUTE find_order(42);"},{"text":"In dynamic SQL inside PL/pgSQL, pass values with `USING`.","sql":"DO $$\nDECLARE n int;\nBEGIN\n    EXECUTE 'SELECT count(*) FROM orders WHERE customer_id = $1' INTO n USING 42;\n    RAISE NOTICE '%', n;\nEND;\n$$;"},{"text":"In application code, pass the values through the driver's parameter API rather than concatenating them.","sql":null}],"diagnostic":"-- Find where the placeholder lands. `$1` is only a parameter inside the SQL\n-- text the server parses; inside a string literal, dollar-quoted body, or a\n-- comment it is just characters.\n\n-- For a DO block or dynamic SQL, confirm the USING side:\n-- EXECUTE '... WHERE id = $1' USING my_id;   -- binds $1\n-- Without USING, $1 has no definition and fails as 42P02.\n\n-- The server log cannot show you Parse or Bind frames. To see whether any\n-- Bind frame with parameter values was sent at all, use the driver's\n-- protocol tracing or a protocol-aware capture. If nothing was bound, the\n-- placeholders are sitting in text the server parses literally, which\n-- points back at string literals, dollar-quoted bodies, or comments.\n\n-- In psql, :vars are client-side and do not bind $1. Inside a dollar-quoted body, :var is not substituted and fails with a 42601 syntax error at the colon.","alternatives":"For one-off testing, replace `$1` with a literal value before running copied SQL. In DO blocks and dynamic SQL, bind with `EXECUTE ... USING`, or format values with `format('... %L', value)` for literals. Pick one placeholder style per driver and stick to it; mixing `?`, `%s`, and `$1` in one codebase is where this error usually comes from.","details":[],"details_title":null,"repro":"SELECT $1;  -- ERROR: there is no parameter $1","repro_note":null,"related":["postgresql/42P18","postgresql/42601"],"sqlly":null,"faqs":[{"question":"Why does the query run fine in my app but fail in the SQL editor?","answer":"The editor has no driver binding parameters, so `$1` arrives as literal text with no definition. Substitute a real value for each `$1` in the text, or bind it with `PREPARE` and `EXECUTE`. A psql `\\set` variable does not bind `$1`: `SELECT $1 + :x` still fails with 42P02."},{"question":"Can I use $1 inside a function body?","answer":"Inside plpgsql, `$1` refers to the function's first parameter, the same as a named parameter, so `RETURN $1 + 1;` works in a one-argument function. A bare `$1` in a DO block, which has no parameters, fails with 42P02. A `$1` inside an EXECUTE string is only valid when EXECUTE supplies USING, because the dynamic query is parsed separately from the function's parameters."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P02","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P04","corpus":"errors","engine":"postgresql","language":"en","title":"database already exists","description":"CREATE DATABASE used a name an existing database already has on this server. Database names are unique per cluster.","body":{"code":"42P04","slug":"42P04","name":"duplicate_database","message":"database \"shop\" already exists","group":"42","severity":null,"sql_state":null,"summary":"CREATE DATABASE used a name an existing database already has on this server. Database names are unique per cluster.","meaning":"All databases in a PostgreSQL cluster (one server instance) share one namespace, so `CREATE DATABASE` fails with 42P04 if the name is taken. Unlike tables, `CREATE DATABASE` has no `IF NOT EXISTS` clause and can't run inside a transaction block or a `DO` block, so scripts have to check before calling it.","causes":["A setup script or container entrypoint that runs `CREATE DATABASE` every time it starts.","Tests that create a fixed-name database without dropping it afterwards.","Restoring with `pg_restore --create` onto a server that already has a database of that name."],"fix":[{"text":"Check whether it exists first.","sql":"SELECT 1 FROM pg_database WHERE datname = 'shop';"},{"text":"In psql scripts, create it only when missing with `\\gexec`.","sql":"SELECT 'CREATE DATABASE shop'\nWHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'shop')\\gexec"},{"text":"If the old database should be replaced, drop it first. A plain DROP DATABASE fails while other sessions are connected; WITH (FORCE) terminates them.","sql":"DROP DATABASE IF EXISTS shop WITH (FORCE);\nCREATE DATABASE shop;"}],"diagnostic":"-- Does the database exist, and who owns it?\nSELECT datname, pg_get_userbyid(datdba) AS owner,\n       pg_size_pretty(pg_database_size(datname)) AS size\nFROM pg_database\nWHERE datname = 'your_db_name';\n\n-- All databases in the cluster, in case the name is close to what you expected\nSELECT datname, datallowconn FROM pg_database ORDER BY datname;","alternatives":"There is no CREATE DATABASE IF NOT EXISTS, so guard the call: in shell, `psql -tAc \"SELECT 1 FROM pg_database WHERE datname='x'\" | grep -q 1 || createdb x`, or run DROP DATABASE IF EXISTS first when the contents are disposable.","details":[],"details_title":null,"repro":"-- Run on a scratch server/database from psql\nCREATE DATABASE scratch_42p04;\n-- Now try again with the same name:\nCREATE DATABASE scratch_42p04;\n-- ERROR:  database \"scratch_42p04\" already exists (42P04)\n-- Cleanup\nDROP DATABASE scratch_42p04;","repro_note":null,"related":["postgresql/3D000","postgresql/55006","postgresql/42P06","postgresql/42P07","postgresql/25001"],"sqlly":null,"faqs":[{"question":"Why is there no CREATE DATABASE IF NOT EXISTS?","answer":"PostgreSQL has not added one, and CREATE DATABASE cannot run inside a transaction, which rules out the usual DO-block guard. Check pg_database first, or catch the error in your script."},{"question":"Can I run CREATE DATABASE from a migration tool?","answer":"Most migration tools wrap statements in a transaction, which fails with 'CREATE DATABASE cannot run inside a transaction block'. Run it outside the migration, in your deploy script or entrypoint."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P04","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P06","corpus":"errors","engine":"postgresql","language":"en","title":"schema already exists","description":"CREATE SCHEMA named a schema that already exists in this database. Add IF NOT EXISTS or choose another name.","body":{"code":"42P06","slug":"42P06","name":"duplicate_schema","message":"schema \"sales\" already exists","group":"42","severity":null,"sql_state":null,"summary":"CREATE SCHEMA named a schema that already exists in this database. Add IF NOT EXISTS or choose another name.","meaning":"Schema names are unique within a database. Creating one that exists fails with 42P06, typically from a migration or setup script that ran before. `CREATE SCHEMA IF NOT EXISTS` (PostgreSQL 9.3 and later) turns it into a notice.","causes":["A setup or migration script running a second time.","Two tools or extensions that create the same schema."],"fix":[{"text":"Make the statement idempotent.","sql":"CREATE SCHEMA IF NOT EXISTS sales AUTHORIZATION your_role;"},{"text":"Check who owns the existing schema if permissions look wrong afterwards.","sql":"SELECT nspname, pg_get_userbyid(nspowner) AS owner FROM pg_namespace WHERE nspname = 'sales';"}],"diagnostic":"-- Does the schema exist and who owns it?\nSELECT nspname, pg_get_userbyid(nspowner) AS owner\nFROM pg_namespace\nWHERE nspname = 'your_schema_name';\n\n-- What is inside it, if anything?\nSELECT c.relkind, c.relname\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE n.nspname = 'your_schema_name'\nORDER BY c.relname;","alternatives":"CREATE SCHEMA IF NOT EXISTS makes a second run a notice instead of an error on PostgreSQL 9.3 and later. If a second tool owns the schema, work inside it rather than recreating it, or agree on one owner for schema creation.","details":[],"details_title":null,"repro":"CREATE SCHEMA public;  -- ERROR: schema \"public\" already exists","repro_note":null,"related":["postgresql/3F000","postgresql/42P07","postgresql/42710","postgresql/42P04"],"sqlly":null,"faqs":[{"question":"Is DROP SCHEMA and recreate safe?","answer":"Only if the schema holds nothing you need. DROP SCHEMA x CASCADE drops every object in it. For a migration that only needed the schema to exist, IF NOT EXISTS is the safer path."},{"question":"Why do I get this for a schema I never created?","answer":"Extensions and provisioning tools can create their own schema. Check the owner in pg_namespace, and look at each extension's namespace in pg_extension."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P06","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P07","corpus":"errors","engine":"postgresql","language":"en","title":"relation already exists","description":"CREATE TABLE, INDEX, VIEW or SEQUENCE used a name that a table-like object already has in that schema.","body":{"code":"42P07","slug":"42P07","name":"duplicate_table","message":"relation \"orders\" already exists","group":"42","severity":null,"sql_state":null,"summary":"CREATE TABLE, INDEX, VIEW or SEQUENCE used a name that a table-like object already has in that schema.","meaning":"Tables, views, materialized views, sequences, indexes and foreign tables share one namespace per schema. Creating any of them with a name that is already taken in the schema fails with 42P07, even if the existing object is a different kind (an index named like a table, for example).\n\nRe-running a migration or setup script is the usual trigger.","causes":["A setup or migration script that ran before, partly or fully.","An index with the same name as an existing table, view or index in the schema.","Two migrations creating the same object.","A temporary table with the same name left over in the same session. A permanent table with that name does not conflict with it."],"fix":[{"text":"Make the script idempotent with `IF NOT EXISTS`.","sql":"CREATE TABLE IF NOT EXISTS orders (id bigint PRIMARY KEY);\nCREATE INDEX IF NOT EXISTS orders_created_at_idx ON orders (created_at);"},{"text":"See what currently has the name.","sql":"SELECT n.nspname, c.relname, c.relkind\nFROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relname = 'orders';"},{"text":"If the old object should be replaced, drop it first, after checking nothing depends on it.","sql":"DROP TABLE IF EXISTS orders_old;\nCREATE OR REPLACE VIEW order_summary AS SELECT 1 AS n;  -- views can be replaced in place if the new query keeps the existing column names and order (renaming a column fails with 42P16)"}],"diagnostic":"-- What kind of object already uses the name? relkind: r=table, v=view, m=matview, S=sequence, i=index\nSELECT n.nspname, c.relname, c.relkind,\n       pg_get_userbyid(c.relowner) AS owner\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relname = 'your_object_name';\n\n-- Left-over temp table from an old session: check the temp schemas\nSELECT n.nspname, c.relname\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE n.nspname LIKE 'pg_temp%' AND c.relname = 'your_object_name';","alternatives":"CREATE TABLE IF NOT EXISTS (PostgreSQL 9.1 and later) skips an existing table but only checks the name, not the shape. DROP TABLE IF EXISTS first works when the old table is disposable. For re-runnable migrations, track applied migrations in a table so each runs once instead of relying on IF EXISTS.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE t (id int);\nCREATE TEMP TABLE t (id int);  -- ERROR: relation \"t\" already exists","repro_note":null,"related":["postgresql/42P01","postgresql/42710","postgresql/42P06","postgresql/42P04","sql-server/2714","mysql/1050","oracle/ora-00955"],"sqlly":null,"faqs":[{"question":"Why does CREATE INDEX fail saying the relation already exists when the name matches a table?","answer":"Tables, views, sequences and indexes share one namespace per schema. An index cannot take the name of a table in the same schema. Name indexes like tablename_colname_idx."},{"question":"CREATE TABLE IF NOT EXISTS ran but the columns don't match. Why no error?","answer":"IF NOT EXISTS only checks the name. If an object with that name exists, PostgreSQL skips the statement and issues a notice, even if the existing table has a different shape."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P07","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P10","corpus":"errors","engine":"postgresql","language":"en","title":"invalid column reference","description":"Most often an ON CONFLICT target that no unique index matches, or ORDER BY with SELECT DISTINCT on a column that isn't selected.","body":{"code":"42P10","slug":"42P10","name":"invalid_column_reference","message":"there is no unique or exclusion constraint matching the ON CONFLICT specification","group":"42","severity":null,"sql_state":null,"summary":"Most often an ON CONFLICT target that no unique index matches, or ORDER BY with SELECT DISTINCT on a column that isn't selected.","meaning":"42P10 (`invalid_column_reference`) is raised when a column list refers to columns in a way the statement doesn't allow. The two cases people hit most:\n\n`INSERT ... ON CONFLICT (cols)` needs a unique index on exactly those columns, so PostgreSQL knows what counts as a conflict. An exclusion constraint can only be named with `ON CONFLICT ON CONSTRAINT name`; a column list does not match it. And with `SELECT DISTINCT`, every `ORDER BY` expression must appear in the select list: `for SELECT DISTINCT, ORDER BY expressions must appear in select list`.","causes":["`ON CONFLICT (email)` on a table with no unique index on `email`, or with a unique index on `lower(email)` or a different column set.","A partial unique index, which `ON CONFLICT` only uses when the statement repeats its `WHERE` predicate.","`SELECT DISTINCT a FROM t ORDER BY b`."],"fix":[{"text":"Create the unique index that defines a conflict, or name the conflict target to match the existing one.","sql":"CREATE UNIQUE INDEX users_email_key ON users (email);\nINSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada')\nON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;"},{"text":"For an expression or partial index, repeat the expression or predicate in the conflict target.","sql":"CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));\nINSERT INTO users (email) VALUES ('Ada@example.com')\nON CONFLICT ((lower(email))) DO NOTHING;"},{"text":"With `DISTINCT`, select what you order by, or use `DISTINCT ON`.","sql":"SELECT DISTINCT customer_id, created_at FROM orders ORDER BY created_at;\n-- or one row per customer, newest first:\nSELECT DISTINCT ON (customer_id) customer_id, created_at\nFROM orders ORDER BY customer_id, created_at DESC;"}],"diagnostic":"-- What unique indexes exist on the target table?\nSELECT indexname, indexdef\nFROM pg_indexes\nWHERE tablename = 'c_users' AND schemaname = 'public';\n\n-- Constraints, which shows whether the unique source is a constraint or a bare index\nSELECT conname, contype, pg_get_constraintdef(oid)\nFROM pg_constraint\nWHERE conrelid = 'c_users'::regclass;\n\n-- Compare with the exact column list in your ON CONFLICT clause, including order.\n-- For SELECT DISTINCT errors, check each ORDER BY expression against the select list.","alternatives":"If you cannot add a unique index, ON CONFLICT has nothing to key on: use update-first-then-insert, or lock and check inside a transaction. If the index is on an expression like lower(email), write ON CONFLICT (lower(email)). For DISTINCT, either add the ORDER BY column to the select list or use GROUP BY, which allows ordering by any column of the grouped result.","details":[],"details_title":null,"repro":"CREATE TEMP TABLE u (email text);\nINSERT INTO u VALUES ('a') ON CONFLICT (email) DO NOTHING;  -- ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification","repro_note":null,"related":["postgresql/23505","postgresql/42830","postgresql/23P01","postgresql/21000"],"sqlly":null,"faqs":[{"question":"Why does ON CONFLICT (email) fail when a unique index on lower(email) exists?","answer":"The clause must match the index expression. Write ON CONFLICT (lower(email)), or use a unique constraint instead of an expression index if you want to target it by name with ON CONFLICT ON CONSTRAINT."},{"question":"Does ON CONFLICT use a partial unique index?","answer":"Yes, but only when the INSERT repeats the index's WHERE predicate, so the conflict target describes the same set of rows as the index."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P10","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/42P18","corpus":"errors","engine":"postgresql","language":"en","title":"could not determine data type of parameter","description":"PostgreSQL couldn't infer a bound parameter's type from where it is used, for example `$1 IS NULL` on its own. Add an explicit cast.","body":{"code":"42P18","slug":"42P18","name":"indeterminate_datatype","message":"could not determine data type of parameter $1","group":"42","severity":null,"sql_state":null,"summary":"PostgreSQL couldn't infer a bound parameter's type from where it is used, for example `$1 IS NULL` on its own. Add an explicit cast.","meaning":"When a statement with placeholders is prepared, PostgreSQL works out each parameter's type from its context, such as the column it is compared with. If the context gives no clue (`SELECT $1`, `$1 IS NULL`, `$1 || 'x'` with an unknown type, a parameter passed to an overloaded function) and the driver sent the parameter as untyped, preparing fails with 42P18 (`indeterminate_datatype`).\n\nA cast on the placeholder tells PostgreSQL the type and fixes it.","causes":["A parameter used only in the select list or in `IS NULL` checks, such as optional filters written as `($1 IS NULL OR col = $1)`.","A parameter passed to a function with several overloads.","A driver that sends all parameters with an unspecified type."],"fix":[{"text":"Cast the placeholder to the intended type.","sql":"SELECT * FROM orders\nWHERE ($1::int IS NULL OR customer_id = $1::int);"},{"text":"Or have the driver send typed parameters; most drivers have a way to bind a value with an explicit type.","sql":null}],"diagnostic":"-- Find where the parameter is used. If it appears in the select list, in\n-- ORDER BY, or only in `IS NULL` / `IS NOT NULL`, PostgreSQL has no other\n-- expression to infer its type from.\n\n-- Overloads make this likelier: show what the name could resolve to. When\n-- more than one candidate accepts an unknown argument, the choice is\n-- ambiguous and the prepare is refused.\nSELECT p.oid::regprocedure\nFROM pg_proc p\nJOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.proname = 'your_function' AND n.nspname = ANY (current_schemas(true));\n\n-- What did the driver declare? Statements that prepare successfully are\n-- listed in pg_prepared_statements with their resolved parameter_types, but\n-- this error means the prepare never got that far, so the server has nothing\n-- to show. Read the types on your side instead: the driver's protocol\n-- tracing where it has one, or a packet capture; Wireshark's PostgreSQL\n-- dissector prints each Parse frame with its parameter type OIDs.","alternatives":"Cast the parameter at its use site: `$1::int`, or state the type in a dummy comparison such as `($1::text IS NULL OR col = $1)`. Some drivers also let you send explicit parameter type OIDs, which fixes it without touching the SQL. When the trick pattern is `($1 IS NULL OR col = $1)`, casting just the first occurrence is enough.","details":[],"details_title":null,"repro":"PREPARE p AS SELECT 1 WHERE $1 IS NULL;  -- ERROR: 42P18 could not determine data type of parameter $1","repro_note":null,"related":["postgresql/42P02","postgresql/42883","postgresql/42804"],"sqlly":null,"faqs":[{"question":"Why does the same parameter work in a WHERE equality but fail in an IS NULL check?","answer":"In `col = $1` the planner infers $1's type from the column. In `$1 IS NULL` there is nothing to infer from: any type is NULL-capable, so the type stays unknown and the prepared statement fails. Cast it once."},{"question":"Does this only affect prepared statements?","answer":"The error is raised when the statement is parsed with unresolved parameter types. PREPARE and the extended protocol (for example psql `\\bind`) both hit it, which is why it appears with JDBC, psycopg, and Npgsql using server-side prepares. Plain psql with literal values never has parameters to type."},{"question":"Which PostgreSQL version changed anything here?","answer":"The core behavior has been stable for years. What changed driver-side: JDBC's prepareThreshold and psycopg3's server-side binding are the usual reasons a query that ran as plain SQL starts hitting 42P18 once prepares kick in."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/42P18","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/53100","corpus":"errors","engine":"postgresql","language":"en","title":"disk full","description":"The file system holding the data directory, WAL or temporary files is full. Writes fail until space is freed; a full WAL disk can stop the server.","body":{"code":"53100","slug":"53100","name":"disk_full","message":"could not extend file \"base/16384/16397\": No space left on device\nHINT:  Check free disk space.","group":"53","severity":null,"sql_state":null,"summary":"The file system holding the data directory, WAL or temporary files is full. Writes fail until space is freed; a full WAL disk can stop the server.","meaning":"PostgreSQL got `No space left on device` from the operating system while growing a table or index file, writing temporary sort files, or writing WAL. The statement fails with 53100 (`disk_full`) and its transaction is rolled back.\n\nIf the WAL directory (`pg_wal`) fills up, the server can't write any changes and shuts down with a PANIC; it won't start again until space is freed. Never delete files from `pg_wal` by hand.","causes":["Data growth, or table and index bloat from heavy updates and deletes without enough vacuuming.","WAL piling up because a replication slot is inactive, archiving (`archive_command`) is failing, or `max_wal_size` / `wal_keep_size` are large.","A large sort, hash or `CREATE INDEX` writing temporary files.","Server logs or other files on the same volume."],"fix":[{"text":"Find what is using the space.","sql":"SELECT pg_size_pretty(pg_database_size(current_database()));\nSELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS size\nFROM pg_class WHERE relkind = 'r'\nORDER BY pg_total_relation_size(oid) DESC LIMIT 10;"},{"text":"Look for replication slots holding WAL back, and drop the ones no longer used.","sql":"SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained\nFROM pg_replication_slots;\nSELECT pg_drop_replication_slot('old_slot');"},{"text":"Check that WAL archiving succeeds.","sql":"SELECT archived_count, failed_count, last_failed_wal, last_failed_time FROM pg_stat_archiver;"},{"text":"Free or add disk space: grow the volume, remove unrelated files, or reclaim bloat with `VACUUM FULL` (which needs room for a full copy of the table) or `pg_repack`.","sql":null},{"text":"Limit temporary file use per server process so one query can't fill the disk.","sql":"ALTER SYSTEM SET temp_file_limit = '20GB';\nSELECT pg_reload_conf();"}],"diagnostic":"-- WAL usage and what is holding it:\nSELECT slot_name, active, restart_lsn,\n       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal\nFROM pg_replication_slots;\n\n-- Archiving stuck? How much is waiting?\nSELECT failed_count, archived_count, last_failed_wal, last_failed_time\nFROM pg_stat_archiver;\n\n-- Temp file usage per database (cumulative since last stats reset)\nSELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp_written\nFROM pg_stat_database WHERE datname IS NOT NULL;\n\n-- Biggest relations, for the data-growth case\nSELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS total\nFROM pg_class\nWHERE relkind IN ('r','i','m')\nORDER BY pg_total_relation_size(oid) DESC LIMIT 10;","alternatives":"On a managed instance, resize the storage; on your own server, free space elsewhere on the volume first, such as old logs or expired WAL archives. Dropping an inactive replication slot releases retained WAL right away. Keep in mind VACUUM FULL and CREATE INDEX need extra disk space, so they can fail on a nearly full disk; CREATE INDEX CONCURRENTLY still needs space for the new index, just with less locking.","details":[],"details_title":null,"repro":"-- Needs superuser and a directory on a filesystem you can fill. Linux demo:\n--   mkdir /mnt/tiny && mount -t tmpfs -o size=1m tmpfs /mnt/tiny\n--   chown postgres:postgres /mnt/tiny && chmod 700 /mnt/tiny\nCREATE TABLESPACE tiny LOCATION '/mnt/tiny';\nCREATE TABLE diskfill (x text) TABLESPACE tiny;\nINSERT INTO diskfill SELECT repeat('x', 100000) FROM generate_series(1, 100000);\n-- ERROR:  could not extend file \"pg_tblspc/...\": No space left on device\nDROP TABLE diskfill;\nDROP TABLESPACE tiny;","repro_note":"Needs superuser and a scratch filesystem; the tmpfs demo fills 1 MB and cleans up after itself.","related":["postgresql/53200","postgresql/57P01","sql-server/9002","sql-server/1105","oracle/ora-01653","sqlite/sqlite-full","mysql/1114"],"sqlly":null,"faqs":[{"question":"Can I delete files in pg_wal to free space?","answer":"No. Deleting WAL files corrupts the cluster. Drop dead replication slots, fix a failing archive_command, or free space elsewhere on the volume. If the server is down because pg_wal is full, free space on the same volume or move pg_wal to another disk via a symlink while the server is stopped."},{"question":"The error went away after I freed space. Anything else to do?","answer":"Check the server log for PANIC lines from the incident and confirm the slots and archiving are moving again. If a slot caused it, decide whether that standby is coming back before keeping it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/53100","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/53200","corpus":"errors","engine":"postgresql","language":"en","title":"out of memory","description":"A server process couldn't allocate memory for the query. Usually a huge sort or hash, a very large result built in memory, or too many busy connections.","body":{"code":"53200","slug":"53200","name":"out_of_memory","message":"out of memory\nDETAIL:  Failed on request of size 1048576 in memory context \"ExecutorState\".","group":"53","severity":null,"sql_state":null,"summary":"A server process couldn't allocate memory for the query. Usually a huge sort or hash, a very large result built in memory, or too many busy connections.","meaning":"PostgreSQL allocates memory in contexts. When the operating system refuses an allocation, the statement fails with 53200 and the `DETAIL` line names the request size and memory context. The server log gets a dump of memory context sizes that shows where the memory went.\n\nOn Linux with memory overcommit, the kernel's OOM killer may instead kill a PostgreSQL process outright; the server then restarts all sessions, and clients see their connections drop.","causes":["`work_mem` set high and multiplied by many sort and hash nodes, in many sessions at once.","A query returning or aggregating a huge amount of data in one value, such as `array_agg` or `string_agg` over millions of rows.","Too many connections for the machine's memory.","A memory leak in an extension, or very large `maintenance_work_mem` during index builds."],"fix":[{"text":"Read the memory context dump in the server log to see which context grew.","sql":null},{"text":"Lower `work_mem` globally, and raise it only for the session that needs it.","sql":"ALTER SYSTEM SET work_mem = '16MB';\nSELECT pg_reload_conf();\n-- for one heavy report:\nSET work_mem = '256MB';"},{"text":"Check the plan for hash joins and sorts over far more rows than expected, and fix the estimates or add an index.","sql":"EXPLAIN (ANALYZE, BUFFERS) SELECT ...;"},{"text":"Cap concurrency with a connection pooler, and on Linux set `vm.overcommit_memory = 2` so allocations fail cleanly instead of triggering the OOM killer.","sql":null}],"diagnostic":"-- Current memory-related settings\nSELECT name, setting, unit FROM pg_settings\nWHERE name IN ('work_mem', 'maintenance_work_mem', 'shared_buffers',\n               'max_connections', 'hash_mem_multiplier', 'temp_buffers');\n\n-- Which sessions are running right now?\nSELECT pid, usename, state, now()-query_start AS running_for,\n       left(query, 80) AS query\nFROM pg_stat_activity\nWHERE state = 'active' AND backend_type = 'client backend'\nORDER BY query_start;\n\n-- After an OOM, the server log's memory-context dump shows which context grew.\n-- On Linux, dmesg or /var/log/syslog shows whether the kernel OOM killer acted instead.","alternatives":"Lower work_mem: it applies per sort or hash node, per session, so a generous global value times many connections is the usual cause. For one heavy query, SET LOCAL work_mem = '256MB' inside its transaction. Move huge aggregations out of the database or paginate them. On Linux, vm.overcommit_memory=2 with a sane overcommit_ratio makes the kernel refuse allocations early instead of sending the OOM killer after a backend.","details":[],"details_title":null,"repro":null,"repro_note":null,"related":["postgresql/53100","postgresql/53300","postgresql/08006","sql-server/701","oracle/ora-04031"],"sqlly":"SQLly's estimated and actual plans show each sort and hash with its row counts, and flag estimates that are far from the actual rows.","faqs":[{"question":"work_mem is 64MB but the query used far more. Why?","answer":"work_mem limits one operation. A query with several sorts and hashes can use several times work_mem, and hash joins add hash_mem_multiplier on top. Multiply by active sessions for the real ceiling."},{"question":"How do I tell a kernel OOM kill from error 53200?","answer":"53200 comes back as an error with a DETAIL naming the request, and the session survives. An OOM kill drops the connection, and the log shows 'server process was terminated by signal 9' followed by crash recovery."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/53200","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/53300","corpus":"errors","engine":"postgresql","language":"en","title":"too many connections","description":"The server has reached max_connections and refuses new sessions. Usually a connection leak or pools that together open more connections than allowed.","body":{"code":"53300","slug":"53300","name":"too_many_connections","message":"sorry, too many clients already","group":"53","severity":null,"sql_state":null,"summary":"The server has reached max_connections and refuses new sessions. Usually a connection leak or pools that together open more connections than allowed.","meaning":"PostgreSQL runs one server process per connection and caps the total with `max_connections` (100 by default). When every slot is taken, a new connection fails with 53300 before it can log in.\n\nA few slots are kept back for superusers (`superuser_reserved_connections`, 3 by default) and, on PostgreSQL 16 and later, for roles in `pg_use_reserved_connections`. Ordinary roles then see `remaining connection slots are reserved for roles with the SUPERUSER attribute` (the wording varies by version) with the same code. A role or database can also have its own `CONNECTION LIMIT`, which fails with `too many connections for role \"app\"`.","causes":["An application leaks connections: it opens them and never closes or returns them to the pool.","Several app instances, each with its own pool, add up to more than `max_connections`.","Many sessions sitting `idle in transaction`, holding slots and locks.","A traffic spike, or a job that opens one connection per task."],"fix":[{"text":"See who is connected and what they are doing (connect as a superuser, who can still get in).","sql":"SELECT usename, application_name, client_addr, state, count(*)\nFROM pg_stat_activity\nGROUP BY 1, 2, 3, 4\nORDER BY count(*) DESC;"},{"text":"End sessions that are stuck idle in a transaction or that belong to a runaway client.","sql":"SELECT pg_terminate_backend(pid)\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\n  AND state_change < now() - interval '10 minutes';"},{"text":"Fix the leak or shrink the pools so their total stays under the limit, and put a pooler such as PgBouncer in front of many small clients.","sql":null},{"text":"Have the server end abandoned sessions automatically.","sql":"ALTER SYSTEM SET idle_in_transaction_session_timeout = '5min';\nSELECT pg_reload_conf();"},{"text":"Raise `max_connections` only if the server has the memory for it; it needs a restart.","sql":"ALTER SYSTEM SET max_connections = 200;  -- takes effect after restart"}],"diagnostic":"-- How close is the server to its cap? reserved_roles is NULL before PostgreSQL 16.\nSELECT (SELECT count(*) FROM pg_stat_activity) AS used,\n       current_setting('max_connections') AS max_connections,\n       current_setting('superuser_reserved_connections') AS reserved_superuser,\n       current_setting('reserved_connections', true) AS reserved_roles;\n\n-- When the message names a role, a per-role or per-database cap fired, not\n-- the server-wide one:\nSELECT rolname, rolconnlimit FROM pg_roles WHERE rolconnlimit <> -1;\nSELECT datname, datconnlimit FROM pg_database WHERE datconnlimit <> -1;","alternatives":"Size every pool against the shared budget, not against max_connections alone: three app instances with 40 slots each do not fit a 100-slot server. Put PgBouncer in transaction mode between many short-lived clients and the server; it multiplexes hundreds of client connections onto a few server slots. A migration tool that opens a connection per statement can often run against one long-lived connection instead.","details":[],"details_title":null,"repro":"-- No cluster tuning needed: a role-level CONNECTION LIMIT fails with the same SQLSTATE.\nCREATE ROLE solo LOGIN CONNECTION LIMIT 1;\n-- Session 1: connect as solo and hold the session (run a long pg_sleep).\n-- Session 2: connect as solo again.\n-- psql: error: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: FATAL:  too many connections for role \"solo\"\nDROP ROLE solo;  -- after both sessions are gone","repro_note":"Run the two sessions as the new role, then drop it.","related":["postgresql/57P03","postgresql/25P03","postgresql/28000","mysql/1040","oracle/ora-00018","oracle/ora-00020"],"sqlly":"SQLly's activity monitor lists PostgreSQL sessions with their state and wait events, so you can spot idle-in-transaction sessions and end them from the app.","faqs":[{"question":"How many connections can PostgreSQL handle?","answer":"The default max_connections is 100. Each connection is a separate process with its own memory, so hundreds of mostly idle connections are better served by a connection pooler than by a very high max_connections."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/53300","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/54000","corpus":"errors","engine":"postgresql","language":"en","title":"program limit exceeded","description":"A hard implementation limit was hit, usually a value too large for a B-tree index entry. Too many columns, select-list entries or function arguments raise 54011 or 54023.","body":{"code":"54000","slug":"54000","name":"program_limit_exceeded","message":"index row size 5016 exceeds btree version 4 maximum 2704 for index \"documents_body_idx\"\nDETAIL:  Index row references tuple (0,2) in relation \"documents\".\nHINT:  Values larger than 1/3 of a buffer page cannot be indexed.\nConsider a function index of an MD5 hash of the value, or use full text indexing.","group":"54","severity":null,"sql_state":null,"summary":"A hard implementation limit was hit, usually a value too large for a B-tree index entry. Too many columns, select-list entries or function arguments raise 54011 or 54023.","meaning":"54000 (`program_limit_exceeded`) is raised when a statement runs into one of PostgreSQL's fixed limits. The one people meet most is the B-tree entry size: an indexed value must fit in about a third of an 8 kB page (2704 bytes for current B-tree indexes), so a unique index on a long text column fails when a big value arrives.\n\nOther limits in this class include at most 1600 columns per table, 100 arguments per function, and 1664 entries in a select list. Those three raise 54011 (too_many_columns) and 54023 (too_many_arguments), not 54000.","causes":["A B-tree index (often from a `UNIQUE` constraint) on a text, jsonb or bytea column that can hold large values.","A generated query with more than 1664 select-list entries; that raises 54011 (too_many_columns), not 54000.","Calling a function with more than 100 arguments, for example a very wide `json_build_object`."],"fix":[{"text":"Index a hash of the value instead of the value itself; this enforces uniqueness for practical purposes; md5 is not collision-resistant, so use a stronger hash if inputs can be adversarial.","sql":"DROP INDEX documents_body_idx;\nCREATE UNIQUE INDEX documents_body_md5_key ON documents (md5(body));"},{"text":"For searching inside long text, use full text search or trigram indexes instead of a B-tree.","sql":"CREATE INDEX documents_body_fts ON documents USING gin (to_tsvector('english', body));"},{"text":"For very wide data, store attributes in fewer columns (`jsonb`), and build objects from rows (`to_jsonb(t)`) rather than passing hundreds of arguments.","sql":null}],"diagnostic":"-- For the B-tree limit: how large are the values you are indexing?\nSELECT max(octet_length(body)) AS max_bytes FROM documents;\n-- B-tree entries must fit in roughly a third of an 8kB page: about 2704 bytes.\n\n-- For the column-count limit (max 1600):\nSELECT count(*) FROM information_schema.columns\nWHERE table_schema = 'public' AND table_name = 'your_table';\n\n-- Function argument limit (max 100):\nSELECT proname, pronargs FROM pg_proc WHERE proname = 'your_function_name';","alternatives":"For long indexed values, index a short surrogate instead: md5(payload) or a generated hash column with the unique index on it. A GIN index handles long jsonb without the B-tree entry limit, and long text when it is indexed through an expression such as to_tsvector('english', body); a plain GIN index on text fails with 42704. GIN cannot enforce uniqueness. For very wide generated rows, split the table or fold rarely-queried fields into a jsonb column.","details":[],"details_title":null,"repro":"CREATE TABLE documents (id int primary key, body text);\nINSERT INTO documents\nSELECT i, array_to_string(array_agg(chr((random()*94+33)::int)), '')\nFROM generate_series(1,5) i, generate_series(1,5000) g\nGROUP BY i;\n-- Five distinct 5000-byte values of random characters, which do not compress.\n-- Compressible values slip under the limit: repeat(md5(random()::text), 160)\n-- builds the index fine, and five identical copies fail with 23505 instead.\nCREATE UNIQUE INDEX documents_body_idx ON documents (body);\n-- ERROR:  index row size 5016 exceeds btree version 4 maximum 2704 for index \"documents_body_idx\"\nDROP TABLE documents;","repro_note":null,"related":["postgresql/22001","postgresql/53200","mysql/1071"],"sqlly":null,"faqs":[{"question":"What is the exact B-tree size limit?","answer":"The whole index entry must fit in about 2704 bytes, a third of an 8 kB page, so the largest indexable text value is about 2692 bytes. The surprise is toasting: a text column can hold a gigabyte, but its B-tree index entry cannot."},{"question":"Is a hash index a good substitute for a unique text index?","answer":"Since PostgreSQL 10, hash indexes are WAL-logged and crash-safe, but they cannot enforce uniqueness: CREATE UNIQUE INDEX ... USING hash fails with 0A000. B-tree is the only access method that supports unique indexes, and it also gives you range scans and ordering."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/54000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/55000","corpus":"errors","engine":"postgresql","language":"en","title":"object not in prerequisite state","description":"The object isn't in the state the command needs, for example currval before nextval in a session, or a replication slot or table that isn't ready.","body":{"code":"55000","slug":"55000","name":"object_not_in_prerequisite_state","message":"currval of sequence \"orders_id_seq\" is not yet defined in this session","group":"55","severity":null,"sql_state":null,"summary":"The object isn't in the state the command needs, for example currval before nextval in a session, or a replication slot or table that isn't ready.","meaning":"55000 (`object_not_in_prerequisite_state`) means the command is valid but the object it acts on isn't ready for it. The most searched case is `currval`: it returns the value most recently produced by `nextval` in the current session, so calling it before any `nextval` (or on a pooled connection that didn't run the insert) fails.\n\nOther messages with this code include `lastval is not yet defined in this session` and errors about replication slots that are in the wrong state for the operation, such as logical decoding when `wal_level` is below `logical`.","causes":["Calling `currval` or `lastval` in a session that hasn't called `nextval`, often because a connection pool sent the `INSERT` and the `SELECT currval(...)` on different connections.","Reading the id of an inserted row with a separate query instead of `RETURNING`.","Operating on a feature that needs a setting such as `wal_level = logical`. A replication slot that is in use raises 55006 (object_in_use) instead."],"fix":[{"text":"Get generated ids from the `INSERT` itself with `RETURNING`; it works on any connection and with any number of rows.","sql":"INSERT INTO orders (customer_id) VALUES (42) RETURNING id;"},{"text":"If you must use `currval`, call it on the same connection (session) as the insert. It does not have to be in the same transaction.","sql":null},{"text":"For other messages, read the full text: it names the state that is missing, such as a setting to change or a slot to release.","sql":null}],"diagnostic":"-- Which missing state applies? Check what the message names against the server.\n-- If it involves sequences and pooling, confirm the session actually ran nextval:\nSHOW server_version;\n-- If it involves logical replication, wal_level must be 'logical':\nSELECT name, setting FROM pg_settings WHERE name IN ('wal_level', 'max_replication_slots');\n-- Slot-related messages: look at slot state here:\nSELECT slot_name, slot_type, active, active_pid FROM pg_replication_slots;","alternatives":"Use RETURNING on the INSERT instead of currval, so the generated id comes back on the same statement no matter which pooled connection runs it. For slot-state errors, drop or release the slot instead of working around it.","details":[],"details_title":null,"repro":"CREATE TEMP SEQUENCE s;\nSELECT currval('s');  -- ERROR: currval of sequence \"s\" is not yet defined in this session","repro_note":null,"related":["postgresql/55006","postgresql/42704","postgresql/23505"],"sqlly":null,"faqs":[{"question":"Why does currval work in psql but fail in my app?","answer":"In psql you run INSERT and SELECT currval on the same connection. A connection pool may hand the two statements to different connections, and currval is per-session. Use INSERT ... RETURNING id instead."},{"question":"Does lastval have the same restriction?","answer":"Yes. lastval returns the value from the most recent nextval in the session and errors with this code if none has run yet."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/55000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/55006","corpus":"errors","engine":"postgresql","language":"en","title":"object in use","description":"The object can't be changed while others use it, typically DROP DATABASE, ALTER DATABASE RENAME or a template copy while sessions are connected.","body":{"code":"55006","slug":"55006","name":"object_in_use","message":"database \"shop\" is being accessed by other users\nDETAIL:  There is 1 other session using the database.","group":"55","severity":null,"sql_state":null,"summary":"The object can't be changed while others use it, typically DROP DATABASE, ALTER DATABASE RENAME or a template copy while sessions are connected.","meaning":"Some operations need exclusive use of an object. Dropping or renaming a database, or creating a database from a template, requires that no other session is connected to it, and PostgreSQL reports 55006 (`object_in_use`) with the number of other sessions. The same code appears for tables in use by the current session, for example `cannot ALTER TABLE \"t\" because it is being used by active queries in this session`.\n\nYour own connection counts too: you can't drop the database you are connected to.","causes":["Application connections, connection pools, monitoring tools or GUI clients are still connected to the database.","You are connected to the database you're trying to drop.","Creating a database from a template database that has open connections."],"fix":[{"text":"Connect to another database (such as `postgres`), then see who is connected.","sql":"SELECT pid, usename, application_name, client_addr\nFROM pg_stat_activity WHERE datname = 'shop';"},{"text":"On PostgreSQL 13 and later, drop the database and terminate its sessions in one step.","sql":"DROP DATABASE shop WITH (FORCE);"},{"text":"On older versions, block new connections, terminate existing ones, then drop.","sql":"ALTER DATABASE shop ALLOW_CONNECTIONS false;\nSELECT pg_terminate_backend(pid) FROM pg_stat_activity\nWHERE datname = 'shop' AND pid <> pg_backend_pid();\nDROP DATABASE shop;"}],"diagnostic":"-- Run this from another database, such as postgres, to see exactly who is holding it:\nSELECT pid, usename, application_name, client_addr, backend_start, state, query\nFROM pg_stat_activity\nWHERE datname = 'shop' AND pid <> pg_backend_pid();\n-- If the only session listed is your own tool, connect elsewhere and retry.","alternatives":"On PostgreSQL 13 and later, DROP DATABASE ... WITH (FORCE) terminates the other sessions and drops in one step. If you cannot kick sessions out, wait for a maintenance window, or create a copy with CREATE DATABASE ... TEMPLATE instead of renaming the original.","details":[],"details_title":null,"repro":"-- Session 1:\nCREATE DATABASE shop_repro;\n\\c shop_repro\n-- Session 2 (connected to postgres):\nDROP DATABASE shop_repro;  -- ERROR: database \"shop_repro\" is being accessed by other users\n-- Session 1, after \\c postgres:\nDROP DATABASE shop_repro;","repro_note":null,"related":["postgresql/57P01","postgresql/55P03","postgresql/3D000","sql-server/3702","sql-server/3101"],"sqlly":"SQLly's activity monitor lists the sessions connected to each PostgreSQL database and can end them, so you can clear a database before dropping or renaming it.","faqs":[{"question":"The count in the DETAIL says 1 other session but I see nothing running. What is it?","answer":"Usually an idle connection from a pool, a GUI client, or a monitoring agent. pg_stat_activity shows it with state 'idle' and the application_name and client_addr tell you who owns it."},{"question":"Can I drop a database while connected to it?","answer":"No. PostgreSQL refuses because your own session would be inside a database being deleted. Connect to postgres or another database first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/55006","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/55P03","corpus":"errors","engine":"postgresql","language":"en","title":"lock not available","description":"A lock request gave up instead of waiting: NOWAIT was used, or lock_timeout expired while another session held a conflicting lock.","body":{"code":"55P03","slug":"55P03","name":"lock_not_available","message":"could not obtain lock on row in relation \"orders\"","group":"55","severity":null,"sql_state":null,"summary":"A lock request gave up instead of waiting: NOWAIT was used, or lock_timeout expired while another session held a conflicting lock.","meaning":"Normally PostgreSQL waits as long as it takes for a lock. 55P03 means the statement was told not to: `SELECT ... FOR UPDATE NOWAIT` or `LOCK TABLE ... NOWAIT` fail immediately if the lock is taken, and when `lock_timeout` is set any statement fails once it has waited that long. A lock timeout reports `canceling statement due to lock timeout` with the same code.\n\nThe other session holding the lock is not affected. Inside a transaction block, the failed statement aborts the transaction.","causes":["`FOR UPDATE NOWAIT`, `FOR SHARE NOWAIT` or `LOCK TABLE ... NOWAIT` hit a row or table another transaction has locked.","A `lock_timeout` expired, typically on DDL such as `ALTER TABLE`, which needs an exclusive lock and waits behind long-running queries.","A long transaction or a session left idle in a transaction holding locks."],"fix":[{"text":"Find the session that holds the lock.","sql":"SELECT pid, usename, state, xact_start, query\nFROM pg_stat_activity\nWHERE pid IN (\n    SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity\n);"},{"text":"For job queues, skip locked rows instead of failing.","sql":"SELECT id FROM jobs\nWHERE status = 'queued'\nORDER BY id\nLIMIT 10\nFOR UPDATE SKIP LOCKED;"},{"text":"For schema changes, use a short `lock_timeout` deliberately and retry, so the `ALTER` doesn't queue behind a long query and block everyone else.","sql":"SET lock_timeout = '3s';\nALTER TABLE orders ADD COLUMN note text;"},{"text":"End or shorten the blocking transaction; if it is abandoned, terminate it.","sql":"SELECT pg_terminate_backend(12345);  -- the blocking pid"}],"diagnostic":"-- Who blocked the statement? From any session:\nSELECT pid, usename, state, xact_start, query\nFROM pg_stat_activity\nWHERE cardinality(pg_blocking_pids(pid)) > 0;\n-- Raw view if you want lock-level detail:\nSELECT l.pid, l.locktype, l.relation::regclass, l.mode, l.granted\nFROM pg_locks l WHERE NOT l.granted;","alternatives":"Use SKIP LOCKED for worker queues so concurrent workers never fight over rows. If NOWAIT is only there to avoid hanging forever, a lock_timeout of a few seconds is usually friendlier: the statement waits briefly and gives a clear error instead of failing on the first attempt.","details":[],"details_title":null,"repro":"-- Session 1:\nCREATE TABLE q (id int PRIMARY KEY);\nINSERT INTO q VALUES (1);\nBEGIN; SELECT * FROM q WHERE id = 1 FOR UPDATE;\n-- Session 2:\nSELECT * FROM q WHERE id = 1 FOR UPDATE NOWAIT;  -- ERROR: could not obtain lock on row in relation \"q\"","repro_note":"Run in two connections; end session 1 with ROLLBACK afterwards.","related":["postgresql/40P01","postgresql/57014","postgresql/55006","sql-server/1222","mysql/1205","mysql/3572","oracle/ora-00054","sqlite/sqlite-busy"],"sqlly":"SQLly's activity monitor shows PostgreSQL blocking chains, so you can see which session holds the lock and end it from the app.","faqs":[{"question":"Did my NOWAIT query lock anything itself?","answer":"No. If the lock cannot be acquired immediately the statement fails and acquires nothing, though the surrounding transaction is now aborted and must be rolled back."},{"question":"Is 'canceling statement due to lock timeout' a different error?","answer":"It is the same SQLSTATE 55P03. It happens when the statement did wait, but lock_timeout ran out before the lock became available."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/55P03","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/57014","corpus":"errors","engine":"postgresql","language":"en","title":"canceling statement","description":"The query was cancelled, either because it ran past statement_timeout or because a client or administrator sent a cancel request.","body":{"code":"57014","slug":"57014","name":"query_canceled","message":"canceling statement due to statement timeout","group":"57","severity":null,"sql_state":null,"summary":"The query was cancelled, either because it ran past statement_timeout or because a client or administrator sent a cancel request.","meaning":"57014 means the running statement was cancelled before it finished. The message says why: `canceling statement due to statement timeout` when it ran longer than `statement_timeout`, and `canceling statement due to user request` when a client pressed cancel (Ctrl+C in psql, a driver's cancel call) or someone ran `pg_cancel_backend()` on it.\n\nOnly the statement is cancelled; the session stays connected. Inside a transaction block the transaction is now failed and must be rolled back.","causes":["A `statement_timeout` set on the server, database, role or session that the query exceeded.","You or your tool cancelled the query.","An administrator or monitoring job cancelled it with `pg_cancel_backend(pid)`.","A slow query: a missing index, a bad plan, or waiting on a lock until the timeout fired."],"fix":[{"text":"Check which timeout applies and where it was set.","sql":"SHOW statement_timeout;\nSELECT name, setting, source FROM pg_settings WHERE name = 'statement_timeout';"},{"text":"Raise it for the one session or transaction that legitimately needs longer, rather than globally.","sql":"SET statement_timeout = '10min';\n-- or only for this transaction:\nBEGIN;\nSET LOCAL statement_timeout = '10min';\n-- long-running work\nCOMMIT;"},{"text":"Make the query faster: look at its plan for sequential scans on big tables and add the index it needs.","sql":"EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 42;"},{"text":"If it was waiting on a lock, find the blocker.","sql":"SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, query\nFROM pg_stat_activity\nWHERE cardinality(pg_blocking_pids(pid)) > 0;"}],"diagnostic":"-- Which timeout fired, and where was it set? The source column says who set\n-- it: 'user' means SET in this session or by the driver, 'database' or\n-- 'role' means ALTER DATABASE or ALTER ROLE set it for many sessions,\n-- 'configuration file' means postgresql.conf or ALTER SYSTEM.\nSELECT name, setting, source, sourcefile\nFROM pg_settings\nWHERE name IN ('statement_timeout', 'lock_timeout', 'idle_in_transaction_session_timeout')\n  AND source <> 'default';","alternatives":"Run heavy batch work under SET LOCAL statement_timeout inside its own transaction so only that transaction gets the larger limit. If cancels come from a monitoring job, tune its threshold instead of the query. pg_cancel_backend cancels one statement, pg_terminate_backend kills the whole session; prefer the former.","details":[],"details_title":null,"repro":"SET statement_timeout = '1s';\nSELECT pg_sleep(5);  -- ERROR: canceling statement due to statement timeout\nRESET statement_timeout;","repro_note":null,"related":["postgresql/55P03","postgresql/57P01","postgresql/25P02","mysql/3024"],"sqlly":"SQLly's Cancel sends a real server-side cancel request to PostgreSQL, so the backend stops working instead of only the client giving up, and each connection can have its own statement timeout. Estimated and actual plans show where a slow query spends its time, with findings such as missing indexes.","faqs":[{"question":"My query got 'canceling statement due to user request' but I did not cancel anything.","answer":"Something on the client or server issued a cancel: a driver timeout, Ctrl+C, an ORM's command timeout, or someone ran pg_cancel_backend on the pid. Check the driver's timeout settings first."},{"question":"After a cancel inside a transaction, can I keep going with more statements?","answer":"No. The transaction is in an aborted state and every following statement errors with 25P02 until you ROLLBACK (COMMIT also ends it, reporting ROLLBACK)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/57014","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/57P01","corpus":"errors","engine":"postgresql","language":"en","title":"terminating connection due to administrator","description":"The server ended this session: an administrator called pg_terminate_backend, or the server is shutting down. Reconnect and retry.","body":{"code":"57P01","slug":"57P01","name":"admin_shutdown","message":"terminating connection due to administrator command","group":"57","severity":null,"sql_state":null,"summary":"The server ended this session: an administrator called pg_terminate_backend, or the server is shutting down. Reconnect and retry.","meaning":"57P01 (`admin_shutdown`) is sent as a `FATAL` error just before the server closes the connection. It happens when someone runs `pg_terminate_backend()` on the session, when the server is stopped with a fast shutdown, or when a managed service restarts or fails over the instance.\n\nAny transaction that was in progress on the session is rolled back. The client's next use of the connection fails, so pools should discard it and open a new one.","causes":["An administrator or a script ran `pg_terminate_backend(pid)`, for example to clear idle sessions or locks.","The server is shutting down or restarting (`pg_ctl stop -m fast`, maintenance, upgrade).","A managed PostgreSQL service failed over or applied maintenance."],"fix":[{"text":"Reconnect and, if the work was in a transaction, run the whole transaction again.","sql":null},{"text":"Configure the connection pool to test connections or retry once on a new connection after this error.","sql":null},{"text":"If sessions are being terminated unexpectedly, check the server log and any jobs that call `pg_terminate_backend`.","sql":"SELECT pid, usename, query FROM pg_stat_activity WHERE query ILIKE '%pg_terminate_backend%';"}],"diagnostic":"-- The server log is the main tool: the terminated backend logs FATAL 57P01 under its own pid, but the log does not name the session that called pg_terminate_backend. From SQL, find terminators that are still running:\nSELECT pid, usename, client_addr, backend_start, query\nFROM pg_stat_activity\nWHERE query ILIKE '%pg_terminate_backend%';\n-- If it coincides with a restart, check uptime and recovery state:\nSELECT pg_postmaster_start_time(), pg_is_in_recovery();","alternatives":"To clear long-running sessions more gently, use pg_cancel_backend, which cancels the current statement but leaves the connection alive. If maintenance restarts cause this regularly, drain connections first and make the pool retry on reconnect.","details":[],"details_title":null,"repro":"-- From any session with permission:\nSELECT pg_terminate_backend(pg_backend_pid());\n-- FATAL: terminating connection due to administrator command (SQLSTATE 57P01 with VERBOSITY verbose)","repro_note":null,"related":["postgresql/57P03","postgresql/08006","postgresql/57014","postgresql/55006"],"sqlly":null,"faqs":[{"question":"Is 57P01 a bug or a sign of a crash?","answer":"No. It is the normal way the server tells a client the session was ended on purpose, by pg_terminate_backend or a shutdown. A backend crash reports a different message and triggers crash recovery; other sessions on the server get SQLSTATE 57P02 (crash_shutdown)."},{"question":"Do I need to reconnect or will the pool do it?","answer":"The connection is gone for good. Most pools notice and open a replacement, but test yours: a pool that returns the dead connection to the caller surfaces this error to the application."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/57P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/57P03","corpus":"errors","engine":"postgresql","language":"en","title":"cannot connect now","description":"The server is up but not accepting connections yet: still starting, recovering after a crash, or shutting down. Wait and retry.","body":{"code":"57P03","slug":"57P03","name":"cannot_connect_now","message":"the database system is starting up","group":"57","severity":null,"sql_state":null,"summary":"The server is up but not accepting connections yet: still starting, recovering after a crash, or shutting down. Wait and retry.","meaning":"57P03 (`cannot_connect_now`) is returned at login while the server is in a state where it can't serve sessions. The message says which: `the database system is starting up`, `the database system is in recovery mode` (replaying WAL after a crash), `the database system is shutting down`, or `the database system is not yet accepting connections` on a standby that hasn't reached a consistent state, or `the database system is not accepting connections` (DETAIL `Hot standby mode is disabled.`) on a standby with `hot_standby = off`.\n\nIt is temporary. After a crash, recovery time depends on how much WAL has to be replayed since the last checkpoint.","causes":["The server was just started or restarted.","A backend crashed, and the server is restarting all sessions and running crash recovery.","A standby is still catching up, or `hot_standby` is off so it never accepts read-only connections.","The server is shutting down."],"fix":[{"text":"Wait a moment and reconnect; have clients retry with a backoff.","sql":null},{"text":"If it keeps happening, read the server log for the reason the server restarted, such as a crash or an out-of-memory kill.","sql":null},{"text":"On a standby that should accept reads, make sure `hot_standby = on` (the default) and wait for it to reach a consistent recovery state.","sql":null}],"diagnostic":"-- While retrying, check from the host (or a session that gets through):\n--   pg_ctl status / systemctl status postgresql\n-- From SQL once a connection succeeds:\nSELECT pg_is_in_recovery(), pg_postmaster_start_time();\n-- Recovery progress after a crash is in the server log: look for 'redo' and 'database system is ready to accept connections'.\n-- On a standby, confirm it is meant to accept reads:\nSELECT name, setting FROM pg_settings WHERE name IN ('hot_standby');","alternatives":"Point clients at another node while one restarts, such as a hot standby or a load balancer health check. If startup takes too long after crashes, shorten checkpoint intervals so less WAL has to be replayed. Nothing can make the server accept connections before recovery finishes.","details":[],"details_title":null,"repro":"-- Needs a scratch cluster. Start it and connect while WAL replay is running:\n--   pg_ctl -D /tmp/scratch -l /tmp/scratch.log start\n-- Connections inside that window fail with:\n--   psql: error: FATAL:  the database system is starting up\n-- The window lasts as long as replay needs to reach a consistent state.","repro_note":"Run against a scratch cluster; the window closes when WAL replay finishes.","related":["postgresql/57P01","postgresql/08001","postgresql/53300","oracle/ora-01034"],"sqlly":null,"faqs":[{"question":"How long does 'the database system is starting up' last?","answer":"Usually seconds. After an unclean shutdown it lasts as long as crash recovery needs to replay WAL since the last checkpoint, which can be minutes if the checkpoint interval is long."},{"question":"Should clients retry on this error?","answer":"Yes, with backoff and a cap. It is one of the few errors where retrying the connection is the right response."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/57P03","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/58P01","corpus":"errors","engine":"postgresql","language":"en","title":"undefined file","description":"A file the server tried to open doesn't exist on the database server, typically COPY FROM a path that exists only on your machine, or a missing extension library.","body":{"code":"58P01","slug":"58P01","name":"undefined_file","message":"could not open file \"/tmp/orders.csv\" for reading: No such file or directory","group":"58","severity":null,"sql_state":null,"summary":"A file the server tried to open doesn't exist on the database server, typically COPY FROM a path that exists only on your machine, or a missing extension library.","meaning":"58P01 (`undefined_file`) means PostgreSQL got \"no such file\" from the operating system. The important detail is where: server-side `COPY ... FROM '/path'`, `pg_read_file()` and `CREATE EXTENSION` look on the database server's file system, not on the client running the query.\n\nThe other frequent case is a missing shared library, `could not access file \"$libdir/postgis-3\": No such file or directory`, after an upgrade or on a server where an extension's package isn't installed.","causes":["`COPY FROM` with a path on your laptop while the server runs on another machine or in a container.","A relative path, which the server resolves against its data directory.","An extension's package isn't installed on the server, or is for a different major version after `pg_upgrade`.","`shared_preload_libraries` lists a library that isn't installed."],"fix":[{"text":"Load client-side files with psql's `\\copy`, which reads the file on the client and streams it to the server.","sql":"\\copy orders FROM 'orders.csv' WITH (FORMAT csv, HEADER true)"},{"text":"Or stream from the client with your driver's `COPY FROM STDIN` support.","sql":null},{"text":"Install the extension's package for the server's major version (for example `postgresql-16-postgis-3`), then create or update the extension.","sql":"CREATE EXTENSION postgis;\nALTER EXTENSION postgis UPDATE;"}],"diagnostic":"-- Is it a missing extension library? Compare installed vs available:\nSELECT name, default_version, installed_version FROM pg_available_extensions WHERE name = 'postgis';\nSELECT * FROM pg_extension WHERE extname = 'postgis';\n-- Is it a shared_preload_libraries entry the server cannot find?\nSELECT name, setting, source FROM pg_settings WHERE name = 'shared_preload_libraries';\n-- Remember the path in the error is looked up on the server host, not your machine:\nSELECT setting FROM pg_settings WHERE name = 'data_directory';","alternatives":"For client files, use \\copy in psql or your driver's COPY FROM STDIN, which need no server file access at all. For extensions, install the package matching the server's major version, or use pg_upgrade's extension handling so old $libdir paths are updated.","details":[],"details_title":null,"repro":"-- Needs superuser or the pg_read_server_files role, because the path is on the server.\nCREATE TABLE t (id int);\nCOPY t FROM '/tmp/definitely-not-there.csv' WITH (FORMAT csv);  -- ERROR: could not open file ... No such file or directory","repro_note":null,"related":["postgresql/42704","postgresql/42501","postgresql/22P02"],"sqlly":"SQLly's CSV import reads the file on your machine and previews the parsed rows, listing values that won't convert, before inserting them into the table.","faqs":[{"question":"The file exists on my machine. Why does COPY not find it?","answer":"Server-side COPY reads paths on the database server. In a container or managed service that is a different file system. Use \\copy or COPY FROM STDIN to send a client file."},{"question":"After pg_upgrade, extensions fail with 'could not access file $libdir/...'. Why?","answer":"The extension binary for the old major version is not installed on the new server. Install the matching package on the new server. pg_upgrade reports extension updates and writes a script to run them later."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/58P01","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/P0001","corpus":"errors","engine":"postgresql","language":"en","title":"raise exception","description":"A PL/pgSQL RAISE EXCEPTION without its own SQLSTATE. The message is whatever text the function or trigger author wrote.","body":{"code":"P0001","slug":"P0001","name":"raise_exception","message":"insufficient funds for account 42","group":"P0","severity":null,"sql_state":null,"summary":"A PL/pgSQL RAISE EXCEPTION without its own SQLSTATE. The message is whatever text the function or trigger author wrote.","meaning":"P0001 (`raise_exception`) is the default code for `RAISE EXCEPTION 'message'` in PL/pgSQL. It isn't a PostgreSQL error as such: a function, procedure or trigger in your database chose to fail, and the message text comes from its code. The `CONTEXT` lines show which function and line raised it.\n\nFunction authors can give a specific SQLSTATE with `USING ERRCODE`, plus `DETAIL` and `HINT`, which makes the error easier for applications to handle.","causes":["A business rule enforced in a trigger or function, such as a balance check, rejected the change.","A validation function called by the application raised an error for bad input.","An `ASSERT` failing reports a different code, P0004 (`assert_failure`)."],"fix":[{"text":"Read the `CONTEXT` lines to find the function and line, then look at its source.","sql":"SELECT pg_get_functiondef('debit_account'::regproc);"},{"text":"Fix the data or the call so the rule is satisfied, or change the rule if it is wrong.","sql":null},{"text":"When writing such checks, give them a meaningful code and detail so callers can tell them apart.","sql":"RAISE EXCEPTION 'insufficient funds for account %', p_account\n    USING ERRCODE = 'check_violation',\n          DETAIL = format('balance %s, requested %s', v_balance, p_amount);"}],"diagnostic":"-- Find which function raises it. With psql, run the failing statement after:\n--   \\set VERBOSITY verbose\n-- and read the CONTEXT lines; they name the function and line.\n-- The message usually comes from someone's RAISE. Search the stored bodies\n-- for the exact text:\nSELECT p.proname, n.nspname\nFROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\nWHERE p.prosrc ILIKE '%insufficient funds%';\n-- Then read the definition:\nSELECT pg_get_functiondef('schema_name.function_name'::regproc);","alternatives":"If the rule is right and the data is wrong, fix the data instead of the function. If you only need to bypass a check for a bulk load, the function author can add a session guard such as a GUC set with set_config, or you can drop and recreate the trigger for the duration of the load.","details":[],"details_title":null,"repro":"DO $$ BEGIN RAISE EXCEPTION 'something went wrong'; END $$;  -- ERROR:  P0001: something went wrong   (with \\set VERBOSITY verbose; default verbosity prints only \"ERROR:  something went wrong\")","repro_note":null,"related":["postgresql/23514","postgresql/25P02","postgresql/XX000"],"sqlly":null,"faqs":[{"question":"Is P0001 always a custom error?","answer":"Almost. It is the default for RAISE EXCEPTION without ERRCODE, so it comes from PL/pgSQL code in your database, not from PostgreSQL core rejecting the statement."},{"question":"Can my application tell custom business errors apart from real errors?","answer":"Yes, if the function sets a code with USING ERRCODE. Without it everything arrives as P0001 with only the message text to distinguish, which is why a specific SQLSTATE is worth adding."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/P0001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/XX000","corpus":"errors","engine":"postgresql","language":"en","title":"internal error","description":"PostgreSQL hit a condition its developers treat as can't-happen. Often a race with concurrent DDL, sometimes a bug or corruption. Note the details.","body":{"code":"XX000","slug":"XX000","name":"internal_error","message":"cache lookup failed for relation 16397","group":"XX","severity":null,"sql_state":null,"summary":"PostgreSQL hit a condition its developers treat as can't-happen. Often a race with concurrent DDL, sometimes a bug or corruption. Note the details.","meaning":"XX000 (`internal_error`) is the code for internal errors raised with `elog(ERROR, ...)`, which PostgreSQL uses for conditions that shouldn't occur in normal operation. Messages are terse and technical, such as `cache lookup failed for relation 16397`, `could not find pathkey item to sort` or `unexpected chunk number`.\n\nSome are triggered by a table or function being dropped while another session was using it. Others point to a bug in PostgreSQL or an extension, or to data corruption, especially when they repeat on the same object.","causes":["Concurrent DDL: an object dropped or recreated while another session's query referred to it by OID.","A bug in PostgreSQL or an extension, often fixed in a later minor release.","Corrupted catalog or table data after a hardware or storage failure."],"fix":[{"text":"Retry the statement. If it was a race with DDL, it succeeds once the other change has finished.","sql":null},{"text":"Check that the server runs the latest minor release for its major version; minor releases fix many internal errors.","sql":"SELECT version();"},{"text":"If the error repeats on one table, check it for corruption (the `amcheck` extension verifies B-tree indexes and, since PostgreSQL 14, heap tables with `pg_amcheck`), and restore from backup if needed.","sql":"CREATE EXTENSION IF NOT EXISTS amcheck;\nSELECT bt_index_check('orders_pkey');"},{"text":"If you can reproduce it, report it to the PostgreSQL bugs list with the version, the full error with `\\set VERBOSITY verbose`, and a script.","sql":null}],"diagnostic":"-- Decode the OID in the message, e.g. 'cache lookup failed for relation 16397':\nSELECT oid, relname, relkind FROM pg_class WHERE oid = 16397;\n-- An empty result means the object was dropped, which points at concurrent DDL.\n-- Re-run the statement with full detail to capture the exact source location:\n--   \\set VERBOSITY verbose\n-- If it repeats on the same object, check that object for damage:\nCREATE EXTENSION IF NOT EXISTS amcheck;\nSELECT bt_index_check('orders_pkey');","alternatives":"If the query only fails under concurrency, serialize the DDL and queries briefly, or retry the statement. On managed services, restart can clear an in-memory state problem, but do that only after copying the log output. Persistent errors on one object point at restore-from-backup territory, not workarounds.","details":[],"details_title":null,"repro":null,"repro_note":null,"related":["postgresql/P0001","postgresql/53200","postgresql/58P01"],"sqlly":null,"faqs":[{"question":"Should I file a bug for every XX000?","answer":"No. Ones tied to a race with DDL go away on retry. Report it if it reproduces on a current minor release with a script, or repeats with no obvious cause."},{"question":"Does XX000 mean my data is corrupt?","answer":"Usually not. Most cases are dropped objects or fixed bugs. Corruption is the suspect when the same error repeats on the same table or index, or XX001 shows up too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/XX000","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/postgresql/XX001","corpus":"errors","engine":"postgresql","language":"en","title":"data corrupted","description":"PostgreSQL read a data page that fails its sanity or checksum checks. Treat it as storage corruption: protect the data, then restore or salvage.","body":{"code":"XX001","slug":"XX001","name":"data_corrupted","message":"invalid page in block 1234 of relation base/16384/16397","group":"XX","severity":null,"sql_state":null,"summary":"PostgreSQL read a data page that fails its sanity or checksum checks. Treat it as storage corruption: protect the data, then restore or salvage.","meaning":"XX001 (`data_corrupted`) means a page read from disk is not valid: its header is garbage, its checksum doesn't match (when data checksums are enabled), or a file is shorter than the table needs (`could not read block ... read only 0 of 8192 bytes`). The file path in the message (`base/<database oid>/<relfilenode>`) identifies the table or index.\n\nPostgreSQL itself very rarely causes this. The usual sources are failing disks or controllers, storage that lies about flushing writes, a crash on hardware without proper write ordering, or files copied or restored inconsistently.","causes":["Hardware or storage faults: disks, RAID controllers, SAN or cloud volumes.","Write caching that doesn't honor `fsync`, followed by a power loss or crash.","`fsync = off` or `full_page_writes = off` in production.","A backup taken by copying the data directory without `pg_basebackup` or the backup API, or files changed by other software."],"fix":[{"text":"Stop and take a file-level copy of the whole data directory before trying any repair, so nothing you do can make it worse.","sql":null},{"text":"Find which object the file belongs to.","sql":"SELECT relname, relkind FROM pg_class WHERE relfilenode = 16397;"},{"text":"If it is an index, rebuild it.","sql":"REINDEX INDEX CONCURRENTLY orders_pkey;"},{"text":"If it is a table, restore it from a backup or a replica. As a last resort to salvage the readable rows, `zero_damaged_pages = on` makes PostgreSQL skip bad pages (losing their rows) while you copy the table out.","sql":"SET zero_damaged_pages = on;  -- superuser, salvage only\nCREATE TABLE orders_salvage AS SELECT * FROM orders;\nRESET zero_damaged_pages;"},{"text":"Check the hardware and storage logs, and enable data checksums on new clusters (`initdb --data-checksums`, or `pg_checksums --enable` on a stopped cluster) so corruption is detected early.","sql":null}],"diagnostic":"-- Map the relfilenode in the message (base/16384/16397) to the object:\nSELECT relname, relkind FROM pg_class WHERE relfilenode = 16397;\n-- relkind 'i' means an index: rebuilding it is safe. 'r' means table data.\n-- With checksums enabled, pg_checksums on a stopped cluster reports bad blocks:\n--   pg_checksums --check -D /path/to/data\n-- Since PostgreSQL 14, check heap and index health without stopping:\n--   pg_amcheck --database=shop --heapallindexed\n-- A different OID in the path? That is the database:\nSELECT datname FROM pg_database WHERE oid = 16384;","alternatives":"If a replica is healthy, read from it while you rebuild or restore the primary. An index can be rebuilt with no data loss, so try REINDEX before anything else. For table pages there is no in-place repair: restore from backup, or salvage readable rows into a new table with zero_damaged_pages as a last resort.","details":[],"details_title":null,"repro":null,"repro_note":null,"related":["postgresql/XX000","postgresql/58P01","postgresql/53100","sql-server/824","sqlite/sqlite-corrupt"],"sqlly":null,"faqs":[{"question":"Can I just ignore one bad page?","answer":"No. Bad pages tend to spread as the hardware degrades, and backups taken from a corrupt cluster are corrupt too. Copy the data directory first, then fix the storage and restore."},{"question":"How do I get data checksums on an existing cluster?","answer":"Checksums are chosen at initdb time. On a stopped cluster, pg_checksums --enable (PostgreSQL 12 and later) can turn them on, after verifying with --check. The cluster must be stopped cleanly."},{"question":"REINDEX fixed it. Was my data corrupt?","answer":"Likely only the index file was damaged, and the table data is fine. Rebuilds copy from the table, so a successful REINDEX of the broken index is a good sign, but still check the storage for the cause."}],"aliases":[]},"source_url":"https://sqlly.app/errors/postgresql/XX001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/ask","corpus":"errors","engine":"redis","language":"en","title":"The key is migrating to another node","description":"The key's slot is being moved to another node: re-send there once, prefixed with ASKING, while the migration finishes.","body":{"code":"ASK","slug":"ask","name":null,"message":"ASK 12182 127.0.0.1:7002","group":"cluster","severity":null,"sql_state":null,"summary":"The key's slot is being moved to another node: re-send there once, prefixed with ASKING, while the migration finishes.","meaning":"ASK looks like MOVED but means something narrower: this node still owns the slot, but the key you asked for is being migrated to another node right now, and that node is its temporary home. The client is expected to re-send the command to the target, preceded by an ASKING command, for this one request only.\n\nThe distinction matters: MOVED updates the client's slot map permanently, while ASK must not, because the slot still belongs to the source node for every other key. You meet ASK mainly while a resharding job is running (redis-cli --cluster reshard) or during a slot import, and clients handle it themselves. Seeing it by hand usually means you are mid-migration on a test cluster.","causes":["A resharding job is moving the key's slot from this node to another one.","A migration was started and interrupted, leaving the slot flagged MIGRATING.","A hand-rolled or naive client does not send ASKING after an ASK redirect, so the target refuses the follow-up."],"fix":[{"text":"See the migration state of the slots on this node:","sql":"redis-cli -p 7000 CLUSTER NODES | grep '\\['\n# Lines like [12182->-<id>] show slot 12182 migrating to node <id>"},{"text":"By hand, send ASKING before the command on the target node:","sql":"redis-cli -p 7002 ASKING\n# OK\nredis-cli -p 7002 GET foo"},{"text":"Let the reshard finish; it moves the remaining keys and clears the MIGRATING flag:","sql":"redis-cli --cluster reshard 127.0.0.1:7000"}],"diagnostic":"redis-cli -p 7000 CLUSTER KEYSLOT foo\nredis-cli -p 7000 CLUSTER NODES\n# The migrating marker [12182->-...] names the target node\nredis-cli -p 7000 CLUSTER COUNTKEYSINSLOT 12182","alternatives":"For planned moves of live traffic, reshard in a maintenance window; well-behaved clients see a short burst of ASK and MOVED and then a fresh slot map. Hash tags reduce how many keys any one migration disturbs.","details":[],"details_title":null,"repro":"redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 0\nredis-cli -p 7000 SET foo bar\nredis-cli -p 7000 CLUSTER SETSLOT 12182 MIGRATING <node-id-of-7002>\nredis-cli -p 7000 MIGRATE 127.0.0.1 7002 foo 0 5000\nredis-cli -p 7000 GET foo\n# (error) ASK 12182 127.0.0.1:7002\nredis-cli --cluster reshard 127.0.0.1:7000   # finishing clears the state","repro_note":"The ASK reply appears once the key itself has moved while the slot is still marked MIGRATING on the source node.","related":["redis/moved","redis/tryagain","redis/clusterdown"],"sqlly":"SQLly shows the ASK line with the slot and target endpoint verbatim, which is enough to finish a manual migration: ASKING and the command against the target node run from the same editor while the reshard does its work.","faqs":[{"question":"ASK or MOVED: when do I update the client's slot map?","answer":"On MOVED, permanently: the slot changed owner. On ASK, never: re-send that single request with ASKING and keep using the source node for everything else."},{"question":"What does ASKING actually do?","answer":"It marks the next request on that connection as 'redirected during migration', letting the importing node serve a key whose slot it does not own yet."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/ask","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/busy","corpus":"errors","engine":"redis","language":"en","title":"Server is blocked by a long script","description":"A Lua script is still running and Redis is single-threaded: until it ends or is killed, only SCRIPT KILL and SHUTDOWN NOSAVE are accepted.","body":{"code":"BUSY","slug":"busy","name":null,"message":"BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.","group":"data-type-command","severity":null,"sql_state":null,"summary":"A Lua script is still running and Redis is single-threaded: until it ends or is killed, only SCRIPT KILL and SHUTDOWN NOSAVE are accepted.","meaning":"Redis executes commands in one thread. A Lua script that runs too long, an accidental infinite loop being the classic case, blocks that thread, and every other client gets BUSY for its commands. The two escape hatches are named in the message: SCRIPT KILL from another connection stops the script if it has not written anything, and SHUTDOWN NOSAVE stops the server when it has, because a script that is mid-write cannot be undone safely.\n\nThe reply tells you the state you are in: if the script already performed writes, SCRIPT KILL refuses and the only way out is SHUTDOWN NOSAVE, losing unsaved data since the last save. That is why unbounded loops in scripts deserve the same review as unbounded loops anywhere else.","causes":["A Lua script with an unbounded loop, or a scan that never reaches its end condition.","A script calling an expensive redis.call repeatedly against a large keyspace.","A Redis Function (7+) stuck the same way; the matching kill command is FUNCTION KILL."],"fix":[{"text":"From a second connection, kill the script if it has not written:","sql":"SCRIPT KILL\n# OK - the blocked clients resume"},{"text":"If SCRIPT KILL refuses because the script already wrote, and the dataset is disposable, the last resort is:","sql":"SHUTDOWN NOSAVE"},{"text":"Fix the script afterwards: bound every loop, limit ranges, and test long scripts on a scratch instance first.","sql":null}],"diagnostic":"CONFIG GET busy-reply-threshold\n# How long a script may run before BUSY replies start (milliseconds, default 5000). Answered only when no script is blocking the server.\nSCRIPT KILL\n# The server's reply tells you whether a kill is possible. CLIENT LIST is refused with BUSY while the script runs, so it cannot locate the connection at that point.","alternatives":"Keep scripts short and move large loops into the client, where blocking one thread is not the price. Set busy-reply-threshold low in development so runaway scripts surface in testing, and reach for Redis Functions only with the same loop discipline.","details":[],"details_title":null,"repro":"redis-server --port 7304 --save '' &\nredis-cli -p 7304 EVAL \"while true do end\" 0 &\nredis-cli -p 7304 PING\n# (error) BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\nredis-cli -p 7304 SCRIPT KILL\n# OK","repro_note":"Run this only against a scratch instance: until SCRIPT KILL lands, that server answers nothing else.","related":["redis/noscript","sqlite/sqlite-busy","postgresql/57014"],"sqlly":"If a script loops, other Redis tabs in SQLly get the BUSY line verbatim instead of a timeout, and a second connection's SCRIPT KILL runs from the same editor, so recovery does not need a shell.","faqs":[{"question":"SCRIPT KILL says the script already wrote. Now what?","answer":"The script cannot be stopped mid-write. The options in the message are the whole truth: wait for it to finish, or SHUTDOWN NOSAVE and lose data since the last save."},{"question":"Does BUSY mean the server crashed?","answer":"No. Redis is alive and single-threaded, waiting on your script. That is exactly why every other client sees BUSY."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/busy","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/busygroup","corpus":"errors","engine":"redis","language":"en","title":"Consumer group already exists","description":"XGROUP CREATE found a group with that name on the stream: group names are unique per stream and are not overwritten.","body":{"code":"BUSYGROUP","slug":"busygroup","name":null,"message":"BUSYGROUP Consumer Group name already exists","group":"streams-pubsub","severity":null,"sql_state":null,"summary":"XGROUP CREATE found a group with that name on the stream: group names are unique per stream and are not overwritten.","meaning":"Consumer groups are named per stream, and XGROUP CREATE mystream workers refuses when a group called workers is already there. Redis does not overwrite it silently, because the group's read pointer, the last-delivered-id, is state that consumers depend on; re-creating it would rewind or skip history for everyone attached.\n\nThe intended pattern for boot code is to treat this error as success: the goal is 'a group named workers exists', not 'this process created it'. There is no create-if-not-exists option, so initialization code catches BUSYGROUP and moves on.","causes":["Startup code creates the group on every boot and does not treat 'already exists' as success.","Two services race to create the same group on boot; one wins and the other receives BUSYGROUP.","The code was renamed and then reverted, or a name was reused, while the old group still exists on the stream."],"fix":[{"text":"List the groups on the stream; that list is the source of truth:","sql":"XINFO GROUPS mystream"},{"text":"Treat BUSYGROUP as success in initialization code, since the desired state already holds.","sql":null},{"text":"If the group genuinely must be rebuilt, with consumers re-reading history, delete and recreate it while nothing is attached:","sql":"XGROUP DESTROY mystream workers\nXGROUP CREATE mystream workers 0"}],"diagnostic":"XINFO GROUPS mystream\n# name, consumers, pending count and last-delivered-id per group\nXINFO STREAM mystream\n# length, first and last entry ids, for context","alternatives":"Choose the starting id deliberately before retrying creation: 0 replays the stream's history, $ starts at new messages only. For fleets of identical workers, create groups in one deploy step, such as a migration job, rather than inside every process.","details":[],"details_title":null,"repro":"redis-cli DEL mystream\nredis-cli XGROUP CREATE mystream workers $ MKSTREAM\nredis-cli XGROUP CREATE mystream workers $\n# (error) BUSYGROUP Consumer Group name already exists","repro_note":null,"related":["redis/nogroup","postgresql/42710"],"sqlly":"SQLly prints the BUSYGROUP line as sent, and XINFO GROUPS runs from the editor, so initialization code can be checked against the stream's real group list instead of guessing whether the create was a duplicate.","faqs":[{"question":"Can two groups share a name on different streams?","answer":"Yes. Uniqueness is per stream: mystream/workers and events/workers coexist without any problem."},{"question":"How do I reset a group's position without recreating it?","answer":"XGROUP SETID mystream workers $ moves the read pointer to the stream's last entry ID, or to any id, while consumers keep their names and state."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/busygroup","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/busykey","corpus":"errors","engine":"redis","language":"en","title":"Target key already exists","description":"A command that restores or moves a key found the target name occupied: RESTORE, MIGRATE and friends refuse without REPLACE.","body":{"code":"BUSYKEY","slug":"busykey","name":null,"message":"BUSYKEY Target key name already exists.","group":"memory-persistence","severity":null,"sql_state":null,"summary":"A command that restores or moves a key found the target name occupied: RESTORE, MIGRATE and friends refuse without REPLACE.","meaning":"BUSYKEY comes from commands that create a key from elsewhere: RESTORE writes a serialized value, and MIGRATE moves a key between instances. Both refuse to overwrite an existing target unless you pass REPLACE, and the refusal is this error. It is a collision check, not corruption: the target key may be live data, and the decision is yours.\n\nPass REPLACE when the source is authoritative, such as a migration replaying state; rename the target when both keys matter. Related commands behave differently on purpose: COPY without REPLACE simply returns 0 when the target exists, so scripts ported between the two need adjusting.","causes":["RESTORE was called on a key name that already exists, without REPLACE.","MIGRATE moved a key to an instance where the same name had already been created.","A migration or cache-warming job re-ran without idempotency and replayed keys that already landed."],"fix":[{"text":"Check the target before the operation:","sql":"EXISTS target-key\nTYPE target-key"},{"text":"Pass REPLACE when the source of truth is the key being moved or restored:","sql":"MIGRATE 127.0.0.1 6380 mykey 0 5000 REPLACE"},{"text":"When both keys are real data, rename the target first instead of overwriting it:","sql":"RENAME target-key target-key-backup"}],"diagnostic":"EXISTS target-key\nTYPE target-key\nOBJECT ENCODING target-key\n# What currently occupies the name you are about to write","alternatives":"For bulk moves, MIGRATE with COPY leaves the source in place and REPLACE makes re-runs safe; together they turn a migration into an idempotent operation. For backup-style restore flows, write to a versioned name (mykey:v42) and switch over with RENAME.","details":[],"details_title":null,"repro":"redis-server --port 7309 --save '' &\nredis-server --port 7310 --save '' &\nredis-cli -p 7309 SET mykey hello\nredis-cli -p 7310 SET mykey occupied\nredis-cli -p 7309 MIGRATE 127.0.0.1 7310 mykey 0 5000\n# (error) BUSYKEY Target key name already exists.\nredis-cli -p 7309 MIGRATE 127.0.0.1 7310 mykey 0 5000 REPLACE\n# OK","repro_note":null,"related":["postgresql/23505","mysql/1062","redis/busygroup"],"sqlly":"The full BUSYKEY reply lands in SQLly's results pane, and EXISTS and MIGRATE run from the same editor against both instances, so a collision is checked in place instead of being scripted around.","faqs":[{"question":"Is BUSYKEY like a duplicate key error?","answer":"In spirit, yes: the name you tried to create is taken. The difference is which commands can raise it, RESTORE and MIGRATE, while SET overwrites silently."},{"question":"Did MIGRATE lose the key when this happened?","answer":"No. MIGRATE is atomic from the source's point of view: on BUSYKEY without REPLACE, the key stays on the source untouched."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/busykey","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/clusterdown","corpus":"errors","engine":"redis","language":"en","title":"The cluster cannot serve this slot","description":"The cluster as a whole is not healthy: slots are unowned or too many nodes are unreachable, so commands are refused instead of half-executed.","body":{"code":"CLUSTERDOWN","slug":"clusterdown","name":null,"message":"CLUSTERDOWN The cluster is down","group":"cluster","severity":null,"sql_state":null,"summary":"The cluster as a whole is not healthy: slots are unowned or too many nodes are unreachable, so commands are refused instead of half-executed.","meaning":"CLUSTERDOWN is the cluster-level refusal: the node you are talking to believes the cluster cannot serve this key correctly right now. The most common form reads The cluster is down and appears when the cluster state is fail, typically because too many primary nodes are unreachable. A second form, Hash slot not served, appears when the key's slot belongs to no node at all, which happens after crashes or an unfinished setup. A third reads The cluster is down and only accepts read commands and appears when cluster-allow-reads-when-down is enabled.\n\nRedis Cluster refuses rather than guessing: routing a write without a verified owner could produce split-brain data that never reconciles. The usual real-world triggers are a crashed primary without a working replica, and networks that partition a minority of nodes.","causes":["Too many primary nodes are unreachable at once, so the cluster marks its state as fail.","The key's slot is covered by no node: a primary crashed and its replicas are gone too, or the slot was never assigned.","A brand new cluster-enabled node has not been given any slots and cannot verify ownership."],"fix":[{"text":"Look at the cluster state and how many slots are actually assigned:","sql":"redis-cli -p 7000 CLUSTER INFO | grep -E 'cluster_state|cluster_slots_assigned'\nredis-cli -p 7000 CLUSTER NODES"},{"text":"Bring the failed nodes back, or reconnect this node's view of them:","sql":"redis-cli -p 7000 CLUSTER MEET 127.0.0.1 7001"},{"text":"After crashes, repair slot coverage; the cluster tool can fix slots that lost their owner:","sql":"redis-cli --cluster fix 127.0.0.1:7000"}],"diagnostic":"redis-cli -p 7000 CLUSTER INFO\n# cluster_state:fail and cluster_slots_assigned below 16384 confirm the diagnosis\nredis-cli -p 7000 CLUSTER NODES\n# Lines not marked online are the nodes this one cannot reach","alternatives":"cluster-allow-reads-when-down yes lets reads through in a degraded cluster when you prefer stale reads to hard failures. For production, run a replica per primary so a single crash does not uncover slots, and alert on cluster_state before users ever see CLUSTERDOWN.","details":[],"details_title":null,"repro":"redis-server --port 7100 --cluster-enabled yes --cluster-config-file nodes-7100.conf --save '' &\nredis-cli -p 7100 GET foo\n# (error) CLUSTERDOWN The cluster is down\nredis-cli -p 7100 CLUSTER INFO | grep cluster_state\n# cluster_state:fail","repro_note":"A fresh cluster-enabled node starts in the fail state with no slots assigned, which reproduces the error without a multi-node setup.","related":["redis/moved","redis/tryagain","mysql/2003"],"sqlly":"SQLly surfaces the full CLUSTERDOWN reply and runs CLUSTER INFO and CLUSTER NODES from the editor, so you can tell a fail state from an uncovered slot before you start restarting nodes.","faqs":[{"question":"CLUSTERDOWN or MOVED: how do they differ?","answer":"MOVED names a healthy owner elsewhere in the cluster. CLUSTERDOWN means the cluster cannot promise any correct owner right now, so it refuses instead."},{"question":"Why does it refuse instead of answering from local data?","answer":"Serving data without a verified slot owner risks split brain: two nodes could accept writes for the same slot and the copies would never reconcile."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/clusterdown","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/crossslot","corpus":"errors","engine":"redis","language":"en","title":"Multi-key command spans two slots","description":"The command touched several keys that hash to different slots, which Redis Cluster refuses instead of running a partial command.","body":{"code":"CROSSSLOT","slug":"crossslot","name":null,"message":"CROSSSLOT Keys in request don't hash to the same slot","group":"cluster","severity":null,"sql_state":null,"summary":"The command touched several keys that hash to different slots, which Redis Cluster refuses instead of running a partial command.","meaning":"CROSSSLOT is a cluster-only error. A command that names more than one key (MGET, MSET, DEL with several keys, SUNION, Lua scripts) must have all its keys in one hash slot, because a cluster can only run a multi-key command atomically on the node that owns that slot. The keys here hash to different slots, so the node refuses the whole command.\n\nNothing was executed: DEL, for example, will not delete the keys that do belong to this node. The standard fix is hash tags: name keys so the shared part sits in {braces}, and only the brace content is hashed to a slot.","causes":["A multi-key command named keys that hash to different slots.","Keys are tagged per entity ({user:1}:..., {user:2}:...) and a batch command groups several entities at once.","A Lua script or a transaction gathers keys from several slots in one call."],"fix":[{"text":"Check the slots the keys map to:","sql":"redis-cli -p 7000 CLUSTER KEYSLOT {user:1000}:profile\nredis-cli -p 7000 CLUSTER KEYSLOT {user:2000}:profile\n# Different slots: the command cannot run as one atomic call"},{"text":"Use hash tags so the keys share a slot:","sql":"MSET {user:1000}:name alice {user:1000}:plan pro\n# Both keys hash on 'user:1000' and land in one slot"},{"text":"When atomicity is not required, split the work into per-key commands:","sql":"DEL {user:1000}:name\nDEL {user:1000}:plan"}],"diagnostic":"redis-cli -p 7000 CLUSTER KEYSLOT key1\nredis-cli -p 7000 CLUSTER KEYSLOT key2\n# Same number: the command can run. Different numbers: expect CROSSSLOT.","alternatives":"Pipelines do not have the problem: each command in a pipeline is routed on its own, so a pipeline of SETs works across slots. Reserve same-slot grouping with hash tags for the operations that genuinely need multi-key atomicity.","details":[],"details_title":null,"repro":"redis-cli -c -p 7000 MSET a 1 b 2\n# (error) CROSSSLOT Keys in request don't hash to the same slot\nredis-cli -c -p 7000 MSET {d}a 1 {d}b 2\n# OK - both keys hash on 'd'","repro_note":null,"related":["redis/moved","redis/tryagain"],"sqlly":"SQLly's editor runs the CLUSTER KEYSLOT lookups next to the failing command in one window, and the full CROSSSLOT reply is printed, so you know the command was refused whole and none of the keys were touched.","faqs":[{"question":"Do pipelines get CROSSSLOT too?","answer":"No. Each command in a pipeline is routed separately. The error is only for a single command naming several keys."},{"question":"Why does the cluster not just forward the command?","answer":"Atomicity. A multi-key command has to run as one unit on one node; splitting it across nodes could apply half of it and break the guarantee your data relies on."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/crossslot","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/execabort","corpus":"errors","engine":"redis","language":"en","title":"Transaction discarded after an error","description":"A command queued during MULTI failed the queue-time check, so EXEC refuses to run any of them and throws the whole transaction away.","body":{"code":"EXECABORT","slug":"execabort","name":null,"message":"EXECABORT Transaction discarded because of previous errors.","group":"data-type-command","severity":null,"sql_state":null,"summary":"A command queued during MULTI failed the queue-time check, so EXEC refuses to run any of them and throws the whole transaction away.","meaning":"MULTI starts a queue: commands after it are not run, only checked and stacked. If one of them fails the queue-time check, an unknown command or a wrong argument count, Redis remembers the failure, and when EXEC arrives it refuses the entire transaction with EXECABORT instead of running the good commands. Nothing from the queue executes; the client starts over.\n\nNote the split in error timing. Commands that fail at queue time abort the transaction. Commands that fail at run time, such as WRONGTYPE against a key, do not: EXEC still runs the others, and the failed one returns its own error inside the results. The bare reply \"EXECABORT Transaction discarded because of previous errors.\" only means the first kind. A second form, \"EXECABORT Transaction discarded because of: <error>\", means Redis refused EXEC itself, for example \"BUSY Redis is busy running a script\" or OOM.","causes":["A queued command had the wrong argument count and failed the arity check when queued.","A queued command name was misspelled or does not exist on this server.","A client library building a transaction from user input passed an empty or malformed entry."],"fix":[{"text":"Read the error the server reported during MULTI; it names the command that poisoned the queue:","sql":"MULTI\nSET msg hello\nGET\n# (error) ERR wrong number of arguments for 'get' command\nEXEC\n# (error) EXECABORT Transaction discarded because of previous errors."},{"text":"Discard explicitly when your code detects a bad queue, instead of waiting for EXEC:","sql":"DISCARD"},{"text":"Re-run the transaction once the failing command is fixed; Redis never returns partial results from an aborted one.","sql":null}],"diagnostic":"MONITOR\n# Watch the connection live: MONITOR lists only commands that run, so queued commands show up only if EXEC runs them. Queue-time errors and EXECABORT are replies, so MONITOR never shows them.\n# Caution: every command on the server is mirrored to this client, so stop it once you have the answer.","alternatives":"Lua scripts via EVAL run atomically, but Redis does not roll them back: a runtime error keeps the writes made before it. For check-then-write flows, WATCH plus MULTI aborts EXEC if a watched key changes; it does not stop a run-time error from applying the other commands.","details":[],"details_title":null,"repro":"redis-cli\nMULTI\nSET msg hello\nGET\n# Queued, but arity-checked: this one is bad\nEXEC\n# (error) EXECABORT Transaction discarded because of previous errors.\nGET msg\n# (nil) - the SET never ran","repro_note":null,"related":["redis/wrong-number-of-arguments","redis/unknown-command","postgresql/25P02"],"sqlly":"SQLly runs each line as its own command on one connection and shows each reply in order. A server error ends the script at that line, so in this repro the queue-time error is shown and EXEC is never sent; the failing command is visible without reaching for MONITOR.","faqs":[{"question":"Did any of my commands run?","answer":"No. EXECABORT means the whole queue was discarded. That differs from a run-time error inside EXEC, where the other commands do run."},{"question":"Why fail the whole transaction for one bad command?","answer":"Queue-time failures are statically checkable: the client sent something structurally wrong. Running the rest would hide the broken call and make the outcome depend on which commands happened to be valid."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/execabort","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/invalid-expire-time","corpus":"errors","engine":"redis","language":"en","title":"Expire value is out of range","description":"The command accepted a TTL option but the number with it is not valid: it must be a positive integer within the supported range.","body":{"code":"ERR invalid expire time","slug":"invalid-expire-time","name":null,"message":"ERR invalid expire time in 'set' command","group":"data-type-command","severity":null,"sql_state":null,"summary":"The command accepted a TTL option but the number with it is not valid: it must be a positive integer within the supported range.","meaning":"Commands that can expire a key, such as SET with EX, PX, EXAT or PXAT, EXPIRE, PEXPIRE, EXPIREAT and GETEX, validate the TTL before doing anything. A zero, a negative number, or a timestamp far outside the representable range produces this error with the command named, and the key is left untouched.\n\nTwo shapes of mistake dominate. A computed TTL that resolved to 0 or negative, where the code meant 'no expiry' and passed it straight through. And confusing relative with absolute: EX takes seconds from now, EXAT takes a unix timestamp. Handing a timestamp to EX does not error; it sets a TTL decades out, so the symptom is a key that never expires.","causes":["A computed TTL resolved to 0 or negative, for example a deadline that was already in the past.","An absolute unix timestamp was passed to the relative option, EX instead of EXAT or the reverse.","The client sent the TTL in the wrong form, such as the string 60s or a nil value."],"fix":[{"text":"Check the value and unit at the call site; relative options need positive integers:","sql":"SET session:abc data EX 3600\n# 3600 seconds from now\nSET session:abc data EXAT 1798761600\n# absolute unix timestamp"},{"text":"Guard computed TTLs before the call, and skip the command entirely when the intent was 'no expiry'.","sql":null},{"text":"When the intent is 'keep the existing TTL', say so instead of recomputing it:","sql":"SET session:abc newdata KEEPTTL"}],"diagnostic":"SET session:abc data EX 0\n# (error) ERR invalid expire time in 'set' command - the check itself\nTTL session:abc\n# The key is unchanged: -1 (no TTL) or -2 (missing)\nTIME\n# The server clock, for computing EXAT values","alternatives":"Centralize TTL computation in one client helper so every expiry goes through the same validation, and prefer EXPIRE after the write when the TTL comes from a later decision. KEEPTTL replaces most recomputation of existing expiries.","details":[],"details_title":null,"repro":"redis-cli SET session:abc data EX 0\n# (error) ERR invalid expire time in 'set' command\nredis-cli SET session:abc data EX 60\n# OK\nredis-cli TTL session:abc\n# (integer) 60 or a little less","repro_note":null,"related":["redis/wrong-number-of-arguments","postgresql/22003","mysql/1264"],"sqlly":"SQLly echoes the invalid-expire line with the command named, so the failing call is identifiable in client logs, and TIME, TTL and the corrected SET run from the same editor to verify the fix.","faqs":[{"question":"Does EX 0 delete the key immediately?","answer":"No, SET rejects it before anything happens. To expire on purpose, use EXPIRE, which treats a non-positive TTL as 'delete now', while SET's EX option validates instead."},{"question":"Is the timestamp in seconds or milliseconds?","answer":"EX and EXAT are seconds; PX and PXAT are milliseconds. Mixing the two does not raise this error; it sets the wrong expiry silently, so read TTL or PTTL after the write to confirm."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/invalid-expire-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/loading","corpus":"errors","engine":"redis","language":"en","title":"Dataset still loading from disk","description":"The server restarted and is still reading its RDB or AOF into memory; commands that need the dataset are refused until loading finishes.","body":{"code":"LOADING","slug":"loading","name":null,"message":"LOADING Redis is loading the dataset in memory","group":"memory-persistence","severity":null,"sql_state":null,"summary":"The server restarted and is still reading its RDB or AOF into memory; commands that need the dataset are refused until loading finishes.","meaning":"LOADING is the startup state: Redis has opened its port but is still reading the dataset from the RDB snapshot or replaying the AOF, and it refuses commands that would touch data it has not loaded yet. INFO and a few management commands work; data commands such as GET are refused, whichever key they name.\n\nIn the happy path this is a wait-it-out error, and otherwise a smoke alarm: how long loading takes is a function of dataset size and disk speed, and if it happens mid-day it usually means an unexpected restart. Clients should retry with backoff, and readiness probes should hold traffic back until INFO persistence reports loading:0.","causes":["A restart, planned or from a crash, left Redis replaying its persistence file.","A large dataset on slow storage makes the loading window long enough for clients to trip over it.","A replica loading the primary's RDB transfer answers LOADING until the load completes."],"fix":[{"text":"Watch progress rather than guessing:","sql":"INFO persistence\n# loading:1, loading_loaded_bytes, loading_total_bytes"},{"text":"Gate traffic until it finishes: readiness checks should treat loading:1 as not ready and retry with backoff.","sql":null},{"text":"If the window is too long for your SLA, shrink the source: faster disk, smaller snapshots through TTLs, or a tightened AOF rewrite schedule.","sql":null}],"diagnostic":"INFO persistence | grep loading\n# loading_loaded_bytes against loading_total_bytes: progress in bytes\nINFO server | grep uptime_in_seconds\n# How long ago this server started, that is, how long it has been loading","alternatives":"For deploy scripts, wait for readiness before running migrations: loop on INFO persistence until loading is 0. In clusters and behind Sentinel, role changes route traffic around a loading node automatically, which is one more reason not to point everything at a single node.","details":[],"details_title":null,"repro":"redis-server --port 7308 --save '' &\nredis-cli -p 7308 SET warmup key\nredis-cli -p 7308 BGSAVE\nredis-cli -p 7308 SHUTDOWN\nredis-server --port 7308 &\nredis-cli -p 7308 SET x 1\n# (error) LOADING Redis is loading the dataset in memory   (if you are quick)","repro_note":"Small datasets load in milliseconds, so the window is easy to miss locally; with a 0.78 GB dump (20M keys) it lasted 12 s on the test machine.","related":["redis/busy","sqlite/sqlite-corrupt"],"sqlly":"SQLly surfaces the verbatim LOADING line instead of a generic timeout, and INFO persistence from the editor shows the byte progress, so a deploy script can wait for the load to finish before running migrations.","faqs":[{"question":"Which commands work during LOADING?","answer":"INFO, CONFIG GET, CLIENT, HELLO, SELECT and ECHO answer normally; anything touching the dataset is refused, and so is PING. That is why INFO-based monitoring keeps working while the application and PING-based health checks do not."},{"question":"Can I skip loading and start empty?","answer":"Yes, deliberately: move the dump file away, or start in a directory that has no dump file. Starting with --save '' does not skip loading, because Redis still reads an existing dump.rdb. Done carelessly, that data is gone: the next save overwrites the original dump file."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/loading","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/masterdown","corpus":"errors","engine":"redis","language":"en","title":"Stale data is not allowed to be served","description":"The replica lost its link to the primary and, because it is set to refuse stale data, it answers reads with MASTERDOWN instead.","body":{"code":"MASTERDOWN","slug":"masterdown","name":null,"message":"MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no'.","group":"cluster","severity":null,"sql_state":null,"summary":"The replica lost its link to the primary and, because it is set to refuse stale data, it answers reads with MASTERDOWN instead.","meaning":"MASTERDOWN comes from a replica whose link to its primary is down while replica-serve-stale-data is no. Normally a disconnected replica keeps answering reads from the data it already has; with that setting it refuses instead, so clients cannot silently read data that may be minutes old.\n\nThe setting exists for caches that must never serve stale content, and it is strict on purpose: while the link is down, read commands fail with this error, including reads of keys that have not changed in days. Writes on the same replica fail with READONLY instead. The fix belongs to the replication link, not to the client.","causes":["The primary is down, restarting, or unreachable from the replica because of a network or firewall change.","replica-serve-stale-data no is set, which turns an ordinary disconnection into failed reads.","A failover left this node replicating from an address that no longer exists."],"fix":[{"text":"Check the link state and when it was last healthy:","sql":"redis-cli -p 7303 INFO replication | grep -E 'master_link_status|master_last_io|master_host'\n# master_link_status:down"},{"text":"Restore the link. Most cases are a restarted primary or a network change:","sql":"redis-cli -p 7303 REPLICAOF <master-host> 6379"},{"text":"If serving stale data temporarily is acceptable for this cache, allow it until the link returns:","sql":"redis-cli -p 7303 CONFIG SET replica-serve-stale-data yes"}],"diagnostic":"redis-cli -p 7303 INFO replication\n# master_link_status:down and master_link_down_since_seconds:N\n# On the primary side, is the replica connecting at all?\nredis-cli -h master-host INFO replication | grep -E 'connected|slave|replica'","alternatives":"Sentinel watches the link and promotes another replica when the primary dies, so reads move to a live node instead of failing. If you rely on replica-serve-stale-data no, put a health check in front that stops routing traffic to a replica with master_link_status:down.","details":[],"details_title":null,"repro":"redis-server --port 7303 --replicaof 127.0.0.1 6399 --replica-serve-stale-data no --save '' &\nredis-cli -p 7303 GET foo\n# (error) MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no'.","repro_note":null,"related":["redis/readonly","redis/loading","libsql/connection-interrupted"],"sqlly":"The master_link_status and master_link_down_since_seconds fields are one INFO replication away in SQLly's editor, and the full MASTERDOWN reply is printed verbatim, so you can tell a stale-data policy problem from a dead primary at a glance.","faqs":[{"question":"MASTERDOWN or READONLY: how do they differ?","answer":"Both come from replicas. READONLY is a write on a healthy replica. MASTERDOWN is any read on a replica configured to refuse stale data while its link is down. A write to that replica gets READONLY first."},{"question":"Which commands still work during MASTERDOWN?","answer":"INFO, REPLICAOF and other management commands work; data commands are refused. That is what lets you fix the link in the first place."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/masterdown","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/misconf","corpus":"errors","engine":"redis","language":"en","title":"Persistence is failing, writes stopped","description":"Redis can't write its snapshot or AOF to disk. With RDB on, stop-writes-on-bgsave-error refuses writes to avoid silent data loss; a broken AOF refuses writes regardless.","body":{"code":"MISCONF","slug":"misconf","name":null,"message":"MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.","group":"memory-persistence","severity":null,"sql_state":null,"summary":"Redis can't write its snapshot or AOF to disk. With RDB on, stop-writes-on-bgsave-error refuses writes to avoid silent data loss; a broken AOF refuses writes regardless.","meaning":"MISCONF is Redis protecting durability. A background save failed (full disk, missing permissions, a dying volume) or the AOF is unwritable, and because stop-writes-on-bgsave-error defaults to yes, every command that could modify data is refused until persistence works again. Reads continue, which is what makes this error confusing: the server looks healthy and only writes fail.\n\nThe AOF variant reads MISCONF Errors writing to the AOF file: ... and names the reason. Both variants mean the same thing: Redis is telling you its durability promise is broken, not that your command is wrong. The fix is almost always on the disk: space, permissions, or the dir and dbfilename configuration.","causes":["The disk holding the snapshot or AOF is full or has gone read-only.","The user Redis runs as lacks write permission on dir, which is common after moving the data directory.","The background-save child keeps failing, for instance on a host too loaded to fork, and the last save stays in error state."],"fix":[{"text":"Read the exact persistence state; the status fields say which side failed:","sql":"INFO persistence\n# rdb_last_bgsave_status, aof_last_write_status"},{"text":"Check the disk and the directory Redis saves into:","sql":"CONFIG GET dir\nCONFIG GET dbfilename\nCONFIG GET appendonly\ndf -h"},{"text":"Clear the cause, then force a save; writes resume once the status is ok:","sql":"BGSAVE\nINFO persistence | grep rdb_last_bgsave_status"}],"diagnostic":"INFO persistence\n# rdb_last_bgsave_status:err stops writes only while save points are set (CONFIG GET save is not empty) and stop-writes-on-bgsave-error is yes; aof_last_write_status:err stops writes whatever those settings are\nCONFIG GET dir\nCONFIG GET stop-writes-on-bgsave-error\n# Space and permissions in the actual save directory:\ndf -h\nls -la <dir-from-CONFIG-GET>","alternatives":"If this instance is a cache backed by another system of record, stop-writes-on-bgsave-error no removes the RDB write stop, accepting that a crash may lose the unsaved slice; it does not clear an AOF write error: a documented trade rather than an accident. Monitoring rdb_last_bgsave_status turns the problem into an ops alert instead of user-visible errors.","details":[{"key":"rdb_last_bgsave_status","value":"ok or err; err is what activates the write stop."},{"key":"aof_last_write_status","value":"ok or err for the append-only side; the AOF variant of MISCONF names it."},{"key":"rdb_changes_since_last_save","value":"How much data exists only in memory right now."},{"key":"stop-writes-on-bgsave-error","value":"The switch that turns a failed RDB save into refused writes, only while save points are set; yes by default. It does not affect AOF write errors."}],"details_title":"Persistence status fields to check","repro":"mkdir -p /private/tmp/redis-nowrite && chmod 000 /private/tmp/redis-nowrite\nredis-server --port 7307 --save '' &\nredis-cli -p 7307 CONFIG SET dir /private/tmp/redis-nowrite\nredis-cli -p 7307 CONFIG SET save '1 1'\nredis-cli -p 7307 SET x 1\n# after about a second, once the failing save is recorded:\nredis-cli -p 7307 SET y 2\n# (error) MISCONF Redis is configured to save RDB snapshots, ...\nchmod 755 /private/tmp/redis-nowrite && redis-cli -p 7307 BGSAVE   # heals the status","repro_note":"Run against a scratch instance: the directory is made unwritable on purpose so the background save fails the way it does on a full disk.","related":["sqlite/sqlite-ioerr","postgresql/58P01","sqlite/sqlite-readonly"],"sqlly":"SQLly shows the full MISCONF text and its editor runs INFO persistence and CONFIG GET dir next to the failed write, so the failing side, RDB or AOF, and the save path are on screen before you touch the disk.","faqs":[{"question":"Why are reads fine while writes fail?","answer":"The write stop is deliberate: Redis refuses to take writes it may not be able to save, while continuing to serve the data it already has."},{"question":"I do not need persistence. Can I ignore MISCONF?","answer":"Turn persistence off properly (an empty save directive and appendonly no) instead of leaving a broken saver plus stop-writes-on-bgsave-error no. Then the state cannot surprise you later."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/misconf","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/moved","corpus":"errors","engine":"redis","language":"en","title":"The key lives on another cluster node","description":"In Redis Cluster the key's hash slot is owned by a different node, which replies with the slot number and the address that owns it.","body":{"code":"MOVED","slug":"moved","name":null,"message":"MOVED 12182 127.0.0.1:7002","group":"cluster","severity":null,"sql_state":null,"summary":"In Redis Cluster the key's hash slot is owned by a different node, which replies with the slot number and the address that owns it.","meaning":"MOVED is how Redis Cluster routes. Every key maps to one of 16384 slots (CRC16 of the key modulo 16384), each slot belongs to exactly one node, and a node that receives a command for a slot it does not own refuses it with MOVED slot host:port, telling the client where the key actually lives.\n\nA cluster-aware client follows the redirect and re-sends to the reported endpoint. You see the error itself when the client is not cluster-aware (plain redis-cli without -c, a naive connection pool), when a resharding changed the slot map and a client has not refreshed yet, or when you point at one node deliberately for debugging. MOVED is normal protocol traffic, not a fault: the command did not run, but the cluster told you exactly where to run it.","causes":["A cluster-unaware client sent the command to a node that does not own the key's slot.","The slot map changed through resharding or failover, and the client is still using its cached map.","During maintenance you connected to a single node directly instead of through the cluster."],"fix":[{"text":"Find which slot the key hashes to, then ask the cluster who owns it:","sql":"redis-cli -p 7000 CLUSTER KEYSLOT foo\n# (integer) 12182\nredis-cli -p 7000 CLUSTER SLOTS"},{"text":"Use a cluster-aware client, or redis-cli with -c, which follows the redirect for you:","sql":"redis-cli -c -p 7000 SET foo bar\n# -> Redirected to slot [12182] located at 127.0.0.1:7002\n# OK"},{"text":"If errors persist after a reshard, force the client to rebuild its slot map by reconnecting; most libraries also refresh on every MOVED they receive.","sql":null}],"diagnostic":"redis-cli -p 7000 CLUSTER KEYSLOT foo\nredis-cli -p 7000 CLUSTER MYID\nredis-cli -p 7000 CLUSTER SLOTS\n# Compare the owner of slot 12182 with the endpoint named in the MOVED reply","alternatives":"Hash tags keep related keys in one slot: keys like {user:1000}:profile and {user:1000}:session hash on the part in braces, so multi-key commands on one user stop bouncing between nodes. For application code, a cluster-aware client removes the problem entirely instead of handling it after the fact.","details":[{"key":"MOVED","value":"The prefix: this node refused the command and named the slot's owner."},{"key":"12182","value":"The hash slot the key maps to, CRC16 of the key modulo 16384."},{"key":"127.0.0.1:7002","value":"The endpoint that owns the slot now; re-send the command there."}],"details_title":"Anatomy of a MOVED reply","repro":"redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 0\nredis-cli -p 7000 SET foo bar\n# (error) MOVED 12182 127.0.0.1:7002\nredis-cli -c -p 7000 SET foo bar\n# OK (the redirect was followed)","repro_note":null,"related":["redis/ask","redis/crossslot","redis/clusterdown"],"sqlly":"SQLly prints the whole MOVED line, slot and target address included, so you can see which node owns the key without running CLUSTER SLOTS first. If you are working node by node, the target node can be added as another SQLly connection and the command retried there.","faqs":[{"question":"Is MOVED a problem I need to fix?","answer":"Not on its own. Cluster-aware clients follow it automatically. Act only when a client keeps failing: it is not following redirects, or its slot map has gone stale."},{"question":"How is the slot number computed?","answer":"CRC16 of the key modulo 16384. If the key contains {braces}, only the part inside them is hashed, which is how hash tags pin keys to the same slot."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/moved","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/noauth","corpus":"errors","engine":"redis","language":"en","title":"Authentication required","description":"The server requires a password and the connection has not authenticated yet, so every command except AUTH, HELLO and QUIT is refused.","body":{"code":"NOAUTH","slug":"noauth","name":null,"message":"NOAUTH Authentication required.","group":"connection-auth","severity":null,"sql_state":null,"summary":"The server requires a password and the connection has not authenticated yet, so every command except AUTH, HELLO and QUIT is refused.","meaning":"NOAUTH means the connection reached Redis but never proved who it is. The server has requirepass set or an ACL setup that demands a login, and until the client sends a successful AUTH (or connects with credentials in the URL), every command except AUTH and QUIT is refused with this exact prefix. HELLO is refused too unless it carries the AUTH option, as in HELLO 3 AUTH default s3cret.\n\nIt is almost always a client-side configuration gap: the application has no password configured, the credentials went to one pool but a second app or job runner opened its own unauthenticated connection, or a monitoring tool connects directly. The error appears on the first data command rather than at connect time, because RESP does not require authentication up front.","causes":["The server has requirepass or ACL authentication enabled and the client connected without sending AUTH.","The credentials are missing from one specific client, such as a job runner or dashboard, while the main application authenticates fine.","A proxy or connection pooler forwards commands from a client that never authenticates."],"fix":[{"text":"Authenticate the connection right after opening it, or put the credentials in the connection string:","sql":"redis-cli -h db.example.com -a s3cret PING\n# or, inside an existing session:\nAUTH s3cret"},{"text":"Check what the server actually requires before guessing at passwords. On the server host:","sql":"redis-cli -a s3cret CONFIG GET requirepass\nredis-cli -a s3cret ACL LIST"},{"text":"Prefer a named ACL user over the legacy global password when you control the server, so each application can be rotated on its own:","sql":"ACL SETUSER app on >s3cret ~app:* +@read +@write\nAUTH app s3cret"}],"diagnostic":"# Does this connection need auth? Run it without credentials:\nredis-cli -h db.example.com PING\n# (error) NOAUTH Authentication required.\n# What the server requires:\nredis-cli -a s3cret CONFIG GET requirepass\nredis-cli -a s3cret ACL LIST","alternatives":"Putting the credentials in a redis:// URL keeps the username and password out of a separate AUTH line: redis://default:s3cret@db.example.com:6379. Typed inline, the URL still lands in shell history just as -a does, so keep it in a config or environment file where that matters. For fleets, named ACL users beat the single requirepass because each application can be re-passworded without touching the others.","details":[],"details_title":null,"repro":"redis-server --port 7300 --requirepass s3cret --save '' &\nredis-cli -p 7300 PING\n# (error) NOAUTH Authentication required.\nredis-cli -p 7300 -a s3cret PING\n# PONG","repro_note":null,"related":["redis/wrongpass","redis/noperm","mysql/1045","sql-server/18456"],"sqlly":"When a Redis connection fails its test in SQLly, the exact server reply is shown, so NOAUTH reads as an auth problem rather than a network one. AUTH, ACL LIST and the diagnostics above then run from the SQL editor in the same window.","faqs":[{"question":"NOAUTH or WRONGPASS: which one means the password was wrong?","answer":"NOAUTH means no credentials were sent at all. WRONGPASS means a password or username was sent and the server rejected it."},{"question":"Why does my client report NOAUTH only on the first query?","answer":"RESP lets a client open a connection and start sending immediately. Redis defers the rejection to the first command that needs auth, so pools that authenticate lazily surface the error on the first real command."},{"question":"Can I just turn auth off?","answer":"You can clear it with CONFIG SET requirepass \"\", but the safer fix is keeping auth on and adding the credentials to the client that is missing them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/noauth","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/nogroup","corpus":"errors","engine":"redis","language":"en","title":"Consumer group does not exist","description":"XREADGROUP or an XGROUP subcommand named a group or a stream that is not there: never created, or the key was deleted or renamed.","body":{"code":"NOGROUP","slug":"nogroup","name":null,"message":"NOGROUP No such key 'orders' or consumer group 'workers' in XREADGROUP with GROUP option","group":"streams-pubsub","severity":null,"sql_state":null,"summary":"XREADGROUP or an XGROUP subcommand named a group or a stream that is not there: never created, or the key was deleted or renamed.","meaning":"NOGROUP is the streams lookup failure: the group name does not exist on that key, or the key itself is gone. On XREADGROUP it means the consumer cannot attach; on XGROUP subcommands such as DELCONSUMER, SETID and DESTROY it means the target group is missing. The reply names both the key and the group, so the miss is unambiguous.\n\nThe missing key is the subtle case. Unlike most Redis types, a stream survives as an empty-but-present key once all its entries are deleted, whether or not it has a group, so NOGROUP on a well-known stream name usually means a FLUSHDB, a rename, a different database index, or consumers that started before the group's creator ran.","causes":["The group was never created on this stream: consumers started before the creator did.","The stream key was deleted, renamed, or expired, and groups live and die with their key.","The consumer and the creator connect to different logical databases or different instances."],"fix":[{"text":"Confirm what exists on the stream, on the database the consumer uses:","sql":"SELECT 0\nTYPE orders\nXINFO GROUPS orders"},{"text":"Recreate the group, choosing the starting id deliberately: 0 replays history, $ starts at new entries:","sql":"XGROUP CREATE orders workers 0"},{"text":"Make creation idempotent at startup so consumers self-heal: run XGROUP CREATE and ignore BUSYGROUP.","sql":null}],"diagnostic":"TYPE orders\nXINFO GROUPS orders\n# Is the key there at all, and which groups exist on it?\nSELECT 0\n# Check the database index too; a mismatch between producer and consumer is a classic","alternatives":"If consumers may start against a fresh stream, create groups with MKSTREAM so the key exists even before the first XADD. For anything with strict ordering guarantees, run the group creation as a deploy step rather than inside consumer processes.","details":[],"details_title":null,"repro":"redis-cli DEL orders\nredis-cli XADD orders * item widget\nredis-cli XREADGROUP GROUP workers consumer-1 COUNT 10 STREAMS orders >\n# (error) NOGROUP No such key 'orders' or consumer group 'workers' in XREADGROUP with GROUP option\nredis-cli XGROUP CREATE orders workers $\nredis-cli XREADGROUP GROUP workers consumer-1 COUNT 10 STREAMS orders >\n# (nil) - attached, nothing new yet","repro_note":null,"related":["redis/busygroup","postgresql/42P01","mysql/1146"],"sqlly":"SQLly shows the NOGROUP line with both names quoted, and XINFO GROUPS and TYPE run in the same editor, so the miss is pinned to the key or the group in one look.","faqs":[{"question":"The stream exists, why still NOGROUP?","answer":"The group name is the miss. Groups are identified by the key and the name together, so a typo in either half produces this error."},{"question":"Does deleting a stream delete its groups?","answer":"Yes. Groups and their pending-entry state belong to the key. DEL or FLUSHDB removes them; recreation starts with an empty pending list."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/nogroup","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/noperm","corpus":"errors","engine":"redis","language":"en","title":"The ACL user lacks permission","description":"The connection authenticated as an ACL user whose rules do not cover this command, key pattern or channel, so Redis refuses it.","body":{"code":"NOPERM","slug":"noperm","name":null,"message":"NOPERM User default has no permissions to run the 'get' command","group":"connection-auth","severity":null,"sql_state":null,"summary":"The connection authenticated as an ACL user whose rules do not cover this command, key pattern or channel, so Redis refuses it.","meaning":"Since Redis 6, permissions are per user in the ACL system. A connection can be fully authenticated and still be refused when the command is not in the user's command set, the key does not match the user's key patterns, or, for pub/sub, the channel is not allowed. A command refusal names the user and the command. A key refusal reads `NOPERM No permissions to access a key` on Redis 8.0 and names neither the user nor the key, so check ACL LOG for the user and key.\n\nIt is the least dramatic of the auth errors: the login works, the first refused command does not. It shows up after someone tightens a user to least privilege and misses a command, after key patterns were written for an old naming scheme, and when occasional jobs call commands outside the new set.","causes":["The user's command rules, such as +@read or +get, do not include the command the application calls.","The key does not match the user's ~pattern, so an otherwise permitted command is refused on that key.","The user was rotated to a narrower rule set and a batch job or admin tool still calls commands outside it."],"fix":[{"text":"Inspect the user's effective permissions:","sql":"ACL GETUSER app\n# flags, key patterns, channels, command rules\nACL LIST"},{"text":"Grant the missing command or category, scoped as narrowly as the app needs:","sql":"ACL SETUSER app ~cache:* +get +set +del"},{"text":"Verify as that user, not as admin, so the test matches what production does:","sql":"AUTH app s3cret\nGET cache:user:1000"}],"diagnostic":"ACL WHOAMI\n# Which user this connection is\nACL GETUSER app\nACL LOG\n# The most recent ACL rejections with the exact command and object; usually the fastest answer","alternatives":"Model roles with ACL categories (+@read, +@write, -@dangerous) instead of long per-command lists, so an upgrade that adds commands does not silently break the app. Keep one user per application and watch ACL LOG to catch what least privilege missed.","details":[],"details_title":null,"repro":"redis-server --port 7305 --save '' &\nredis-cli -p 7305 ACL SETUSER app on '>s3cret' '~cache:*' '+get'\nredis-cli -p 7305 --user app --pass s3cret GET cache:x\n# (nil) - allowed\nredis-cli -p 7305 --user app --pass s3cret SET cache:x 1\n# (error) NOPERM User app has no permissions to run the 'set' command","repro_note":null,"related":["redis/noauth","mysql/1142","postgresql/42501","sql-server/229"],"sqlly":"When a connection SQLly tests authenticates but a query is refused, the full NOPERM line appears in the results pane with the user and command named, and ACL GETUSER and ACL LOG run from the editor to show exactly which rule is missing.","faqs":[{"question":"The user has +@read, why is GET still refused?","answer":"Commands and key patterns are separate checks: both must match. A user with +@read whose patterns do not cover the key still gets NOPERM."},{"question":"Where does Redis record these refusals?","answer":"ACL LOG keeps the recent security events. For a command refusal the object is the command name; for a key refusal it is the key. ACL LOG RESET clears the list."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/noperm","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/noreplicas","corpus":"errors","engine":"redis","language":"en","title":"Too few healthy replicas to write","description":"With min-replicas-to-write set, the primary refuses writes when fewer than that many replicas are connected and within the lag bound.","body":{"code":"NOREPLICAS","slug":"noreplicas","name":null,"message":"NOREPLICAS Not enough good replicas to write.","group":"cluster","severity":null,"sql_state":null,"summary":"With min-replicas-to-write set, the primary refuses writes when fewer than that many replicas are connected and within the lag bound.","meaning":"NOREPLICAS is a write-availability guard. When min-replicas-to-write and min-replicas-max-lag are set, the primary tracks how many replicas are connected and acknowledging within the lag window, and it refuses writes while that count is short. The point is bounded data loss: a primary that cannot replicate should not be accepting writes nobody will see if it dies.\n\nIt reads like a replica-side error, but it is the primary refusing. Typical triggers are network partitions that silence replicas, replicas down for maintenance, and lag bounds set tighter than the workload allows, so the guard trips even though the replicas are technically connected.","causes":["Replicas are disconnected, crashed or cut off by the network, and the connected count fell below the minimum.","Replicas are connected but too slow: their acknowledgements exceed min-replicas-max-lag seconds.","The bounds were configured for an older topology and no longer match the fleet."],"fix":[{"text":"Compare the healthy-replica count with the configured minimum:","sql":"INFO replication\nCONFIG GET min-replicas-to-write\nCONFIG GET min-replicas-max-lag"},{"text":"Restore connectivity or capacity to the replicas; writes resume automatically once the guard is satisfied.","sql":null},{"text":"Relax the guard only consciously, such as for a maintenance window. CONFIG SET takes effect at once but is lost on restart. To persist it, set min-replicas-to-write in the config file the server was started with, then run CONFIG REWRITE (it fails with \"The server is running without a config file\" when the server was started from the command line):","sql":"CONFIG SET min-replicas-to-write 0\nCONFIG REWRITE"}],"diagnostic":"INFO replication\n# The connected replicas with their lag\nCONFIG GET min-replicas-*\nredis-cli -h replica-1 INFO replication | grep master_link_status\n# Are the replicas healthy from their own point of view?","alternatives":"The two settings work as a pair: a wide lag bound tolerates slow replicas, a low minimum tolerates fewer of them. Redis Sentinel fails over when it marks the master down (+sdown/+odown), and a primary that still answers PING while refusing writes does not meet that test, so Sentinel does not clear a NOREPLICAS guard. Restoring replica health is the fix.","details":[],"details_title":null,"repro":"redis-server --port 7311 --min-replicas-to-write 1 --min-replicas-max-lag 10 --save '' &\nredis-cli -p 7311 SET foo bar\n# (error) NOREPLICAS Not enough good replicas to write.","repro_note":null,"related":["redis/misconf","redis/readonly"],"sqlly":"SQLly's editor runs INFO replication and the CONFIG GET pair in one window, and the NOREPLICAS reply is printed verbatim, so the guard and the replica state behind it are both visible before you relax anything.","faqs":[{"question":"Why is my healthy primary refusing writes?","answer":"It is the durability guard: not enough replicas are acknowledging in time. The primary itself is fine; its replication is not."},{"question":"Does this apply to Redis Cluster?","answer":"Yes, per primary. A cluster primary with the guard configured also refuses writes when its replica count dips below the minimum."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/noreplicas","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/noscript","corpus":"errors","engine":"redis","language":"en","title":"Script SHA1 is not cached","description":"EVALSHA named a script digest the server has not cached since its last restart or SCRIPT FLUSH, so the script must be sent again with EVAL.","body":{"code":"NOSCRIPT","slug":"noscript","name":null,"message":"NOSCRIPT No matching script. Please use EVAL.","group":"data-type-command","severity":null,"sql_state":null,"summary":"EVALSHA named a script digest the server has not cached since its last restart or SCRIPT FLUSH, so the script must be sent again with EVAL.","meaning":"Lua scripts are usually run through EVALSHA <sha1>, which saves sending the whole script on every call. The sha1 is a key into a server-side cache: if the server has never seen the script, or has lost it through a restart, a SCRIPT FLUSH or a failover to a replica that was never sent it, the server refuses with NOSCRIPT instead of guessing. The digest is matched case-insensitively, so one wrong character lands here too.\n\nThe standard client pattern is the fallback: try EVALSHA, catch NOSCRIPT, send the full script once with EVAL, then return to EVALSHA. Drivers that support Lua do this transparently; hand-rolled RESP clients have to implement it themselves.","causes":["The server restarted or failed over after the script was loaded, clearing the in-memory script cache.","SCRIPT FLUSH ran, often from an admin script or a test harness sharing the instance.","The digest passed to EVALSHA was computed over different text than the script that was loaded.","A fresh node in a cluster received the EVALSHA before it was ever sent the EVAL."],"fix":[{"text":"Send the script once with EVAL, or load it and keep the digest it returns:","sql":"SCRIPT LOAD \"return redis.call('GET', KEYS[1])\"\n# Returns the sha1 hex string to pass to EVALSHA"},{"text":"Check whether a digest is actually cached before calling it:","sql":"SCRIPT EXISTS <sha1-from-your-logs>\n# 1 means cached; 0 means expect NOSCRIPT"},{"text":"Implement the EVALSHA to NOSCRIPT to EVAL fallback in the client, or use a driver that does it for you.","sql":null}],"diagnostic":"SCRIPT EXISTS <sha1>\n# 0: not loaded on this server right now\nINFO server | grep uptime_in_seconds\n# A recent restart clears the cache; there is no command to list cached scripts,\n# so test specific digests with SCRIPT EXISTS","alternatives":"Redis Functions (Redis 7+) register server-side libraries by name and survive failover in cluster mode, removing most EVALSHA misses; call them with FCALL. For hot paths, load scripts at startup and after every reconnect instead of lazily on first use.","details":[],"details_title":null,"repro":"redis-cli EVALSHA 0123456789012345678901234567890123456789 1 mykey\n# (error) NOSCRIPT No matching script. Please use EVAL.\nredis-cli SCRIPT LOAD \"return 1\"\n# a sha1 hex string comes back\nredis-cli EVALSHA <that-sha1> 0\n# (integer) 1","repro_note":null,"related":["redis/busy","redis/execabort","mysql/1305"],"sqlly":"SQLly prints the NOSCRIPT line verbatim and runs SCRIPT LOAD and EVAL from the editor, so the load-once-then-EVALSHA cycle becomes a copy-paste job in one window rather than a driver change.","faqs":[{"question":"Does SCRIPT LOAD survive forever?","answer":"No. The cache lives in memory: restarts, SCRIPT FLUSH and failover clear it. Clients must be ready to re-send the script."},{"question":"Why does Redis not just return an empty result?","answer":"Refusing loudly stops a client from treating a missing script as an empty result, which would look like silent data loss."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/noscript","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/oom-command-not-allowed","corpus":"errors","engine":"redis","language":"en","title":"Memory limit reached","description":"The dataset reached the maxmemory limit and the eviction policy cannot free enough memory, so Redis refuses write commands.","body":{"code":"OOM","slug":"oom-command-not-allowed","name":null,"message":"OOM command not allowed when used memory > 'maxmemory'.","group":"memory-persistence","severity":null,"sql_state":null,"summary":"The dataset reached the maxmemory limit and the eviction policy cannot free enough memory, so Redis refuses write commands.","meaning":"OOM is the write-path refusal when used_memory is over maxmemory and the configured maxmemory-policy cannot free enough: noeviction evicts nothing by definition, and even an allkeys policy can fail when the incoming write is larger than what eviction can reclaim. Read commands keep working, and so do commands without the deny-oom flag, such as DEL; a SET is refused at the limit even when the new value is smaller.\n\nThe message names the two knobs precisely: the ceiling is maxmemory and the behavior at the ceiling is maxmemory-policy. Which one to change depends on what the data is: a cache wants an eviction policy; a system of record wants more memory or a smaller dataset.","causes":["maxmemory is set and the working set grew past it, with the policy at its default of noeviction.","An allkeys or volatile policy still could not free enough for the incoming write.","A single very large value arrives at a moment when eviction has already freed everything it can."],"fix":[{"text":"See where you stand before changing anything:","sql":"INFO memory\n# used_memory_human, maxmemory_human, maxmemory_policy\nCONFIG GET maxmemory"},{"text":"For a cache, let Redis free space itself by switching the policy:","sql":"CONFIG SET maxmemory-policy allkeys-lru"},{"text":"For data that must not be evicted, raise the limit or shrink the dataset, then persist the change:","sql":"CONFIG SET maxmemory 2gb\nCONFIG REWRITE"}],"diagnostic":"INFO memory\n# used_memory versus maxmemory, and the policy in force\nINFO stats | grep evicted\n# How often eviction already ran to make room\nredis-cli --bigkeys\n# Where the bytes are: the largest keys by type","alternatives":"Split by tier: keep evictable data such as sessions and caches in one instance with allkeys-lru, and durable data in another with noeviction plus alerts on used_memory. On the client, tolerate OOM for best-effort writes but never for ledger-style ones.","details":[{"key":"noeviction","value":"The default. Write commands are refused with OOM, including ones that would not grow memory; reads keep working."},{"key":"allkeys-lru / allkeys-lfu","value":"Evicts the least recently or least frequently used key, across all keys, to fit the write."},{"key":"volatile-*","value":"Evicts only keys with a TTL. When no key has one, it behaves like noeviction."},{"key":"allkeys-random / volatile-random","value":"Evicts a random key from the eligible set."}],"details_title":"maxmemory policies at the limit","repro":"redis-server --port 7306 --maxmemory 2mb --maxmemory-policy noeviction --save '' &\nhead -c 3000000 /dev/zero | tr '\\0' 'a' | redis-cli -p 7306 -x SET big\n# (error) OOM command not allowed when used memory > 'maxmemory'.","repro_note":null,"related":["duckdb/out-of-memory","sqlite/sqlite-nomem","postgresql/53200","sql-server/701"],"sqlly":"SQLly prints the OOM line verbatim and INFO memory runs in the same editor, so the ceiling and the policy in force are one query away before you decide between a policy change and a resize.","faqs":[{"question":"Why do reads still work when writes get OOM?","answer":"The limit guards memory growth. Reads are not flagged to be refused at the limit, so Redis serves them, while write commands flagged deny-oom are refused whether or not they grow the dataset."},{"question":"What does maxmemory 0 mean?","answer":"No Redis-side limit: the process grows until the operating system stops it. The OOM refusal only applies when maxmemory is set to a byte value."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/oom-command-not-allowed","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/readonly","corpus":"errors","engine":"redis","language":"en","title":"Write rejected on a read only replica","description":"The connection points at a replica, and Redis refuses writes there: only the primary accepts commands that modify data.","body":{"code":"READONLY","slug":"readonly","name":null,"message":"READONLY You can't write against a read only replica.","group":"cluster","severity":null,"sql_state":null,"summary":"The connection points at a replica, and Redis refuses writes there: only the primary accepts commands that modify data.","meaning":"READONLY means the write landed on a replica. A Redis replica serves reads (by default, possibly stale data), but every write must go to the primary so it can be replicated in order. With replica-read-only at its default of yes, any write command on a replica gets this error instead of executing.\n\nIt usually means the client is pointed at the wrong host: a connection string still naming yesterday's primary, a DNS record that moved after a failover, or a proxy that hands out replicas to writers. It also bites after a manual promotion when the old primary was never demoted and clients keep writing to it.","causes":["The connection string or DNS name points at a replica instead of the primary.","A failover or promotion finished and clients still hold the old primary's address, which is now a replica.","A proxy or service discovery layer includes replicas in the pool it hands to writers."],"fix":[{"text":"Check what the node you are connected to believes it is:","sql":"redis-cli -h node-2 INFO replication | grep 'role:'\n# role:slave means writes fail here"},{"text":"Ask any replica where the primary is now:","sql":"redis-cli -h node-2 INFO replication | grep master_host\nredis-cli -h node-2 ROLE"},{"text":"Point writers at the primary. After a promotion, demote the old primary so it follows the new one:","sql":"redis-cli -h old-primary REPLICAOF new-primary 6379"}],"diagnostic":"redis-cli -h node-2 ROLE\n# The role (slave; Redis keeps this word in ROLE on every version) plus the master's host and port\nredis-cli -h node-2 INFO replication\n# role, master_host, master_link_status\n# From the suspected primary, who follows it?\nredis-cli -h node-1 INFO replication | grep -E 'role:|slave[0-9]|replica[0-9]'","alternatives":"For failover, let the nodes agree on roles themselves: Redis Sentinel or Redis Cluster reassign them and clients follow. If you promote by hand, demote the old primary the moment writes move, or you will be chasing READONLY across half the fleet.","details":[],"details_title":null,"repro":"redis-server --port 7302 --replicaof 127.0.0.1 6399 --save '' &\nredis-cli -p 7302 SET foo bar\n# (error) READONLY You can't write against a read only replica.\nredis-cli -p 7302 GET foo\n# (nil) - reads still work; stale data is served by default","repro_note":null,"related":["redis/masterdown","sqlite/sqlite-readonly","postgresql/25006"],"sqlly":"SQLly shows the full READONLY line instead of hiding it behind a driver wrapper, and ROLE and INFO replication run in the same editor, so you can confirm the node's role and find the current primary without another tool.","faqs":[{"question":"Can I make a replica writable?","answer":"replica-read-only no exists, but such writes are not replicated and vanish on the next synchronization. It is meant for special setups, not as a workaround."},{"question":"Why did the same write work yesterday and fail today?","answer":"The node changed role. Failover tools swap primaries and replicas; your client kept the old address, which is now a replica."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/readonly","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/tryagain","corpus":"errors","engine":"redis","language":"en","title":"Slot is rehashing, retry the command","description":"A multi-key command hit keys that are being moved between nodes; the cluster asks the client to retry, and the command can succeed then.","body":{"code":"TRYAGAIN","slug":"tryagain","name":null,"message":"TRYAGAIN Multiple keys request during rehashing of slot","group":"cluster","severity":null,"sql_state":null,"summary":"A multi-key command hit keys that are being moved between nodes; the cluster asks the client to retry, and the command can succeed then.","meaning":"TRYAGAIN is a temporary refusal, sent only for multi-key commands or Lua scripts whose keys sit in a slot that is being resharded: the command would need keys this node no longer has, and the cluster will not run it half-done. Unlike MOVED or CLUSTERDOWN it does not say the slot map is wrong; it says try the same command again, because once the migration step passes, it will go through.\n\nClients that follow redirects retry as part of normal handling. By hand, the error shows up while redis-cli --cluster reshard is running against a busy multi-key workload.","causes":["A resharding job moved the slot while a multi-key command referenced keys in it.","A Lua script touched keys in a migrating slot and not all of them are local yet.","Repeated or interrupted reshard attempts left the slot flagged MIGRATING between runs."],"fix":[{"text":"Retry the same command; the window is usually short:","sql":"MGET {u}:a {u}:b\n# (error) TRYAGAIN Multiple keys request during rehashing of slot\n# ... a moment later the same command succeeds"},{"text":"If it persists, check whether the slot is stuck migrating:","sql":"redis-cli -p 7000 CLUSTER NODES | grep '\\['\n# [12182->-...] shows an unfinished migration for slot 12182"},{"text":"Finish the job with the cluster tool, or roll the slot back with CLUSTER SETSLOT on both nodes:","sql":null}],"diagnostic":"redis-cli -p 7000 CLUSTER NODES | grep -E '\\[|myself'\nredis-cli -p 7000 CLUSTER COUNTKEYSINSLOT 12182\nredis-cli -p 7000 CLUSTER SLOTS\n# Together these show which slot is mid-migration and how many keys remain on the source","alternatives":"Run resharding for multi-key-heavy workloads in low-traffic windows; the TRYAGAIN rate follows your multi-key traffic. Hash tags keep a user's keys together, which shrinks the set of commands that can ever hit a moving slot.","details":[],"details_title":null,"repro":"redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 0\nredis-cli -p 7000 MSET {u}:a 1 {u}:b 2\nredis-cli -p 7000 CLUSTER SETSLOT <slot-of-{u}> MIGRATING <node-id>\nredis-cli -p 7000 MGET {u}:a {u}:b\n# (error) TRYAGAIN Multiple keys request during rehashing of slot\nredis-cli --cluster reshard 127.0.0.1:7000   # completing the job clears it","repro_note":"The slot number for the key prefix comes from CLUSTER KEYSLOT '{u}'; the error only fires while keys of that slot are still being moved.","related":["redis/ask","redis/crossslot","sqlite/sqlite-busy"],"sqlly":"SQLly prints TRYAGAIN verbatim and runs CLUSTER NODES and CLUSTER SLOTS from the same editor, so you can confirm a reshard is in flight instead of suspecting your client library.","faqs":[{"question":"Should I back off exponentially on TRYAGAIN?","answer":"A short retry is enough. The error only exists while that one slot is moving, and redirect-aware clients already retry it as part of normal handling."},{"question":"Why not just serve the keys the node still has?","answer":"Multi-key commands are atomic by contract. Running them over a subset would silently change what the command means."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/tryagain","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/unknown-command","corpus":"errors","engine":"redis","language":"en","title":"Redis does not know this command","description":"The first word of the command is not one this server knows: a typo, an unsupported module command, or a client newer than the server.","body":{"code":"ERR unknown command","slug":"unknown-command","name":null,"message":"ERR unknown command 'HGETALLX', with args beginning with: 'myhash' ","group":"data-type-command","severity":null,"sql_state":null,"summary":"The first word of the command is not one this server knows: a typo, an unsupported module command, or a client newer than the server.","meaning":"This is Redis's failure for the command name itself. The server looked up the first token and found no command with that name, so it reports the name and the first arguments it received, and nothing executed.\n\nThe common causes are a typo, a command that exists only in a newer Redis than the server runs, a module command arriving while the module is not loaded, and proxies or ORMs that mangle the name. Redis is case-insensitive about command names, so casing is never the problem, but appended suffixes are. A close sibling message, unknown subcommand '...', appears when a known command gets an unrecognized subcommand.","causes":["A typo in the command name, or a client library assembling the command array wrong.","The command exists only in Redis versions newer than the one connected to.","A module command was sent to a server that has not loaded that module.","A proxy or query builder split or prefixed the command line on the way through."],"fix":[{"text":"Confirm the spelling and whether this server supports the command at all:","sql":"COMMAND INFO XADD\n# (nil) means this server has never heard of it\nCOMMAND COUNT"},{"text":"Compare the server version with the version that introduced the command, and upgrade if the command is newer:","sql":"INFO server | grep redis_version"},{"text":"Load the module if the command belongs to one:","sql":"MODULE LIST\nMODULE LOAD /usr/lib/redis/modules/redistimeseries.so"}],"diagnostic":"COMMAND INFO hgetallx\n# (nil): not a command on this server\nCOMMAND INFO hgetall\n# The correctly spelled command, with its arity and flags\nINFO server | grep redis_version\nMODULE LIST\n# Compare against the module or version the feature needs","alternatives":"For version-dependent features, gate the call in code on the server version from INFO server instead of catching the error at runtime. Where a module is required, load it through the loadmodule configuration directive so a restart does not silently drop the command again.","details":[],"details_title":null,"repro":"redis-cli HGETALLX myhash\n# (error) ERR unknown command 'HGETALLX', with args beginning with: 'myhash' \nredis-cli HGETALL myhash\n# works","repro_note":null,"related":["redis/wrong-number-of-arguments","postgresql/42601","mysql/1064","duckdb/parser-syntax-error"],"sqlly":"SQLly sends commands over RESP exactly as typed, so the error shows the raw unknown name, and COMMAND INFO and INFO server run in the same editor to settle whether the server is too old or the name is simply wrong.","faqs":[{"question":"Are Redis command names case-sensitive?","answer":"No. GET and get are the same command. The name in the error is what you sent, so check spelling, not case."},{"question":"Why does the same code work in another environment?","answer":"The other server is probably a newer Redis or has the module loaded. Compare redis_version from INFO server and MODULE LIST between the two environments."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/unknown-command","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/wrong-number-of-arguments","corpus":"errors","engine":"redis","language":"en","title":"Argument count is wrong","description":"The command name is known but the argument count is not: each command declares a minimum, and fixed-arity commands also refuse extra arguments.","body":{"code":"ERR wrong number of arguments","slug":"wrong-number-of-arguments","name":null,"message":"ERR wrong number of arguments for 'get' command","group":"data-type-command","severity":null,"sql_state":null,"summary":"The command name is known but the argument count is not: each command declares a minimum, and fixed-arity commands also refuse extra arguments.","meaning":"Every Redis command declares an arity: how many arguments it accepts, counting the command name itself. When the client sends fewer arguments than the minimum, or more than a fixed-arity command allows, Redis refuses with this message naming the command. The check happens before anything executes, so a rejected call has written nothing: SETNX k v extra fails with this message and leaves k unset. SET takes a variable number of arguments, so a stray token there gives ERR syntax error instead.\n\nThe usual source is the client layer: a nil argument dropped from the array, an option appended twice, or a driver joining arguments into one string instead of sending them as separate bulk strings. Commands with fixed shapes such as GET are strict; SET is deliberately loose because it takes many option forms.","causes":["A nil or empty value was dropped by the client library, leaving a gap in the argument list.","Arguments were joined into one string or split wrongly instead of being sent as separate RESP bulk strings.","An option was repeated, or an extra positional argument was appended to a fixed-arity command."],"fix":[{"text":"Check the exact arity Redis expects; a negative value means 'at least':","sql":"COMMAND INFO get\n# arity 2: GET key, exactly\nCOMMAND INFO set\n# arity -3: SET key value [options...], at least"},{"text":"Log the argument array the client actually builds, including nils and empty strings, and compare it with the intended call.","sql":null},{"text":"Run the command by hand with the intended arguments to separate a client bug from a usage bug:","sql":"GET mykey\n# (nil) is a missing key, not an error\nGET\n# (error) ERR wrong number of arguments for 'get' command"}],"diagnostic":"COMMAND INFO zadd\n# arity -4: ZADD key [options] score member [score member ...]\n# What the server actually runs, one line per executed command. A call rejected by the arity check does not appear:\nMONITOR\n# Watch a single request, then stop: MONITOR mirrors every command and costs latency","alternatives":"Typed clients build arity correctly for the commands they support; drop to raw EVAL or custom commands only when a wrapper lags behind a new server feature. For commands with variable arguments, validate the count in application code before the call.","details":[],"details_title":null,"repro":"redis-cli GET\n# (error) ERR wrong number of arguments for 'get' command\nredis-cli GET mykey extra\n# (error) ERR wrong number of arguments for 'get' command\nredis-cli GET mykey\n# (nil)","repro_note":null,"related":["redis/unknown-command","postgresql/42601","sql-server/156"],"sqlly":"The reply is printed as sent, naming the exact command, and COMMAND INFO for the arity runs in the SQLly editor while you read the message, which settles at-least versus exact without opening the docs.","faqs":[{"question":"Does the argument count include the command name?","answer":"Yes. GET has arity 2: the word GET plus one key. That is why a bare GET is reported against the get command."},{"question":"Can a command accept unlimited arguments?","answer":"Commands such as RPUSH, SADD and DEL have negative arity, meaning 'at least N'. For them the error means you dropped below the minimum, not above a maximum."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/wrong-number-of-arguments","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/wrongpass","corpus":"errors","engine":"redis","language":"en","title":"Password or username rejected","description":"The connection sent credentials but Redis rejected them: the pair is wrong for that username, or the ACL user has been disabled.","body":{"code":"WRONGPASS","slug":"wrongpass","name":null,"message":"WRONGPASS invalid username-password pair or user is disabled.","group":"connection-auth","severity":null,"sql_state":null,"summary":"The connection sent credentials but Redis rejected them: the pair is wrong for that username, or the ACL user has been disabled.","meaning":"WRONGPASS arrives when the client did send credentials and the server looked at them and said no. Since Redis 6, authentication is per ACL user: the reply means either the password does not match that user's list, or the user exists but is flagged off.\n\nThe usual trap is mixing the two eras. A legacy requirepass password is the password of the user called default, so AUTH s3cret works while AUTH app s3cret fails with WRONGPASS. The other common shape is rotation: the server got the new password, a client still retries the old one, and every reconnect produces this error until its configuration is updated.","causes":["The password is correct for the default user but sent with a named user, or the other way around.","The ACL user was rotated or disabled with ACL SETUSER and clients still connect as that user with old credentials.","A stale environment variable or secrets store entry still serves the pre-rotation password."],"fix":[{"text":"List the users and their flags before guessing further:","sql":"redis-cli -a s3cret ACL LIST\nredis-cli -a s3cret ACL GETUSER app"},{"text":"Test the exact pair the client uses, username first for named users:","sql":"AUTH app s3cret\n# or, for the legacy default user:\nAUTH s3cret"},{"text":"Re-enable and re-password the user if a rotation disabled it underneath the application:","sql":"ACL SETUSER app on resetkeys >newpass ~app:* +@read +@write"}],"diagnostic":"# Who is this connection, and does the login hold?\nredis-cli -u redis://app:bad@db.example.com:6379 ACL WHOAMI\n# Inspect the user: flags include on/off and its passwords (hashed):\nredis-cli -a s3cret ACL GETUSER app\n# What the server would accept:\nredis-cli -a s3cret ACL LIST\n# Recent auth failures:\nredis-cli -a s3cret ACL LOG","alternatives":"Store the pair as one redis:// URL so the username cannot be dropped from configuration. For rotation without downtime, add the new password to the user first, deploy the clients with the new credentials, then remove the old password from the user afterwards.","details":[],"details_title":null,"repro":"redis-server --port 7301 --save '' &\nredis-cli -p 7301 ACL SETUSER app on '>goodpass' '~*' '+ping'\nredis-cli -p 7301 --user app --pass badpass PING\n# AUTH failed: WRONGPASS invalid username-password pair or user is disabled.\nredis-cli -p 7301 --user app --pass goodpass PING\n# PONG","repro_note":null,"related":["redis/noauth","postgresql/28P01","mysql/1045"],"sqlly":"SQLly's connection dialog reports the server's exact reply when the test fails, so a rejected Redis login is not mistaken for an unreachable host. The username and password fields match Redis 6+ ACL users, including the default-user case.","faqs":[{"question":"I only set requirepass, why does WRONGPASS talk about a user?","answer":"Since Redis 6 the legacy requirepass password belongs to the default user. AUTH pass logs in as default; AUTH someuser pass fails unless that user exists with that password."},{"question":"Does Redis lock the account after failed tries?","answer":"No. There is no lockout counter; the client can retry immediately. ACL LOG records the failures, which is how you spot brute forcing."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/wrongpass","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/redis/wrongtype","corpus":"errors","engine":"redis","language":"en","title":"The key holds a different data type","description":"The command expects one Redis data type and the key holds another: a list command on a string key, for example.","body":{"code":"WRONGTYPE","slug":"wrongtype","name":null,"message":"WRONGTYPE Operation against a key holding the wrong kind of value","group":"data-type-command","severity":null,"sql_state":null,"summary":"The command expects one Redis data type and the key holds another: a list command on a string key, for example.","meaning":"WRONGTYPE means the key exists but holds a different data type than the command needs. Redis keys are not schema-bound: strings, lists, sets, sorted sets, hashes and streams share one namespace, and the type is a property of the value, not of the key name. LPUSH on a key that holds a string fails exactly like this.\n\nIt is the Redis equivalent of a schema mismatch, and it usually starts as a naming collision: two parts of the application using one key name for two purposes, or an older writer that created the key as a string before a feature switched it to a hash. The investigation starts with TYPE, which tells you what you are actually holding.","causes":["Two code paths use the same key name for different types, so whichever creates the key first wins.","A migration or refactor changed the type a feature uses, and keys from the previous format are still there.","A deserializer or ORM hands the command the wrong field name, pointing at a string key next to the collection key."],"fix":[{"text":"Check the actual type and encoding before changing any code:","sql":"TYPE user:1000\nOBJECT ENCODING user:1000"},{"text":"Rename one side of the collision so each purpose has its own key:","sql":"RENAME user:1000 user:1000:profile-backup"},{"text":"Once nothing else writes to the old key, delete or rebuild it with the right commands:","sql":"DEL user:1000\nHSET user:1000 name alice plan pro"}],"diagnostic":"TYPE user:1000\nOBJECT ENCODING user:1000\nTTL user:1000\n# Scan the prefix to spot who else is writing nearby:\nSCAN 0 MATCH user:1000* COUNT 100","alternatives":"Where the type genuinely varies, encode the type in the key name (session:1000:hash, queue:jobs:list) so collisions are visible in code review. For legacy data, read the old value once with GET, convert it, write it back with the right command, and remove the old key in the same deploy.","details":[{"key":"GET, SET, INCR, APPEND","value":"string"},{"key":"LPUSH, RPUSH, LRANGE, LPOP","value":"list"},{"key":"HSET, HGET, HGETALL","value":"hash"},{"key":"SADD, SMEMBERS, SINTER","value":"set"},{"key":"ZADD, ZRANGE, ZRANK","value":"sorted set"},{"key":"XADD, XREAD, XGROUP","value":"stream"}],"details_title":"Commands and the types they require","repro":"redis-cli SET user:1000 alice\nredis-cli LPUSH user:1000 tasks\n# (error) WRONGTYPE Operation against a key holding the wrong kind of value\nredis-cli TYPE user:1000\n# string","repro_note":null,"related":["duckdb/conversion-could-not-convert","postgresql/42804","sqlite/sqlite-mismatch"],"sqlly":"SQLly prints the full WRONGTYPE line in the results pane, and TYPE and OBJECT ENCODING run from the same editor, so the mismatch is a two-command check rather than a code hunt.","faqs":[{"question":"How do I see a key's type?","answer":"TYPE key prints it: string, list, set, zset, hash, stream, bitmap or vectorset. OBJECT ENCODING adds the internal encoding, which explains behavior differences inside one type."},{"question":"Why is Redis strict about this?","answer":"Commands are typed per data structure. Silently coercing types would make every writer depend on the order in which readers and writers happened to run."},{"question":"Can one key hold two types?","answer":"No. A key has exactly one value with one type. Put the second structure under a different key."}],"aliases":[]},"source_url":"https://sqlly.app/errors/redis/wrongtype","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/102","corpus":"errors","engine":"sql-server","language":"en","title":"Incorrect syntax near","description":"The T-SQL parser hit something it didn't expect. The quoted text is where parsing stopped; the real mistake is often just before it.","body":{"code":"102","slug":"102","name":null,"message":"Incorrect syntax near '%.*ls'.","group":"syntax","severity":15,"sql_state":null,"summary":"The T-SQL parser hit something it didn't expect. The quoted text is where parsing stopped; the real mistake is often just before it.","meaning":"SQL Server parses the whole batch before running any of it. Error 102 means the parser found a token that can't appear at that point and quotes it (`Incorrect syntax near ','`). The token named is where the parser gave up, which is usually right after the actual mistake: a missing comma, an unclosed parenthesis, or syntax from another database. Because parsing failed, nothing in the batch ran.","causes":["Syntax from another database: `LIMIT 10` (MySQL, PostgreSQL), backtick-quoted names, `||` for string concatenation in older versions, `CREATE TABLE IF NOT EXISTS`.","A missing or extra comma in a column list, or a trailing comma before `FROM` or `)`.","Unbalanced parentheses or quotes.","A statement that must be first in its batch, such as `CREATE VIEW` or `CREATE PROCEDURE`, without a `GO` before it.","A missing semicolon before `WITH` (a CTE) or `THROW`, which then get read as part of the previous statement. `WITH` reports Msg 319 instead; `THROW` usually reports Msg 102 quoting its first argument, such as '50000'.","Newer syntax on an older server version, such as `STRING_AGG` (SQL Server 2017 or later) or `CREATE OR ALTER` (2016 SP1 or later). Compatibility level does not gate either one."],"fix":[{"text":"Look at the text just before the quoted token and the line number in the message; that's where the mistake usually is.","sql":null},{"text":"Replace other dialects' syntax with T-SQL. For example, use `TOP` or `OFFSET ... FETCH` instead of `LIMIT`, and square brackets or double quotes instead of backticks.","sql":"SELECT TOP (10) * FROM dbo.Orders ORDER BY OrderDate DESC;\nSELECT * FROM dbo.Orders ORDER BY OrderDate DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;"},{"text":"End the previous statement with a semicolon before a CTE or `THROW`.","sql":"DECLARE @n int = 5;\nWITH recent AS (SELECT TOP (@n) * FROM dbo.Orders ORDER BY OrderDate DESC)\nSELECT * FROM recent;"},{"text":"Put `GO` before statements that must start a batch.","sql":"CREATE TABLE dbo.T (id int);\nGO\nCREATE VIEW dbo.V AS SELECT id FROM dbo.T;"},{"text":"Check the database's compatibility level if newer syntax is rejected.","sql":"SELECT name, compatibility_level FROM sys.databases WHERE name = DB_NAME();"}],"diagnostic":"-- Find the exact line the batch failed on from client code\nBEGIN TRY\n  EXEC (@your_batch);\nEND TRY\nBEGIN CATCH\n  SELECT ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE();\nEND CATCH\n-- For a stored proc or view, dump its definition and read it\nSELECT OBJECT_SCHEMA_NAME(object_id) AS [schema], OBJECT_NAME(object_id) AS obj\nFROM sys.sql_modules\nWHERE definition LIKE '% suspect_token %';","alternatives":"If the script was written for MySQL or PostgreSQL, run it through a translation step or check the dialect first. Many ORMs and migration tools also let you log the generated SQL so you can paste it into SSMS and see the same error with real line numbers.","details":[],"details_title":null,"repro":"SELECT * FROM sys.objects LIMIT 10;  -- Msg 102: Incorrect syntax near '10'.","repro_note":null,"related":["sql-server/156","sql-server/105","sql-server/4145","postgresql/42601","mysql/1064","oracle/ora-00933"],"sqlly":"SQLly maps the line number in SQL Server's message to the right line of your whole script (not just the current batch) and highlights the failing token in the editor. Validate SQL (Cmd+Shift+V or Ctrl+Shift+V) checks a query without running it.","faqs":[{"question":"The error points at a comma. Where is the actual mistake?","answer":"Usually one token earlier. Look at the code just before the quoted position for a missing comma, an unmatched parenthesis, or a string that was never closed. The parser reports where it got stuck, not where you typed the mistake."},{"question":"Nothing ran at all?","answer":"Correct. Parsing happens before execution, so if one statement in the batch has a syntax error, none of the statements in that batch run. Fix the error and run the batch again."},{"question":"The same script works on another server. Why?","answer":"Check the server version, not the compatibility level. STRING_AGG needs SQL Server 2017 or later and works at any compatibility level. DROP TABLE IF EXISTS needs SQL Server 2016 or later. On an older server the new syntax fails, but the error number may differ from 102."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/102","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/105","corpus":"errors","engine":"sql-server","language":"en","title":"Unclosed quotation mark after the string","description":"A string literal was opened with a single quote and never closed, usually because the text itself contains an apostrophe that wasn't doubled.","body":{"code":"105","slug":"105","name":null,"message":"Unclosed quotation mark after the character string '%.*ls'.","group":"syntax","severity":15,"sql_state":null,"summary":"A string literal was opened with a single quote and never closed, usually because the text itself contains an apostrophe that wasn't doubled.","meaning":"T-SQL strings are delimited by single quotes, and a quote inside a string must be written twice (`'O''Brien'`). If the parser reaches the end of the batch while still inside a string, it raises 105, often accompanied by 102 or 156, depending on which error the parser reaches first.","causes":["An apostrophe in the data, such as `O'Brien` or `don't`, inside a hand-written literal.","SQL built by concatenating user input into a string, which is also an SQL injection risk.","A missing closing quote, or a closing quote typed as a different character (a curly quote pasted from a document)."],"fix":[{"text":"Double any single quote inside a literal.","sql":"SELECT * FROM dbo.Customers WHERE LastName = 'O''Brien';"},{"text":"Better, pass values as parameters instead of building strings. In dynamic SQL use `sp_executesql`.","sql":"EXEC sys.sp_executesql\n    N'SELECT * FROM dbo.Customers WHERE LastName = @name',\n    N'@name nvarchar(100)',\n    @name = N'O''Brien';"},{"text":"If you must embed a value in dynamic SQL, quote it with `QUOTENAME(@value, '''')`, which doubles embedded quotes (for values up to 128 characters).","sql":null}],"diagnostic":"-- Isolate the broken batch and count the quotes in the offending line\nBEGIN TRY\n  EXEC (@your_batch);\nEND TRY\nBEGIN CATCH\n  SELECT ERROR_MESSAGE(), ERROR_LINE();\nEND CATCH\n-- Escape test: this should return the value itself, not error\nSELECT 'O''Brien' AS escaped_ok;","alternatives":"Passing strings as parameters spares you from quoting entirely, so move string values into parameters where you can. For generated SQL, use QUOTENAME for names, and for literals use QUOTENAME(@value, '''') or wrap REPLACE(@value, '''', '''''') in your own single quotes instead of hand-building quotes.","details":[],"details_title":null,"repro":"SELECT 'it''s fine';\nSELECT 'it's not';  -- Msg 105 and Msg 156","repro_note":null,"related":["sql-server/102","sql-server/156","postgresql/42601","mysql/1064","oracle/ora-01756"],"sqlly":"An unterminated quote fails the parse that Validate SQL (Cmd+Shift+V or Ctrl+Shift+V) performs, so SQLly's editor flags the string before the batch ever goes to the server.","faqs":[{"question":"Why do quotes have to be doubled?","answer":"Single quote is the string delimiter in T-SQL. Writing it twice inside a string means one literal quote, the same way \"\" escapes a quote in CSV."},{"question":"I see the closing quote right there. Why is it unclosed?","answer":"Look one line up. A string from the previous statement probably never ended, and the parser kept reading until it found a quote it thought was an opening one."},{"question":"Does QUOTENAME help here?","answer":"Yes, when the second argument is a single quote: QUOTENAME(@value, '''') wraps the value in single quotes and doubles embedded quotes, for inputs up to 128 characters (longer inputs return NULL). A parameter is still the better choice."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/105","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1101","corpus":"errors","engine":"sql-server","language":"en","title":"Could not allocate a new page","description":"SQL Server needed a new page in the filegroup and every data file is full and unable to grow. Free disk space or let the files grow.","body":{"code":"1101","slug":"1101","name":null,"message":"Could not allocate a new page for database '%.*ls' because the '%.*ls' filegroup is full due to lack of storage space or database files reaching the maximum allowed size. Note that UNLIMITED files are still limited to 16TB. Create the necessary space by dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.","group":"resources","severity":17,"sql_state":null,"summary":"SQL Server needed a new page in the filegroup and every data file is full and unable to grow. Free disk space or let the files grow.","meaning":"Error 1101 is raised when SQL Server can't allocate a new page in a filegroup: all of its files are full, and autogrowth is off, a maximum size was reached, or the disk has no room. It is the page-level counterpart of 1105 and has the same fixes.","causes":["Data files with autogrowth disabled or a `MAXSIZE` that has been reached.","A full disk.","The 10 GB database limit of SQL Server Express."],"fix":[{"text":"Check the files and how full the volume is.","sql":"SELECT f.name, f.size / 128 AS size_mb, vs.available_bytes / 1048576 AS disk_free_mb\nFROM sys.database_files AS f\nCROSS APPLY sys.dm_os_volume_stats(DB_ID(), f.file_id) AS vs;"},{"text":"Allow growth or add a file, as for error 1105.","sql":"ALTER DATABASE SalesDb MODIFY FILE (NAME = SalesDb_data, MAXSIZE = UNLIMITED, FILEGROWTH = 64MB);"}],"diagnostic":"-- File-level space picture\nSELECT f.name, f.size/128.0 AS size_mb, f.max_size, f.is_read_only,\n       FILEPROPERTY(f.name, 'SpaceUsed')/128.0 AS used_mb\nFROM sys.database_files f;\n-- Who is consuming pages in this filegroup?\nSELECT au.type_desc, SUM(p.rows) AS rows_total\nFROM sys.partitions p\nJOIN sys.allocation_units au ON au.container_id = p.hobt_id\nGROUP BY au.type_desc;\n-- Disk free space for the volume the file lives on\nEXEC master.sys.xp_fixeddrives;","alternatives":"If the table is mostly free space after deletes, rebuilding the index reclaims pages: ALTER INDEX ... REBUILD. Splitting a huge table across filegroups, or adding a second data file on another disk, gives the filegroup room without a restore.","details":[],"details_title":null,"repro":"-- Same shape as 1105: a data file that cannot grow\nCREATE DATABASE err1101 ON (NAME = err1101, FILENAME = 'C:\\temp\\err1101.mdf', SIZE = 4MB, MAXSIZE = 4MB, FILEGROWTH = 0)\nLOG ON (NAME = err1101_log, FILENAME = 'C:\\temp\\err1101.ldf', SIZE = 8MB, MAXSIZE = UNLIMITED);\nUSE err1101;\nCREATE TABLE t (filler CHAR(4000) DEFAULT 'x');\n-- Insert rows until allocation of a new page fails\n-- Cleanup: DROP DATABASE err1101;","repro_note":null,"related":["sql-server/1105","sql-server/9002","mysql/1114","oracle/ora-01653"],"sqlly":"Run the sys.database_files query in SQLly's editor: the grid lays out growth settings per file, so the filegroup that ran out of pages is identifiable in one result set.","faqs":[{"question":"Can 1101 happen from one huge INSERT?","answer":"A single INSERT into an existing table that exhausts a capped file raises 1105, the object-level error. 1101 appears when the allocation has no named object yet, such as SELECT INTO a new table. Check the error number before choosing a fix."},{"question":"Does shrinking the database fix it?","answer":"It frees space back to the operating system, but if the workload needs that space again the error returns. Fix the cap or add disk instead of scheduling shrinks."},{"question":"Tempdb can hit 1101 too?","answer":"Yes, tempdb is a database like any other. Check its files with the same sys.database_files query while connected to tempdb, and remember tempdb is recreated on restart so the fix is usually sizing the tempdb files, not the data in them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1101","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1105","corpus":"errors","engine":"sql-server","language":"en","title":"Filegroup is full, cannot allocate","description":"A data file in the filegroup reached its maximum size or the disk is full, so SQL Server can't allocate space for the table or index.","body":{"code":"1105","slug":"1105","name":null,"message":"Could not allocate space for object '%.*ls'%.*ls in database '%.*ls' because the '%.*ls' filegroup is full due to lack of storage space or database files reaching the maximum allowed size. Note that UNLIMITED files are still limited to 16TB. Create the necessary space by dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.","group":"resources","severity":17,"sql_state":null,"summary":"A data file in the filegroup reached its maximum size or the disk is full, so SQL Server can't allocate space for the table or index.","meaning":"Tables and indexes live in filegroups made of one or more data files. When none of the files in the filegroup has free space and none can grow, because autogrowth is off, a `MAXSIZE` was reached or the disk is full, inserts into a table that already has pages fail with 1105, and index builds can fail with 1101 instead. Error 1101 is the same condition when allocating a new page. In SQL Server Express, the 10 GB database size limit causes it too.","causes":["Autogrowth disabled, or `MAXSIZE` set on the data files.","The disk or volume holding the data files is full.","SQL Server Express reached its 10 GB per-database limit.","An index rebuild or large load that temporarily needs much more space."],"fix":[{"text":"Check file sizes, limits and growth settings.","sql":"SELECT name, physical_name, size / 128 AS size_mb,\n       CASE max_size WHEN -1 THEN NULL ELSE max_size / 128 END AS max_mb,\n       growth, is_percent_growth\nFROM sys.database_files;"},{"text":"Let the file grow, or raise its limit.","sql":"ALTER DATABASE SalesDb MODIFY FILE (NAME = SalesDb_data, MAXSIZE = UNLIMITED, FILEGROWTH = 1GB);"},{"text":"Add a file on another volume if the disk is full.","sql":"ALTER DATABASE SalesDb ADD FILE (NAME = SalesDb_data2, FILENAME = N'E:\\Data\\SalesDb_data2.ndf', SIZE = 10GB, FILEGROWTH = 1GB) TO FILEGROUP [PRIMARY];"},{"text":"Free space by archiving or purging old data, then rebuild fragmented indexes.","sql":null}],"diagnostic":"-- Where is the space going and how close is each file to its cap?\nSELECT f.name, f.type_desc, f.size/128.0 AS size_mb,\n       f.max_size, f.growth,\n       FILEPROPERTY(f.name, 'SpaceUsed')/128.0 AS used_mb\nFROM sys.database_files f;\n-- Instance-wide view: file size vs disk free space\nSELECT DB_NAME(vfs.database_id) AS db, mf.name, vfs.size_on_disk_bytes/1048576 AS mb\nFROM sys.dm_io_virtual_file_stats(NULL, NULL) vfs\nJOIN sys.master_files mf ON mf.database_id = vfs.database_id AND mf.file_id = vfs.file_id;\n-- In Express, check the 10 GB per-database limit first:\nSELECT SUM(size/128.0)/1024.0 AS total_gb FROM sys.database_files WHERE type = 0;","alternatives":"Moving a big table or index to its own filegroup spreads the load across files and disks, and shrinking is a last resort because the space usually just fills again. Archiving old rows out of the database frees space without touching files.","details":[],"details_title":null,"repro":"-- Scratch database with a hard 16 MB cap on the data file\nCREATE DATABASE err1105 ON (NAME = err1105, FILENAME = 'C:\\temp\\err1105.mdf', SIZE = 8MB, MAXSIZE = 16MB, FILEGROWTH = 8MB)\nLOG ON (NAME = err1105_log, FILENAME = 'C:\\temp\\err1105.ldf', SIZE = 8MB, MAXSIZE = UNLIMITED);\nUSE err1105;\nCREATE TABLE t (filler CHAR(4000) DEFAULT 'x');\n-- Keep filling until it fails: INSERT INTO t DEFAULT VALUES; (in a loop)\n-- Cleanup: DROP DATABASE err1105;","repro_note":null,"related":["sql-server/1101","sql-server/9002","postgresql/53100","mysql/1114","oracle/ora-01653","sqlite/sqlite-full"],"sqlly":"From the editor, a quick query of sys.database_files puts each file's size, max size and growth setting into SQLly's grid, which points at the file that hit its cap.","faqs":[{"question":"How is 1105 different from 1101?","answer":"Same condition, different allocation step. In testing, 1101 came up when the first page of a new table or index was allocated, and 1105 when an existing table needed more space. Both are severity 17, and the diagnostics and fixes are identical, so check both articles against the same output."},{"question":"Autogrowth is on. Why did this still fail?","answer":"Autogrowth has a ceiling: the file's MAXSIZE, or the free space on the disk. On, but capped, still fails. The sys.database_files query above shows max_size for every file."},{"question":"Should I just set files to UNLIMITED growth?","answer":"Usually no. Fast unlimited growth on a busy disk makes the drive run out during business hours instead of during a planned change. Set a sane MAXSIZE and alert before it is hit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1105","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1204","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot obtain a LOCK resource","description":"SQL Server ran out of memory for locks. Too many locks are held at once, usually by a huge transaction or a long-running one.","body":{"code":"1204","slug":"1204","name":null,"message":"The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions.","group":"resources","severity":19,"sql_state":null,"summary":"SQL Server ran out of memory for locks. Too many locks are held at once, usually by a huge transaction or a long-running one.","meaning":"Each lock uses a little memory. When SQL Server can't allocate memory for another lock, the statement fails with 1204 and the active transaction is rolled back. Lock escalation normally replaces thousands of row or page locks with one table lock, so this usually means escalation was prevented or the instance is short of memory.","causes":["A single transaction that modifies a very large number of rows while lock escalation is disabled (`LOCK_ESCALATION = DISABLE` or trace flags 1211/1224).","Many concurrent transactions each holding many locks.","Low memory available to SQL Server."],"fix":[{"text":"Break large modifications into smaller transactions.","sql":"WHILE 1 = 1\nBEGIN\n    UPDATE TOP (5000) dbo.Orders SET Archived = 1 WHERE Archived = 0 AND OrderDate < '2023-01-01';\n    IF @@ROWCOUNT = 0 BREAK;\nEND;"},{"text":"Check lock escalation settings on the table.","sql":"SELECT name, lock_escalation_desc FROM sys.tables WHERE name = N'Orders';"},{"text":"See which sessions hold the most locks.","sql":"SELECT request_session_id, COUNT(*) AS locks\nFROM sys.dm_tran_locks GROUP BY request_session_id ORDER BY locks DESC;"}],"diagnostic":"-- Lock counts per session tell you whether one transaction is hoarding:\nSELECT request_session_id, request_mode, COUNT(*) AS lock_count\nFROM sys.dm_tran_locks\nGROUP BY request_session_id, request_mode\nORDER BY lock_count DESC;\n\n-- Is escalation turned off on the offending table?\nSELECT name, lock_escalation_desc\nFROM sys.tables WHERE lock_escalation_desc <> 'TABLE';\n\n-- Trace flags 1211/1224 disable escalation instance-wide; check them:\nDBCC TRACESTATUS(-1);\n\n-- Was this really memory for locks? Look for MEMORY_ALLOCATION_EXT or\n-- low RESOURCE_SEMAPHORE-style pressure around the failure time:\nSELECT * FROM sys.dm_os_ring_buffers\nWHERE ring_buffer_type = N'RING_BUFFER_MEMORY_BROKER';","alternatives":"If escalation must stay off, batch the writes into chunks small enough that their lock count stays affordable. Row versioning (READ_COMMITTED_SNAPSHOT, SNAPSHOT) reduces reader locks but does not help the writer's own locks in a huge transaction.","details":[],"details_title":null,"repro":"-- One transaction over a big table with escalation disabled is the classic repro.\nCREATE TABLE dbo.BigTargets (Id int IDENTITY PRIMARY KEY, Val int NOT NULL);\nWITH n AS (SELECT 1 AS x UNION ALL SELECT x + 1 FROM n WHERE x < 100000)\nINSERT INTO dbo.BigTargets (Val) SELECT x FROM n OPTION (MAXRECURSION 0);\n\nALTER TABLE dbo.BigTargets SET (LOCK_ESCALATION = DISABLE);\n\nBEGIN TRAN;\nUPDATE dbo.BigTargets SET Val = Val + 1;\n-- On a memory-constrained instance (or after lowering max server memory),\n-- the lock manager runs out and error 1204 is raised. Keep the transaction\n-- open and check the lock count:\nSELECT COUNT(*) FROM sys.dm_tran_locks WHERE request_session_id = @@SPID;\nROLLBACK;\nALTER TABLE dbo.BigTargets SET (LOCK_ESCALATION = TABLE);","repro_note":null,"related":["sql-server/1222","sql-server/701","mysql/1206"],"sqlly":"SQLly's activity monitor lists sessions with their blocking chains and open transactions, which is the fastest way to find the transaction that had the lock manager under pressure.","faqs":[{"question":"What trace flags disable lock escalation?","answer":"1211 disables escalation entirely. 1211 disables all lock escalation. 1224 disables escalation based on the number of locks. Both are instance-wide and override the table setting: a table set to TABLE still does not escalate while 1211 is on. Prefer the per-table ALTER TABLE SET (LOCK_ESCALATION ...) option, which limits the change to one table."},{"question":"How many locks does escalation kick in at?","answer":"Roughly 5,000 locks on a single statement, though escalation also considers memory pressure and lock conflict, so the exact point varies. Microsoft documents this as at least 5,000 locks acquired by one statement on a nonpartitioned table. Escalation also happens when lock memory crosses its threshold, and it is retried every 1,250 locks when conflicts block it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1204","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1205","corpus":"errors","engine":"sql-server","language":"en","title":"Deadlocked and chosen as the victim","description":"Two sessions were each waiting on locks the other held. SQL Server rolled back this transaction so the other could finish. Retry it.","body":{"code":"1205","slug":"1205","name":null,"message":"Transaction (Process ID %d) was deadlocked on %.*ls resources with another process and has been chosen as the deadlock victim. Rerun the transaction.","group":"transactions","severity":13,"sql_state":null,"summary":"Two sessions were each waiting on locks the other held. SQL Server rolled back this transaction so the other could finish. Retry it.","meaning":"A deadlock is a cycle of lock waits: session A holds a lock B needs, while B holds a lock A needs. SQL Server's deadlock monitor detects the cycle and ends it by choosing a victim, rolling back that session's whole transaction and raising 1205. The victim is the session with the lowest `DEADLOCK_PRIORITY`, and among equal priorities the one that is cheapest to roll back.\n\nThe other session continues as if nothing happened. Deadlocks are a normal outcome under concurrency; the goal is to make them rare and to retry when they happen.","causes":["Two code paths update the same tables or rows in opposite order.","A read under the default read committed isolation level, waiting on a writer that is in turn waiting on the reader's shared lock (common with lookups through nonclustered indexes).","Missing indexes that make updates and deletes scan and lock far more rows than they change.","Long transactions, or user interaction in the middle of an open transaction.","Higher isolation levels such as `SERIALIZABLE` holding range locks."],"fix":[{"text":"Retry the transaction in the application when it fails with 1205. In T-SQL, a retry loop looks like this:","sql":"DECLARE @tries int = 0;\nWHILE @tries < 3\nBEGIN\n    BEGIN TRY\n        BEGIN TRANSACTION;\n        UPDATE dbo.Accounts SET Balance -= 100 WHERE AccountId = 1;\n        UPDATE dbo.Accounts SET Balance += 100 WHERE AccountId = 2;\n        COMMIT;\n        BREAK;\n    END TRY\n    BEGIN CATCH\n        IF @@TRANCOUNT > 0 ROLLBACK;\n        IF ERROR_NUMBER() <> 1205 OR @tries = 2 THROW;\n        SET @tries += 1;\n        WAITFOR DELAY '00:00:00.100';\n    END CATCH\nEND;"},{"text":"Read the deadlock graph. The built-in `system_health` Extended Events session records every deadlock.","sql":"SELECT xed.value('@timestamp', 'datetime2') AS occurred_at, xed.query('.') AS deadlock_graph\nFROM (SELECT CAST(target_data AS xml) AS target_data\n      FROM sys.dm_xe_session_targets AS t\n      JOIN sys.dm_xe_sessions AS s ON s.address = t.event_session_address\n      WHERE s.name = N'system_health' AND t.target_name = N'ring_buffer') AS data\nCROSS APPLY target_data.nodes('RingBufferTarget/event[@name=\"xml_deadlock_report\"]') AS x(xed);"},{"text":"Access tables and rows in the same order in every transaction, and keep transactions short.","sql":null},{"text":"Add indexes so writes touch only the rows they change; the deadlock graph shows which index each lock was on.","sql":null},{"text":"Consider read committed snapshot isolation, so readers use row versions instead of shared locks and no longer deadlock with writers.","sql":"ALTER DATABASE SalesDb SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;"},{"text":"Mark less important work as the preferred victim.","sql":"SET DEADLOCK_PRIORITY LOW;"}],"diagnostic":"-- The deadlock graph from the system_health Extended Events session shows exactly\n-- which sessions, statements and resources were involved and who was chosen as victim\nSELECT\n    XEvent.query('(data/value/deadlock)[1]') AS DeadlockReport\nFROM (\n    SELECT CAST(target_data AS xml) AS TargetData\n    FROM sys.dm_xe_session_targets st\n    JOIN sys.dm_xe_sessions s ON s.address = st.event_session_address\n    WHERE s.name = 'system_health' AND st.target_name = 'ring_buffer'\n) AS Data\nCROSS APPLY TargetData.nodes(\n    'RingBufferTarget/event[@name=\"xml_deadlock_report\"]') AS x(XEvent);\n\n-- Who is running long transactions right now\nSELECT r.session_id, r.status, r.wait_type, r.blocking_session_id,\n       r.wait_time, r.open_transaction_count, st.text\nFROM sys.dm_exec_requests r\nOUTER APPLY sys.dm_exec_sql_text(r.sql_handle) st\nWHERE r.open_transaction_count > 0 OR r.blocking_session_id <> 0;","alternatives":"Enable read committed snapshot isolation for the database to remove reader-writer blocking without dirty reads, and access hot rows in a consistent order across all code paths. Setting DEADLOCK_PRIORITY on batch jobs lets them lose to interactive sessions instead of the other way around.","details":[],"details_title":null,"repro":"-- Setup (once):\nCREATE TABLE dbo.DL (id int PRIMARY KEY, v int);\nINSERT INTO dbo.DL VALUES (1, 0), (2, 0);\n-- Session 1:\nBEGIN TRAN; UPDATE dbo.DL SET v = 1 WHERE id = 1;\n-- Session 2:\nBEGIN TRAN; UPDATE dbo.DL SET v = 2 WHERE id = 2;\nUPDATE dbo.DL SET v = 2 WHERE id = 1;  -- waits\n-- Session 1:\nUPDATE dbo.DL SET v = 1 WHERE id = 2;  -- one session gets Msg 1205","repro_note":"Run the steps in two separate connections to a scratch database, in the order shown, then roll back the surviving session and drop the table.","related":["sql-server/1222","sql-server/3960","sql-server/266","postgresql/40P01","mysql/1213","oracle/ora-00060"],"sqlly":"SQLly's activity monitor shows SQL Server sessions with their blocking chains and waits, so you can see who is blocking whom while it's happening, and kill a stuck session if you need to.","faqs":[{"question":"Is my data lost after a deadlock?","answer":"The victim's whole transaction is rolled back, so none of its changes were saved. Nothing else is affected. Run the transaction again."},{"question":"Does NOLOCK fix deadlocks?","answer":"It can stop readers from taking shared locks, but it allows dirty and inconsistent reads (missing or duplicated rows). Read committed snapshot isolation removes reader-writer blocking without those risks."},{"question":"After a 1205, is my transaction still open?","answer":"Yes, but it is doomed. The victim's changes are undone and its locks are released, but in the CATCH block `@@TRANCOUNT` is 1 and `XACT_STATE()` is -1. Issue `ROLLBACK`; any write before that fails with Msg 3930. A lock timeout (1222) is different: its transaction stays open and can still commit."},{"question":"How do I find the deadlock after it has happened?","answer":"`system_health` keeps only recent deadlock graphs: the ring buffer holds about 4 MB, and the event file rolls over. Pull `xml_deadlock_report` from its ring buffer (see the diagnostic above) and read which session was the victim and which resources the two statements wanted. The graph also shows the lock modes, so you can see which missing index turned two updates into a scan-and-lock fight."},{"question":"Should I make my batch less likely to be the victim with DEADLOCK_PRIORITY HIGH?","answer":"HIGH wins only against lower priorities. When both sessions are HIGH, the one cheaper to roll back is still chosen, and the rollback moves to someone else's transaction. Use HIGH only for genuinely critical work, and treat it as a stopgap: consistent access order, indexes that narrow the locks, and retries are what make deadlocks rare. Use HIGH only for genuinely critical work, and treat it as a stopgap: consistent access order, indexes that narrow the locks, and retries are what make deadlocks rare."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1205","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1222","corpus":"errors","engine":"sql-server","language":"en","title":"Lock request time out period exceeded","description":"A statement waited longer than the session's LOCK_TIMEOUT for a lock another session holds, so SQL Server cancelled the statement.","body":{"code":"1222","slug":"1222","name":null,"message":"Lock request time out period exceeded.","group":"transactions","severity":16,"sql_state":null,"summary":"A statement waited longer than the session's LOCK_TIMEOUT for a lock another session holds, so SQL Server cancelled the statement.","meaning":"By default SQL Server waits for a lock indefinitely (`LOCK_TIMEOUT` is -1). When a session sets `SET LOCK_TIMEOUT` to a number of milliseconds, any lock wait longer than that fails with 1222. Some tools, including SSMS's Object Explorer, set a lock timeout for their own queries, which is why 1222 often appears when browsing a database while a long transaction holds locks.\n\nOnly the statement is cancelled. The transaction stays open unless `XACT_ABORT` is on, so code that catches 1222 must decide whether to roll back.","causes":["Another session holds locks for a long time, typically an open transaction someone forgot to commit, or a long-running update or index rebuild.","Schema modification locks held by `ALTER TABLE` or other DDL in progress.","Object Explorer or a monitoring query with a short timeout running during heavy write activity."],"fix":[{"text":"Find who is blocking.","sql":"SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time, t.text\nFROM sys.dm_exec_requests AS r\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t\nWHERE r.blocking_session_id <> 0;"},{"text":"Look for sessions with open transactions that are idle.","sql":"SELECT s.session_id, s.login_name, s.host_name, s.program_name, s.last_request_end_time\nFROM sys.dm_exec_sessions AS s\nWHERE s.open_transaction_count > 0 AND s.status = 'sleeping';"},{"text":"Commit or roll back the blocking transaction, or as a last resort end that session.","sql":"KILL 57;  -- the blocking session_id"},{"text":"If your code sets `LOCK_TIMEOUT`, handle 1222 by rolling back and retrying, and keep write transactions short.","sql":null}],"diagnostic":"-- Find the session holding the locks: blocking_session_id points at it\nSELECT r.session_id, r.blocking_session_id, r.status, r.wait_type,\n       r.wait_time, r.command, st.text\nFROM sys.dm_exec_requests r\nOUTER APPLY sys.dm_exec_sql_text(r.sql_handle) st\nWHERE r.blocking_session_id <> 0;\n\n-- What the blocker is doing and where it came from\nSELECT s.session_id, s.login_name, s.host_name, s.program_name,\n       s.last_request_start_time, st.text\nFROM sys.dm_exec_sessions s\nOUTER APPLY sys.dm_exec_sql_text(s.sql_handle) st\nWHERE s.session_id = <blocking_session_id>;\n\n-- Which locks it holds\nSELECT request_session_id, resource_type, resource_database_id,\n       resource_associated_entity_id, request_mode, request_status\nFROM sys.dm_tran_locks\nWHERE request_session_id = <blocking_session_id>;\n\n-- The last batch the client sent on this session (the whole batch, not only the current statement)\nDBCC INPUTBUFFER(<blocking_session_id>);","alternatives":"Fix the blocker rather than the waiter: commit or kill the stray transaction, or move bulk work into batches so locks are held briefly. If timeouts are intentional, catching 1222 and retrying keeps the application responsive without raising LOCK_TIMEOUT globally.","details":[],"details_title":null,"repro":"-- Session 1:\nBEGIN TRAN; UPDATE dbo.DL SET v = v WHERE id = 1;\n-- Session 2:\nSET LOCK_TIMEOUT 1000;\nSELECT * FROM dbo.DL WHERE id = 1;  -- Msg 1222 after 1 second","repro_note":"Uses the scratch table from the 1205 example; roll back session 1 afterwards.","related":["sql-server/1205","sql-server/5030","postgresql/55P03","mysql/1205","oracle/ora-00054","sqlite/sqlite-busy"],"sqlly":"SQLly's activity monitor lists SQL Server sessions with their blocking chains and waits, and can kill a session. In SQLly itself, a transaction your script leaves open in auto-commit mode is rolled back when the run ends, so it can't sit there holding locks.","faqs":[{"question":"Why do I get this when just expanding tables in SSMS?","answer":"Object Explorer runs its metadata queries with a short lock timeout of its own. A long-running transaction or DDL statement on the table blocks it and you see 1222 even though you only browsed. The problem is the blocker, not your click."},{"question":"Does SET LOCK_TIMEOUT change other sessions?","answer":"No. It is a session setting and lasts for the connection unless changed again. Check DBCC USEROPTIONS to see the current value for your session."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1222","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/15023","corpus":"errors","engine":"sql-server","language":"en","title":"User, group, or role already exists","description":"CREATE USER or a similar statement named a principal that already exists in the database, often an orphaned user left behind by a restore.","body":{"code":"15023","slug":"15023","name":null,"message":"User, group, or role '%s' already exists in the current database.","group":"permissions","severity":16,"sql_state":null,"summary":"CREATE USER or a similar statement named a principal that already exists in the database, often an orphaned user left behind by a restore.","meaning":"Database principal names are unique per database. Error 15023 appears when you create a user or role that is already there. After restoring a database to another server, the old database user is usually still present but no longer linked to a login, and trying to create it again fails with 15023.","causes":["Running a setup script twice.","Restoring a database to a new server: the database user exists but is orphaned, because the new server's login has a different SID.","Mapping a login to a database in SSMS when a user of that name already exists."],"fix":[{"text":"If the existing user is orphaned, link it to the login instead of creating a new one.","sql":"ALTER USER app_user WITH LOGIN = app_user;"},{"text":"Make setup scripts idempotent.","sql":"IF DATABASE_PRINCIPAL_ID(N'app_user') IS NULL\n    CREATE USER app_user FOR LOGIN app_user;"}],"diagnostic":"-- Does a user of that name exist, and is it mapped to a live login?\nSELECT dp.name, dp.type_desc, dp.sid,\n       CASE WHEN sp.sid IS NULL THEN N'orphaned' ELSE N'linked' END AS state\nFROM sys.database_principals dp\nLEFT JOIN sys.server_principals sp ON sp.sid = dp.sid\nWHERE dp.name = N'app_user' AND dp.type IN ('S','U');\n-- Sweep the whole database for orphaned users (restored databases usually have some):\nSELECT dp.name AS orphaned_user\nFROM sys.database_principals dp\nLEFT JOIN sys.server_principals sp ON sp.sid = dp.sid\nWHERE dp.type = 'S' AND sp.sid IS NULL AND dp.name NOT IN ('dbo','guest','INFORMATION_SCHEMA','sys');","alternatives":"After a restore, ALTER USER ... WITH LOGIN re-links the existing user instead of dropping and recreating it, which keeps grants on that user intact. In setup scripts, guard the CREATE with IF DATABASE_PRINCIPAL_ID(...) IS NULL so reruns are harmless. On contained availability groups or containers where you want SIDs to match everywhere, create the login on the new server with the same SID: CREATE LOGIN ... WITH SID = 0x..., copied from the old server before the restore.","details":[],"details_title":null,"repro":"CREATE LOGIN repro_user WITH PASSWORD = 'Repro!2345';\nCREATE USER repro_user FOR LOGIN repro_user;\n-- Running the create again (typical of a setup script on second run):\nCREATE USER repro_user FOR LOGIN repro_user;  -- Msg 15023: User, group, or role 'repro_user' already exists in the current database.\n-- The orphaned-user case: same name, different SID on the new server.\nALTER USER repro_user WITH LOGIN = repro_user;  -- fixes the orphan instead of re-creating\nDROP USER repro_user;\nDROP LOGIN repro_user;","repro_note":null,"related":["sql-server/15151","sql-server/916","sql-server/2714"],"sqlly":"Query sys.database_principals in SQLly's grid to see the principal that already holds the name, then decide whether to alter it or pick a new name in the editor.","faqs":[{"question":"I restored a database and now the app cannot log in. Is that 15023?","answer":"Related but one step earlier: the app's login reaches the server, but the database user's SID no longer matches, so SQL Server cannot open the requested database. The session falls back to the login's default database (master here), with message 4063, and a USE of the database then returns error 916. Fix it with ALTER USER app_user WITH LOGIN = app_user in the restored database. Fix it with ALTER USER app_user WITH LOGIN = app_user in the restored database. The 15023 error shows up if you instead try to CREATE USER with that name."},{"question":"Can I just DROP USER and recreate it?","answer":"It works, but you lose the grants on the user. DROP USER also fails if the user owns a schema (error 15138), so transfer that ownership first. ALTER USER ... WITH LOGIN preserves permissions, so prefer that for an orphaned user."},{"question":"Why does the error mention groups and roles?","answer":"The message covers all database principal kinds. CREATE ROLE raises 15023 too when the role name is taken, and users and roles share the same namespace per database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/15023","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/15025","corpus":"errors","engine":"sql-server","language":"en","title":"The server principal already exists","description":"CREATE LOGIN used a name that already exists on the instance. Check for the existing login, or create it only if missing.","body":{"code":"15025","slug":"15025","name":null,"message":"The server principal '%s' already exists.","group":"permissions","severity":16,"sql_state":null,"summary":"CREATE LOGIN used a name that already exists on the instance. Check for the existing login, or create it only if missing.","meaning":"Login names are unique across the SQL Server instance, and so are login SIDs. Error 15025 appears when you create a login whose name is already taken. A SID that is already taken raises error 15433 ('Supplied parameter sid is in use.') instead.","causes":["Re-running a script that creates logins.","Copying logins between servers with `SID = ...` when a login with the same name already exists. A SID clash alone raises 15433 instead.","A Windows login added again under a different spelling of the same account."],"fix":[{"text":"Check existing logins by name and SID.","sql":"SELECT name, sid, type_desc FROM sys.server_principals WHERE name = N'app_user';"},{"text":"Create the login only when it's missing.","sql":"IF SUSER_ID(N'app_user') IS NULL\n    CREATE LOGIN app_user WITH PASSWORD = N'<strong password>';"}],"diagnostic":"-- Is the name taken, and what type of principal holds it?\nSELECT name, sid, type_desc, is_disabled\nFROM sys.server_principals\nWHERE name = N'app_user';\n-- If you were specifying a SID, find which login already owns it:\nSELECT name, sid, type_desc\nFROM sys.server_principals\nWHERE sid = 0x0123456789ABCDEF; -- the SID from your script\n-- SUSER_ID(N'app_user') returns NULL when no login has that name.","alternatives":"Guard creation with IF SUSER_ID(N'app_user') IS NULL before CREATE LOGIN so reruns are safe. If the login is for a contained availability group or a migration and you need matching SIDs across servers, check whether the existing login already has the right SID rather than creating a second one. If the old login is genuinely unwanted, drop it first, then create the new one.","details":[],"details_title":null,"repro":"-- Scratch instance repro: create the same login twice\nCREATE LOGIN app_user WITH PASSWORD = N'C0rrect-Horse-1!';\nGO\n-- Raises 15025: server principal 'app_user' already exists\nCREATE LOGIN app_user WITH PASSWORD = N'Another-Pass-2@';\nGO\nDROP LOGIN app_user;","repro_note":null,"related":["sql-server/15023","sql-server/15151","mysql/1396"],"sqlly":"Query sys.server_principals in SQLly's grid to find the login that already holds the name or SID, then alter it or pick a new name in the editor.","faqs":[{"question":"Does a duplicate SID cause this error?","answer":"SIDs must be unique on the instance too, but a SID clash raises error 15433 ('Supplied parameter sid is in use.'), not 15025. Error 15025 comes from the name: a login with the same name collides even when its SID differs. Query sys.server_principals by both name and SID to see which one collided."},{"question":"Is a login the same as a database user?","answer":"No. A login is a server-level principal that lets you connect; a user maps a login into one database. The 15025 collision is at the server level. A database can be missing the user even though the login exists, which is why you sometimes create the login successfully and still cannot get into a database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/15025","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1505","corpus":"errors","engine":"sql-server","language":"en","title":"Duplicate key found, unique index","description":"A unique index or constraint can't be created because the table already contains duplicate values in those columns. The message shows one of them.","body":{"code":"1505","slug":"1505","name":null,"message":"The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name '%.*ls' and the index name '%.*ls'. The duplicate key value is %ls.","group":"constraints","severity":16,"sql_state":null,"summary":"A unique index or constraint can't be created because the table already contains duplicate values in those columns. The message shows one of them.","meaning":"Before a unique index or a primary key or unique constraint can be built, every existing row must have a distinct key. If the data already contains duplicates, the build stops with 1505 and shows one duplicate value. Error 1750 usually follows when the index was part of a constraint.","causes":["Duplicate rows that crept in before the uniqueness rule was added.","Multiple NULLs in a column you're making unique (SQL Server counts NULLs as equal in unique indexes)."],"fix":[{"text":"Find all duplicate keys.","sql":"SELECT Email, COUNT(*) AS n FROM dbo.Customers GROUP BY Email HAVING COUNT(*) > 1;"},{"text":"Remove duplicates, keeping one row per non-NULL key; NULL rows are left alone.","sql":"WITH d AS (\n    SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CustomerId) AS rn FROM dbo.Customers WHERE Email IS NOT NULL\n)\nDELETE FROM d WHERE rn > 1;"},{"text":"If many NULLs should be allowed, create a filtered unique index (`WHERE Email IS NOT NULL`).","sql":null}],"diagnostic":"-- The message shows one duplicate value; this shows all of them.\nSELECT Email, COUNT(*) AS n\nFROM dbo.C\nGROUP BY Email\nHAVING COUNT(*) > 1;\n-- Case sensitivity can matter: a CI (case-insensitive) collation treats 'A@x.com' and 'a@x.com' as duplicates even though they look different.\nSELECT SERVERPROPERTY(N'Collation') AS server_collation;\n-- To check the exact column collation:\nSELECT name, collation_name FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.C') AND name = N'Email';","alternatives":"If the duplicates are legitimate, a unique index is the wrong tool. A non-unique index still speeds lookups, and application-side checks can enforce the rule where it applies. For many-NULL columns, the filtered unique index in the repro is the standard answer and also stays smaller than a full index.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.C (Id int IDENTITY PRIMARY KEY, Email nvarchar(200) NULL);\nINSERT INTO dbo.C (Email) VALUES ('a@x.com'), (NULL), (NULL);\n-- NULLs count as duplicates in a plain unique index, so this fails with 1505 showing a NULL key:\nCREATE UNIQUE INDEX IX_C_Email ON dbo.C(Email);\n-- For a case like this, a filtered index allows many NULLs:\nCREATE UNIQUE INDEX IX_C_Email ON dbo.C(Email) WHERE Email IS NOT NULL;","repro_note":null,"related":["sql-server/1750","sql-server/2601","sql-server/2627","postgresql/23505"],"sqlly":"Find the duplicates before rebuilding the index: a GROUP BY on the key columns in SQLly's grid puts the offending values and their counts in front of you.","faqs":[{"question":"Why does NULL appear as a duplicate key value?","answer":"A unique index permits exactly one NULL. Filtered indexes with WHERE Col IS NOT NULL are the supported way to allow several NULLs while keeping the rest unique."},{"question":"My data has no visible duplicates. Why the error?","answer":"Check for trailing spaces (they compare equal under most collations), case differences under case-insensitive collations, and NULLs. The GROUP BY query surfaces all of these."},{"question":"Was a partial index created?","answer":"No. The CREATE UNIQUE INDEX failed atomically, so no index exists afterward."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1505","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/15138","corpus":"errors","engine":"sql-server","language":"en","title":"User owns a schema, cannot be dropped","description":"DROP USER failed because the user owns a schema (or other securable). Transfer ownership to another principal first, then drop the user.","body":{"code":"15138","slug":"15138","name":null,"message":"The database principal owns a %S_MSG in the database, and cannot be dropped.","group":"permissions","severity":16,"sql_state":null,"summary":"DROP USER failed because the user owns a schema (or other securable). Transfer ownership to another principal first, then drop the user.","meaning":"A database user that owns a schema or another securable (such as a symmetric key) can't be dropped, because the object would be left without an owner. Owning a database role raises 15421 instead. The message names the kind of object owned (for example `owns a schema in the database`).","causes":["The user owns a schema, usually one created with CREATE SCHEMA ... AUTHORIZATION for that user. SQL Server does not create a same-name schema automatically.","The user owns a symmetric key or another securable. Owning a database role raises 15421 instead."],"fix":[{"text":"Find what the user owns.","sql":"SELECT s.name AS schema_name FROM sys.schemas AS s WHERE s.principal_id = USER_ID(N'old_user');\nSELECT r.name AS role_name FROM sys.database_principals AS r WHERE r.owning_principal_id = USER_ID(N'old_user');"},{"text":"Transfer ownership, then drop the user.","sql":"ALTER AUTHORIZATION ON SCHEMA::old_user TO dbo;\nDROP USER old_user;"}],"diagnostic":"-- What does the user own? Schemas first, then roles and other securables\nSELECT s.name AS owned_schema\nFROM sys.schemas AS s\nWHERE s.principal_id = USER_ID(N'dropme_user');\n\nSELECT r.name AS owned_role, r.type_desc\nFROM sys.database_principals AS r\nWHERE r.owning_principal_id = USER_ID(N'dropme_user');\n-- The 15138 message itself names the object type. An empty schema the\n-- user no longer needs can be dropped with DROP SCHEMA; one holding\n-- objects should be transferred to dbo or another principal.","alternatives":"Transfer the schema with ALTER AUTHORIZATION ON SCHEMA::name TO dbo, then drop the user. If the schema is empty and unneeded, DROP SCHEMA first. When the user owns roles or other securables, ALTER AUTHORIZATION works on those too. Some teams pre-create shared schemas like app_rw and assign them as default schemas, so no user has to own a schema of their own.","details":[],"details_title":null,"repro":"-- Scratch DB repro: an explicit schema owned by the user blocks the drop\nCREATE LOGIN dropme_user WITH PASSWORD = N'Throwaway-3#';\nGO\nUSE tempdb;\nCREATE USER dropme_user FOR LOGIN dropme_user;\nGO\nCREATE SCHEMA dropme_schema AUTHORIZATION dropme_user;\nGO\n-- Raises 15138: the database principal owns a schema in the database\nDROP USER dropme_user;\nGO\nALTER AUTHORIZATION ON SCHEMA::dropme_schema TO dbo;\nDROP USER dropme_user;\nDROP LOGIN dropme_user;","repro_note":null,"related":["sql-server/15151","sql-server/15023","postgresql/2BP01"],"sqlly":"Query sys.schemas in SQLly's grid, filtered on the user's name, and the schema it owns shows up immediately; ALTER AUTHORIZATION from the editor clears the way for the drop.","faqs":[{"question":"Why does the user own a schema I never created?","answer":"SQL Server does not create a schema for a new user. A user created without DEFAULT_SCHEMA gets dbo as its default schema and owns nothing. A user owns a schema only when someone created it with AUTHORIZATION for that user, or ownership was assigned to them."},{"question":"Can I just drop the schema instead?","answer":"Only if it is empty. If the schema contains tables or other objects, DROP SCHEMA fails, and dropping those objects is usually the wrong move. Transfer the schema to dbo with ALTER AUTHORIZATION, which keeps the objects in place under an owner that survives the user's removal."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/15138","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/15151","corpus":"errors","engine":"sql-server","language":"en","title":"Object doesn't exist or no permission","description":"A security statement such as ALTER LOGIN, DROP USER or GRANT named a principal that doesn't exist, or that you aren't allowed to see.","body":{"code":"15151","slug":"15151","name":null,"message":"Cannot %S_MSG the %S_MSG '%.*ls', because it does not exist or you do not have permission.","group":"permissions","severity":16,"sql_state":null,"summary":"A security statement such as ALTER LOGIN, DROP USER or GRANT named a principal that doesn't exist, or that you aren't allowed to see.","meaning":"SQL Server raises 15151 from statements that manage security (`ALTER LOGIN`, `DROP USER`, `ALTER ROLE`, `GRANT ... TO`) when the target can't be found. Like 3701, it doesn't tell you which: the name may be wrong, it may live in another database or on the server instead of the database, or you may lack permission to see it.","causes":["A typo in the login, user or role name.","Mixing up a server login and a database user: `ALTER LOGIN` works on server logins, `ALTER USER` on users in the current database.","Running in the wrong database, so the user or role isn't there.","Missing permission such as `ALTER ANY LOGIN` or `ALTER ANY USER`, which makes the principal invisible to you."],"fix":[{"text":"Check that the server login exists.","sql":"SELECT name, type_desc FROM sys.server_principals WHERE name = N'app_user';"},{"text":"Check the database user or role in the database you're in.","sql":"SELECT DB_NAME() AS current_db, name, type_desc FROM sys.database_principals WHERE name = N'app_user';"},{"text":"Run the statement in the right database (`USE SalesDb;`), or as a principal with the needed permission.","sql":null}],"diagnostic":"-- Server level: does the login exist at all?\nSELECT name, type_desc, is_disabled FROM sys.server_principals WHERE name = N'app_user';\n-- Database level: which database am I in, and does the user or role exist there?\nSELECT DB_NAME() AS current_db, name, type_desc\nFROM sys.database_principals\nWHERE name = N'app_user' AND type IN ('S','U','R');\n-- Do I have the permission to even see or alter it?\nSELECT * FROM fn_my_permissions(NULL, 'SERVER');   -- look for ALTER ANY LOGIN\nSELECT * FROM fn_my_permissions(NULL, 'DATABASE'); -- look for ALTER ANY USER\n-- Which logins are missing a user in this database (server-side check, 2016+):\nSELECT sp.name AS login_without_user\nFROM sys.server_principals sp\nWHERE sp.type = 'S'\n  AND NOT EXISTS (SELECT 1 FROM sys.database_principals dp WHERE dp.sid = sp.sid);","alternatives":"When the point is to attach an existing login to this database, CREATE USER ... FOR LOGIN works in the same situation that ALTER USER fails in, as long as no user of that name exists. If you cannot tell server login from database user apart in tooling output,  splitting the script into a server-level part and a per-database part makes the mistake visible.","details":[],"details_title":null,"repro":"-- The login exists on the server, but not as a user in this database.\nCREATE LOGIN repro_user WITH PASSWORD = 'Repro!2345';\nDROP USER IF EXISTS repro_user;  -- no-op if absent\nALTER USER repro_user WITH LOGIN = repro_user;  -- Msg 15151: Cannot alter the user 'repro_user', because it does not exist or you do not have permission.\nDROP LOGIN repro_user;","repro_note":null,"related":["sql-server/15023","sql-server/3701","sql-server/18456"],"sqlly":"Query sys.server_principals (or sys.database_principals) in SQLly's editor; the grid shows only the names your login can see. A principal you cannot see returns no row, the same as one that does not exist, so rerun as a more privileged login before concluding the name is wrong.","faqs":[{"question":"The login exists in sys.server_principals. Why does ALTER USER still say it cannot find it?","answer":"ALTER USER looks for a user in the current database, not a server login. If no user is mapped to that login here, the fix is CREATE USER x FOR LOGIN x, not ALTER USER."},{"question":"Could this really be a permission problem rather than a missing name?","answer":"Yes. SQL Server hides principals you lack ALTER ANY USER or VIEW DEFINITION rights to see, and the error text is the same in both cases. Run as a more privileged principal, or check your own permissions with fn_my_permissions before assuming the name is wrong."},{"question":"How is 15151 different from 3701?","answer":"Both say 'cannot find X'. 15151 covers security principals like logins, users and roles. 3701 covers database objects like tables and procedures."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/15151","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/156","corpus":"errors","engine":"sql-server","language":"en","title":"Incorrect syntax near the keyword","description":"A reserved keyword appeared where SQL Server didn't expect one, often a column or table named like a keyword, or a misplaced clause.","body":{"code":"156","slug":"156","name":null,"message":"Incorrect syntax near the keyword '%.*ls'.","group":"syntax","severity":15,"sql_state":null,"summary":"A reserved keyword appeared where SQL Server didn't expect one, often a column or table named like a keyword, or a misplaced clause.","meaning":"Error 156 is the keyword version of 102: the parser met a reserved word such as `FROM`, `WHERE`, `ORDER`, `KEY` or `USER` at a point where it doesn't fit. Either the keyword is being used as a name without quoting, or a clause is out of order or incomplete.","causes":["A column or table named after a reserved word, such as `User`, `Order`, `Key` or `Table`, used without brackets.","Clauses in the wrong order, such as `ORDER BY` before `GROUP BY`, or `WHERE` after `GROUP BY`.","A trailing comma right before `FROM`.","A derived table without an alias: `SELECT * FROM (SELECT 1 AS x)` needs `AS t` after the parenthesis.","`ORDER BY` inside a view, subquery or CTE without `TOP` or `OFFSET`."],"fix":[{"text":"Quote names that are reserved words with brackets (or double quotes with `QUOTED_IDENTIFIER ON`).","sql":"SELECT [User], [Order], [Key] FROM dbo.[Table];"},{"text":"Give every derived table an alias.","sql":"SELECT t.x FROM (SELECT 1 AS x) AS t;"},{"text":"Put clauses in the standard order: `SELECT`, `FROM`, `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`.","sql":null}],"diagnostic":"-- Check whether the keyword is also a column or table name in the query\nSELECT c.name, OBJECT_NAME(c.object_id) AS tbl\nFROM sys.columns c\nWHERE c.name IN ('KEY', 'USER', 'ORDER', 'FROM', 'PERCENT');\n-- If the error comes from an existing object, compare its definition\nSELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID('dbo.YourProc');","alternatives":"If you need a keyword as a name, rename it to something non-reserved instead of bracketing it everywhere; that saves the next person the same trip. If the keyword is part of a feature, confirm your server version supports it, since an unknown keyword reads the same as a misplaced one.","details":[],"details_title":null,"repro":"SELECT 1 AS x, FROM sys.objects;  -- Msg 156: Incorrect syntax near the keyword 'FROM'.","repro_note":null,"related":["sql-server/102","sql-server/105","postgresql/42601","mysql/1064","oracle/ora-00936"],"sqlly":"Validate SQL in SQLly (Cmd+Shift+V or Ctrl+Shift+V) parses the statement before anything runs and marks where the parse breaks, which is usually the keyword doing duty as a column name.","faqs":[{"question":"How do I use a column named KEY or USER?","answer":"Wrap it in brackets: [KEY], [USER]. Quoting fixes the parse error, but renaming the column is usually less painful over time."},{"question":"ORDER BY gave me error 156. What broke?","answer":"It usually means a clause before it is incomplete, like a WHERE without a comparison (`WHERE ORDER BY name` fails at 'ORDER') or a trailing comma before FROM. A missing comma between select items usually fails earlier, at the second item with Msg 102, and reports 156 only when that item is a reserved word such as KEY."},{"question":"Is 156 different from error 102?","answer":"Only in what the parser quotes. 102 names a generic token, 156 names a reserved word. The fix is the same kind of reading of the surrounding code."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/156","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1750","corpus":"errors","engine":"sql-server","language":"en","title":"Could not create constraint or index","description":"A constraint or index couldn't be created. 1750 is the closing message; the error just before it (such as 1505 duplicate key, 2714 or 1776) is the cause.","body":{"code":"1750","slug":"1750","name":null,"message":"Could not create constraint or index. See previous errors.","group":"constraints","severity":16,"sql_state":null,"summary":"A constraint or index couldn't be created. 1750 is the closing message; the error just before it (such as 1505 duplicate key, 2714 or 1776) is the cause.","meaning":"SQL Server reports 1750 after another error prevented `ALTER TABLE ... ADD CONSTRAINT` from creating a PRIMARY KEY or UNIQUE constraint and its index. A standalone `CREATE UNIQUE INDEX` reports 1505 without 1750. It says nothing on its own; look at the error immediately before it.","causes":["Existing duplicate rows when adding a primary key or unique constraint.","Existing rows that violate a new foreign key or check constraint raise error 547 on their own, with no 1750 after it.","A constraint name already used in the schema (error 2714).","Referencing a parent column that has no primary key or unique constraint when creating a foreign key."],"fix":[{"text":"Read the preceding error and fix that first.","sql":null},{"text":"For duplicates blocking a new unique key, find them.","sql":"SELECT Email, COUNT(*) FROM dbo.Customers GROUP BY Email HAVING COUNT(*) > 1;"},{"text":"A foreign key must reference a primary key or unique constraint on the parent.","sql":"ALTER TABLE dbo.Customers ADD CONSTRAINT UQ_Customers_Code UNIQUE (Code);\nALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerCode) REFERENCES dbo.Customers (Code);"}],"diagnostic":"-- 1750 is a wrapper. Read the error before it and act on that. In SSMS the messages pane shows them in order; in a client, iterate Error/InfoMessage events, not just the first one.\n-- To find the cause before rerunning, check for what the preceding error mentioned. Duplicates:\nSELECT Id, COUNT(*) FROM dbo.P GROUP BY Id HAVING COUNT(*) > 1;\n-- Parent column missing a PK or unique constraint (blocks a foreign key):\nSELECT name, type_desc FROM sys.key_constraints WHERE parent_object_id = OBJECT_ID(N'dbo.Parent');\n-- Constraint name already taken in the schema (error 2714 precedes):\nSELECT name FROM sys.objects WHERE name = N'PK_P' AND schema_id = SCHEMA_ID(N'dbo');","alternatives":"When you need the constraint created despite bad rows, add it WITH NOCHECK for foreign keys or check constraints. The constraint is then recorded as not trusted (`is_not_trusted = 1`): existing rows were never validated, so the optimizer cannot rely on it, though new writes are enforced. Clean up the bad rows, then re-check it with `ALTER TABLE ... WITH CHECK CHECK CONSTRAINT ...` to make the constraint trusted again.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.P (Id int NOT NULL);\nINSERT INTO dbo.P VALUES (1), (1);  -- duplicate key\nGO\nALTER TABLE dbo.P ADD CONSTRAINT PK_P PRIMARY KEY (Id);\n-- Message 1505 reports the duplicate, then 1750 closes the batch.","repro_note":null,"related":["sql-server/2714","sql-server/547","sql-server/2627","sql-server/1913"],"sqlly":"SQLly shows the real error and the 1750 wrap-up together in the Messages tab, so the constraint name and the reason above it are both visible when you read the failure.","faqs":[{"question":"Was the constraint created if I got 1750?","answer":"No. The whole ALTER TABLE statement failed, so nothing was added."},{"question":"Why do I only see 1750 in my application log?","answer":"Many clients surface only the last error. Enable full error collection (SqlError events in .NET, PRINT/message handling elsewhere) so you can see the real cause above 1750."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1750","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18452","corpus":"errors","engine":"sql-server","language":"en","title":"Login is from an untrusted domain","description":"Windows authentication failed: the client's Windows identity couldn't be verified by the server, often a domain trust, Kerberos or local-account problem.","body":{"code":"18452","slug":"18452","name":null,"message":"Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication.%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"Windows authentication failed: the client's Windows identity couldn't be verified by the server, often a domain trust, Kerberos or local-account problem.","meaning":"With Windows (integrated) authentication, SQL Server relies on Windows to vouch for the client. Error 18452 means Windows couldn't authenticate the caller to the server: the account isn't from a domain the server trusts, or the security handshake (Kerberos or NTLM) failed.","causes":["The client machine or user is not in the server's domain or a trusted domain, for example a workgroup laptop or a different forest without a trust.","The server is configured for Windows authentication only and the client tried a SQL login.","Kerberos problems such as missing or duplicate SPNs, or a clock difference between client and domain controller.","Connecting by IP address or a DNS alias that doesn't match the server's SPN, so the handshake falls back and fails.","Loopback protection when connecting to the local machine by a fully qualified name or alias."],"fix":[{"text":"If you meant to use a SQL login, enable SQL Server and Windows Authentication mode on the server (Properties, Security) and restart the service.","sql":null},{"text":"Connect from a machine and account in the server's domain or a trusted domain, or create a SQL login for this client.","sql":null},{"text":"Check the SPNs for the SQL Server service account with `setspn -L <service account>` and fix missing or duplicate entries; Microsoft's SQLCheck tool reports these.","sql":null},{"text":"Connect using the server's real host name rather than an IP address or alias.","sql":null}],"diagnostic":"-- The server can tell you its side even if you can't log in with Windows,\n-- as long as you have another way in (SQL login as admin, or DAC).\n-- Is the server Windows-auth-only?\nSELECT CASE SERVERPROPERTY('IsIntegratedSecurityOnly')\n    WHEN 1 THEN 'Windows authentication only' ELSE 'Mixed mode' END AS auth_mode;\n\n-- From a domain machine, check the SPNs registered for the service account:\n--   setspn -L <service_account>\n-- A missing MSSQLSvc/<host>:<port> entry, or the same SPN on two accounts,\n-- breaks Kerberos. Large clock skew against the domain controller breaks it too.\n\n-- The error log records the failed handshake with the client identity:\nEXEC sys.xp_readerrorlog 0, 1, N'18452';","alternatives":"For clients outside the domain (workgroup machines, vendors, CI runners), the practical answer is usually a SQL login or a Microsoft Entra login rather than fighting the trust boundary. Kerberos problems can be sidestepped with NTLM in some environments, but that trades away the stronger authentication, so it is a stopgap.","details":[],"details_title":null,"repro":"-- Reproduce the trust failure from a machine that is not joined to any domain\n-- the server trusts (a workgroup laptop, a vendor box, a CI runner):\n--   sqlcmd -S theserver -E -Q \"SELECT 1\"\n-- Windows cannot vouch for that local account across the trust boundary, so\n-- the server refuses it with 18452. Connecting from a domain machine, or with\n-- a SQL login after enabling mixed mode, succeeds.","repro_note":null,"related":["sql-server/18456","sql-server/53"],"sqlly":"SQLly's connection test surfaces the driver's full error text, so 18452 comes back as itself instead of a generic timeout, and each saved connection in the connection manager records which authentication mode it uses.","faqs":[{"question":"Is 18452 the same as 18456?","answer":"No. 18456 is SQL Server rejecting the login's credentials. 18452 is Windows itself failing to vouch for the caller, before SQL Server evaluates any login: trust, domain or handshake problem."},{"question":"Why does it fail only when I connect by IP address or alias?","answer":"Kerberos builds its service ticket from the name the client used. An IP or a mismatched alias doesn't match the server's SPN, the handshake falls back to NTLM or fails outright, and restricted or delegated environments reject the fallback."},{"question":"Can I see which client triggered 18452?","answer":"Yes. The error log entry for the failed logon includes the client address and the Windows identity Windows reported. Match the timestamp against your clients' connection attempts. Match the timestamp against your clients' connection attempts."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18452","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18456","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed for user","description":"SQL Server rejected the login. The client always sees state 1; the real reason (bad password, unknown login, no database access) is in the server's error log.","body":{"code":"18456","slug":"18456","name":null,"message":"Login failed for user '%.*ls'.%.*ls%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"SQL Server rejected the login. The client always sees state 1; the real reason (bad password, unknown login, no database access) is in the server's error log.","meaning":"18456 is the generic login failure. SQL Server deliberately tells the client nothing more than `Login failed for user '...'`, so an attacker can't tell a wrong password from a missing login. The specific reason is written to the SQL Server error log as a reason sentence, together with the client's IP address, for example `Login failed for user 'app_user'. Reason: Password did not match that for the login provided. [CLIENT: 10.0.0.5]`. The numeric state is recorded in the error_reported extended event and in older log formats (`Error: 18456, Severity: 14, State: 8.`).\n\nSo the first step is always the same: find the matching entry in the error log and read its reason, or the state if you have it.","causes":["Wrong password, or a SQL login typed with the wrong name.","The login doesn't exist on this instance, which is common after restoring a database to a new server: the database user exists but the server login doesn't.","The server allows Windows authentication only, and you connected with a SQL login.","The login's default database is offline, was dropped, or the login has no user in it.","The login is disabled, locked out, or its password expired or must be changed (these have their own messages: 18470, 18486, 18487, 18488).","Connecting to an Azure SQL database without naming the database, when the login exists only as a contained user in that database."],"fix":[{"text":"Find the failure in the error log and read the state. In SSMS it's under Management, SQL Server Logs; or query it:","sql":"EXEC sys.xp_readerrorlog 0, 1, N'Login failed';"},{"text":"State 8 or 9: the password is wrong. Reset it, or connect with the right one.","sql":"ALTER LOGIN app_user WITH PASSWORD = N'<new strong password>';"},{"text":"State 2 or 5: the login doesn't exist. Create it, and if the database was restored from another server, map the existing database user back to it.","sql":"CREATE LOGIN app_user WITH PASSWORD = N'<strong password>';\nUSE SalesDb;\nALTER USER app_user WITH LOGIN = app_user;"},{"text":"State 58: the server is in Windows-only mode. Enable SQL Server and Windows authentication mode in the server properties (Security page), then restart the SQL Server service.","sql":null},{"text":"State 38 or 46: name a database the login can open in the connection, or fix its default database.","sql":"ALTER LOGIN app_user WITH DEFAULT_DATABASE = master;"},{"text":"Disabled or locked login: re-enable or unlock it.","sql":"ALTER LOGIN app_user ENABLE;\nALTER LOGIN app_user WITH PASSWORD = N'<password>' UNLOCK;"}],"diagnostic":"-- The client's state is always 1. Read the true state from the error log first.\nEXEC sys.xp_readerrorlog 0, 1, N'Login failed';\n\n-- Then check the login itself, if it exists at all:\nSELECT name, is_disabled FROM sys.sql_logins WHERE name = N'app_user';\n\n-- No row means state 2 or 5: the login does not exist on this instance.\n-- A row with is_disabled = 1 gives 18470 when the password is right, and 18456 state 7 when it is wrong.\n\n-- Check the server's authentication mode (1 = Windows only, 0 = mixed):\nSELECT CASE SERVERPROPERTY('IsIntegratedSecurityOnly')\n    WHEN 1 THEN 'Windows authentication only' ELSE 'Mixed mode' END AS auth_mode;\n\n-- Check the login's default database, a common cause of state 38:\nSELECT name, default_database_name,\n    (SELECT state_desc FROM sys.databases d WHERE d.name = l.default_database_name) AS db_state\nFROM sys.server_principals l WHERE name = N'app_user';","alternatives":"For applications, a dedicated Windows or Azure AD (Microsoft Entra) group login avoids the password-rotation lockouts that cause most 18456 incidents. If the login exists but its default database is the problem, connect naming any database the login can use, such as master, and fix the mapping afterwards.","details":[{"key":"1","value":"Error information isn't available, usually because you lack permission to see the details."},{"key":"2, 5","value":"The user ID isn't valid: there is no login with that name."},{"key":"6","value":"A Windows login name was used with SQL Server authentication."},{"key":"7","value":"The login is disabled and the password is incorrect."},{"key":"8","value":"The password is incorrect."},{"key":"9","value":"The password isn't valid."},{"key":"11, 12","value":"The login is valid, but server access failed. A common case is a Windows user who reaches SQL Server only through the local Administrators group without running the program as administrator."},{"key":"18","value":"The password must be changed. On SQL Server 2022 a must-change login with the correct password reports 18488 instead, so this state is rarely seen."},{"key":"38, 46","value":"The database requested by the user couldn't be found. In tests on SQL Server 2022, a missing database in the connection or an unusable default database did not fail the login: it fell back to master with a warning."},{"key":"58","value":"SQL authentication was used while the server is set to Windows authentication only, or the SIDs don't match."},{"key":"62","value":"A Windows account tried to use a contained database whose SID doesn't match."},{"key":"102 to 111, 132 to 133","value":"Azure AD (Microsoft Entra ID) authentication failure."},{"key":"122 to 124","value":"The user name or password was empty."},{"key":"126","value":"The database requested by the user doesn't exist."}],"details_title":"What the state number means","repro":"-- Reproduce the generic failure on a scratch instance: a login that does not exist,\n-- and a login with a wrong password, both report plain 18456 state 1 to the client.\n-- Run on the scratch server as admin:\nUSE master;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_user')\n    CREATE LOGIN scratch_user WITH PASSWORD = N'C0rrect-Horse-9!', CHECK_POLICY = OFF;\nGO\n-- From a shell, both of these fail with the same client-side message:\n--   sqlcmd -S localhost -U scratch_user -P wrong-password\n--   sqlcmd -S localhost -U no_such_login -P anything\n-- The real state is only in the error log:\nEXEC sys.xp_readerrorlog 0, 1, N'Login failed';","repro_note":null,"related":["sql-server/4060","sql-server/4064","sql-server/18452","sql-server/18470","sql-server/18486","sql-server/18487","sql-server/18488","sql-server/916"],"sqlly":"SQLly shows SQL Server errors in full, as `Msg 18456, Level 14, State 1`, and its connection test reports the server's exact error and the round-trip time, so you can tell a login problem from a network one (error 53, timeouts) at a glance. The real state is still only in the server's error log.","faqs":[{"question":"Why does the error always say State 1?","answer":"SQL Server sends state 1 to every client on purpose, so an attacker can't probe which logins exist or why one failed. The real state is only written to the SQL Server error log entry for the same login attempt, which takes admin rights to read."},{"question":"What does error 18456 state 38 mean?","answer":"Per Microsoft's state table, state 38 means the database requested by the user could not be found. In tests on SQL Server 2022, a missing or unusable database fell back to master with a warning and no 18456 was raised, so check the error log and the connection's database name."},{"question":"Why does sa fail with state 7 after I enabled mixed mode?","answer":"When SQL Server is installed with Windows authentication only and later switched to SQL Server and Windows authentication, the `sa` login starts out disabled. Enable it with `ALTER LOGIN sa ENABLE;` and give it a strong password."},{"question":"I got 18456 right after restoring a database to a new server. Why?","answer":"Two usual reasons: the login was never created on the new server, or the login exists but its default database is the restored one and the login has no user in it. Read the error log state, then create the login or remap the user."},{"question":"How do I find which application kept sending bad passwords?","answer":"The error log entry includes the client's IP address. Match it to a host, then check connection strings and cached credentials on that machine. If it's a service, its stored password is out of date with the login."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18456","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18461","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed, single user mode","description":"SQL Server was started in single-user mode (-m), and another connection, often a service or tool, already took the one administrator slot.","body":{"code":"18461","slug":"18461","name":null,"message":"Login failed for user '%.*ls'. Reason: Server is in single user mode. Only one administrator can connect at this time.%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"SQL Server was started in single-user mode (-m), and another connection, often a service or tool, already took the one administrator slot.","meaning":"Starting SQL Server with the `-m` startup option (used for recovery tasks such as restoring `master` or regaining sysadmin access) allows only one administrator connection. Whoever connects first gets it. Every other attempt fails with 18461, and SQL Server Agent or an unknown client application can grab the slot before you do.","causes":["SQL Server Agent or an unknown client application connected first and holds the single connection.","The instance was left in single-user mode after maintenance."],"fix":[{"text":"Stop SQL Server Agent and other services or applications that connect automatically, then connect again.","sql":null},{"text":"Restrict the single connection to one program name with `-m\"sqlcmd\"` (or `-m\"Microsoft SQL Server Management Studio - Query\"` for an SSMS query window), so other clients can't take it.","sql":null},{"text":"When the maintenance is done, remove `-m` from the startup parameters and restart the service.","sql":null}],"diagnostic":"-- If you cannot connect at all, check the mode from the ERRORLOG instead of T-SQL.\n-- Look for 'Server is in single user mode' near the startup entries in ERRORLOG.\n-- On a Windows host (run as administrator):\n--   Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\MSSQL*.MSSQLSERVER\\MSSQLServer\\Parameters' | Select SQLArg*\n-- An SQLArg value of -m (or -m\"prog\") confirms single-user mode and shows any program restriction.\n-- Once connected, confirm who holds the slot:\nSELECT session_id, login_name, host_name, program_name FROM sys.dm_exec_sessions WHERE is_user_process = 1;","alternatives":"Use a dedicated administrator connection instead of fighting for the slot: connect with ADMIN:SERVERNAME\\INSTANCE as the server name (sqlcmd -A). Only one DAC connection is available at a time, and it is often the fastest way in. Dedicated Administrator Connection from a remote machine requires the remote admin connections server option turned on, which you can check once you are in.","details":[],"details_title":null,"repro":"No safe repro script. Single-user mode is set at startup with the -m flag or via SSMS server properties, and reproducing it on a scratch instance means restarting a service with restricted access. On a throwaway instance you can start sqlservr.exe from the console with -m, try a second connection, and watch it fail with 18461, but never do this on a server anyone else uses.","repro_note":null,"related":["sql-server/18456","sql-server/3101"],"sqlly":"The connection test in SQLly shows the single-user-mode message in full, and the connection manager makes it obvious which saved entry points at an instance where someone else's tool took the one slot.","faqs":[{"question":"Why did SQL Server Agent connect before me?","answer":"SQL Server Agent might connect first when it starts, taking the only available connection and blocking you from signing in. Stop the Agent service (and any app pools or schedulers that connect on startup) before you reconnect."},{"question":"How do I reserve the connection for my own tool?","answer":"Add -m\"sqlcmd\" to the startup parameters, restart, and connect with sqlcmd. Only clients whose reported program name matches can log in."},{"question":"Can I just remove -m while the instance is running?","answer":"No. Startup parameters are read at start. Change them, then restart the service."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18461","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18470","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed, account disabled","description":"The SQL Server login exists but has been disabled, so SQL Server refuses it even with the right password.","body":{"code":"18470","slug":"18470","name":null,"message":"Login failed for user '%.*ls'. Reason: The account is disabled.%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"The SQL Server login exists but has been disabled, so SQL Server refuses it even with the right password.","meaning":"A login can be disabled with `ALTER LOGIN ... DISABLE`, which keeps the login and its permissions but blocks every new connection. Sessions that are already open are not affected. The `sa` login is disabled by default when SQL Server is installed in Windows authentication mode.","causes":["An administrator disabled the login on purpose, for example while decommissioning an application.","The `sa` login is still disabled from installation.","A script or policy disabled logins after a security review."],"fix":[{"text":"Check the login's state.","sql":"SELECT name, is_disabled FROM sys.server_principals WHERE name = N'app_user';"},{"text":"Enable it again if it should be allowed to connect.","sql":"ALTER LOGIN app_user ENABLE;"}],"diagnostic":"-- Is the login disabled, and is that the whole story?\nSELECT name, is_disabled FROM sys.sql_logins WHERE name = N'app_user';\n-- is_disabled = 1 confirms the cause. If it is 0, the failure is a different\n-- member of the 18456 family (password expired, locked out) and the error log\n-- state will say which.\n\n-- Who or what disabled it is not in the catalog, but the error log shows the\n-- failed attempts:\nEXEC sys.xp_readerrorlog 0, 1, N'disabled';","alternatives":"If the login belongs to a decommissioned app, leave it disabled and drop its users instead, so orphaned permissions don't linger. For the disabled sa login on a fresh install, enabling it should be a deliberate decision with a strong password, since it is a favorite brute-force target.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: disable a login and try to connect.\nUSE master;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_18470')\n    CREATE LOGIN scratch_18470 WITH PASSWORD = N'Scratch-18470!', CHECK_POLICY = OFF;\nGO\nALTER LOGIN scratch_18470 DISABLE;\nGO\n-- From a shell, even with the correct password:\n--   sqlcmd -S localhost -U scratch_18470 -P 'Scratch-18470!'\n-- fails with 18470. The state is visible server-side:\nSELECT name, is_disabled FROM sys.sql_logins WHERE name = 'scratch_18470';\n-- Cleanup:\nDROP LOGIN scratch_18470;","repro_note":null,"related":["sql-server/18456","sql-server/18486","sql-server/18487"],"sqlly":"Edit the saved connection in SQLly's connection manager to check which login it sends, and the connection test prints the server's exact reason, so a disabled account reads differently from a wrong password.","faqs":[{"question":"Does disabling a login drop its permissions?","answer":"No. DISABLE only blocks connections. The login keeps its server roles and its mapped database users, and everything is intact when it is enabled again."},{"question":"Why is sa disabled on my new server?","answer":"When SQL Server is installed in Windows authentication mode, setup disables sa by default. Enabling mixed mode does not enable sa; you have to do both."},{"question":"How do I tell disabled from locked out?","answer":"Disabled is a flag an administrator set: is_disabled = 1 in sys.sql_logins. Locked out is automatic after failed passwords when the Windows password policy applies (CHECK_POLICY and CHECK_EXPIRATION on): LOGINPROPERTY(name, 'IsLocked') = 1. They raise different errors, 18470 and 18486."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18470","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18486","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed, account locked out","description":"A SQL login was locked after too many failed passwords under the Windows account lockout policy. An administrator can unlock it, or it unlocks when the lockout ends.","body":{"code":"18486","slug":"18486","name":null,"message":"Login failed for user '%.*ls' because the account is currently locked out. The system administrator can unlock it. %.*ls","group":"connection","severity":14,"sql_state":null,"summary":"A SQL login was locked after too many failed passwords under the Windows account lockout policy. An administrator can unlock it, or it unlocks when the lockout ends.","meaning":"SQL logins created with `CHECK_POLICY = ON` follow the Windows password policy of the server, including account lockout. After the configured number of bad passwords, the login is locked and refuses every attempt, even with the right password, until it is unlocked or the lockout duration passes.","causes":["An application or service kept retrying with an old password after the password was changed.","Someone mistyped the password repeatedly.","A brute-force attempt against the login."],"fix":[{"text":"Check whether the login is locked.","sql":"SELECT LOGINPROPERTY(N'app_user', 'IsLocked') AS is_locked,\n       LOGINPROPERTY(N'app_user', 'BadPasswordCount') AS bad_password_count;"},{"text":"Unlock it. `UNLOCK` has to be combined with setting a password.","sql":"ALTER LOGIN app_user WITH PASSWORD = N'<password>' UNLOCK;"},{"text":"Find and fix whatever was sending the wrong password (old connection strings, scheduled jobs, linked servers), or it will lock again.","sql":null}],"diagnostic":"-- Is the login locked, and how many bad passwords got it there?\nSELECT LOGINPROPERTY(N'app_user', 'IsLocked') AS is_locked,\n       LOGINPROPERTY(N'app_user', 'BadPasswordCount') AS bad_password_count,\n       LOGINPROPERTY(N'app_user', 'BadPasswordTime') AS bad_password_time,\n       LOGINPROPERTY(N'app_user', 'LockoutTime') AS lockout_time;\n-- Check the login actually follows the policy:\nSELECT name, is_policy_checked FROM sys.sql_logins WHERE name = N'app_user';\n-- The lockout threshold and duration themselves come from the machine's local\n-- or domain security policy (secpol.msc or gpedit), not from SQL Server.\n\n-- The error log shows the failed attempts and the client IP:\nEXEC sys.xp_readerrorlog 0, 1, N'Login failed';","alternatives":"If the lockout keeps recurring, the durable fix is finding the client that retries with a stale password, usually a service or a connection pool with a cached credential. Where the Windows lockout policy is too aggressive for a service account, an administrator can recreate the login with CHECK_POLICY = OFF, but that also disables password complexity checks, so treat it as a deliberate exception.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: send wrong passwords until the Windows\n-- account lockout policy locks the login (CHECK_POLICY = ON is the default):\nUSE master;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_18486')\n    CREATE LOGIN scratch_18486 WITH PASSWORD = N'Scratch-18486!';\nGO\n-- Loop in a shell, threshold + 1 times (secpol.msc sets the threshold; 5 and\n-- 10 are common, and a policy with lockout disabled never locks):\n--   for ($i = 1; $i -le 11; $i++) { sqlcmd -S localhost -U scratch_18486 -P 'wrong' 2> $null }\n-- Now even the correct password fails with 18486, and the server side shows why:\nSELECT LOGINPROPERTY(N'scratch_18486', 'IsLocked') AS is_locked,\n       LOGINPROPERTY(N'scratch_18486', 'BadPasswordCount') AS bad_password_count;\n-- Cleanup:\nDROP LOGIN scratch_18486;","repro_note":null,"related":["sql-server/18456","sql-server/18470","sql-server/18487","sql-server/18488"],"sqlly":"SQLly shows the server's full message instead of just the number, so the lockout wording in 18486 is visible right in the connection test rather than hidden behind a generic failure.","faqs":[{"question":"Will the login unlock itself?","answer":"It can. If the Windows policy sets a lockout duration, the login unlocks when it passes. If the duration is zero (unlock only by administrator), it stays locked until someone runs ALTER LOGIN with UNLOCK."},{"question":"Why does UNLOCK require setting a password too?","answer":"SQL Server's syntax only allows UNLOCK combined with PASSWORD in ALTER LOGIN. Supply the current password if you don't want to change it; the statement still counts as a password set."},{"question":"My app has the right password. Why is it still locked out?","answer":"A lockout rejects everything, right passwords included, until it clears. It almost certainly got locked by earlier attempts with an old or mistyped password, often from a retry loop that kept hammering after the first failure."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18486","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18487","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed, password expired","description":"The SQL login's password has expired under the server's Windows password policy. Set a new password to let it connect again.","body":{"code":"18487","slug":"18487","name":null,"message":"Login failed for user '%.*ls'. Reason: The password of the account has expired.%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"The SQL login's password has expired under the server's Windows password policy. Set a new password to let it connect again.","meaning":"SQL logins created with `CHECK_EXPIRATION = ON` follow the server's Windows password expiration policy. When the password is older than the maximum password age, SQL Server rejects the login until a new password is set.","causes":["The login was created with `CHECK_EXPIRATION = ON` and the password reached the maximum age set in the Windows password policy.","A service account login nobody rotates was given an expiring password."],"fix":[{"text":"Set a new password as an administrator.","sql":"ALTER LOGIN app_user WITH PASSWORD = N'<new strong password>';"},{"text":"For a service account whose password you rotate yourself, turn expiration off (password policy still applies).","sql":"ALTER LOGIN app_user WITH CHECK_EXPIRATION = OFF;"},{"text":"See how close other logins are to expiring.","sql":"SELECT name, LOGINPROPERTY(name, 'DaysUntilExpiration') AS days_left\nFROM sys.sql_logins WHERE is_expiration_checked = 1;"}],"diagnostic":"-- How close is the password to expiring?\nSELECT LOGINPROPERTY(N'app_user', 'IsExpired') AS is_expired,\n       LOGINPROPERTY(N'app_user', 'PasswordLastSetTime') AS password_last_set,\n       LOGINPROPERTY(N'app_user', 'IsMustChange') AS is_must_change;\n-- Confirm the login enforces expiration, and check every login at once:\nSELECT name, is_expiration_checked, is_policy_checked\nFROM sys.sql_logins\nWHERE is_expiration_checked = 1\nORDER BY name;\n-- The maximum age itself comes from the Windows password policy of the server,\n-- visible with: net accounts\n-- (Maximum password age line). SQL Server applies that policy to SQL logins\n-- with CHECK_EXPIRATION = ON.","alternatives":"For logins that applications use, most teams turn expiration off (CHECK_EXPIRATION = OFF) and rotate the password through the deployment pipeline instead, so rotation is coordinated with the config change. For human logins, keep expiration on and let SSMS or sqlcmd handle the change-at-login flow.","details":[],"details_title":null,"repro":"-- Reproducing needs a password older than the maximum password age in the\n-- server's Windows password policy, and CREATE LOGIN stamps the password now.\n-- The honest drill on a scratch instance:\n-- 1. On Windows only, lower the age limit once: net accounts /maxpwage:1 (one day). On Linux this cannot be forced here, because DaysUntilExpiration reports 90 days and the password cannot be backdated.\n-- 2. Create the scratch login, then wait out the day, or point the test at an\n--    existing login whose password was last set more than a day ago:\n--      CREATE LOGIN scratch_18487 WITH PASSWORD = N'Scratch-18487!',\n--                     CHECK_EXPIRATION = ON;\n-- 3. Connect: sqlcmd -S localhost -U scratch_18487 -P 'Scratch-18487!'\n--    fails with 18487, and the server side shows why:\nSELECT LOGINPROPERTY(N'scratch_18487', 'IsExpired') AS is_expired,\n       LOGINPROPERTY(N'scratch_18487', 'DaysUntilExpiration') AS days_left;","repro_note":null,"related":["sql-server/18488","sql-server/18456","sql-server/18486","oracle/ora-28001"],"sqlly":"When the connection test comes back with 18487, SQLly displays the expired-password reason in full, and the ALTER LOGIN that sets the new password can run from an admin connection kept in the connection manager.","faqs":[{"question":"Do all SQL logins have expiring passwords?","answer":"No. Only logins created or altered with CHECK_EXPIRATION = ON follow the Windows expiration policy. By default, logins check complexity (CHECK_POLICY = ON) but not expiration."},{"question":"Can I un-expire a password without changing it?","answer":"No. The normal way out is setting a new password with ALTER LOGIN (Fix 1). If you set the same value again, that resets the clock. Password history blocks reuse only when ALTER LOGIN is given OLD_PASSWORD; without it, the history check is ignored."},{"question":"Why did expiration kick in only after a Windows policy update?","answer":"The maximum password age likely got shortened by a Group Policy change. Passwords already older than the new limit expire at the next login, which makes it look sudden."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18487","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/18488","corpus":"errors","engine":"sql-server","language":"en","title":"Login failed, password must be changed","description":"The SQL login is flagged MUST_CHANGE, so it has to set a new password before it can connect. Many drivers can't do that, so the login just fails.","body":{"code":"18488","slug":"18488","name":null,"message":"Login failed for user '%.*ls'. Reason: The password of the account must be changed.%.*ls","group":"connection","severity":14,"sql_state":null,"summary":"The SQL login is flagged MUST_CHANGE, so it has to set a new password before it can connect. Many drivers can't do that, so the login just fails.","meaning":"A login created or reset with `MUST_CHANGE` must choose a new password the first time it connects. Tools such as SSMS offer to change it during login; sqlcmd changes it only with -z (--change-password); applications and many drivers don't, so they fail with 18488.","causes":["The login was created or its password reset with `MUST_CHANGE`.","An application connects with a newly created login that was meant for a person to sign in with first."],"fix":[{"text":"Have an administrator set a password without `MUST_CHANGE`.","sql":"ALTER LOGIN app_user WITH PASSWORD = N'<new strong password>';"},{"text":"Or sign in once with SSMS, or run `sqlcmd -z <new password>` to set it, then use that password in the application.","sql":null}],"diagnostic":"-- Is the login flagged MUST_CHANGE?\nSELECT LOGINPROPERTY(N'app_user', 'IsMustChange') AS must_change,\n       LOGINPROPERTY(N'app_user', 'IsExpired') AS expired;\n-- must_change = 1 confirms this error. If it is 0, look at the other members of\n-- the 18456 family and the error log state instead.","alternatives":"For logins that only applications use, avoid MUST_CHANGE entirely: applications and most drivers cannot complete the change-at-first-login flow. Reserve MUST_CHANGE for logins a person will sign in with through SSMS or sqlcmd, and have the administrator set a final password without the flag when the person is unavailable.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: a login created with MUST_CHANGE.\nUSE master;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_18488')\n    CREATE LOGIN scratch_18488 WITH PASSWORD = N'Scratch-18488!' MUST_CHANGE,\n        CHECK_POLICY = ON, CHECK_EXPIRATION = ON;\nGO\n-- From a shell, with the password it was created with:\n--   sqlcmd -S localhost -U scratch_18488 -P 'Scratch-18488!'\n-- fails with 18488 because the login must pick a new password first.\n-- sqlcmd -z <new password> sets the new password non-interactively; most drivers do not.\nSELECT LOGINPROPERTY('scratch_18488', 'IsMustChange') AS must_change;\n-- Cleanup:\nDROP LOGIN scratch_18488;","repro_note":null,"related":["sql-server/18487","sql-server/18456"],"sqlly":"SQLly's connection test records a redacted summary of the driver error.","faqs":[{"question":"Can a .NET application complete the MUST_CHANGE password change?","answer":"Microsoft.Data.SqlClient exposes the flow as the static `SqlConnection.ChangePassword(connectionString, newPassword)` method, which Microsoft documents for SQL Server on Windows Server; it is not a connection-string keyword. Most application code never implements it. The reliable paths are SSMS, or an administrator setting the password without `MUST_CHANGE`."},{"question":"Where does MUST_CHANGE come from?","answer":"It's set by CREATE LOGIN or ALTER LOGIN with the MUST_CHANGE option. MUST_CHANGE is not implied by CHECK_POLICY or CHECK_EXPIRATION; both must be ON when it is used. It clears as soon as one successful login changes the password."},{"question":"Is 18488 different from 18487?","answer":"Yes. 18487 means the password expired under policy. 18488 means a new password is required at first login because the current one was flagged MUST_CHANGE. Both are fixed by setting a new password, but the diagnostics differ."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/18488","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1913","corpus":"errors","engine":"sql-server","language":"en","title":"Index or statistics name already exists","description":"CREATE INDEX used a name an index or statistics object already has on that table or view; index names are unique per table. CREATE STATISTICS raises 1927 instead.","body":{"code":"1913","slug":"1913","name":null,"message":"The operation failed because an index or statistics with name '%.*ls' already exists on %S_MSG '%.*ls'.","group":"constraints","severity":16,"sql_state":null,"summary":"CREATE INDEX used a name an index or statistics object already has on that table or view; index names are unique per table. CREATE STATISTICS raises 1927 instead.","meaning":"Index and statistics names must be unique within a table or view (unlike constraint names, which are unique per schema). Re-running an index script, or creating an index with the same name as an existing statistics object, raises 1913.","causes":["Running a deployment script that creates an index twice.","An index or statistics object with the same name was created earlier, possibly by a tuning tool."],"fix":[{"text":"Rebuild the existing index in place with `DROP_EXISTING`.","sql":"CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId)\nINCLUDE (OrderDate)\nWITH (DROP_EXISTING = ON);"},{"text":"Or guard the create.","sql":"IF NOT EXISTS (SELECT 1 FROM sys.indexes\n               WHERE object_id = OBJECT_ID(N'dbo.Orders') AND name = N'IX_Orders_CustomerId')\n    CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);"},{"text":"Check statistics names too.","sql":"SELECT name FROM sys.stats WHERE object_id = OBJECT_ID(N'dbo.Orders');"}],"diagnostic":"-- Does an index, or a statistics object, already own that name on the table? A normal index has a statistics object with the same name, so an index hit also returns a 'statistics' row.\nSELECT N'index' AS kind, i.name, i.type_desc, i.is_unique\nFROM sys.indexes AS i\nWHERE i.object_id = OBJECT_ID(N'dbo.Orders') AND i.name = N'IX_Orders_CustomerId'\nUNION ALL\nSELECT N'statistics', s.name, NULL, NULL\nFROM sys.stats AS s\nWHERE s.object_id = OBJECT_ID(N'dbo.Orders') AND s.name = N'IX_Orders_CustomerId';\n-- Names only collide within the same table, so check what exists elsewhere\nSELECT OBJECT_NAME(object_id) AS table_name, name FROM sys.indexes WHERE name = N'IX_Orders_CustomerId';","alternatives":"If the existing index already does the job, rebuild it with DROP_EXISTING = ON instead of dropping and recreating, which keeps the statistics history. If you genuinely need a second, differently shaped index, give it a distinct name that says what it covers.","details":[],"details_title":null,"repro":"-- On a scratch database\nCREATE TABLE dbo.Orders (id int, CustomerId int);\nCREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);\nCREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);  -- Msg 1913: The operation failed because an index or statistics with name 'IX_Orders_CustomerId' already exists on table 'dbo.Orders'.\nDROP TABLE dbo.Orders;","repro_note":null,"related":["sql-server/2714","sql-server/2601","postgresql/42P07","mysql/1061"],"sqlly":"Query sys.indexes in SQLly's editor: the grid lists the names already on the table, which is exactly the set the new index name has to avoid.","faqs":[{"question":"Index names are unique per table, but what about across the database?","answer":"Index and statistics names only need to be unique within one table or view. Two tables can both have an index called IX_Id. Constraint names, by contrast, are unique per schema."},{"question":"The name belongs to a statistics object I never created. Where did it come from?","answer":"SQL Server creates auto-created statistics (_WA_Sys_...) and the query store or tuning tools can create named ones. Check sys.stats on the table; if it is auto-created you can drop it and reuse the name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1913","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/1934","corpus":"errors","engine":"sql-server","language":"en","title":"SET options have incorrect settings","description":"A statement touched an indexed view, filtered index, computed column index or XML method with the wrong SET options, usually QUOTED_IDENTIFIER or ANSI_NULLS off.","body":{"code":"1934","slug":"1934","name":null,"message":"%ls failed because the following SET options have incorrect settings: '%.*ls'. Verify that SET options are correct for use with %S_MSG.","group":"syntax","severity":16,"sql_state":null,"summary":"A statement touched an indexed view, filtered index, computed column index or XML method with the wrong SET options, usually QUOTED_IDENTIFIER or ANSI_NULLS off.","meaning":"Indexed views, filtered indexes, indexes on computed columns, XML data type methods and some other features require specific session settings, mainly `ANSI_NULLS`, `QUOTED_IDENTIFIER`, `ANSI_PADDING`, `ANSI_WARNINGS`, `ARITHABORT` and `CONCAT_NULL_YIELDS_NULL` ON, and `NUMERIC_ROUNDABORT` OFF. If a session (or a stored procedure, which keeps the settings it was created with) has them wrong, the statement fails with 1934, which names the offending options.","causes":["A stored procedure or trigger created with `QUOTED_IDENTIFIER OFF` or `ANSI_NULLS OFF`. Those two settings are saved with the module at create time.","An older client library or tool that connects with `ARITHABORT` or other options off.","A SQL Agent job or `sqlcmd` script with different defaults from SSMS."],"fix":[{"text":"Set the required options before the statement.","sql":"SET ANSI_NULLS ON;\nSET QUOTED_IDENTIFIER ON;\nSET ANSI_PADDING ON;\nSET ANSI_WARNINGS ON;\nSET ARITHABORT ON;\nSET CONCAT_NULL_YIELDS_NULL ON;\nSET NUMERIC_ROUNDABORT OFF;"},{"text":"Recreate procedures and triggers with the right settings, since they keep the values from when they were created.","sql":"SELECT OBJECT_NAME(object_id) AS module, uses_ansi_nulls, uses_quoted_identifier\nFROM sys.sql_modules WHERE uses_ansi_nulls = 0 OR uses_quoted_identifier = 0;"},{"text":"For `sqlcmd`, pass `-I` to turn `QUOTED_IDENTIFIER` on.","sql":null}],"diagnostic":"-- What settings were the modules created with?\nSELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name, OBJECT_NAME(object_id) AS module,\n       uses_ansi_nulls, uses_quoted_identifier\nFROM sys.sql_modules\nWHERE uses_ansi_nulls = 0 OR uses_quoted_identifier = 0;\n-- What are this session's current settings? DBCC USEROPTIONS lists\n-- them. Compare the output against the options the indexed object\n-- requires: ANSI_NULLS, QUOTED_IDENTIFIER, ANSI_PADDING, ANSI_WARNINGS,\n-- ARITHABORT, CONCAT_NULL_YIELDS_NULL on, NUMERIC_ROUNDABORT off.","alternatives":"Set the required options at the top of the failing script or connection. Recreate any procedure or trigger that was created with the wrong options, because those two values are stored with the module and override the session. For the ODBC sqlcmd, pass -I to turn QUOTED_IDENTIFIER on; the Go sqlcmd (1.x) always has it on and ignores -I. DB-Library clients default QUOTED_IDENTIFIER and ANSI_NULLS to OFF, and ODBC and OLE DB clients default ARITHABORT to OFF, so those are the usual suspects.","details":[],"details_title":null,"repro":"-- Scratch DB repro: insert into an indexed view with QUOTED_IDENTIFIER OFF\nSET QUOTED_IDENTIFIER ON;\nGO\nCREATE TABLE dbo.Lines (LineId int NOT NULL PRIMARY KEY, Amount money NOT NULL);\nGO\nCREATE VIEW dbo.LineTotals WITH SCHEMABINDING AS\n    SELECT LineId, SUM(Amount) AS Total, COUNT_BIG(*) AS N\n    FROM dbo.Lines GROUP BY LineId;\nGO\nCREATE UNIQUE CLUSTERED INDEX IX_LineTotals ON dbo.LineTotals (LineId);\nGO\nSET QUOTED_IDENTIFIER OFF;\nGO\n-- Raises 1934: INSERT failed because SET QUOTED_IDENTIFIER is OFF for this session\nINSERT INTO dbo.Lines VALUES (1, 10.00);\nGO\nSET QUOTED_IDENTIFIER ON;\nDROP VIEW dbo.LineTotals;\nDROP TABLE dbo.Lines;","repro_note":null,"related":["sql-server/102","sql-server/1913"],"sqlly":"Run DBCC USEROPTIONS in SQLly's grid to see the session's SET values, then compare them against the options the index or indexed view requires in its definition.","faqs":[{"question":"The same code works in SSMS but fails in my app. Why?","answer":"SSMS turns QUOTED_IDENTIFIER and ANSI_NULLS on by default, while some drivers and tools do not. The error follows the session settings, so the app's connection settings are the difference. Check the driver defaults or set the options explicitly after connecting."},{"question":"Why does recreating the procedure fix it? I set the options in the session.","answer":"For CREATE PROCEDURE and CREATE TRIGGER, the QUOTED_IDENTIFIER and ANSI_NULLS settings in effect at create time are saved with the module and used every time it runs, regardless of the caller's session. A module created with them off needs to be recreated with them on."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/1934","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/207","corpus":"errors","engine":"sql-server","language":"en","title":"Invalid column name","description":"A column the query refers to doesn't exist in any table in scope: a typo, a column from another table, or a SELECT alias used where SQL Server can't see it.","body":{"code":"207","slug":"207","name":null,"message":"Invalid column name '%.*ls'.","group":"objects","severity":16,"sql_state":null,"summary":"A column the query refers to doesn't exist in any table in scope: a typo, a column from another table, or a SELECT alias used where SQL Server can't see it.","meaning":"SQL Server binds every column reference to a table or alias in scope (the `FROM` clause or an outer query) at compile time. If a name doesn't match a column of any table or alias in scope, the statement fails with 207 and names the column.","causes":["A typo, or a column that was renamed or dropped.","Using a `SELECT` list alias in `WHERE`, `GROUP BY` or `HAVING`. Those clauses are processed before the select list, so the alias doesn't exist there yet (it is visible in `ORDER BY`).","A string literal written in double quotes, which SQL Server reads as an identifier when `QUOTED_IDENTIFIER` is on: `WHERE status = \"open\"`.","A column added in the same batch by `ALTER TABLE` and used before a `GO`, because the whole batch is compiled first.","Querying a view whose underlying table changed. `sp_refreshview` picks up an added column in a `SELECT *` view, but a view that uses a renamed or dropped column must be rewritten with `ALTER VIEW`, because `sp_refreshview` fails with the same error."],"fix":[{"text":"List the table's real columns.","sql":"SELECT name, TYPE_NAME(user_type_id) AS type_name\nFROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.Orders');"},{"text":"Repeat the expression instead of the alias in `WHERE`, or wrap the query in a derived table or CTE.","sql":"SELECT *\nFROM (SELECT OrderId, Quantity * UnitPrice AS Total FROM dbo.OrderLines) AS t\nWHERE t.Total > 100;"},{"text":"Use single quotes for string values.","sql":"SELECT * FROM dbo.Tickets WHERE Status = 'open';"},{"text":"Put a `GO` between an `ALTER TABLE ... ADD` and statements that use the new column.","sql":null}],"diagnostic":"-- What columns does the table (or view) actually have?\nSELECT c.name, TYPE_NAME(c.user_type_id) AS type_name\nFROM sys.columns c\nWHERE c.object_id = OBJECT_ID(N'dbo.Orders')\nORDER BY c.column_id;\n-- Was the column renamed recently? Schema change tracking needs DDL trigger or query store; query store shows plan/regression changes, not column names.\n-- Views that reference columns which no longer exist:\nSELECT v.name AS stale_view, r.referenced_entity_name\nFROM sys.sql_expression_dependencies r\nJOIN sys.views v ON v.object_id = r.referencing_id\nWHERE NOT EXISTS (\n  SELECT 1 FROM sys.columns c\n  WHERE c.object_id = r.referenced_id AND c.name = r.referenced_column_name\n) AND r.is_incomplete = 0 AND r.referenced_column_name IS NOT NULL;","alternatives":"Quote string literals with single quotes and identifiers with brackets, so QUOTED_IDENTIFIER can never reinterpret a value as a column. Wrap select-list expressions in a derived table or CTE when filtering on an alias. After adding a column to an underlying table, run sp_refreshview on dependent `SELECT *` views so they show it. After renaming or dropping a column, rewrite the view with ALTER VIEW; sp_refreshview fails with the same error 207.","details":[],"details_title":null,"repro":"SELECT 1 AS n WHERE n = 1;  -- Msg 207: Invalid column name 'n'.","repro_note":null,"related":["sql-server/208","sql-server/209","sql-server/4104","postgresql/42703","mysql/1054","oracle/ora-00904"],"sqlly":"SQLly's Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V elsewhere) checks a query against the connection's schema without running it and marks unknown columns, and the editor's IntelliSense lists the real columns of each table as you type.","faqs":[{"question":"Why does the alias work in ORDER BY but not in WHERE?","answer":"SQL Server processes WHERE before the select list, so the alias does not exist there yet. ORDER BY runs after the select list, which is why it can see aliases. Repeat the expression in WHERE or wrap the query in a derived table."},{"question":"The column exists. Why is it still invalid?","answer":"Check three things: the column is on a table in this query's FROM, you are in the right database, and the column was not added by an ALTER TABLE earlier in the same batch. The whole batch compiles at once, so a column added in line 5 is not visible to line 2 until a GO splits them."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/207","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/208","corpus":"errors","engine":"sql-server","language":"en","title":"Invalid object name","description":"SQL Server can't find the table, view or other object the query names: wrong database, missing schema, a typo, or an object that doesn't exist yet.","body":{"code":"208","slug":"208","name":null,"message":"Invalid object name '%.*ls'.","group":"objects","severity":16,"sql_state":null,"summary":"SQL Server can't find the table, view or other object the query names: wrong database, missing schema, a typo, or an object that doesn't exist yet.","meaning":"When a statement is compiled, SQL Server resolves every table and view name. A one-part name like `Orders` is looked up in your default schema and then in `dbo` of the current database. If nothing matches, the batch fails with 208 and names the object it couldn't find.\n\nOne exception is worth knowing: inside a stored procedure, a missing table is allowed at create time (deferred name resolution) and only fails with 208 when the procedure runs.","causes":["The query runs in the wrong database, often `master`, because the connection's default database isn't the one you meant.","The object is in another schema than your default and the name isn't schema-qualified.","A typo, or a case difference on a database with a case-sensitive collation.","The object was dropped, renamed, or not created yet, for example a temp table created in a different scope or session.","A synonym that points to an object that no longer exists."],"fix":[{"text":"Check where you are and whether the object exists there.","sql":"SELECT DB_NAME() AS current_db, SCHEMA_NAME() AS default_schema;\nSELECT s.name AS schema_name, o.name, o.type_desc\nFROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id\nWHERE o.name LIKE N'%Order%';"},{"text":"Switch to the right database, or qualify the name fully.","sql":"USE SalesDb;\nSELECT TOP (10) * FROM Sales.Orders;\n-- or: SELECT TOP (10) * FROM SalesDb.Sales.Orders;"},{"text":"If the object lives in another database or server, use a three- or four-part name, or create a synonym.","sql":"CREATE SYNONYM dbo.Orders FOR SalesDb.Sales.Orders;"},{"text":"For temp tables, remember that a `#temp` table created inside a procedure or dynamic SQL disappears when that scope ends.","sql":null}],"diagnostic":"-- Where am I, and does the object exist in this database at all?\nSELECT DB_NAME() AS current_db, SCHEMA_NAME() AS my_default_schema;\nSELECT s.name AS schema_name, o.name, o.type_desc\nFROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id\nWHERE o.name = N'Orders';\n-- Search every online database you can reach (2017+). A three-part name cannot\n-- be built from a column value, so generate one SELECT per database and run the\n-- combined text:\nDECLARE @sql nvarchar(max) =\n    (SELECT STRING_AGG(\n        CONCAT(N'SELECT ', QUOTENAME(name), N' AS db, o.name, o.type_desc FROM ',\n               QUOTENAME(name), N'.sys.objects o WHERE o.name = N''Orders'''),\n        N' UNION ALL ')\n     FROM sys.databases\n     WHERE state_desc = N'ONLINE' AND database_id <> 2 AND HAS_DBACCESS(name) = 1);\nEXEC (@sql);\n-- Synonyms that point at something missing (four-part linked-server targets\n-- cannot be checked this way):\nSELECT s.name + N'.' + syn.name AS synonym, syn.base_object_name\nFROM sys.synonyms syn JOIN sys.schemas s ON s.schema_id = syn.schema_id\nWHERE OBJECT_ID(syn.base_object_name) IS NULL;","alternatives":"Schema-qualify every object reference so the default-schema lookup never bites. If the table might genuinely be missing, deploy it before the batch rather than wrapping the query in TRY/CATCH, since 208 aborts the batch at compile time and TRY/CATCH will not catch it from the same batch.","details":[],"details_title":null,"repro":"SELECT * FROM dbo.TableThatDoesNotExist;  -- Msg 208: Invalid object name 'dbo.TableThatDoesNotExist'.","repro_note":null,"related":["sql-server/207","sql-server/2812","sql-server/4104","postgresql/42P01","mysql/1146","oracle/ora-00942"],"sqlly":"SQLly's Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V on Windows and Linux) checks a query against the connected database's schema without running it and marks unknown tables and columns in the editor. When a query does fail, the editor jumps to the line SQL Server reported.","faqs":[{"question":"Why does the query work in SSMS but fail with 208 in my application?","answer":"The two connections usually start in different databases or run as different users with different default schemas. Schema-qualify the name and set the database in the connection string."},{"question":"Why does TRY/CATCH not catch error 208?","answer":"When the missing table is in the same batch, name resolution fails at compile time before execution starts, so no TRY block is entered. Put the SELECT in a child stored procedure called from inside the TRY block, or in an EXEC string run inside the TRY block, and it becomes catchable. A SELECT in a separate GO batch sits outside the TRY block and is not caught."},{"question":"My temp table exists. Why 208?","answer":"Temp tables created inside a stored procedure or EXEC string go out of scope when that block ends. Also, a #temp created inside dynamic SQL (EXEC or sp_executesql) is not visible to the code that ran it. A #temp created in the calling batch is visible to dynamic SQL that batch runs. Create it in the scope that reads it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/208","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/209","corpus":"errors","engine":"sql-server","language":"en","title":"Ambiguous column name","description":"Two or more tables in the query have a column with this name, so SQL Server can't tell which one you mean. Prefix it with a table alias.","body":{"code":"209","slug":"209","name":null,"message":"Ambiguous column name '%.*ls'.","group":"objects","severity":16,"sql_state":null,"summary":"Two or more tables in the query have a column with this name, so SQL Server can't tell which one you mean. Prefix it with a table alias.","meaning":"When several joined tables share a column name, such as `Id` or `CustomerId`, an unqualified reference could mean any of them. SQL Server refuses to guess and raises 209.","causes":["Joining tables that share a column name and using that name without a prefix in `SELECT`, `WHERE`, `ORDER BY` or `GROUP BY`.","A column added to one table later, which makes previously unique names ambiguous in existing queries."],"fix":[{"text":"Qualify the column with its table alias.","sql":"SELECT o.CustomerId, c.Name\nFROM dbo.Orders AS o\nJOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nORDER BY o.CustomerId;"},{"text":"Always qualifying columns in multi-table queries prevents this when someone adds a column later.","sql":null}],"diagnostic":"-- Which tables in the query share the ambiguous column name?\nSELECT c.name AS column_name, COUNT(*) AS tables_with_it\nFROM sys.columns c\nWHERE c.object_id IN (OBJECT_ID(N'dbo.Orders'), OBJECT_ID(N'dbo.Customers'))\nGROUP BY c.name HAVING COUNT(*) > 1;\n-- Every table in this list that holds the name (sys.columns stores no creation time, so recent additions are not shown):\nSELECT OBJECT_NAME(object_id) AS table_name, name AS column_name\nFROM sys.columns\nWHERE name = N'CustomerId'\n  AND OBJECT_NAME(object_id) IN (N'Orders', N'Customers');","alternatives":"Two habits prevent 209 entirely: alias every table in a join, and prefix every column with its alias. Code generators and ORMs that emit SELECT * over joins are a common source of surprises here. SELECT * itself does not raise 209; it returns both columns. A derived table over SELECT * that references the duplicated name raises 8156 instead. A new column with a duplicate name does break previously working queries that use the bare name, without any query change.","details":[],"details_title":null,"repro":"CREATE TABLE #a (CustomerId int, Name nvarchar(50));\nCREATE TABLE #b (CustomerId int);\nSELECT CustomerId FROM #a JOIN #b ON #b.CustomerId = #a.CustomerId;  -- Msg 209: Ambiguous column name 'CustomerId'.\nDROP TABLE #a; DROP TABLE #b;","repro_note":null,"related":["sql-server/207","sql-server/4104","postgresql/42702","mysql/1052","oracle/ora-00918"],"sqlly":"Run the failing SELECT in SQLly's editor and the message's line number maps onto your script, so the two tables sharing the column name are both visible in the FROM clause you need to qualify.","faqs":[{"question":"Does ORDER BY also refuse ambiguous names?","answer":"Yes. Any clause where the name is unresolved, including SELECT, WHERE, GROUP BY, HAVING and ORDER BY, raises 209. ORDER BY has one exception: if the column matches exactly one table, it resolves. If the name appears in several tables and not in the select list, it fails; when the select list already contains a column with that name, ORDER BY accepts it. A positional ORDER BY or an explicit alias avoids the question."},{"question":"The column exists in both tables with the same value. Why complain?","answer":"SQL Server does not check whether the values would agree. Ambiguity is a name-resolution rule: two sources could provide the column, so the reference is rejected regardless of data."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/209","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/220","corpus":"errors","engine":"sql-server","language":"en","title":"Arithmetic overflow error for data type","description":"A constant or result doesn't fit in a small integer type such as tinyint or smallint. The message shows the type and the value.","body":{"code":"220","slug":"220","name":null,"message":"Arithmetic overflow error for data type %ls, value = %ld.","group":"data","severity":16,"sql_state":null,"summary":"A constant or result doesn't fit in a small integer type such as tinyint or smallint. The message shows the type and the value.","meaning":"Error 220 is raised when a value is too large (or negative, for `tinyint`) for an integer type, typically when assigning a constant or a computed integer: `tinyint` holds 0 to 255, `smallint` -32,768 to 32,767. It is closely related to 8115, which covers conversions such as decimal overflow.","causes":["Storing a value over 255 in a `tinyint`, or a negative value in one.","An identity or counter column defined as `tinyint` or `smallint` running out of range.","Arithmetic on small integer columns whose result exceeds the type."],"fix":[{"text":"Use a wider type for the column or variable.","sql":"ALTER TABLE dbo.Settings ALTER COLUMN RetryCount smallint NOT NULL;"},{"text":"For tinyint or smallint arithmetic that overflows inside the small type (error 8115), cast before doing arithmetic so the result has room.","sql":"SELECT CAST(a AS int) * b FROM dbo.SmallNumbers;"}],"diagnostic":"-- Find tinyint and smallint columns that are close to their limits, especially identity or counter columns.\nSELECT OBJECT_NAME(c.object_id) AS table_name, c.name, t.name AS type_name, c.is_identity, ic.seed_value, ic.last_value\nFROM sys.columns c\nJOIN sys.types t ON t.user_type_id = c.user_type_id\nLEFT JOIN sys.identity_columns ic ON ic.object_id = c.object_id\nWHERE t.name IN ('tinyint', 'smallint') AND OBJECTPROPERTY(c.object_id, 'IsUserTable') = 1;\n-- If it is an identity column, check how much headroom remains.\nSELECT name, seed_value, last_value FROM sys.identity_columns WHERE object_id = OBJECT_ID(N'dbo.Settings');\n-- Check the current column contents to size the new type.\nSELECT MAX(RetryCount) AS max_val, MIN(RetryCount) AS min_val FROM dbo.Settings;","alternatives":"ALTER COLUMN is an online-in-name-only operation for most cases and rebuilds the table, so on a large table consider adding a new wider column, backfilling in batches, then swapping. For computed results, an explicit CAST before the arithmetic avoids the overflow without touching any schema.","details":[],"details_title":null,"repro":"DECLARE @t tinyint = 256;  -- Msg 220: Arithmetic overflow error for data type tinyint, value = 256.","repro_note":null,"related":["sql-server/8115","sql-server/248","postgresql/22003","mysql/1264"],"sqlly":"SQLly's grid is a quick bench for the range question: SELECT CAST(300 AS tinyint) fails exactly as your insert would, so you can confirm the type's ceiling without touching real data.","faqs":[{"question":"Why did 255 fit yesterday and 256 fail today?","answer":"tinyint holds exactly the values 0 through 255. Nothing was wrong before; the column simply reached the top of its range. This is common on tinyint identity or status columns that quietly count upward."},{"question":"Does widening a column break foreign keys or indexes?","answer":"ALTER COLUMN on a column referenced by a foreign key, index, or check constraint fails until those are dropped or it refuses the change depending on the object. Plan for rebuilding dependent indexes, and note the data type change can also require re-creating statistics."},{"question":"Is error 220 the same as error 8115?","answer":"They are siblings, not the same. 220 covers arithmetic overflow for integer types such as tinyint and smallint; 8115 covers conversion and aggregate overflow, including numeric and identity cases. The fix direction, a wider type, is usually the same."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/220","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/229","corpus":"errors","engine":"sql-server","language":"en","title":"Permission denied on object","description":"You can reach the database, but you lack SELECT, INSERT, UPDATE, DELETE or EXECUTE permission on the named object or its schema.","body":{"code":"229","slug":"229","name":null,"message":"The %ls permission was denied on the object '%.*ls', database '%.*ls', schema '%.*ls'.","group":"permissions","severity":14,"sql_state":null,"summary":"You can reach the database, but you lack SELECT, INSERT, UPDATE, DELETE or EXECUTE permission on the named object or its schema.","meaning":"Database users only get the permissions granted to them, their roles or `public`. Error 229 names the permission that was missing (`SELECT`, `EXECUTE`...) and the object, database and schema. A `DENY` anywhere in the chain wins over any `GRANT`.","causes":["The user or its roles were never granted the permission.","A `DENY` on the object, the schema or a role the user is in (for example `db_denydatareader`).","Ownership chaining is broken: a view or procedure references an object owned by a different owner, so the caller's own permission on the underlying table is checked.","Dynamic SQL inside a procedure runs with the caller's permissions, not the procedure owner's."],"fix":[{"text":"Grant the permission on the object, or on the whole schema.","sql":"GRANT SELECT ON dbo.Orders TO app_user;\n-- every table and view in the schema:\nGRANT SELECT ON SCHEMA::dbo TO app_user;\n-- procedures in the schema:\nGRANT EXECUTE ON SCHEMA::dbo TO app_user;"},{"text":"Check what the user actually has on the object.","sql":"EXECUTE AS USER = 'app_user';\nSELECT * FROM fn_my_permissions('dbo.Orders', 'OBJECT');\nREVERT;"},{"text":"Look for `DENY` entries that override grants.","sql":"SELECT USER_NAME(grantee_principal_id) AS grantee, permission_name, state_desc,\n       OBJECT_NAME(major_id) AS object_name\nFROM sys.database_permissions WHERE state = 'D';"},{"text":"For dynamic SQL in a procedure, sign the procedure with a certificate or use `EXECUTE AS OWNER`, instead of granting table access to every caller.","sql":null}],"diagnostic":"-- What the principal actually has on the object, vs what a DENY takes away.\nEXECUTE AS USER = 'app_user';\nSELECT * FROM fn_my_permissions('dbo.Orders', 'OBJECT');\nSELECT * FROM fn_my_permissions(NULL, 'DATABASE');\nREVERT;\n-- Any DENY that touches the object, its schema, or the database:\nSELECT USER_NAME(grantee_principal_id) AS grantee, permission_name,\n       state_desc, class_desc, OBJECT_NAME(major_id) AS object_name\nFROM sys.database_permissions\nWHERE state = 'D';\n-- Does ownership chaining apply? Same owner on the procedure and the table means no per-table check.\n-- sys.objects.principal_id is only filled when the object is owned directly, so\n-- compare the owners of the schemas instead:\nSELECT OBJECT_SCHEMA_NAME(p.object_id) AS proc_schema, OBJECT_NAME(p.object_id) AS proc_name,\n       USER_NAME(sp.principal_id) AS proc_schema_owner,\n       OBJECT_SCHEMA_NAME(t.object_id) + N'.' + OBJECT_NAME(t.object_id) AS referenced_table,\n       USER_NAME(st.principal_id) AS table_schema_owner\nFROM sys.sql_expression_dependencies d\nJOIN sys.objects p ON p.object_id = d.referencing_id\nJOIN sys.objects t ON t.object_id = d.referenced_id\nJOIN sys.schemas sp ON sp.schema_id = p.schema_id\nJOIN sys.schemas st ON st.schema_id = t.schema_id\nWHERE p.type IN ('P','V') AND sp.principal_id <> st.principal_id;","alternatives":"If callers only go through stored procedures, keep table access closed and fix chaining instead: make the procedure and tables share one owner, or sign the procedure with a certificate so it runs with extra rights. For ad hoc reporting needs, a view exposing only the needed columns is narrower than granting SELECT on the base table, but only when the view and the table share an owner. If they do not, the caller also needs SELECT on the table.","details":[],"details_title":null,"repro":"-- Run as a login with no grants in the scratch database.\nCREATE LOGIN repro_user WITH PASSWORD = 'Repro!2345';\nCREATE USER repro_user FOR LOGIN repro_user;\nEXECUTE AS USER = 'repro_user';\nSELECT * FROM dbo.Orders;  -- Msg 229: The SELECT permission was denied on the object 'Orders', database '...', schema 'dbo'.\nREVERT;\nDROP USER repro_user;\nDROP LOGIN repro_user;","repro_note":null,"related":["sql-server/262","sql-server/916","postgresql/42501","mysql/1142","oracle/ora-01031"],"sqlly":"Run fn_my_permissions in SQLly's editor and the grant list lands in the grid, next to a schema tree you can expand to confirm you are in the database you think you are.","faqs":[{"question":"The user is in db_datareader. Why is SELECT still denied?","answer":"Either a DENY reaches the principal somewhere in the chain, or ownership chaining broke. db_datareader covers base tables, but if the query goes through a view or procedure whose owner differs from the table owner, the caller's own permission on the table is checked again. Compare the owners, or run fn_my_permissions as that user to see what is actually granted."},{"question":"Why does the stored procedure work in SSMS but fail from the application?","answer":"The application probably runs dynamic SQL instead of calling the procedure. Dynamic SQL runs with the caller's permissions, so it hits the table check directly even when the procedure's owner would have been allowed through. Same connection string, different code path."},{"question":"Should I just add the user to db_owner to make it stop?","answer":"That grants far more than the one missing permission. Grant the specific permission on the object or schema, and keep the blast radius small. If several objects are involved, grant on the schema instead of listing each one."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/229","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/241","corpus":"errors","engine":"sql-server","language":"en","title":"Conversion failed for date and/or time","description":"A string couldn't be converted to a date or time: wrong format for the session's language and DATEFORMAT, or not a real date.","body":{"code":"241","slug":"241","name":null,"message":"Conversion failed when converting date and/or time from character string.","group":"data","severity":16,"sql_state":null,"summary":"A string couldn't be converted to a date or time: wrong format for the session's language and DATEFORMAT, or not a real date.","meaning":"SQL Server parses date strings according to the format and the session's `DATEFORMAT` and `LANGUAGE` settings. If the text isn't a valid date in that interpretation (`'31/12/2025'` under a month-first setting, `'2025-02-30'`, `'yesterday'`), conversion to `date`, `datetime` or `datetime2` fails with 241.","causes":["Ambiguous formats like `'03/04/2025'`, read differently depending on `SET DATEFORMAT` and the login's language, and day-first strings like `'31/12/2025'` that fail under a month-first setting.","Dates that don't exist, such as February 30.","Free text in a column that should hold dates, such as `'yesterday'`. An empty string doesn't raise 241; it converts to `1900-01-01`.","Using `CONVERT` with a style number that doesn't match the string."],"fix":[{"text":"Use unambiguous ISO formats: `'20251231'` or `'2025-12-31T14:30:00'`. These parse the same under every language and DATEFORMAT setting (with `datetime2` and `date`, `'2025-12-31'` is also safe).","sql":"SELECT CAST('20251231' AS date), CAST('2025-12-31T14:30:00' AS datetime2);"},{"text":"Parse known formats with an explicit style. Style 103 is dd/mm/yyyy, 101 is mm/dd/yyyy.","sql":"SELECT CONVERT(date, '31/12/2025', 103);"},{"text":"Find the bad values with `TRY_CONVERT`.","sql":"SELECT RawDate FROM staging.Events WHERE TRY_CONVERT(date, RawDate, 103) IS NULL AND RawDate IS NOT NULL;"},{"text":"Pass dates from applications as typed parameters (`date`, `datetime2`), never as formatted strings.","sql":null}],"diagnostic":"-- Find the rows that fail conversion (SQL Server 2012+, TRY_CONVERT returns NULL on failure)\nSELECT pk, bad_date_col\nFROM dbo.MyTable\nWHERE bad_date_col IS NOT NULL\n  AND TRY_CONVERT(date, bad_date_col) IS NULL;\n\n-- See what the session currently expects for date order\nDBCC USEROPTIONS;  -- look for 'dateformat mdy' / 'dmy' etc.\n\n-- Test one ambiguous string under both orders\nSET DATEFORMAT mdy; SELECT TRY_CONVERT(date, '03/04/2025');  -- 2025-03-04\nSET DATEFORMAT dmy; SELECT TRY_CONVERT(date, '03/04/2025');  -- 2025-04-03","alternatives":"Store dates in columns typed `date` or `datetime2` so no string parsing happens at all, and pass dates from applications as typed parameters rather than concatenated strings. When you must parse text, use `TRY_CONVERT` with an explicit style number instead of relying on session settings.","details":[],"details_title":null,"repro":"SET DATEFORMAT mdy;\nSELECT CAST('31/12/2025' AS date);  -- Msg 241","repro_note":null,"related":["sql-server/242","sql-server/245","postgresql/22007","postgresql/22008","mysql/1292","oracle/ora-01843","oracle/ora-01861"],"sqlly":"Test the failing literal in isolation from SQLly's editor: SELECT TRY_CONVERT(datetime, the_value) and the grid shows either the parsed value or NULL, which tells you whether the format or the data is at fault.","faqs":[{"question":"Why does the same string work on one server and fail on another?","answer":"The session's language and DATEFORMAT differ, usually inherited from each login's default language. '01/02/2025' is January 2nd under us_english and February 1st under British English. Use an unambiguous format like '2025-01-02T00:00:00' or a style number in CONVERT."},{"question":"Is '2025-01-02' always safe?","answer":"For date, datetime2 and datetimeoffset it is, since ISO 8601 parsing ignores DATEFORMAT. For the old datetime type, the 'yyyy-mm-dd' form is still interpreted under DATEFORMAT, so 'yyyy-mm-ddThh:mm:ss' or style 126 is the safer habit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/241","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/242","corpus":"errors","engine":"sql-server","language":"en","title":"Out-of-range date conversion","description":"A value was converted between date types (usually varchar to datetime) and the result is outside the target type's range or isn't a real date.","body":{"code":"242","slug":"242","name":null,"message":"The conversion of a %ls data type to a %ls data type resulted in an out-of-range value.","group":"data","severity":16,"sql_state":null,"summary":"A value was converted between date types (usually varchar to datetime) and the result is outside the target type's range or isn't a real date.","meaning":"Error 242 means the conversion understood the format but the resulting date can't be stored. A common case is `datetime`, which only covers 1753-01-01 to 9999-12-31, receiving an earlier date such as `0001-01-01` from an application's default date value. Another is a day or month out of range for the format being used, such as month 13.","causes":["Converting a string like `'0001-01-01'` into `datetime`, whose minimum is the year 1753. A .NET `DateTime.MinValue` sent to a `datetime` parameter fails earlier, in the client, with a `SqlDateTime overflow` exception.","Day and month swapped under the session's `DATEFORMAT`, so `'13/01/2025'` is read as month 13.","Converting a `datetime2` value outside the `datetime` range into `datetime`."],"fix":[{"text":"Use `datetime2`, which covers years 1 to 9999 with better precision, for new columns.","sql":"ALTER TABLE dbo.Events ALTER COLUMN OccurredAt datetime2(3) NOT NULL;"},{"text":"Map placeholder dates from applications to NULL instead of storing year 1.","sql":null},{"text":"Use the unseparated `yyyyMMdd` or `yyyy-MM-ddTHH:mm:ss` string forms, which ignore `SET DATEFORMAT`, or an explicit `CONVERT` style that matches the input (103 for dd/mm/yyyy). Avoid the date-only `yyyy-MM-dd` form with `datetime`: under `SET DATEFORMAT dmy` it is read as year-day-month, so `'2025-01-13'` fails with 242 and `'2025-13-01'` silently becomes 2025-01-13.","sql":"SELECT CONVERT(datetime, '13/01/2025', 103);"}],"diagnostic":"-- Rows that parse as datetime2 but not as datetime: outside the 1753-9999 datetime range\nSELECT pk, bad_date_col,\n       TRY_CONVERT(datetime2, bad_date_col) AS as_datetime2,\n       TRY_CONVERT(datetime,  bad_date_col) AS as_datetime\nFROM dbo.MyTable\nWHERE TRY_CONVERT(datetime2, bad_date_col) IS NOT NULL\n  AND TRY_CONVERT(datetime,  bad_date_col) IS NULL;\n\n-- Check the column's declared type; datetime is the usual victim\nSELECT c.name, t.name AS type_name\nFROM sys.columns c\nJOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID(N'dbo.MyTable') AND t.name IN ('datetime','smalldatetime','datetime2','date');","alternatives":"Move the column to `datetime2`, which covers the year 0001 to 9999, so values like `0001-01-01` fit. If you must keep `datetime`, have the application send NULL instead of `DateTime.MinValue` for missing dates, or clamp the value before the insert.","details":[],"details_title":null,"repro":"SELECT CAST('0001-01-01' AS datetime);  -- Msg 242","repro_note":null,"related":["sql-server/241","sql-server/8115","postgresql/22008","mysql/1292","oracle/ora-01843"],"sqlly":"SQLly's grid is a quick bench for date formats: run the conversion with an explicit style argument like CONVERT(datetime, the_value, 120) and compare the output before changing the real query.","faqs":[{"question":"Why do I see this with default parameter values in .NET?","answer":"C#'s DateTime.MinValue is 0001-01-01, which predates datetime's floor of 1753-01-01. An uninitialized DateTime property sent as a parameter produces exactly this error. Send DBNull.Value or use nullable DateTime instead."},{"question":"What is the difference between 241 and 242?","answer":"241 means the string could not be understood as a date at all under the session settings. 242 means it was understood but the resulting value does not fit the target type, like year 0001 into datetime."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/242","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/245","corpus":"errors","engine":"sql-server","language":"en","title":"Conversion failed converting a value","description":"SQL Server tried to convert a string to a number (or another type) and the string isn't a valid value of that type, often through implicit conversion.","body":{"code":"245","slug":"245","name":null,"message":"Conversion failed when converting the %ls value '%.*ls' to data type %ls.","group":"data","severity":16,"sql_state":null,"summary":"SQL Server tried to convert a string to a number (or another type) and the string isn't a valid value of that type, often through implicit conversion.","meaning":"When an expression mixes types, SQL Server converts the lower-precedence type to the higher one. Numbers outrank strings, so comparing a `varchar` column with an `int` converts every string to `int`. If any value isn't a valid number, the query fails with 245 and shows the value, for example `Conversion failed when converting the varchar value 'N/A' to data type int`.","causes":["Comparing or joining a character column to a numeric value or column: `WHERE Code = 42` on a `varchar` column containing non-numeric codes.","Building a string with `+` and a number, which tries to convert the string to a number: `'Total: ' + @Count`.","A `CASE` expression whose branches return both strings and numbers.","Bad data in a column that is supposed to hold numbers but is typed as text."],"fix":[{"text":"Compare like with like: quote the literal or convert the number to a string.","sql":"SELECT * FROM dbo.Products WHERE Code = '42';"},{"text":"Concatenate with `CONCAT`, which converts everything to strings, or convert explicitly.","sql":"DECLARE @Count int = 5;\nSELECT CONCAT('Total: ', @Count);\nSELECT 'Total: ' + CAST(@Count AS varchar(20));"},{"text":"Find the values that won't convert with `TRY_CONVERT`, which returns NULL instead of failing.","sql":"SELECT Code FROM dbo.Products WHERE TRY_CONVERT(int, Code) IS NULL AND Code IS NOT NULL;"},{"text":"Make every branch of a `CASE` return the same type.","sql":null}],"diagnostic":"-- What does the column actually contain that won't convert? TRY_CONVERT returns NULL for bad values.\nSELECT Code, LEN(Code) AS code_len\nFROM dbo.Products\nWHERE TRY_CONVERT(int, Code) IS NULL AND Code IS NOT NULL;\n-- Check the declared types on both sides of a join or comparison\nSELECT c.name, TYPE_NAME(c.user_type_id) AS type_name\nFROM sys.columns AS c\nWHERE c.object_id IN (OBJECT_ID(N'dbo.Products'), OBJECT_ID(N'dbo.Orders'));\n-- Find queries that compare the column to a number, in case the fix belongs in the SQL\nSELECT OBJECT_NAME(object_id) AS object_name FROM sys.sql_modules WHERE definition LIKE N'%Code = %';","alternatives":"Prefer TRY_CAST or TRY_CONVERT over ISNUMERIC when validating: ISNUMERIC returns 1 for strings like '$1,000' that an int conversion still rejects. If the column really holds only numbers, change its type to int so the conversion happens once, on write, instead of on every read.","details":[],"details_title":null,"repro":"SELECT 'N/A' + 1;  -- Msg 245: Conversion failed when converting the varchar value 'N/A' to data type int.","repro_note":null,"related":["sql-server/8114","sql-server/241","sql-server/8115","postgresql/22P02","mysql/1366","oracle/ora-01722"],"sqlly":"SQLly's execution plan findings flag implicit conversions, which are behind many 245 errors and also keep indexes from being used.","faqs":[{"question":"Why does WHERE Code = 42 fail even though no row has a bad Code value visible in my top rows?","answer":"SQL Server converts the varchar column to int for each row the plan evaluates. A non-numeric value fails the query only when the plan reads a row that contains it. A seek or TOP that stops before that row avoids the error, and a scan that reaches it fails even when another predicate would reject that row."},{"question":"Why does 'Total: ' + @Count break when @Count is a number?","answer":"With +, a string operand can only concatenate with a string, so SQL Server tries to convert 'Total: ' to int. Use CONCAT, which converts everything to strings, or CAST the number explicitly."},{"question":"Is this related to error 8114?","answer":"Yes. Both come from a string that cannot be converted to a number. 245 is raised by a conversion inside an expression, such as a WHERE comparison, a CAST, or a + concatenation. 8114 is raised when a value bound to a typed parameter fails to convert, for example an int parameter passed to sp_executesql. The fixes are the same family."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/245","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/248","corpus":"errors","engine":"sql-server","language":"en","title":"Conversion overflowed an int column","description":"A string holding a number larger than the int range (about 2.1 billion) was converted to int. Use bigint or decimal for big numbers.","body":{"code":"248","slug":"248","name":null,"message":"The conversion of the %ls value '%.*ls' overflowed an int column.","group":"data","severity":16,"sql_state":null,"summary":"A string holding a number larger than the int range (about 2.1 billion) was converted to int. Use bigint or decimal for big numbers.","meaning":"When converting a character value to `int`, SQL Server checks the range -2,147,483,648 to 2,147,483,647. A string like `'3000000000'`, or a long numeric code such as a phone number stored as text, overflows and raises 248.","causes":["Phone numbers, account numbers or other long codes converted to `int`.","Implicit conversion of a large numeric string to `int` because it's compared with an `int` column or value."],"fix":[{"text":"Convert to `bigint` or `decimal` instead.","sql":"SELECT CAST('3000000000' AS bigint);"},{"text":"Keep identifiers that aren't quantities (phone numbers, codes with leading zeros) as strings and compare them as strings.","sql":null}],"diagnostic":"-- Find which values are too big for int. Anything outside this range will fail.\nSELECT RawValue FROM staging.Payments\nWHERE ISNUMERIC(RawValue) = 1\n  AND TRY_CONVERT(bigint, RawValue) NOT BETWEEN -2147483648 AND 2147483647;\n-- If the error came from a comparison, check whether the parameter or the column is the int side forcing the conversion.\nSELECT c.name, t.name AS type_name FROM sys.columns c JOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID(N'dbo.Payments');\n-- On 2012+, TRY_CONVERT(int, ...) returns NULL instead of raising, which makes bad rows easy to list.\nSELECT RawValue, TRY_CONVERT(int, RawValue) AS as_int FROM staging.Payments WHERE TRY_CONVERT(int, RawValue) IS NULL AND RawValue IS NOT NULL;","alternatives":"Convert to bigint or decimal instead of int when the value can exceed about 2.1 billion. For identifiers that are not quantities, such as phone numbers or codes with leading zeros, store and compare them as strings; converting them to numbers loses leading zeros even when it doesn't overflow.","details":[],"details_title":null,"repro":"SELECT CAST('3000000000' AS int);  -- Msg 248","repro_note":null,"related":["sql-server/220","sql-server/8115","sql-server/245","postgresql/22003"],"sqlly":"Run TRY_CONVERT(int, the_column) over the suspect rows in SQLly's grid; NULLs mark the values that overflow int, and the result is easy to count and copy out.","faqs":[{"question":"Why is SQL Server converting my string to int at all?","answer":"Data type precedence: int outranks varchar, so when you compare a varchar value with an int column or variable, SQL Server converts the string to int, and any string over the int range raises 248. Convert the int side to the string type or use an explicit bigint/decimal cast instead."},{"question":"A phone number caused this. Should I store phone numbers as int?","answer":"No. Phone numbers are not numbers in the mathematical sense; they have leading zeros, formatting, and country codes that int discards or cannot hold. Store them as varchar with a length that covers the longest value you accept."},{"question":"What is the largest number int can hold?","answer":"2,147,483,647, with -2,147,483,648 at the low end. Anything bigger needs bigint (up to about 9.2 quintillion) or decimal for exact larger values."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/248","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2601","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot insert duplicate key row","description":"An INSERT or UPDATE would put a duplicate value into a unique index. The message names the table, the index and the duplicate key value.","body":{"code":"2601","slug":"2601","name":null,"message":"Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.","group":"constraints","severity":14,"sql_state":null,"summary":"An INSERT or UPDATE would put a duplicate value into a unique index. The message names the table, the index and the duplicate key value.","meaning":"Error 2601 is raised by a unique index created with `CREATE UNIQUE INDEX`, including filtered unique indexes. It is the index counterpart of 2627, which comes from PRIMARY KEY and UNIQUE constraints. The statement stops and its changes are rolled back.","causes":["Writing a value that another row already has in a column covered by a unique index.","A unique index on a nullable column: SQL Server treats NULLs as equal in unique indexes, so only one row may have NULL unless the index is filtered.","A load whose source contains duplicates."],"fix":[{"text":"Find the conflicting row with the value from the message, then update it or skip the new one.","sql":"SELECT * FROM dbo.Users WHERE UserName = N'ada';"},{"text":"To allow many NULLs but keep non-NULL values unique, make the index filtered.","sql":"DROP INDEX UX_Users_TaxId ON dbo.Users;\nCREATE UNIQUE INDEX UX_Users_TaxId ON dbo.Users (TaxId) WHERE TaxId IS NOT NULL;"},{"text":"Check which columns the index covers.","sql":"EXEC sp_helpindex 'dbo.Users';"}],"diagnostic":"-- List every unique index on the table, with the key columns\nSELECT i.name AS index_name, i.is_unique, i.has_filter, i.filter_definition,\n       STRING_AGG(c.name, ', ') AS key_columns\nFROM sys.indexes AS i\nJOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.key_ordinal > 0\nJOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id\nWHERE i.object_id = OBJECT_ID(N'dbo.Users') AND i.is_unique = 1\nGROUP BY i.name, i.is_unique, i.has_filter, i.filter_definition;\n-- Check the staging data for duplicates before the load\nSELECT v, COUNT(*) FROM staging.Users GROUP BY v HAVING COUNT(*) > 1;","alternatives":"If NULLs keep colliding, rebuild the index as filtered (WHERE Col IS NOT NULL) so any number of rows may hold NULL while non-NULL values stay unique. If both values are legitimate, the index may be stricter than the business rule and dropping or widening it is the honest fix.","details":[],"details_title":null,"repro":"CREATE TABLE #u (v int NULL);\nCREATE UNIQUE INDEX ux ON #u (v);\nINSERT INTO #u VALUES (NULL);\nINSERT INTO #u VALUES (NULL);  -- Msg 2601: The duplicate key value is (<NULL>).\nDROP TABLE #u;","repro_note":null,"related":["sql-server/2627","sql-server/1913","postgresql/23505","mysql/1062","oracle/ora-00001"],"sqlly":"Run the SELECT that feeds your INSERT in SQLly's grid first and sort by the unique column, so the duplicate shows up in the results before the write fails.","faqs":[{"question":"Why can't I insert a second NULL into a unique column?","answer":"In SQL Server a unique index or constraint treats NULL as a value, so only one NULL is allowed. A filtered unique index with WHERE column IS NOT NULL allows any number of NULLs."},{"question":"Why did a second NULL fail the unique index? NULLs are supposed to be unknown.","answer":"In a plain unique index, SQL Server treats NULL as equal to NULL, so only one row may hold it. Create the index as filtered, for example WHERE TaxId IS NOT NULL, when you want many NULLs."},{"question":"How is 2601 different from 2627?","answer":"2627 comes from a PRIMARY KEY or UNIQUE constraint; 2601 comes from a unique index created with CREATE UNIQUE INDEX. The cause is the same and only the message names an index instead of a constraint, but the fix differs: a filter can't be applied to a PRIMARY KEY or UNIQUE constraint, so drop the constraint and create a filtered unique index (CREATE UNIQUE INDEX ... WHERE Col IS NOT NULL)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2601","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/262","corpus":"errors","engine":"sql-server","language":"en","title":"Permission denied in database","description":"You tried a statement that needs a database-level permission you don't have, such as CREATE TABLE, CREATE PROCEDURE or SHOWPLAN.","body":{"code":"262","slug":"262","name":null,"message":"%ls permission denied in database '%.*ls'.","group":"permissions","severity":14,"sql_state":null,"summary":"You tried a statement that needs a database-level permission you don't have, such as CREATE TABLE, CREATE PROCEDURE or SHOWPLAN.","meaning":"Some statements are not about one object but need a permission on the database itself: `CREATE TABLE`, `CREATE VIEW`, `CREATE PROCEDURE`, `SHOWPLAN` and so on. Error 262 names the permission (for example `CREATE TABLE permission denied in database 'SalesDb'`).","causes":["The user can read and write data but was never granted DDL permissions.","Viewing an execution plan without `SHOWPLAN` permission.","Creating an object in a schema you don't own and have no `ALTER` permission on (`CREATE TABLE` also needs `ALTER` on the schema)."],"fix":[{"text":"Grant the database permission and, for creating objects, `ALTER` on the target schema.","sql":"GRANT CREATE TABLE TO app_user;\nGRANT ALTER ON SCHEMA::dbo TO app_user;"},{"text":"For execution plans, grant `SHOWPLAN` and `SELECT` on each table the plan reads; without `SELECT` the plan fails with error 229.","sql":"GRANT SHOWPLAN TO app_user;"},{"text":"For a developer who needs full DDL rights in a dev database, add them to `db_ddladmin`.","sql":"ALTER ROLE db_ddladmin ADD MEMBER dev_user;"}],"diagnostic":"-- Which database-level permissions does this principal hold?\nEXECUTE AS USER = 'app_user';\nSELECT * FROM fn_my_permissions(NULL, 'DATABASE');\nREVERT;\n-- Direct role memberships only (nested roles are not expanded):\nSELECT DP1.name AS role_name, DP2.name AS member_name\nFROM sys.database_role_members DRM\nJOIN sys.database_principals DP1 ON DP1.principal_id = DRM.role_principal_id\nJOIN sys.database_principals DP2 ON DP2.principal_id = DRM.member_principal_id\nWHERE DP2.name = N'app_user';\n-- Who owns the schema the new object would land in? CREATE TABLE also needs ALTER on it:\nSELECT s.name AS schema_name, USER_NAME(s.principal_id) AS owner,\n       ISNULL(MAX(CASE WHEN dp.permission_name = 'ALTER' THEN 1 END), 0) AS has_alter\nFROM sys.schemas s\nLEFT JOIN sys.database_permissions dp ON dp.class = 3 AND dp.major_id = s.schema_id AND dp.grantee_principal_id = USER_ID(N'app_user')\nWHERE s.name = N'dbo'\nGROUP BY s.name, USER_NAME(s.principal_id);","alternatives":"For developers who need schema changes only in dev, db_ddladmin is fine there. In shared or production databases, grant ALTER on one schema rather than broad CREATE rights, so the user can manage objects under dbo_staging but nothing else. Plans without SHOWPLAN: a login with sysadmin always sees plans, but for regular users SHOWPLAN is the only grant and it works without any table permission.","details":[],"details_title":null,"repro":"CREATE LOGIN repro_user WITH PASSWORD = 'Repro!2345';\nCREATE USER repro_user FOR LOGIN repro_user;\nEXECUTE AS USER = 'repro_user';\nCREATE TABLE dbo.t (Id int);  -- Msg 262: CREATE TABLE permission denied in database '...'.\nREVERT;\nDROP USER repro_user;\nDROP LOGIN repro_user;","repro_note":null,"related":["sql-server/229","sql-server/916","mysql/1227","postgresql/42501","oracle/ora-01031"],"sqlly":"SQLly's connection manager keeps separate entries per login, so you can switch to an admin connection and rerun the failing statement; the editor highlights the exact line the error names.","faqs":[{"question":"I granted CREATE TABLE. Why does the CREATE still fail?","answer":"CREATE TABLE also needs ALTER on the target schema. A user whose default schema is dbo cannot create in dbo without it. Either grant ALTER ON SCHEMA::dbo or have the user create in a schema they own. Without the ALTER the error is 2760, not 262."},{"question":"Does CREATE TABLE permission let the user drop or alter tables later?","answer":"No. It only allows creating. Altering or dropping a table requires ALTER on the object or on its schema, or membership in db_ddladmin or db_owner."},{"question":"Why can I not even display an estimated execution plan?","answer":"Estimated plans need SHOWPLAN and SELECT on the tables the query reads; without SELECT the plan fails with error 229. Actual plans need SHOWPLAN plus the permissions to run the query itself. SHOWPLAN is a database-level grant, so it has to exist in each database the user queries."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/262","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2627","corpus":"errors","engine":"sql-server","language":"en","title":"Violation of PRIMARY KEY or UNIQUE KEY","description":"An INSERT or UPDATE would duplicate a value in a PRIMARY KEY or UNIQUE constraint. The message names the constraint, table and duplicate key value.","body":{"code":"2627","slug":"2627","name":null,"message":"Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'. The duplicate key value is %ls.","group":"constraints","severity":14,"sql_state":null,"summary":"An INSERT or UPDATE would duplicate a value in a PRIMARY KEY or UNIQUE constraint. The message names the constraint, table and duplicate key value.","meaning":"Primary key and unique constraints guarantee that no two rows share the same key. When a write would create a duplicate, SQL Server stops the statement with 2627, followed by 3621 (\"The statement has been terminated\"). The message says which kind of constraint (`PRIMARY KEY` or `UNIQUE KEY`), its name, the table, and the duplicate value itself (SQL Server 2022 shows it; older versions were not tested).\n\nError 2601 is the same failure on a unique index that is not a constraint.","causes":["Inserting a row whose key already exists, for example re-running a load.","Inserting explicit values into an identity column with `IDENTITY_INSERT` on, or an identity seed reset below existing values.","A batch insert from a source that itself contains duplicate keys.","Two sessions inserting the same key concurrently: the check-then-insert pattern (`IF NOT EXISTS ... INSERT`) isn't safe without locking hints."],"fix":[{"text":"Find the existing row using the value shown in the message.","sql":"SELECT * FROM dbo.Customers WHERE Email = N'ada@example.com';"},{"text":"Skip rows that already exist when loading.","sql":"INSERT INTO dbo.Customers (Email, Name)\nSELECT s.Email, s.Name\nFROM staging.Customers AS s\nWHERE NOT EXISTS (SELECT 1 FROM dbo.Customers AS c WHERE c.Email = s.Email);"},{"text":"Look for duplicates inside the source before inserting.","sql":"SELECT Email, COUNT(*) FROM staging.Customers GROUP BY Email HAVING COUNT(*) > 1;"},{"text":"For an upsert that is safe under concurrency, update first and insert if nothing was updated, holding a range lock.","sql":"DECLARE @Email nvarchar(200) = N'ada@example.com', @Name nvarchar(100) = N'Ada';\nBEGIN TRANSACTION;\nUPDATE dbo.Customers WITH (UPDLOCK, SERIALIZABLE) SET Name = @Name WHERE Email = @Email;\nIF @@ROWCOUNT = 0\n    INSERT INTO dbo.Customers (Email, Name) VALUES (@Email, @Name);\nCOMMIT;"},{"text":"If an identity column collides, check and reseed it.","sql":"DBCC CHECKIDENT ('dbo.Customers', NORESEED);  -- shows current and max values\nDBCC CHECKIDENT ('dbo.Customers', RESEED);"}],"diagnostic":"-- What does the named constraint enforce, and on which table?\nSELECT kc.name, kc.type_desc, OBJECT_NAME(kc.parent_object_id) AS table_name\nFROM sys.key_constraints AS kc\nWHERE kc.name = N'PK_Customers';\n-- Find duplicate groups in the table (always empty for an enforced PK or UNIQUE column; run it on a source or non-key column)\nSELECT Email, COUNT(*) AS copies\nFROM dbo.Customers\nGROUP BY Email\nHAVING COUNT(*) > 1;\n-- If the key is an identity column, compare the current and max values\nDBCC CHECKIDENT ('dbo.Customers', NORESEED);","alternatives":"You can set IGNORE_DUP_KEY = ON on the index or constraint, which turns the duplicate into a warning and skips the offending row. That is handy for idempotent loads but hides real problems in normal writes, so use it sparingly. Wrapping the insert in TRY/CATCH is another route when you want the batch to survive a duplicate.","details":[],"details_title":null,"repro":"CREATE TABLE #k (id int PRIMARY KEY);\nINSERT INTO #k VALUES (1);\nINSERT INTO #k VALUES (1);  -- Msg 2627 ... The duplicate key value is (1).\nDROP TABLE #k;","repro_note":null,"related":["sql-server/2601","sql-server/547","sql-server/515","postgresql/23505","mysql/1062","oracle/ora-00001","sqlite/sqlite-constraint-primarykey"],"sqlly":"Sort the key column in SQLly's grid and scan for the repeated value the message names; it takes seconds to confirm which row is already holding the key.","faqs":[{"question":"What is the difference between error 2627 and 2601?","answer":"2627 is raised by a PRIMARY KEY or UNIQUE constraint; 2601 by a unique index created with CREATE UNIQUE INDEX. The cause and the fixes are the same."},{"question":"Can I make SQL Server ignore duplicate keys?","answer":"A unique index created WITH (IGNORE_DUP_KEY = ON) discards duplicate rows in an INSERT with a warning instead of failing the statement. Use it deliberately, since it silently drops data."},{"question":"Why did I also see error 3621?","answer":"3621 ('The statement has been terminated') is just the notice that the failing statement was rolled back. 2627 is the actual reason. Nothing extra is wrong."},{"question":"Is IF NOT EXISTS followed by INSERT safe with concurrent writers?","answer":"No. Two sessions can both pass the check and then one hits 2627. Use the UPDLOCK, SERIALIZABLE pattern shown in the fix, or accept the error and retry."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2627","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2628","corpus":"errors","engine":"sql-server","language":"en","title":"Truncated in table, column","description":"A value is too long for its column. Unlike 8152, the message names the table, the column and the start of the value as it was truncated.","body":{"code":"2628","slug":"2628","name":null,"message":"String or binary data would be truncated in table '%.*ls', column '%.*ls'. Truncated value: '%.*ls'.","group":"data","severity":16,"sql_state":null,"summary":"A value is too long for its column. Unlike 8152, the message names the table, the column and the start of the value as it was truncated.","meaning":"Error 2628 is the detailed form of 8152. It tells you exactly which column overflowed and shows the value (itself truncated in the message), so you can find the offending row. It is the default at database compatibility level 150 and later. Below level 150 it is an opt-in through trace flag 460, which shipped in SQL Server 2016 SP2 CU6 and 2017 CU12.","causes":["A value longer than the column's declared length.","Columns mapped in the wrong order in an `INSERT ... SELECT` or import.","A column defined narrower than the data it receives in production."],"fix":[{"text":"Use the column and value from the message to locate the source row.","sql":"SELECT * FROM staging.Customers WHERE Email LIKE N'ada.lovelace.extremely.long%';"},{"text":"Widen the column if the value is valid.","sql":"ALTER TABLE dbo.Customers ALTER COLUMN Email nvarchar(320) NOT NULL;"},{"text":"Or trim deliberately with `LEFT()` where cutting is acceptable.","sql":null}],"diagnostic":"-- The message names the table and column. Check its declared width and find the offending rows.\n-- max_length is in bytes: nvarchar counts 2 per character.\nSELECT c.name, c.max_length, TYPE_NAME(c.user_type_id) AS type_name\nFROM sys.columns AS c\nWHERE c.object_id = OBJECT_ID(N'dbo.Customers') AND c.name = N'Email';\n-- Rows whose source value exceeds the column\nSELECT * FROM staging.Customers WHERE LEN(Email) > 255 ORDER BY LEN(Email) DESC;","alternatives":"If the value in the message is genuinely garbage, reject it upstream with a TRY_CONVERT or length check in the staging query rather than widening the column to fit it. Where shortening is acceptable, LEFT() makes the cut explicit.","details":[],"details_title":null,"repro":"CREATE TABLE #t (code varchar(3));\nINSERT INTO #t VALUES ('ABCD');\n-- Msg 2628: String or binary data would be truncated in table 'tempdb.dbo.#t...', column 'code'. Truncated value: 'ABC'.\nDROP TABLE #t;","repro_note":null,"related":["sql-server/8152","postgresql/22001","mysql/1406","oracle/ora-12899"],"sqlly":"Run a LEN() comparison in SQLly's grid, ORDER BY the length descending, and the offending rows sit at the top of the result set ready to fix.","faqs":[{"question":"Why is the 'Truncated value' in the message itself cut off?","answer":"The message shows only the start of the value, capped at 100 characters (or the column's width when that is smaller), so very long inputs appear shorter than they are. Use the value as a search prefix, for example WHERE Email LIKE N'ada.lovelace%'."},{"question":"Which versions produce 2628 instead of 8152?","answer":"SQL Server 2019 and later, on by default at database compatibility level 150 and above. On earlier versions you can get the same detail with trace flag 460, introduced in 2016 SP2 CU6 and 2017 CU12."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2628","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/266","corpus":"errors","engine":"sql-server","language":"en","title":"Transaction count mismatch after EXECUTE","description":"A stored procedure or batch ended with a different number of open transactions than it started with: a BEGIN TRANSACTION without COMMIT, or a ROLLBACK too many.","body":{"code":"266","slug":"266","name":null,"message":"Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = %ld, current count = %ld.","group":"transactions","severity":16,"sql_state":null,"summary":"A stored procedure or batch ended with a different number of open transactions than it started with: a BEGIN TRANSACTION without COMMIT, or a ROLLBACK too many.","meaning":"SQL Server counts open transactions in `@@TRANCOUNT`. When a stored procedure or RPC call (such as `sp_executesql`) returns, SQL Server compares the count with the value it had on entry. If they differ, it raises 266 to tell you the module left the transaction state unbalanced.\n\nThe error is raised at severity 16 and stops a batch run with sqlcmd -b, and it describes the shape of your transaction code. The work inside the procedure has already run; what happens next depends on whether the caller commits or rolls back the transaction that is still open, or never opened one that was rolled back.","causes":["A procedure runs `BEGIN TRANSACTION` and returns early (an `IF ... RETURN`, or an error path) without `COMMIT` or `ROLLBACK`.","A procedure runs `ROLLBACK TRANSACTION` inside a transaction its caller opened. `ROLLBACK` always rolls back to the outermost transaction and sets `@@TRANCOUNT` to 0, so the caller's count no longer matches.","A client library or tool sends a `BEGIN TRANSACTION` through `sp_executesql` (an RPC call) and expects it to stay open for later statements."],"fix":[{"text":"Check `@@TRANCOUNT` at the start of the procedure and only open (and later commit) a transaction when there isn't one already. Use a savepoint for nested work, so an error rolls back only the procedure's own changes.","sql":"CREATE OR ALTER PROCEDURE dbo.TransferFunds @From int, @To int, @Amount money\nAS\nBEGIN\n    SET NOCOUNT ON;\n    DECLARE @OwnTran bit = CASE WHEN @@TRANCOUNT = 0 THEN 1 ELSE 0 END;\n    IF @OwnTran = 1 BEGIN TRANSACTION;\n    ELSE SAVE TRANSACTION TransferFunds;\n    BEGIN TRY\n        UPDATE dbo.Accounts SET Balance -= @Amount WHERE AccountId = @From;\n        UPDATE dbo.Accounts SET Balance += @Amount WHERE AccountId = @To;\n        IF @OwnTran = 1 COMMIT TRANSACTION;\n    END TRY\n    BEGIN CATCH\n        IF @OwnTran = 1 AND @@TRANCOUNT > 0 ROLLBACK TRANSACTION;\n        ELSE IF XACT_STATE() = 1 ROLLBACK TRANSACTION TransferFunds;\n        THROW;\n    END CATCH\nEND;"},{"text":"Make every exit path balance the transaction. Replace bare `RETURN` statements inside a transaction with a jump to a single exit that commits or rolls back.","sql":null},{"text":"When a tool or driver needs a transaction across several statements, open it with the driver's transaction API or send `BEGIN TRANSACTION` as a plain batch, not as a parameterized `sp_executesql` call.","sql":null},{"text":"If you see 266 together with another error, fix that error first. 266 is often the second message after a failure (for example 1205 or 547) made the procedure roll back.","sql":null}],"diagnostic":"-- Which cause applies? Watch @@TRANCOUNT at each step of the module.\n-- Add this temporarily at the entry, before every RETURN, and at the exit:\nPRINT CONCAT('trancount entering: ', @@TRANCOUNT);\n-- inside, after BEGIN TRANSACTION:\nPRINT CONCAT('trancount after BEGIN: ', @@TRANCOUNT);\n-- at every exit path:\nPRINT CONCAT('trancount leaving: ', @@TRANCOUNT);\n\n-- If the count drops to 0 somewhere in the middle, something ran ROLLBACK.\n-- Find ROLLBACK and COMMIT statements in the failing module:\nSELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name, OBJECT_NAME(object_id) AS proc_name, definition\nFROM sys.sql_modules\nWHERE definition LIKE N'%ROLLBACK%' AND OBJECT_NAME(object_id) = N'YourProc';\n\n-- Check whether XACT_ABORT is set in the current session (16384 = on):\nSELECT (@@OPTIONS & 16384) AS xact_abort_on;","alternatives":"Some teams wrap every procedure body in a standard pattern that records the entry @@TRANCOUNT and only manages a transaction it opened itself. Another option is to move transaction control up to the caller and keep procedures transaction-free, which makes this error impossible at the cost of coarser transaction boundaries.","details":[],"details_title":null,"repro":"-- Run on a scratch database.\nCREATE OR ALTER PROCEDURE dbo.LeavesTranOpen AS BEGIN TRANSACTION;\nGO\nEXEC dbo.LeavesTranOpen;   -- Msg 266: Previous count = 0, current count = 1\nSELECT @@TRANCOUNT;        -- 1: the transaction is still open\nROLLBACK;\nDROP PROCEDURE dbo.LeavesTranOpen;","repro_note":null,"related":["sql-server/3902","sql-server/3903","sql-server/3930","sql-server/1205","sql-server/3609"],"sqlly":"SQLly sends your script to SQL Server as plain batches split on `GO`, not wrapped in `sp_executesql`, so a `BEGIN TRANSACTION` you run yourself doesn't trip 266 the way it does in tools that send every query as an RPC call. Its own transaction statements for grid editing also go as plain batches.\n\nIn the default auto-commit mode, if a run leaves a transaction open SQLly rolls it back before reusing the connection and says so in the Messages tab, so no stray transaction keeps holding locks. Switch the tab to manual commit when you want the transaction kept open; the status bar shows how many changes are pending.","faqs":[{"question":"Does error 266 roll back my changes?","answer":"No. 266 itself does not roll anything back. The changes made inside the procedure are still part of whatever transaction is open; they are kept if the caller commits and undone if it rolls back. Check `@@TRANCOUNT` right after the call."},{"question":"Why do I get 266 from my application but not in SSMS?","answer":"Many drivers send parameterized statements through `sp_executesql`, which is an RPC call that SQL Server checks for a balanced transaction count. SSMS sends your text as a plain batch, so a `BEGIN TRANSACTION` there simply stays open."},{"question":"The procedure raised 266 but my data changed anyway. Was anything committed?","answer":"The statements in the procedure ran and were written to the log, but whether they survive depends on what happens to the still-open transaction. If the caller does not wrap the call in TRY/CATCH and later commits, they persist. If the call is inside TRY/CATCH, the transaction is uncommittable and a COMMIT fails with 3930; if the session rolls back or dies, they don't. SQL Server cannot tell you after the fact; check @@TRANCOUNT while the connection is still open."},{"question":"Why did my trigger start raising 266 when I only added a TRY/CATCH?","answer":"CATCH blocks often run ROLLBACK, and inside a trigger a ROLLBACK cancels the whole batch with error 3609 ('The transaction ended in the trigger. The batch has been aborted.') and zeroes @@TRANCOUNT. This is 3609, not 266. In triggers, prefer THROW from the CATCH block over ROLLBACK, or check @@TRANCOUNT before rolling back."},{"question":"Does the transaction count mismatch roll anything back?","answer":"Error 266 by itself rolls nothing back. It only reports the imbalance. However, if the module ran ROLLBACK, everything back to the outermost transaction is already undone, the next statement that tries to COMMIT reports 3902 (no corresponding BEGIN TRANSACTION); 3930 appears only when a write runs in a transaction that can no longer be committed."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/266","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2705","corpus":"errors","engine":"sql-server","language":"en","title":"Column names must be unique","description":"A CREATE TABLE, ALTER TABLE ADD or SELECT INTO would create two columns with the same name in one table.","body":{"code":"2705","slug":"2705","name":null,"message":"Column names in each table must be unique. Column name '%.*ls' in table '%.*ls' is specified more than once.","group":"objects","severity":16,"sql_state":null,"summary":"A CREATE TABLE, ALTER TABLE ADD or SELECT INTO would create two columns with the same name in one table.","meaning":"Within a table every column name must be unique, compared using the database's collation (so on a case-insensitive database `Name` and `NAME` clash). Error 2705 names the duplicate column.","causes":["Adding a column that already exists, for example re-running a migration.","`SELECT ... INTO` from a join where two tables have a column of the same name, such as `Id`.","Two expressions given the same alias in a `SELECT INTO`."],"fix":[{"text":"Guard `ALTER TABLE ... ADD` in migrations.","sql":"IF COL_LENGTH(N'dbo.Orders', N'ShippedAt') IS NULL\n    ALTER TABLE dbo.Orders ADD ShippedAt datetime2 NULL;"},{"text":"Alias clashing columns in `SELECT INTO`.","sql":"SELECT o.Id AS OrderId, c.Id AS CustomerId\nINTO #orders\nFROM dbo.Orders AS o JOIN dbo.Customers AS c ON c.Id = o.CustomerId;"}],"diagnostic":"-- Does the column already exist, and under which collation rules?\nSELECT c.name, c.column_id, TYPE_NAME(c.user_type_id) AS type_name\nFROM sys.columns AS c\nWHERE c.object_id = OBJECT_ID(N'dbo.Shipments');\n-- On a case-insensitive collation, Name and NAME collide even though\n-- they look different. Check the database collation if the two spellings\n-- seem distinct:\nSELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS db_collation;","alternatives":"In idempotent migration scripts, guard the ADD with IF COL_LENGTH(N'dbo.Shipments', N'TrackingNumber') IS NULL. In SELECT INTO, alias every column explicitly so names from joined tables cannot collide. If a previous run already added the column, skip the ADD with the IF COL_LENGTH guard above; drop the existing column only when its definition has to change, because a failed ALTER leaves no second copy behind.","details":[],"details_title":null,"repro":"-- Scratch DB repro: re-running an ADD COLUMN migration\nCREATE TABLE dbo.Shipments (Id int NOT NULL PRIMARY KEY);\nGO\nALTER TABLE dbo.Shipments ADD TrackingNumber nvarchar(40) NULL;\nGO\n-- Running the same ALTER again raises 2705: column already exists\nALTER TABLE dbo.Shipments ADD TrackingNumber nvarchar(40) NULL;\nGO\nDROP TABLE dbo.Shipments;","repro_note":null,"related":["sql-server/2714","mysql/1060"],"sqlly":"Run the inner SELECT in SQLly's grid first: the result header shows the exact column names SELECT INTO would create, duplicates and all, before anything is written.","faqs":[{"question":"Why does SELECT INTO give me columns like OrderId and Id_1?","answer":"SELECT INTO from a query that produces two columns with the same name raises 2705; it never renames a duplicate for you. Names like Id_1 that appear after an import were invented by the import tool, not by SELECT INTO. The reliable fix is to alias every selected column yourself so each output name is deliberate."},{"question":"Are 'Name' and 'NAME' the same column name?","answer":"It depends on the database collation. On the default case-insensitive collations SQL Server uses, they collide. On a case-sensitive collation they are distinct names. The comparison follows the database collation, not the server or column collation."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2705","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2714","corpus":"errors","engine":"sql-server","language":"en","title":"There is already an object named","description":"CREATE TABLE, VIEW, PROCEDURE or a constraint uses a name that already exists in the schema. Object and constraint names share one namespace.","body":{"code":"2714","slug":"2714","name":null,"message":"There is already an object named '%.*ls' in the database.","group":"objects","severity":16,"sql_state":null,"summary":"CREATE TABLE, VIEW, PROCEDURE or a constraint uses a name that already exists in the schema. Object and constraint names share one namespace.","meaning":"Within a schema, tables, views, procedures, functions and constraints (primary keys, foreign keys, defaults, checks) all share one namespace. Creating a table, view, procedure, function or constraint whose name is already taken fails with 2714. Index names are scoped to their table and fail with 1913 instead. Temp tables raise it too when a `#temp` of that name already exists in the session.","causes":["Running a deployment script twice without a guard.","A constraint name that matches another object, for example two tables each declaring a primary key named `PK_Id`.","`SELECT ... INTO #t` or `CREATE TABLE #t` when `#t` still exists from an earlier run in the same session.","Two `CREATE TABLE #t` statements in the same batch or procedure, even in different `IF` branches."],"fix":[{"text":"Use `CREATE OR ALTER` for views, procedures, functions and triggers (SQL Server 2016 SP1 and later).","sql":"CREATE OR ALTER VIEW dbo.ActiveCustomers AS\nSELECT CustomerId, Name FROM dbo.Customers WHERE IsActive = 1;"},{"text":"Drop first with `DROP ... IF EXISTS` (SQL Server 2016 and later), including for temp tables.","sql":"DROP TABLE IF EXISTS #work;\nSELECT * INTO #work FROM dbo.Orders WHERE 1 = 0;"},{"text":"Find what owns the name.","sql":"SELECT SCHEMA_NAME(schema_id) AS schema_name, name, type_desc, OBJECT_NAME(parent_object_id) AS parent\nFROM sys.objects WHERE name = N'PK_Id';"},{"text":"Give constraints table-specific names, such as `PK_Orders` and `FK_Orders_Customers`.","sql":null}],"diagnostic":"-- What is holding the name, and of what type?\nSELECT s.name AS schema_name, o.name, o.type_desc,\n       CASE WHEN o.parent_object_id <> 0 THEN OBJECT_NAME(o.parent_object_id) END AS parent_object\nFROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id\nWHERE o.name = N'PK_repro_t';\n-- All objects a name collides with across the schema (constraints are listed with their parent table):\nSELECT o.name, o.type_desc, OBJECT_NAME(o.parent_object_id) AS parent\nFROM sys.objects o\nWHERE o.name IN (N'PK_Orders', N'Orders');","alternatives":"CREATE OR ALTER (SQL Server 2016 SP1+) removes the rerun problem for modules, and DROP ... IF EXISTS covers tables and constraints on 2016+. For temp tables, dropping at the end of the procedure with DROP TABLE IF EXISTS makes reruns in the same session safe. Name constraints per table, PK_TableName and FK_Child_Parent, so two tables never compete for one name.","details":[],"details_title":null,"repro":"CREATE TABLE dbo.repro_t (Id int CONSTRAINT PK_repro_t PRIMARY KEY);\nCREATE TABLE dbo.repro_t (Id int);  -- Msg 2714: There is already an object named 'repro_t' in the database.\n-- Constraint names share the namespace too:\nCREATE TABLE dbo.repro_t2 (Id int CONSTRAINT PK_repro_t PRIMARY KEY);  -- Msg 2714 on PK_repro_t\nDROP TABLE dbo.repro_t; DROP TABLE dbo.repro_t2;","repro_note":null,"related":["sql-server/1913","sql-server/15023","postgresql/42P07","mysql/1050","oracle/ora-00955"],"sqlly":"Expand the schema tree under the database and look for the name first; if it is already there, the fix is a new name or a drop, not another CREATE that fails.","faqs":[{"question":"Two different tables each got a primary key named PK_Id. How is that a collision?","answer":"Constraints live in the same per-schema namespace as tables and views, so PK_Id can only exist once even though it belongs to one table each time. Rename them PK_Orders and PK_Customers. The same rule covers defaults and check constraints."},{"question":"My procedure creates #work twice in two IF branches. Why 2714?","answer":"Temp table definitions in a procedure are checked when CREATE PROCEDURE runs, and each branch's CREATE #work registers against the same name. Use one CREATE before the IF, or use distinct table names per branch. Adding DROP TABLE IF EXISTS #work before each create does not avoid the error, because CREATE PROCEDURE itself fails with 2714."},{"question":"Why is there no CREATE OR ALTER for tables?","answer":"Table CREATE OR ALTER was never shipped; it exists for views, procedures, functions and triggers as of SQL Server 2016 SP1. For tables, the idempotent pattern is DROP TABLE IF EXISTS followed by CREATE, or ALTER TABLE for incremental changes, keeping in mind the data-loss implication of the drop."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2714","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2760","corpus":"errors","engine":"sql-server","language":"en","title":"Schema does not exist or no permission","description":"CREATE named a schema that doesn't exist in this database, or that you aren't allowed to use. Create the schema or fix the name.","body":{"code":"2760","slug":"2760","name":null,"message":"The specified schema name \"%.*ls\" either does not exist or you do not have permission to use it.","group":"objects","severity":16,"sql_state":null,"summary":"CREATE named a schema that doesn't exist in this database, or that you aren't allowed to use. Create the schema or fix the name.","meaning":"Creating an object such as `CREATE TABLE sales.Orders` requires the schema `sales` to exist, the CREATE TABLE permission in the database, and `ALTER` permission on the schema. Schema owners and holders of ALTER ANY SCHEMA (such as db_ddladmin) do not need the schema grant. If the schema is missing, or you have CREATE TABLE but no permission on the schema, SQL Server raises 2760. Without CREATE TABLE you get 262 instead.","causes":["The schema hasn't been created in this database yet.","Running the script in the wrong database.","Missing `ALTER` permission on the schema."],"fix":[{"text":"Create the schema if it should exist. `CREATE SCHEMA` must be alone in its batch, or run through `EXEC`.","sql":"IF SCHEMA_ID(N'sales') IS NULL\n    EXEC (N'CREATE SCHEMA sales AUTHORIZATION dbo');"},{"text":"Grant permission to create objects in it.","sql":"GRANT ALTER ON SCHEMA::sales TO app_user;\nGRANT CREATE TABLE TO app_user;"}],"diagnostic":"-- Does the schema exist, and who owns it?\nSELECT s.name AS schema_name, USER_NAME(s.principal_id) AS owner\nFROM sys.schemas s WHERE s.name = N'sales';\n-- Does the current user have ALTER on it? An empty result does not mean CREATE will fail: schema owners and ALTER ANY SCHEMA holders (such as db_ddladmin) can create without a schema grant.\nSELECT dp.permission_name, dp.state_desc\nFROM sys.database_permissions dp\nJOIN sys.schemas s ON s.schema_id = dp.major_id\nWHERE dp.class = 3 AND s.name = N'sales' AND dp.minor_id = 0\n  AND (dp.grantee_principal_id = USER_ID()\n        OR dp.grantee_principal_id IN (SELECT role_principal_id FROM sys.database_role_members WHERE member_principal_id = USER_ID()));","alternatives":"If the schema does not belong in this database, create the object with an explicit CREATE TABLE without the schema prefix so it lands in your default schema, or fully qualify the intended schema after creating it. When several objects share the prefix, CREATE SCHEMA also supports adding the first table and grants inside one batch.","details":[],"details_title":null,"repro":"-- Scratch database, schema 'sales' not created yet\nCREATE TABLE sales.Orders (Id int NOT NULL);\n-- Fails with 2760 when this statement runs, not at compile time. Statements earlier in the same batch still run, and the batch stops here.\nGO\n-- CREATE SCHEMA must be the only statement in its batch:\nCREATE SCHEMA sales AUTHORIZATION dbo;\nGO\nCREATE TABLE sales.Orders (Id int NOT NULL);\n-- Now it works.","repro_note":null,"related":["sql-server/262","sql-server/208","postgresql/3F000"],"sqlly":"SQLly's IntelliSense draws its suggestions from the connected database's schema, so a schema name that doesn't exist stands out while you type the three-part name.","faqs":[{"question":"Why does CREATE SCHEMA have to be the only statement in its batch?","answer":"That is a language rule: CREATE SCHEMA must be the first statement in the batch. Wrap it in EXEC or separate it with GO when scripting."},{"question":"I am db_owner. Why does 2760 still happen?","answer":"Most likely you are connected to the wrong database. Check DB_NAME() first. Sysadmin members map into dbo in every database. A plain login with only db_datareader in another database gets 262 (CREATE TABLE permission denied) when the schema exists there, and 2760 when it does not."},{"question":"Does the schema owner matter?","answer":"Yes. The schema owner can create objects in it without a separate ALTER grant. Everyone else needs ALTER on that schema, plus the CREATE TABLE permission in the database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2760","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/2812","corpus":"errors","engine":"sql-server","language":"en","title":"Could not find stored procedure","description":"The EXEC names a procedure that doesn't exist in the current database or schema, or a string was run as a procedure name by mistake.","body":{"code":"2812","slug":"2812","name":null,"message":"Could not find stored procedure '%.*ls'.","group":"objects","severity":16,"sql_state":null,"summary":"The EXEC names a procedure that doesn't exist in the current database or schema, or a string was run as a procedure name by mistake.","meaning":"`EXEC name` looks the procedure up in the current database, first in your default schema and then in `dbo` (and in `master` for system procedures whose names start with `sp_`). If no procedure has that name, you get 2812.","causes":["The procedure is in another database or schema and the name isn't qualified.","A typo, or the procedure wasn't deployed to this environment.","Running a dynamic SQL string with `EXEC @sql` instead of `EXEC (@sql)`: without parentheses SQL Server treats the whole string as a procedure name."],"fix":[{"text":"Check that the procedure exists and where.","sql":"SELECT SCHEMA_NAME(schema_id) AS schema_name, name\nFROM sys.procedures WHERE name LIKE N'%GetOrders%';"},{"text":"Qualify the call with schema (and database if needed).","sql":"EXEC SalesDb.Sales.GetOrders @CustomerId = 42;"},{"text":"Run dynamic SQL with parentheses, or better with `sp_executesql`.","sql":"DECLARE @sql nvarchar(max) = N'SELECT TOP (5) name FROM sys.objects';\nEXEC (@sql);\nEXEC sys.sp_executesql @sql;"}],"diagnostic":"-- Does the procedure exist, and in which schema and database?\nSELECT DB_NAME() AS current_db, SCHEMA_NAME(schema_id) AS schema_name, name\nFROM sys.procedures WHERE name = N'GetOrders';\n-- Search all databases you can reach (2017+). Generate one SELECT per database:\nDECLARE @sql nvarchar(max) =\n    (SELECT STRING_AGG(\n        CONCAT(N'SELECT ', QUOTENAME(name), N' AS db, o.name FROM ',\n               QUOTENAME(name), N'.sys.procedures o WHERE o.name = N''GetOrders'''),\n        N' UNION ALL ')\n     FROM sys.databases\n     WHERE state_desc = N'ONLINE' AND database_id <> 2 AND HAS_DBACCESS(name) = 1);\nEXEC (@sql);\n-- What name did the failing call actually use? Check the app or the request cache:\nSELECT TOP (5) TEXT AS last_batch_text\nFROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle)\nWHERE r.command LIKE 'EXEC%' OR r.status = 'running';","alternatives":"Qualify procedure calls with schema (dbo.GetOrders), which also skips the two-step name lookup and helps plan caching. For dynamic SQL, prefer sys.sp_executesql over bare EXEC: it takes parameters, and it always reads its first argument as Transact-SQL batch text, so the string is never treated as a procedure variable name. A bare procedure name inside that string still runs as an implicit EXEC and fails with the same 2812.","details":[],"details_title":null,"repro":"DECLARE @sql nvarchar(100) = N'SELECT 1';\nEXEC @sql;  -- Msg 2812: Could not find stored procedure 'SELECT 1'.","repro_note":null,"related":["sql-server/208","sql-server/8144","sql-server/8145","postgresql/42883","mysql/1305","oracle/ora-06550"],"sqlly":"SQLly's IntelliSense completes object names from the connected database's schema, so the right schema prefix for the procedure is one keystroke away instead of a guess.","faqs":[{"question":"Why does EXEC sp_whatever work from any database?","answer":"Names starting with sp_ also resolve when called from another database, because system procedures appear in the sys schema of every database (Microsoft Learn, Stored Procedures (Database Engine))., so system-style procedures found there always resolve. That behavior is a compatibility legacy and Microsoft advises against the sp_ prefix for your own procedures, because your master copy would shadow a same-named user procedure."},{"question":"EXEC works in one environment and fails in another. What differs?","answer":"Usually deployment. Check sys.procedures in the failing database: the procedure was either never deployed, deployed to another schema, or deployed to a different database than the connection uses. The connection string's Initial Catalog is worth comparing too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/2812","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3013","corpus":"errors","engine":"sql-server","language":"en","title":"BACKUP or RESTORE ended abnormally","description":"A BACKUP or RESTORE failed. 3013 is the closing message; the error printed just before it says why (file access, wrong backup set, space).","body":{"code":"3013","slug":"3013","name":null,"message":"%hs is terminating abnormally.","group":"backup","severity":16,"sql_state":null,"summary":"A BACKUP or RESTORE failed. 3013 is the closing message; the error printed just before it says why (file access, wrong backup set, space).","meaning":"SQL Server ends every failed backup or restore with 3013 (`BACKUP DATABASE is terminating abnormally`, `RESTORE DATABASE is terminating abnormally`, or `VERIFY DATABASE is terminating abnormally` for `RESTORE VERIFYONLY`). It is a summary, not a cause. Look at the message immediately before it, such as 3201 (can't open the backup device), 3154 (backup is of a different database), 5120 (can't open a physical file) or an operating system error.","causes":["The SQL Server service account can't read or write the backup path (error 3201, operating system error 5).","Restoring over an existing database from a backup of a different one without `REPLACE` (error 3154).","Data or log file paths in the backup can't be used on this server and `MOVE` wasn't used. On Windows a missing folder fails. On Linux SQL Server creates a missing folder, so the failure comes from a path it cannot use (for example one under a regular file), reported as 3634 and 3156 before 3013.","Not enough disk space for the backup or the restored files.","A damaged or incomplete backup file, or a backup from a newer SQL Server version than the target."],"fix":[{"text":"Read the error before 3013 and look it up; that is the real problem.","sql":null},{"text":"Verify the backup file and see what's in it.","sql":"RESTORE VERIFYONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';\nRESTORE HEADERONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';\nRESTORE FILELISTONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';"},{"text":"Restore with `MOVE` to paths that exist on this server.","sql":"RESTORE DATABASE SalesDb FROM DISK = N'D:\\Backup\\SalesDb.bak'\nWITH MOVE N'SalesDb' TO N'D:\\Data\\SalesDb.mdf',\n     MOVE N'SalesDb_log' TO N'D:\\Data\\SalesDb_log.ldf',\n     STATS = 10;"},{"text":"Give the SQL Server service account permission on the backup folder, not just your own Windows account.","sql":null}],"diagnostic":"-- The real error is the message before 3013 in the output or error log.\n-- Pull the backup/restore failures from the log:\nEXEC sys.sp_readerrorlog 0, 1, N'3013';\nEXEC sys.sp_readerrorlog 0, 1, N'Error:';\n\n-- Inspect the backup file to rule out a bad or foreign file:\nRESTORE HEADERONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';\nRESTORE VERIFYONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';\n\n-- Version mismatch check: DatabaseVersion in HEADERONLY must not exceed the\n-- server's build. SELECT @@VERSION to compare.","alternatives":"If the backup is from a newer version, restore it on a server at that version or later, or export the data (BACPAC, BCP, SSMS import/export) instead of restoring the file. If the file is damaged, try a copy taken from a different disk or tape.","details":[],"details_title":null,"repro":"-- 3013 always follows a real error, so repro by triggering one.\n-- Repro the 3154 case: restore a different database's backup over an existing db.\nCREATE DATABASE ScratchDb;\nBACKUP DATABASE ScratchDb TO DISK = N'C:\\Temp\\scratch.bak' WITH INIT;\nCREATE DATABASE OtherDb;\nRESTORE DATABASE OtherDb FROM DISK = N'C:\\Temp\\scratch.bak';\n-- Fails with 3154, then 3013 terminates abnormally.\n\n-- Repro the 3201 case: back up to a path that does not exist.\nBACKUP DATABASE ScratchDb TO DISK = N'C:\\No\\Such\\Dir\\x.bak';\n-- Fails with 3201 + operating system error 3, then 3013.\n\nDROP DATABASE ScratchDb; DROP DATABASE OtherDb;","repro_note":null,"related":["sql-server/3201","sql-server/3154","sql-server/5120","sql-server/3101"],"sqlly":"SQLly shows every message of a BACKUP or RESTORE run in order, not just the last one, so the real failure printed above the 3013 wrap-up stays visible.","faqs":[{"question":"Can I fix 3013 directly?","answer":"No. It is a wrapper saying the backup or restore stopped. Fix the error printed before it, and 3013 goes away with it."},{"question":"The message before 3013 is an operating system error. What now?","answer":"On Windows the common ones are 5 (access denied, fix service account permissions on the folder), 2 and 3 (file or path missing on the server), and 112 (not enough disk space). On Linux a missing folder is created, so 2 and 3 are mainly a Windows case. All are environment issues, not database issues."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3013","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3101","corpus":"errors","engine":"sql-server","language":"en","title":"Exclusive access could not be obtained","description":"RESTORE needs the database to itself, but other sessions are connected to it. Put it in single-user mode or close the connections first.","body":{"code":"3101","slug":"3101","name":null,"message":"Exclusive access could not be obtained because the database is in use.","group":"backup","severity":16,"sql_state":null,"summary":"RESTORE needs the database to itself, but other sessions are connected to it. Put it in single-user mode or close the connections first.","meaning":"Restoring over a database replaces it completely, so nobody else may be using it. If another session has the target database as its current database, the restore fails with 3101 (followed by 3013). Your own query window pointed at the target fails with 3102 ('in use by this session') instead, which is also followed by 3013.","causes":["Applications, jobs or other users connected to the database.","Your own connection has the target database as its current database.","Object Explorer or another tool browsing the database."],"fix":[{"text":"Switch your own session away from the database, then disconnect everyone else and restore.","sql":"USE master;\nALTER DATABASE SalesDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nRESTORE DATABASE SalesDb FROM DISK = N'D:\\Backup\\SalesDb.bak' WITH REPLACE;\nALTER DATABASE SalesDb SET MULTI_USER;"},{"text":"See who is connected.","sql":"SELECT session_id, login_name, host_name, program_name\nFROM sys.dm_exec_sessions WHERE database_id = DB_ID(N'SalesDb');"}],"diagnostic":"-- Who has the target as its current database, and from where?\nSELECT session_id, login_name, host_name, program_name, status\nFROM sys.dm_exec_sessions\nWHERE database_id = DB_ID(N'SalesDb');\n\n-- Your own session counts. Check what your window is pointed at:\nSELECT DB_NAME() AS current_database;\n\n-- Object Explorer and IntelliSense hold connections too; a session listed with\n-- program_name like 'Microsoft SQL Server Management Studio' may be just a\n-- browse window, safe to close before restoring.","alternatives":"If you cannot kick users out, restore to a new database name with WITH MOVE for each file and swap names later. Without MOVE the restore fails with 1834 and 3156, because the original database still holds the default file paths. ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE is the standard forced path; ROLLBACK AFTER 30 gives connections a grace period instead.","details":[],"details_title":null,"repro":"-- A session whose current database is the target blocks the restore.\nCREATE DATABASE ScratchDb;\nBACKUP DATABASE ScratchDb TO DISK = N'C:\\Temp\\scratch.bak' WITH INIT;\n\n-- From a second connection:\nUSE ScratchDb;  -- keep this window open\n\n-- From the first connection:\nRESTORE DATABASE ScratchDb FROM DISK = N'C:\\Temp\\scratch.bak';\n-- Msg 3101: Exclusive access could not be obtained because the database is in use.\n\n-- Close the second window, or force it out:\nUSE master;\nALTER DATABASE ScratchDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nRESTORE DATABASE ScratchDb FROM DISK = N'C:\\Temp\\scratch.bak' WITH REPLACE;\nALTER DATABASE ScratchDb SET MULTI_USER;\nDROP DATABASE ScratchDb;","repro_note":null,"related":["sql-server/3702","sql-server/5030","sql-server/3013"],"sqlly":"SQLly's activity monitor lists the sessions connected to a database, so before a RESTORE you can see who has to leave and kill the session from the same view.","faqs":[{"question":"I ran the restore from SSMS and it still says the database is in use. Is it me?","answer":"Probably. Your query window's current database, or an Object Explorer tab expanded on that database, holds a session. If it is your own query window you will see 3102 ('in use by this session') rather than 3101. Run USE master first and close any Object Explorer nodes on the target."},{"question":"Does ROLLBACK IMMEDIATE lose committed data?","answer":"No. It rolls back open transactions only. Committed changes stay. It is abrupt for the users whose work was in flight, which is why the change belongs in a maintenance window."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3101","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3154","corpus":"errors","engine":"sql-server","language":"en","title":"Backup set is of a different database","description":"RESTORE is overwriting an existing database with a backup of a different database. Add WITH REPLACE if that's intended, or restore under a new name.","body":{"code":"3154","slug":"3154","name":null,"message":"The backup set holds a backup of a database other than the existing '%ls' database.","group":"backup","severity":16,"sql_state":null,"summary":"RESTORE is overwriting an existing database with a backup of a different database. Add WITH REPLACE if that's intended, or restore under a new name.","meaning":"As a safety check, SQL Server refuses to restore over an existing database when the backup came from a different database (a different name or database GUID). This protects you from overwriting the wrong database by mistake. Error 3013 follows it.","causes":["Restoring a backup of `SalesDb` over a database called `SalesDb_Test`, or over a database of the same name that was created separately.","Refreshing a test copy from production without `REPLACE`."],"fix":[{"text":"If you really mean to overwrite the target, use `REPLACE`, with `MOVE` so the files don't collide with the source database's files.","sql":"RESTORE DATABASE SalesDb_Test FROM DISK = N'D:\\Backup\\SalesDb.bak'\nWITH REPLACE,\n     MOVE N'SalesDb' TO N'D:\\Data\\SalesDb_Test.mdf',\n     MOVE N'SalesDb_log' TO N'D:\\Data\\SalesDb_Test_log.ldf';"},{"text":"Or restore to a new database name that doesn't exist yet, which needs no `REPLACE`.","sql":null},{"text":"Double-check the target first: `REPLACE` discards everything in it.","sql":null}],"diagnostic":"-- Confirm the mismatch before overriding it: whose backup is this file?\nRESTORE HEADERONLY FROM DISK = N'D:\\Backup\\SalesDb.bak';\n-- DatabaseName identifies the source database. BindingID is its database GUID and FamilyGUID is its family GUID.\n-- Compare with the target:\nSELECT name, database_guid FROM sys.databases WHERE name = N'SalesDb_Test';\n-- Different GUID means this backup never came from the target: the check is\n-- doing its job, and you should decide deliberately whether REPLACE is safe.\n\n-- What exists at the target right now?\nSELECT name, create_date FROM sys.databases WHERE name = N'SalesDb_Test';","alternatives":"Restore to a fresh database name, which avoids the safety check altogether. For a refresh cycle of a test database, scripted restore jobs usually include WITH REPLACE plus MOVE on purpose so the check stops blocking routine work.","details":[],"details_title":null,"repro":"-- Backup one database, try to restore it over another that already exists.\nCREATE DATABASE SrcDb;\nBACKUP DATABASE SrcDb TO DISK = N'C:\\Temp\\src.bak' WITH INIT;\nCREATE DATABASE TargetDb;\n\nRESTORE DATABASE TargetDb FROM DISK = N'C:\\Temp\\src.bak';\n-- Msg 3154: the backup set holds a backup of a database other than the\n-- existing database. Msg 3013 follows.\n\n-- Now confirm WITH REPLACE makes it work:\nRESTORE DATABASE TargetDb FROM DISK = N'C:\\Temp\\src.bak' WITH REPLACE;\n\nDROP DATABASE SrcDb; DROP DATABASE TargetDb;","repro_note":null,"related":["sql-server/3013","sql-server/3101","sql-server/5120"],"sqlly":"Add WITH REPLACE in SQLly's editor and rerun the RESTORE; the Messages tab keeps each step's output in order so you can confirm which backup set went in.","faqs":[{"question":"When is WITH REPLACE the right call?","answer":"When the target is disposable and you intend to overwrite it: test copies refreshed from production, or restoring a renamed copy. Never when the target still holds data you might need; take a backup of it first."},{"question":"The backup is of the same database but it still fails. Why?","answer":"If the target database was recreated rather than restored (new family GUID), SQL Server still treats it as a different database. The family GUID comparison is what matters, not the name. A restored copy keeps its family GUID even though its database GUID changes, so it does not trigger the check."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3154","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3201","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot open backup device","description":"SQL Server couldn't open the backup file or path. The operating system error in the message (2, 3, 5...) tells you if it's missing or access denied.","body":{"code":"3201","slug":"3201","name":null,"message":"Cannot open backup device '%ls'. Operating system error %ls.","group":"backup","severity":16,"sql_state":null,"summary":"SQL Server couldn't open the backup file or path. The operating system error in the message (2, 3, 5...) tells you if it's missing or access denied.","meaning":"Backups and restores are performed by the SQL Server service, not by your client. Error 3201 means the service couldn't open the file, and the message includes the operating system error: 2 (file not found), 3 (path not found) or 5 (access denied) are the common ones.","causes":["Operating system error 5: the SQL Server service account has no permission on the folder or share.","Operating system error 2 or 3: the path or file doesn't exist on the server. A path on your own machine, or a mapped drive letter, isn't visible to the service.","A network share used through a mapped drive instead of a UNC path (`\\\\server\\share\\...`).","On Linux, a path the `mssql` user can't access."],"fix":[{"text":"Find which account SQL Server runs as, then grant it access to the folder.","sql":"SELECT servicename, service_account FROM sys.dm_server_services;"},{"text":"Use a path on the server itself or a UNC path, not a mapped drive.","sql":"BACKUP DATABASE SalesDb TO DISK = N'\\\\fileserver\\sqlbackups\\SalesDb.bak' WITH COMPRESSION;"},{"text":"Check that the folder exists from SQL Server's point of view.","sql":"EXEC master.sys.xp_dirtree N'D:\\Backup', 1, 1;"}],"diagnostic":"-- Which OS error? The message text names it: 2 file not found, 3 path not\n-- found, 5 access denied, 32 in use.\n\n-- Who runs the service, so you know whose permissions matter:\nSELECT servicename, service_account FROM sys.dm_server_services;\n\n-- Does the path exist from the server's side?\nEXEC master.sys.xp_dirtree N'C:\\Temp', 1, 1;\n\n-- Recent backup device errors in the log:\nEXEC sys.sp_readerrorlog 0, 1, N'Cannot open backup device';","alternatives":"For ad-hoc copies off the server, back up to a local path you control, then copy the file with your own credentials. Backup to URL (Azure Blob) avoids file-share and service-account folder permissions, but needs a SQL credential for the storage account.","details":[],"details_title":null,"repro":"-- The service, not your session, opens the file. Back up a real database to a\n-- nonexistent path:\nBACKUP DATABASE model TO DISK = N'C:\\Temp\\no_such_folder\\x.bak';\n-- Msg 3201, Level 16, State 1: Cannot open backup device ...\n-- Operating system error 3 (path not found) on Windows. On Linux the same statement reports 5(Access is denied.).\n-- (tempdb cannot stand in here: BACKUP DATABASE tempdb fails with 3147,\n-- \"Backup and restore operations are not allowed on database tempdb\",\n-- before any device is opened.)\n\n-- Access denied needs a folder the service account cannot write to. Find the\n-- account first:\nSELECT service_account FROM sys.dm_server_services WHERE servicename LIKE 'SQL Server (%';\n-- Create a folder with that account excluded, or deny it, then back up there\n-- to see operating system error 5.","repro_note":null,"related":["sql-server/3013","sql-server/5120"],"sqlly":"Run the BACKUP against the corrected path in SQLly's editor and the operating-system error in the message tells you immediately whether it was the folder, the permissions or the service account.","faqs":[{"question":"The backup works in SSMS on the server but fails from my machine. Why?","answer":"The path is evaluated on the server, so that is not the difference. The difference is usually who invoked it versus which folder: check that the path is identical, and that the service account has rights to it in both cases."},{"question":"Can I back up to a mapped drive letter?","answer":"Not reliably. Mapped drives are per-user logon sessions and the service does not see yours. Use a UNC path, and give the service account access to the share."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3201","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3609","corpus":"errors","engine":"sql-server","language":"en","title":"Transaction ended in the trigger","description":"A trigger ran ROLLBACK (or an error inside it rolled back), which undoes the whole transaction and aborts the rest of the batch.","body":{"code":"3609","slug":"3609","name":null,"message":"The transaction ended in the trigger. The batch has been aborted.","group":"transactions","severity":16,"sql_state":null,"summary":"A trigger ran ROLLBACK (or an error inside it rolled back), which undoes the whole transaction and aborts the rest of the batch.","meaning":"A trigger runs inside the transaction of the statement that fired it. If the trigger issues `ROLLBACK TRANSACTION`, everything in the transaction is undone, including work done before the triggering statement, and SQL Server aborts the batch with 3609. Triggers that validate data often do this on purpose; the 3609 just reports that the batch stopped.","causes":["A trigger that enforces a business rule with `ROLLBACK` when the rule is broken.","An error inside the trigger that, with `XACT_ABORT` (which is on by default inside triggers), rolls back the transaction.","Callers that don't expect a trigger on the table and assume their transaction is still open."],"fix":[{"text":"Read the message the trigger raised just before 3609; it usually explains the rule that was broken.","sql":null},{"text":"Prefer a `CHECK` or foreign key constraint, because a violation leaves the caller's explicit transaction committable. A `THROW` from a trigger makes an explicit transaction uncommittable (`XACT_STATE() = -1`), so the batch's COMMIT fails with Msg 3998.","sql":"CREATE OR ALTER TRIGGER dbo.trg_Orders_NoNegative ON dbo.Orders AFTER INSERT, UPDATE AS\nBEGIN\n    IF EXISTS (SELECT 1 FROM inserted WHERE Quantity < 0)\n        THROW 50001, 'Quantity cannot be negative.', 1;\nEND;"},{"text":"List triggers on a table to find out what's running.","sql":"SELECT name, is_disabled FROM sys.triggers WHERE parent_id = OBJECT_ID(N'dbo.Orders');"}],"diagnostic":"-- Find triggers that can roll back the transaction\nSELECT OBJECT_SCHEMA_NAME(m.object_id) AS schema_name,\n       OBJECT_NAME(m.object_id) AS trigger_name,\n       OBJECT_NAME(t.parent_id) AS on_table\nFROM sys.sql_modules m\nJOIN sys.triggers t ON t.object_id = m.object_id\nWHERE m.definition LIKE '%ROLLBACK%' COLLATE Latin1_General_CI_AI;\n\n-- List the triggers on the table you inserted into\nSELECT t.name AS trigger_name, OBJECT_NAME(t.parent_id) AS on_table\nFROM sys.triggers t WHERE t.parent_id = OBJECT_ID(N'dbo.T');","alternatives":"Enforce rules with constraints such as CHECK, FOREIGN KEY or unique indexes so violations raise an ordinary error the caller can catch, and reserve trigger ROLLBACK for cases constraints cannot express. When a trigger must reject a change, prefer raising an error that does not doom the caller's transaction, such as the constraint violation above. A THROW from a trigger rolls back an explicit transaction and leaves it uncommittable, so the caller cannot choose to commit the rest of its work.","details":[],"details_title":null,"repro":"-- Setup:\nCREATE TABLE dbo.T (id int PRIMARY KEY, v int);\nGO\nCREATE TRIGGER dbo.TR_T_NoNegative ON dbo.T AFTER INSERT AS\nBEGIN\n    IF EXISTS (SELECT 1 FROM inserted WHERE v < 0)\n        ROLLBACK TRANSACTION;\nEND\nGO\n-- Then in one batch (the batch aborts with 3609, and the second statement never runs):\nINSERT INTO dbo.T VALUES (1, 5);   -- fine\nINSERT INTO dbo.T VALUES (2, -1);  -- trigger rolls back: Msg 3609\nPRINT 'reached';                   -- never prints: the batch was aborted","repro_note":null,"related":["sql-server/3616","sql-server/266","sql-server/3902","oracle/ora-04088"],"sqlly":"SQLly shows the trigger's own error and the 3609 follow-up in the Messages tab in order, so the actual cause above the boilerplate is one glance away.","faqs":[{"question":"Did only the triggering statement get undone?","answer":"Only the transaction is undone, not just the triggering statement. If the caller used an explicit `BEGIN TRAN`, that includes statements run before it. In autocommit mode each statement is its own transaction, so earlier statements stay committed."},{"question":"Can I continue the batch after 3609?","answer":"Yes, if the insert runs inside TRY with a CATCH block: the error is caught there, @@TRANCOUNT is 0 after the rollback, and the rest of the batch proceeds. Without a TRY/CATCH the whole batch aborts."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3609","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3616","corpus":"errors","engine":"sql-server","language":"en","title":"Error raised during trigger execution","description":"An error inside a trigger aborted the batch and rolled back the user's transaction. The trigger's own error message comes just before this one.","body":{"code":"3616","slug":"3616","name":null,"message":"An error was raised during trigger execution. The batch has been aborted and the user transaction, if any, has been rolled back.","group":"transactions","severity":16,"sql_state":null,"summary":"An error inside a trigger aborted the batch and rolled back the user's transaction. The trigger's own error message comes just before this one.","meaning":"When an error occurs inside a trigger, SQL Server (with the default `XACT_ABORT` behavior in triggers) aborts the batch and rolls back the whole transaction, including the statement that fired the trigger. Error 3616 reports that, after the trigger's actual error.","causes":["The trigger raised an error on purpose with `THROW` or `RAISERROR` to reject a change.","A bug in the trigger, such as a constraint violation or conversion error in the table it writes to.","A trigger written for one row that fails on multi-row statements."],"fix":[{"text":"Read the error above 3616; it is the one to fix.","sql":null},{"text":"List the triggers on the table and review the one that failed.","sql":"SELECT t.name, OBJECT_DEFINITION(t.object_id) AS definition\nFROM sys.triggers AS t WHERE t.parent_id = OBJECT_ID(N'dbo.Orders');"},{"text":"Make triggers set-based so they work for any number of rows in `inserted` and `deleted`.","sql":null}],"diagnostic":"-- 3616 itself is a follow-up message: the real error is the one printed\n-- immediately before it. To capture that error programmatically, wrap the\n-- statement in TRY/CATCH and log ERROR_NUMBER / ERROR_MESSAGE:\nBEGIN TRY\n    UPDATE dbo.Accounts SET Balance = Balance - 200.00 WHERE AccountId = 1;\nEND TRY\nBEGIN CATCH\n    SELECT ERROR_NUMBER() AS err, ERROR_MESSAGE() AS msg,\n           ERROR_PROCEDURE() AS proc_name, ERROR_LINE() AS line_no;\nEND CATCH;\n-- List the triggers on the table that could have raised it:\nSELECT t.name, t.is_disabled, OBJECT_DEFINITION(t.object_id) AS definition\nFROM sys.triggers AS t\nWHERE t.parent_id = OBJECT_ID(N'dbo.Accounts');","alternatives":"If the trigger's rejection is intended, handle the error in the caller with TRY/CATCH instead of letting the batch abort. If it is a bug, fix the trigger itself, most often its handling of multi-row statements. Some applications also move validation out of the trigger into a CHECK constraint, which produces a clearer error and rolls back only the statement.","details":[],"details_title":null,"repro":"-- Scratch DB repro: an engine error inside the trigger aborts the batch\nCREATE TABLE dbo.Accounts (AccountId int NOT NULL PRIMARY KEY, Balance money NOT NULL);\nINSERT INTO dbo.Accounts VALUES (1, 100.00);\nGO\nCREATE TRIGGER dbo.tr_Accounts_Ratio ON dbo.Accounts\nAFTER UPDATE\nAS\nBEGIN\n    SET NOCOUNT ON;\n    DECLARE @cap money;\n    -- Divide by zero inside the trigger body raises engine error 8134\n    SELECT @cap = SUM(Balance) / 0 FROM inserted;\nEND\nGO\nUPDATE dbo.Accounts SET Balance = Balance - 200.00 WHERE AccountId = 1;\n-- Msg 8134, Level 16: Divide by zero error encountered.\n-- Msg 3616, Level 16: An error was raised during trigger execution. The batch\n-- has been aborted and the user transaction, if any, has been rolled back.\n-- (An explicit THROW in the trigger takes the 3609 path instead: \"The\n-- transaction ended in the trigger. The batch has been aborted.\")\nGO\nSELECT * FROM dbo.Accounts; -- balance unchanged: the update rolled back\nDROP TRIGGER dbo.tr_Accounts_Ratio;\nDROP TABLE dbo.Accounts;","repro_note":null,"related":["sql-server/3609","sql-server/512","oracle/ora-04088"],"sqlly":"SQLly shows the trigger's error and the 3616 follow-up together in the Messages tab, in order, so the real cause above the boilerplate is visible without opening the error log.","faqs":[{"question":"How is 3616 different from 3609?","answer":"3609 (\"The transaction ended in the trigger\") follows when the trigger issues ROLLBACK itself or raises its own error with THROW or RAISERROR. 3616 follows when an engine error inside the trigger body, such as a conversion or divide-by-zero failure, aborts the batch. Either way the real cause is the message printed above the follow-up."},{"question":"Can the caller catch 3616 and continue?","answer":"No. Once an error escapes the trigger, SQL Server has already rolled back the statement and the whole transaction, and the batch is over. Handle the risky statement inside the trigger with TRY/CATCH, or fix the bug in the trigger, so the error never gets that far."},{"question":"Why is data from earlier statements gone too?","answer":"A trigger failure rolls back the entire open transaction, not just the statement that fired it. The transaction was already doomed once the trigger raised an error, and keeping part of it would leave an inconsistent half-state behind."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3616","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3621","corpus":"errors","engine":"sql-server","language":"en","title":"The statement has been terminated","description":"An informational follow-up: the statement before it failed and was rolled back. The real error is the message printed just above 3621.","body":{"code":"3621","slug":"3621","name":null,"message":"The statement has been terminated.","group":"transactions","severity":10,"sql_state":null,"summary":"An informational follow-up: the statement before it failed and was rolled back. The real error is the message printed just above 3621.","meaning":"Error 3621 has severity 10, so it is informational. SQL Server prints it after a statement-level error, such as a constraint violation (2627, 547, 515) or truncation (8152), to say that the failing statement was stopped and its changes undone. This applies with the default SET XACT_ABORT OFF; with SET XACT_ABORT ON, the whole transaction is rolled back instead and 3621 is not printed. Whether the rest of the batch and the surrounding transaction continue depends on the original error and on `XACT_ABORT`.","causes":["Any error that terminates a single statement, most often 2627, 2601, 547, 515, 8152 or 2628."],"fix":[{"text":"Look at the error just before 3621 and fix that one.","sql":null},{"text":"Remember that only the failed statement was undone: earlier statements in an open transaction are still pending until you commit or roll back.","sql":"SELECT @@TRANCOUNT AS open_transactions;"}],"diagnostic":"-- 3621 is a follow-up. Capture the real error above it. This block needs a row with Id 1 already in dbo.R (the repro above creates one); on an empty table the INSERT succeeds and CATCH is never reached. In a TRY...CATCH block the CATCH sees the original error, not 3621:\nBEGIN TRY\n    INSERT INTO dbo.R VALUES (1, 'z');\nEND TRY\nBEGIN CATCH\n    SELECT ERROR_NUMBER() AS real_error, ERROR_MESSAGE() AS msg;\nEND CATCH;\n-- In batch output, read the messages in order: the error before 3621 names the failing statement and reason.\n-- If an open transaction survived, decide its fate:\nSELECT @@TRANCOUNT AS open_transactions;","alternatives":"If you want the batch to keep going past single-row failures, wrap each statement in TRY...CATCH and log ERROR_NUMBER(). The statement still fails and is undone, but the batch keeps going and 3621 is not printed on that path. If you want the whole batch to abort on the first failure, SET XACT_ABORT ON so errors also roll back the transaction instead of leaving it half done.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.R (Id int NOT NULL CONSTRAINT PK_R PRIMARY KEY, V nvarchar(10) NULL);\nINSERT INTO dbo.R VALUES (1, 'x');\nINSERT INTO dbo.R VALUES (1, 'y');  -- 2627 duplicate key, then 3621: The statement has been terminated\nGO\n-- Note the statement was the only thing undone; earlier rows remain:\nSELECT * FROM dbo.R;  -- row 1 from the first insert is still there","repro_note":null,"related":["sql-server/2627","sql-server/547","sql-server/515","sql-server/8152"],"sqlly":"SQLly shows the pair in order in the Messages tab: the real error first, then 3621, so the follow-up never hides which statement was terminated.","faqs":[{"question":"Was the whole transaction rolled back?","answer":"Not with the default SET XACT_ABORT OFF. There, 3621 means only the failing statement was undone, and earlier statements in an open transaction are still pending until you commit or roll back. With SET XACT_ABORT ON, the error rolls back the whole transaction and stops the batch, and SQL Server does not print 3621."},{"question":"Why do I not see 3621 in my client code?","answer":"It is severity 10, an informational message. Many drivers only surface real errors to the exception path; 3621 shows up in message events or in SSMS output. The exception your code sees is the original error."},{"question":"Does 3621 change anything for error handling?","answer":"No. Handle the original error; 3621 is a confirmation that the failed statement left no changes behind."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3621","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3701","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot drop, object not found","description":"A DROP named an object not in the current database, or one you can't drop without ALTER on the schema or CONTROL on the table. Use DROP ... IF EXISTS in scripts.","body":{"code":"3701","slug":"3701","name":null,"message":"Cannot %S_MSG the %S_MSG '%.*ls', because it does not exist or you do not have permission.","group":"objects","severity":11,"sql_state":null,"summary":"A DROP named an object not in the current database, or one you can't drop without ALTER on the schema or CONTROL on the table. Use DROP ... IF EXISTS in scripts.","meaning":"SQL Server raises 3701 when `DROP TABLE`, `DROP VIEW`, `DROP PROCEDURE` and similar statements can't find the object. It deliberately doesn't say whether the object is missing or hidden from you by permissions. The severity is 11 when the name does not exist. When the object exists but you lack permission to drop it, the severity is 14 (State 20, and the message shows the name without its schema). Either way the batch continues after it.","causes":["The object was already dropped, or never created in this environment.","Running in the wrong database or without the schema prefix.","Lacking permission to drop the object. A user with SELECT but not ALTER still gets 3701 for a table they can see."],"fix":[{"text":"Use the `IF EXISTS` form so scripts can be run repeatedly.","sql":"DROP TABLE IF EXISTS dbo.Staging;\nDROP PROCEDURE IF EXISTS dbo.LoadStaging;"},{"text":"On versions before SQL Server 2016, guard with `OBJECT_ID`.","sql":"IF OBJECT_ID(N'dbo.Staging', N'U') IS NOT NULL\n    DROP TABLE dbo.Staging;"},{"text":"Check the current database and the schema-qualified name.","sql":null}],"diagnostic":"-- Is it really gone, or are you in the wrong database / missing permission?\nUSE YourDatabase;\nSELECT OBJECT_ID(N'dbo.Staging', N'U') AS object_id;  -- NULL means not visible to you\n-- Look across all schemas, names can hide in another schema\nSELECT s.name AS schema_name, o.name, o.type_desc\nFROM sys.objects AS o\nJOIN sys.schemas AS s ON s.schema_id = o.schema_id\nWHERE o.name = N'Staging';\n-- Do you have any permission on it? 0 or NULL means you cannot see it\nSELECT HAS_PERMS_BY_NAME(N'dbo.Staging', N'OBJECT', 'SELECT') AS can_select;\nSELECT DB_NAME() AS current_database;","alternatives":"Prefer DROP ... IF EXISTS (SQL Server 2016 and later) in every script so re-runs are harmless. For objects you only want to swap out, sp_rename the old one aside instead of dropping it on the spot.","details":[],"details_title":null,"repro":"-- On a scratch database\nCREATE TABLE dbo.Staging (id int);\nDROP TABLE dbo.Staging;\nDROP TABLE dbo.Staging;  -- Msg 3701: Cannot drop the table 'dbo.Staging', because it does not exist or you do not have permission.","repro_note":null,"related":["sql-server/208","sql-server/15151","sql-server/3726","postgresql/42P01","mysql/1051"],"sqlly":"The schema tree shows what actually exists under the database, so a DROP that failed on a missing or mistyped name can be checked against the tree before you rerun it.","faqs":[{"question":"Why does the message refuse to tell me whether the object exists?","answer":"It is deliberate. If SQL Server confirmed an object exists to users who lack permission on it, that would leak metadata. The same error covers both cases, so check your current database, the schema prefix, and your permissions."},{"question":"Does DROP TABLE IF EXISTS work on older versions?","answer":"No, it was added in SQL Server 2016. On older versions, guard the drop with IF OBJECT_ID(N'dbo.Staging', N'U') IS NOT NULL."},{"question":"The object is in my database. Why do I still get 3701?","answer":"Check which database you are connected to with SELECT DB_NAME(), and whether the object lives in a schema other than dbo. Both are common in shared dev servers."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3701","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3702","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot drop database, currently in use","description":"DROP DATABASE failed because sessions, possibly including your own, are connected to it. Close them or set the database to SINGLE_USER first.","body":{"code":"3702","slug":"3702","name":null,"message":"Cannot drop database \"%.*ls\" because it is currently in use.","group":"objects","severity":16,"sql_state":null,"summary":"DROP DATABASE failed because sessions, possibly including your own, are connected to it. Close them or set the database to SINGLE_USER first.","meaning":"SQL Server won't drop a database while anyone is using it. Your own connection counts if its current database is the one you are dropping.","causes":["Your session ran `USE` on the database, or connected to it directly.","Applications, jobs, replication or other users have open connections."],"fix":[{"text":"Move your own session away, close other connections, then drop.","sql":"USE master;\nALTER DATABASE OldDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nDROP DATABASE OldDb;"},{"text":"Check who is connected before forcing them out.","sql":"SELECT session_id, login_name, program_name FROM sys.dm_exec_sessions WHERE database_id = DB_ID(N'OldDb');"}],"diagnostic":"-- List every session in the database, including yours:\nSELECT session_id, login_name, host_name, program_name, status\nFROM sys.dm_exec_sessions\nWHERE database_id = DB_ID(N'OldDb');\n\n-- Your own window:\nSELECT DB_NAME() AS current_database;\n\n-- Active requests inside those sessions, so you can see who is really doing\n-- work versus just parked:\nSELECT r.session_id, r.status, r.command, t.text\nFROM sys.dm_exec_requests r\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t\nWHERE r.session_id IN (\n    SELECT session_id FROM sys.dm_exec_sessions WHERE database_id = DB_ID(N'OldDb'));","alternatives":"If the database must come down but something keeps reconnecting (a job, a website pool), stop the source first or the connections return and the drop may still succeed but the app floods errors. Replication also holds references; remove replication from the database before dropping it.","details":[],"details_title":null,"repro":"-- Open a second connection, USE the database, then drop it from the first.\nCREATE DATABASE ScratchDb;\n\n-- Connection 2:\nUSE ScratchDb;  -- keep open\n\n-- Connection 1:\nDROP DATABASE ScratchDb;\n-- Msg 3702, Level 16, State 4: Cannot drop database \"ScratchDb\" because it is currently in use.\n-- The DROP waits about 20 seconds for the other session to finish before it fails.\n\n-- Close connection 2, then:\nUSE master;\nDROP DATABASE ScratchDb;","repro_note":null,"related":["sql-server/3101","sql-server/5030","postgresql/55006"],"sqlly":"The activity monitor shows every open session on the instance with its database, including your own connection, which is usually the one quietly holding the database in use.","faqs":[{"question":"Is SET SINGLE_USER WITH ROLLBACK IMMEDIATE safe before a drop?","answer":"It is the standard way. It disconnects everyone and rolls back only their open transactions. Since you are dropping the whole database anyway, nothing in it survives regardless."},{"question":"The drop succeeded but the database came back in the list. Why?","answer":"It did not come back; a dropped database cannot reappear. An open Object Explorer view or a cached connection in a tool is showing a stale entry. Refresh, and check that no monitoring job is recreating a database of the same name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3702","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3726","corpus":"errors","engine":"sql-server","language":"en","title":"Can't drop: referenced by a FOREIGN KEY","description":"DROP TABLE failed because another table's foreign key references it. Drop the referencing constraint (or that table) first.","body":{"code":"3726","slug":"3726","name":null,"message":"Could not drop object '%.*ls' because it is referenced by a FOREIGN KEY constraint.","group":"constraints","severity":16,"sql_state":null,"summary":"DROP TABLE failed because another table's foreign key references it. Drop the referencing constraint (or that table) first.","meaning":"SQL Server won't drop a table that is the parent of a foreign key, because the child table's constraint would point to nothing. The message names the table; the foreign keys that reference it are listed in `sys.foreign_keys`. `TRUNCATE TABLE` on such a table fails too, with error 4712.","causes":["Dropping tables in the wrong order in a teardown script.","Recreating a table during a migration while other tables still reference it."],"fix":[{"text":"Find the foreign keys that reference the table.","sql":"SELECT fk.name, OBJECT_SCHEMA_NAME(fk.parent_object_id) AS child_schema,\n       OBJECT_NAME(fk.parent_object_id) AS child_table\nFROM sys.foreign_keys AS fk\nWHERE fk.referenced_object_id = OBJECT_ID(N'dbo.Customers');"},{"text":"Drop those constraints (or the child tables) first, then the table.","sql":"ALTER TABLE dbo.Orders DROP CONSTRAINT FK_Orders_Customers;\nDROP TABLE dbo.Customers;"},{"text":"In teardown scripts, drop child tables before parents.","sql":null}],"diagnostic":"-- Every foreign key that references the table, including multi-column keys\nSELECT fk.name AS constraint_name,\n       OBJECT_SCHEMA_NAME(fk.parent_object_id) AS child_schema,\n       OBJECT_NAME(fk.parent_object_id) AS child_table,\n       STUFF((SELECT ', ' + c.name\n              FROM sys.foreign_key_columns AS fkc\n              JOIN sys.columns AS c\n                  ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id\n              WHERE fkc.constraint_object_id = fk.object_id\n              ORDER BY fkc.constraint_column_id\n              FOR XML PATH('')), 1, 2, '') AS child_columns\nFROM sys.foreign_keys AS fk\nWHERE fk.referenced_object_id = OBJECT_ID(N'dbo.Customers');\n-- Do the children hold rows? The DROP succeeds either way once the constraint is gone, but those rows are no longer checked against the parent\nSELECT COUNT(*) FROM dbo.Orders;","alternatives":"In teardown scripts, generate the drops from sys.foreign_keys so the order is always right instead of hardcoding it. If you are rebuilding the parent table in a migration, rename the old table aside and point the children at the new one, rather than dropping and recreating under the old name. sp_rename does not rename constraints, so give the new table's primary key and foreign keys names that do not already exist, or CREATE TABLE fails with Msg 2714.","details":[],"details_title":null,"repro":"-- On a scratch database (temp tables support foreign keys)\nCREATE TABLE #parent (id int PRIMARY KEY);\nCREATE TABLE #child (pid int NOT NULL REFERENCES #parent(id));\nDROP TABLE #parent;  -- Msg 3726: Could not drop object '#parent' because it is referenced by a FOREIGN KEY constraint.\nDROP TABLE #child;\nDROP TABLE #parent;","repro_note":null,"related":["sql-server/547","sql-server/3701","mysql/1451","oracle/ora-02449","postgresql/2BP01"],"sqlly":"SQLly's ER diagram draws the referencing foreign keys, so the tables blocking the DROP are visible as edges into the table rather than names in an error message.","faqs":[{"question":"Why does DROP TABLE not drop the referencing foreign keys for me?","answer":"SQL Server refuses rather than guessing. Dropping the parent silently would leave the child constraint pointing at nothing, so you must drop each referencing constraint or table yourself."},{"question":"Can I drop several tables in one statement?","answer":"Yes, DROP TABLE dbo.Orders, dbo.Customers; is valid, but SQL Server does not reorder the names for you. If a named parent comes before its child in the list you still get 3726."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3726","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3902","corpus":"errors","engine":"sql-server","language":"en","title":"COMMIT has no corresponding BEGIN","description":"COMMIT TRANSACTION ran when no transaction was open, usually because an earlier error, trigger or ROLLBACK already ended it.","body":{"code":"3902","slug":"3902","name":null,"message":"The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.","group":"transactions","severity":16,"sql_state":null,"summary":"COMMIT TRANSACTION ran when no transaction was open, usually because an earlier error, trigger or ROLLBACK already ended it.","meaning":"`COMMIT` needs an open transaction (`@@TRANCOUNT` > 0). If the transaction was already rolled back, by an error with `XACT_ABORT` on, a `ROLLBACK` in a nested procedure or trigger, or a deadlock, the `COMMIT` that follows has nothing to commit and raises 3902. The real problem is whatever ended the transaction early.","causes":["A nested procedure or trigger ran `ROLLBACK`, which rolls back to the outermost transaction and sets `@@TRANCOUNT` to 0.","A runtime error with `XACT_ABORT ON`, or a deadlock, rolled the transaction back before reaching `COMMIT`.","Unbalanced code: `COMMIT` in more places than `BEGIN TRANSACTION`, or a `COMMIT` without any `BEGIN` at all."],"fix":[{"text":"Guard the commit and look for the earlier error.","sql":"IF @@TRANCOUNT > 0 COMMIT TRANSACTION;"},{"text":"Use `TRY...CATCH` so an error goes to the `CATCH` block instead of running into the `COMMIT`.","sql":"BEGIN TRY\n    BEGIN TRANSACTION;\n    -- work\n    COMMIT TRANSACTION;\nEND TRY\nBEGIN CATCH\n    IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;\n    THROW;\nEND CATCH;"},{"text":"In nested procedures, roll back to a savepoint instead of the whole transaction (see error 266).","sql":null}],"diagnostic":"-- Check the transaction state right before the COMMIT:\n-- 0 means something already rolled it back\nSELECT @@TRANCOUNT AS trancount, XACT_STATE() AS xact_state;\n\n-- Find triggers that issue ROLLBACK, a classic hidden cause (run in each database; this checks only the current one)\nSELECT OBJECT_SCHEMA_NAME(m.object_id) AS schema_name,\n       OBJECT_NAME(m.object_id) AS trigger_name, OBJECT_NAME(t.parent_id) AS on_table\nFROM sys.sql_modules m\nJOIN sys.triggers t ON t.object_id = m.object_id\nWHERE m.definition LIKE '%ROLLBACK%';\n\n-- What the current batch actually is\nDBCC INPUTBUFFER(@@SPID);","alternatives":"Guard the commit: `IF @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT;` keeps unbalanced code from raising 3902. On a doomed transaction (XACT_STATE() = -1) it skips the COMMIT and leaves the transaction open, so follow it with a ROLLBACK; a plain `IF @@TRANCOUNT > 0 COMMIT;` raises Msg 3930 there. A cleaner fix is one transaction owner per operation, with nested procedures never issuing their own ROLLBACK and only the outermost scope committing.","details":[],"details_title":null,"repro":"COMMIT TRANSACTION;  -- Msg 3902","repro_note":null,"related":["sql-server/3903","sql-server/266","sql-server/3930","sql-server/3609"],"sqlly":"In SQLly's default auto-commit mode each run is a plain batch, so a stray COMMIT fails right in the editor where you can see it, rather than inside a tool that wraps everything in its own transaction.","faqs":[{"question":"I have BEGIN and COMMIT in the same procedure. Why does this still happen?","answer":"Something between them ended the transaction: a trigger or nested procedure rolled back, or a runtime error with XACT_ABORT ON rolled back behind your back. Check @@TRANCOUNT just before the COMMIT and look at the trigger search above."},{"question":"Does a trigger's ROLLBACK undo my whole transaction?","answer":"Yes. ROLLBACK in a trigger rolls back to the outermost transaction and sets @@TRANCOUNT to 0. The trigger also aborts the batch with Msg 3609, so a COMMIT later in that same batch never runs. A COMMIT in a later batch has nothing left to commit and raises 3902."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3902","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3903","corpus":"errors","engine":"sql-server","language":"en","title":"ROLLBACK has no corresponding BEGIN","description":"ROLLBACK TRANSACTION ran when no transaction was open, typically a second rollback after the transaction was already rolled back.","body":{"code":"3903","slug":"3903","name":null,"message":"The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.","group":"transactions","severity":16,"sql_state":null,"summary":"ROLLBACK TRANSACTION ran when no transaction was open, typically a second rollback after the transaction was already rolled back.","meaning":"Like 3902, this means `@@TRANCOUNT` was 0 when `ROLLBACK` ran. The usual reason is that the transaction was already rolled back: by an inner procedure or a trigger, or by an `XACT_ABORT` or deadlock error that ends the batch outside `TRY...CATCH`. Inside `TRY...CATCH`, `XACT_ABORT` and deadlocks leave the transaction open with `XACT_STATE()` = -1, and an unguarded `ROLLBACK` there succeeds. Error handling that always calls `ROLLBACK` without checking hits this.","causes":["A `CATCH` block that calls `ROLLBACK` unconditionally after the transaction was already rolled back.","Both an inner and an outer procedure rolling back.","A `ROLLBACK` with no `BEGIN TRANSACTION` in the batch."],"fix":[{"text":"Only roll back when a transaction is open.","sql":"IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;"},{"text":"Use `XACT_STATE()` in `CATCH` blocks, which also tells you whether the transaction can still be committed.","sql":"IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;"}],"diagnostic":"-- Is there anything to roll back at all?\nSELECT @@TRANCOUNT AS trancount, XACT_STATE() AS xact_state;\n\n-- Find error-handling code that rolls back unconditionally\nSELECT OBJECT_SCHEMA_NAME(m.object_id) AS schema_name,\n       OBJECT_NAME(m.object_id) AS object_name\nFROM sys.sql_modules m\nWHERE m.definition LIKE '%ROLLBACK%'\n  AND (OBJECTPROPERTY(m.object_id, 'IsProcedure') = 1\n    OR OBJECTPROPERTY(m.object_id, 'IsTrigger') = 1);\n\n-- Any transaction still open on this session?\nSELECT * FROM sys.dm_tran_session_transactions WHERE session_id = @@SPID;","alternatives":"Check first: `IF @@TRANCOUNT > 0 ROLLBACK;` makes cleanup code safe to call whether or not a transaction is open. In a CATCH block, follow the standard pattern of testing XACT_STATE() and rolling back only when the transaction still exists.","details":[],"details_title":null,"repro":"ROLLBACK TRANSACTION;  -- Msg 3903","repro_note":null,"related":["sql-server/3902","sql-server/266","sql-server/3930","sql-server/6401"],"sqlly":"SQLly's editor runs scripts as plain batches split on GO, so a ROLLBACK with no transaction open is the honest error it looks like, shown next to the statement that triggered it.","faqs":[{"question":"Why does my CATCH block raise 3903?","answer":"The transaction was already rolled back by a ROLLBACK in a trigger or a nested procedure, and that rollback raised the error that sent you to CATCH (Msg 3609 from a trigger, Msg 266 from an EXEC). Your unconditional ROLLBACK then runs with @@TRANCOUNT at 0. Guard it with IF @@TRANCOUNT > 0. XACT_ABORT ON does not roll the transaction back inside TRY...CATCH; XACT_STATE() is -1 there and the CATCH ROLLBACK succeeds."},{"question":"Is a ROLLBACK with no open transaction harmful?","answer":"With error 3903 the statement fails, so it is never a harmless no-op in T-SQL. Unlike some databases, SQL Server requires an open transaction to roll back."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3903","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3930","corpus":"errors","engine":"sql-server","language":"en","title":"Transaction cannot be committed","description":"An error made the transaction uncommittable (XACT_STATE() = -1). It can only be rolled back; anything that writes to the log fails until you do.","body":{"code":"3930","slug":"3930","name":null,"message":"The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.","group":"transactions","severity":16,"sql_state":null,"summary":"An error made the transaction uncommittable (XACT_STATE() = -1). It can only be rolled back; anything that writes to the log fails until you do.","meaning":"Some errors leave a transaction doomed: it still exists, but SQL Server will not commit it. Inside a `CATCH` block, `XACT_STATE()` returns -1 in this state. Any statement that would write to the transaction log, including `COMMIT` and inserts into a logging table, fails with 3930 until the transaction is rolled back.","causes":["An error inside a `TRY` block while `SET XACT_ABORT ON` is in effect: every runtime error then dooms the transaction.","Errors that doom a transaction even when XACT_ABORT is OFF, such as a deadlock. Inside a trigger XACT_ABORT is ON by default, so a conversion or constraint error there also dooms the transaction.","A `CATCH` block that tries to write an error log row or commit before rolling back."],"fix":[{"text":"In every `CATCH` block, check `XACT_STATE()` and roll back first, then log or rethrow.","sql":"BEGIN CATCH\n    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;\n    INSERT INTO dbo.ErrorLog (Number, Message) VALUES (ERROR_NUMBER(), ERROR_MESSAGE());\n    THROW;\nEND CATCH"},{"text":"If you need to keep part of the work, you can only commit when `XACT_STATE()` is 1; with -1 the only option is a full rollback.","sql":null},{"text":"Find and fix the original error, which `ERROR_NUMBER()` and `ERROR_MESSAGE()` report in the `CATCH` block.","sql":null}],"diagnostic":"-- Inside the CATCH block, this tells you the state you are in:\n-- XACT_STATE() = -1: uncommittable (doomed) transaction, must ROLLBACK\n-- XACT_STATE() =  1: committable\nSELECT XACT_STATE() AS xact_state, @@TRANCOUNT AS trancount,\n       ERROR_NUMBER() AS err, ERROR_MESSAGE() AS msg;\n\n-- Is XACT_ABORT on for this session?\nDBCC USEROPTIONS;  -- look for the row xact_abort with value SET\n\n-- Confirms this session has an open transaction (open_transaction_count = 1); the cause is only in the error messages\nSELECT r.session_id, r.open_transaction_count\nFROM sys.dm_exec_requests r WHERE r.session_id = @@SPID;","alternatives":"Use the standard pattern of checking `XACT_STATE()` at the top of the CATCH block: roll back when it is -1, log afterward, then rethrow. Where you want partial work to survive, set XACT_ABORT OFF, wrap the risky writes in a savepoint (SAVE TRANSACTION name) and ROLLBACK TRANSACTION name on error. A savepoint is not an inner transaction, and once XACT_ABORT has doomed the transaction, rolling back to the savepoint fails with Msg 3931.","details":[],"details_title":null,"repro":"SET XACT_ABORT ON;\nBEGIN TRY\n    BEGIN TRAN;\n    SELECT 1/0;\nEND TRY\nBEGIN CATCH\n    SELECT XACT_STATE();  -- -1\n    COMMIT;               -- Msg 3930\nEND CATCH;\nIF @@TRANCOUNT > 0 ROLLBACK;","repro_note":null,"related":["sql-server/266","sql-server/3902","sql-server/3903","sql-server/1205","postgresql/25P02"],"sqlly":"SQLly reports every message of a run in order in the Messages tab, so the error that doomed the transaction is right above the follow-up, and a ROLLBACK from the editor is one statement away.","faqs":[{"question":"Can I log the error before rolling back?","answer":"Not while the transaction is doomed: even an insert into a log table needs log space, and writes to the log fail with 3930. Capture ERROR_MESSAGE into variables, ROLLBACK, then write the log entry after the rollback."},{"question":"Why did my transaction become doomed without XACT_ABORT?","answer":"A few errors doom the transaction on their own, deadlocks being the common one, and XACT_ABORT is on by default inside triggers. Either way the rule is the same: XACT_STATE() = -1 means commit is refused until you roll back."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3930","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3960","corpus":"errors","engine":"sql-server","language":"en","title":"Snapshot isolation update conflict","description":"Under SNAPSHOT isolation, this transaction tried to change a row another transaction changed after this one started. Retry the transaction.","body":{"code":"3960","slug":"3960","name":null,"message":"Snapshot isolation transaction aborted due to update conflict. You cannot use snapshot isolation to access table '%.*ls' directly or indirectly in database '%.*ls' to update, delete, or insert the row that has been modified or deleted by another transaction. Retry the transaction or change the isolation level for the update/delete statement.","group":"transactions","severity":16,"sql_state":null,"summary":"Under SNAPSHOT isolation, this transaction tried to change a row another transaction changed after this one started. Retry the transaction.","meaning":"A transaction at `SNAPSHOT` isolation reads data as it was when the transaction started. If it then updates or deletes a row that another transaction has modified and committed since then, SQL Server can't apply the change without losing the other update, so it rolls the transaction back with 3960. This is optimistic concurrency working as designed. Read committed snapshot isolation (RCSI) doesn't raise 3960; only the `SNAPSHOT` level does.","causes":["Two `SNAPSHOT` transactions updating the same row concurrently.","A long `SNAPSHOT` transaction that reads, waits, then writes rows that others are actively changing."],"fix":[{"text":"Retry the whole transaction; it will see the newer data the second time.","sql":null},{"text":"Keep snapshot transactions short, especially between the read and the write.","sql":null},{"text":"For hot rows, run the read-modify-write at READ COMMITTED (the default, not SNAPSHOT) and take an update lock when reading, so the second writer waits for the first to commit and then reads the latest value.","sql":"SELECT Balance FROM dbo.Accounts WITH (UPDLOCK) WHERE AccountId = 1;"}],"diagnostic":"-- Is snapshot isolation even allowed, and which sessions use it?\nSELECT name, snapshot_isolation_state_desc FROM sys.databases WHERE database_id = DB_ID();\n\n-- Which transactions are at snapshot level right now\nSELECT st.session_id, tat.transaction_id, tat.name\nFROM sys.dm_tran_active_transactions tat\nJOIN sys.dm_tran_session_transactions st ON st.transaction_id = tat.transaction_id\nWHERE tat.transaction_type = 1;\n\n-- Version store size: long snapshot transactions keep old row versions alive\nSELECT SUM(ranged_column_count + record_count) AS version_store_rows\nFROM sys.dm_tran_version_store;","alternatives":"At READ COMMITTED, take an UPDLOCK when you read rows you intend to modify. The second writer waits for the first to commit and then reads the latest committed value, with no rollback. Under SNAPSHOT the same hint still ends in 3960 after the wait. Read committed snapshot isolation (RCSI) avoids 3960 for general reads; reserve full SNAPSHOT isolation for cases that genuinely need a consistent point-in-time view.","details":[],"details_title":null,"repro":"-- Setup (once):\nALTER DATABASE Scratch SET ALLOW_SNAPSHOT_ISOLATION ON;\nCREATE TABLE dbo.S (id int PRIMARY KEY, v int);\nINSERT INTO dbo.S VALUES (1, 0);\n-- Session 1:\nSET TRANSACTION ISOLATION LEVEL SNAPSHOT;\nBEGIN TRAN;\nSELECT v FROM dbo.S WHERE id = 1;  -- reads 0\n-- Session 2:\nBEGIN TRAN;\nUPDATE dbo.S SET v = 1 WHERE id = 1;\nCOMMIT;\n-- Session 1 again:\nUPDATE dbo.S SET v = 2 WHERE id = 1;  -- Msg 3960, whole transaction rolls back","repro_note":null,"related":["sql-server/1205","postgresql/40001","oracle/ora-08177"],"sqlly":"SQLly's activity monitor shows the other session's open transaction and blocking chain while you retry, so you can tell a one-off snapshot conflict from a persistent writer you keep colliding with.","faqs":[{"question":"Why did my update fail when nobody held a lock?","answer":"Snapshot reads take no locks, so another transaction changed and committed the row while yours was open. When you tried to write it, SQL Server detected the conflict and rolled your transaction back rather than overwrite their change. If the other writer is still open when you write, your statement waits on its lock first and then fails the same way. The fix is to retry and see the newer data."},{"question":"Why does this not happen under read committed snapshot?","answer":"RCSI gives each statement the last committed version but takes locks again for writes within the current read committed transaction, so there is no long-lived point-in-time view to conflict against. 3960 is specific to transactions started with SNAPSHOT isolation."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3960","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/3998","corpus":"errors","engine":"sql-server","language":"en","title":"Uncommittable transaction rolled back","description":"A batch ended while its transaction was in an uncommittable state (XACT_STATE() = -1), so SQL Server rolled the transaction back.","body":{"code":"3998","slug":"3998","name":null,"message":"Uncommittable transaction is detected at the end of the batch. The transaction is rolled back.","group":"transactions","severity":16,"sql_state":null,"summary":"A batch ended while its transaction was in an uncommittable state (XACT_STATE() = -1), so SQL Server rolled the transaction back.","meaning":"If an error dooms a transaction and the batch finishes without the code rolling back, SQL Server rolls it back itself at the end of the batch and reports 3998. Any changes in that transaction are gone. It typically appears after a `CATCH` block that handled an error but didn't roll back.","causes":["A `TRY...CATCH` that swallows an error inside a transaction with `XACT_ABORT ON`, leaving the doomed transaction open.","Errors that doom the transaction regardless of `XACT_ABORT`, handled without a rollback."],"fix":[{"text":"Roll back in every `CATCH` block when `XACT_STATE()` isn't 0.","sql":"BEGIN CATCH\n    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;\n    THROW;\nEND CATCH"},{"text":"Find the original error, which `ERROR_MESSAGE()` reports in the `CATCH` block, and fix it.","sql":null}],"diagnostic":"-- Inside the CATCH block, before any rollback, capture the original error and the transaction state:\nBEGIN CATCH\n    SELECT ERROR_NUMBER() AS err, ERROR_MESSAGE() AS msg,\n           XACT_STATE() AS xact_state, @@TRANCOUNT AS trancount;\n    IF XACT_STATE() = -1 ROLLBACK TRANSACTION;  -- doomed, must roll back\n    ELSE IF XACT_STATE() = 1 ROLLBACK TRANSACTION;  -- roll back here, or COMMIT instead when the work must survive\n    THROW;\nEND CATCH;\n-- XACT_STATE() = -1 is the signature of an uncommittable transaction: no writes and no COMMIT are allowed until it is rolled back.","alternatives":"If the catch block must keep some work, split the transaction: put each fallible statement in its own TRY...CATCH with an explicit rollback and log, rather than one big transaction that gets doomed wholesale. SET XACT_ABORT OFF changes which errors doom a transaction, but leaving it ON plus a rollback in CATCH is the safer combination.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.T (Id int NOT NULL, N int NOT NULL);\nSET XACT_ABORT ON;\nBEGIN TRY\n    BEGIN TRAN;\n    INSERT INTO dbo.T VALUES (1, 10);\n    INSERT INTO dbo.T VALUES (2, NULL);  -- NOT NULL violation dooms the transaction\nEND TRY\nBEGIN CATCH\n    -- BUG: swallowed the error without rolling back\nEND CATCH;\nGO\n-- At the end of the batch SQL Server rolls back and prints 3998.\nSELECT COUNT(*) AS rows_survived FROM dbo.T;  -- 0: the first insert was rolled back too","repro_note":null,"related":["sql-server/3930","sql-server/266","sql-server/3903"],"sqlly":"SQLly shows every message from the failed batch in order in the Messages tab, so the error that put the transaction into the uncommittable state is right above the 3998 follow-up.","faqs":[{"question":"What is the difference between 3998 and error 3930?","answer":"3930 is raised the moment code tries to write to or commit an already-doomed transaction. 3998 comes later, when the batch finishes normally with the doomed transaction still open and SQL Server cleans it up. If the 3930 is not caught, it ends the batch first and the transaction is rolled back without a 3998."},{"question":"Is any of my data saved?","answer":"No. The whole transaction was rolled back, including statements that succeeded before the error."},{"question":"Do I need the rollback if I rethrow?","answer":"Yes, if the batch keeps running. THROW inside CATCH does not roll back an open doomed transaction, so when an outer CATCH handles the rethrown error, the batch ends with the transaction still doomed and you see 3998 unless you roll back. An uncaught THROW ends the batch and the transaction is rolled back without 3998."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/3998","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4060","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot open database requested","description":"The login is valid, but the database named in the connection doesn't exist, is offline or restoring, or the login has no user in it.","body":{"code":"4060","slug":"4060","name":null,"message":"Cannot open database \"%.*ls\" requested by the login. The login failed.","group":"connection","severity":11,"sql_state":null,"summary":"The login is valid, but the database named in the connection doesn't exist, is offline or restoring, or the login has no user in it.","meaning":"SQL Server accepted the login but couldn't open the database the connection asked for (the `Database` or `Initial Catalog` setting). Because the connection can't continue without a database, the login fails as a whole. Error 18456 with state 38 is usually logged alongside it.","causes":["The database name is misspelled, or the connection points to a server where that database doesn't exist. On a case-sensitive server collation the name's case matters.","The database is offline, restoring, in recovery, suspect, or in single-user mode with someone else connected.","The login has no database user mapped in that database, for example after restoring the database onto another server.","In Azure SQL Database, the database was dropped, renamed, or is paused (serverless)."],"fix":[{"text":"Check that the database exists and is online.","sql":"SELECT name, state_desc, user_access_desc FROM sys.databases WHERE name = N'SalesDb';"},{"text":"If it is offline, bring it online.","sql":"ALTER DATABASE SalesDb SET ONLINE;"},{"text":"If the login has no user in the database, create one (or remap an orphaned user).","sql":"USE SalesDb;\nCREATE USER app_user FOR LOGIN app_user;\nALTER ROLE db_datareader ADD MEMBER app_user;"},{"text":"Correct the database name in the connection string, or connect to `master` first to see which databases you can open.","sql":null}],"diagnostic":"-- Is the database there, and in what state?\nSELECT name, state_desc, user_access_desc, is_read_only\nFROM sys.databases WHERE name = N'SalesDb';\n\n-- No row: the name doesn't exist on this server (or its case differs on a\n-- case-sensitive collation). OFFLINE/RESTORING: fix the state. MULTI_USER with\n-- a state_desc of ONLINE points at missing mapping, checked next.\n\n-- Does the login have a user in that database?\nSELECT dp.name AS db_user, dp.sid, sp.name AS server_login\nFROM sys.server_principals sp\nLEFT JOIN sys.database_principals dp ON dp.sid = sp.sid\nWHERE sp.name = N'app_user';\n-- Run this from the target database's context (USE SalesDb first) or the\n-- database_principals side will be empty. A NULL db_user means the login has no\n-- user in this database, or a user with its name is mapped to a different sid\n-- (the join is on sid, so that user also shows as NULL). Compare dp.name with\n-- sp.name to tell those apart.","alternatives":"If the connection only needs any database to start in, drop the database name from the connection string and connect to master, then USE the target database (which will then fail with 916 if mapping is the real problem, a clearer error). For application connection strings, point them at a database that always exists, such as master or tempdb, and handle database selection in code.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: a valid login asking for a database it has no user in.\nUSE master;\nIF DB_ID('scratch_4060') IS NULL CREATE DATABASE scratch_4060;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_4060_login')\n    CREATE LOGIN scratch_4060_login WITH PASSWORD = N'Scratch-4060!', CHECK_POLICY = OFF;\nGO\n-- The login maps to no user in scratch_4060. From a shell:\n--   sqlcmd -S localhost -U scratch_4060_login -P 'Scratch-4060!' -d scratch_4060\n-- fails with 4060, while the same connection without -d succeeds into master.\n-- Cleanup:\nDROP LOGIN scratch_4060_login; DROP DATABASE scratch_4060;","repro_note":null,"related":["sql-server/18456","sql-server/4064","sql-server/916","postgresql/3D000","mysql/1049","mysql/1044"],"sqlly":"The connection form in SQLly's connection manager has the database field right there: fix the name or point the connection at master, then run the connection test again to confirm the login can actually open it.","faqs":[{"question":"What is the difference between 4060 and 4064?","answer":"4060 means the database named in the connection couldn't be opened. 4064 means no database was named and the login's default database couldn't be opened."},{"question":"18456 state 38 keeps appearing in the log next to 4060. Is that separate?","answer":"No, they're the same failure. The 4060 text is sent to the client, followed by error 18456 (\"Login failed for user ...\"), which is the error number most drivers report. State 38 appears only in the server error log and means the database couldn't be opened for this login."},{"question":"Why did this start after failing over to a mirror or availability group secondary?","answer":"The database name exists on both replicas, but the secondary may be unreadable, or the login exists on the primary and was never created on the secondary. Check that logins and users are synced across replicas, not just the database."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4060","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4064","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot open user default database","description":"The connection didn't name a database, and the login's default database is missing, offline or not accessible, so the login fails.","body":{"code":"4064","slug":"4064","name":null,"message":"Cannot open user default database. Login failed.","group":"connection","severity":11,"sql_state":null,"summary":"The connection didn't name a database, and the login's default database is missing, offline or not accessible, so the login fails.","meaning":"Every login has a default database that SQL Server opens when a connection doesn't ask for a specific one. If that database was dropped, is offline, or the login has no user in it, the connection can't start and you get 4064. On SQL Server 2022 our tests of a dropped or offline default showed the client message 4062 (\"Using master database instead\") rather than 4064, so check for both.","causes":["The login's default database was dropped, renamed or detached.","The default database is offline, restoring or in single-user mode.","The login's database user was removed from its default database."],"fix":[{"text":"Connect anyway by naming an available database in the connection, for example `master`. In SSMS that's Options, Connection Properties, Connect to database.","sql":null},{"text":"Point the login's default database at one that exists.","sql":"ALTER LOGIN app_user WITH DEFAULT_DATABASE = master;"},{"text":"Check which default database each login has.","sql":"SELECT name, default_database_name FROM sys.server_principals WHERE type IN ('S', 'U', 'G');"}],"diagnostic":"-- Which database is the login pointed at, and does it exist and run?\nSELECT l.name AS login_name, l.default_database_name,\n       d.state_desc, d.user_access_desc\nFROM sys.server_principals l\nLEFT JOIN sys.databases d ON d.name = l.default_database_name\nWHERE l.name = N'app_user';\n-- A NULL on the sys.databases side means the default database doesn't exist.\n-- OFFLINE or RESTORING means it exists but can't be opened. If the state looks\n-- fine, the login probably has no user in that database (see 916; a named database that the login cannot use reports 4061).","alternatives":"When you're locked out, connect naming a database that always exists (master or tempdb) and fix the login afterwards. For service accounts whose jobs must never depend on a default database, some teams set DEFAULT_DATABASE to master on purpose so a dropped application database can't break logins.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: a login whose default database is dropped after the login exists.\nUSE master;\nIF DB_ID('scratch_4064_db') IS NULL CREATE DATABASE scratch_4064_db;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_4064_login')\n    CREATE LOGIN scratch_4064_login WITH PASSWORD = N'Scratch-4064!', CHECK_POLICY = OFF,\n        DEFAULT_DATABASE = scratch_4064_db;\nGO\nDROP DATABASE scratch_4064_db;\nGO\n-- From a shell, with no -d flag (so the default database is used):\n--   sqlcmd -S localhost -U scratch_4064_login -P 'Scratch-4064!'\n-- On SQL Server 2022 this attempt reported message 4062 (\"Cannot open user default database. Using master database instead.\") in our test, not 4064.\n-- Naming an existing database works:\n--   sqlcmd -S localhost -U scratch_4064_login -P 'Scratch-4064!' -d master\n-- Cleanup:\nDROP LOGIN scratch_4064_login;\nDROP DATABASE IF EXISTS scratch_4064_db;","repro_note":null,"related":["sql-server/4060","sql-server/18456","sql-server/916"],"sqlly":"Clear the database field in SQLly's connection manager to get in without naming a default database, then fix the login's default with an ALTER LOGIN from the editor and the original connection works again.","faqs":[{"question":"Can I get in at all when my default database is gone?","answer":"Yes. Name any database you can use in the connection: in sqlcmd use -d master, in SSMS use Options, Connection Properties, Connect to database. Once in, run ALTER LOGIN to set a valid default."},{"question":"Does changing the default database break running sessions?","answer":"No. Existing connections keep working; only new logins are affected. ALTER LOGIN ... WITH DEFAULT_DATABASE takes effect for future connections."},{"question":"Why does my app get 4064 but SSMS connects fine?","answer":"SSMS probably has a specific database selected in its connection properties, while the app relies on the login's default. They are failing on different paths, not because the server behaves differently for each client."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4064","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4104","corpus":"errors","engine":"sql-server","language":"en","title":"Multi-part identifier not bound","description":"A reference like t.Column or Table.Column names a table or alias that isn't in scope at that point of the query, often after aliasing a table.","body":{"code":"4104","slug":"4104","name":null,"message":"The multi-part identifier \"%.*ls\" could not be bound.","group":"objects","severity":16,"sql_state":null,"summary":"A reference like t.Column or Table.Column names a table or alias that isn't in scope at that point of the query, often after aliasing a table.","meaning":"A multi-part identifier is a column reference with a prefix, such as `o.OrderId` or `dbo.Orders.OrderId`. SQL Server raises 4104 when the prefix doesn't match any table name or alias visible in that part of the query.","causes":["The table was given an alias, but the query still uses the full table name (`FROM dbo.Orders o ... WHERE Orders.Id = 1`). Once aliased, only the alias works.","A typo in the alias.","Referring to a table from an outer query or another join in a place it isn't visible, for example in an `ON` clause before that table is joined.","In an `UPDATE ... FROM` or `DELETE ... FROM`, using a name that isn't in the `FROM` clause."],"fix":[{"text":"Use the alias consistently once you've defined it.","sql":"SELECT o.OrderId, c.Name\nFROM dbo.Orders AS o\nJOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.OrderDate >= '2025-01-01';"},{"text":"Order joins so each `ON` clause only refers to tables already joined.","sql":"SELECT *\nFROM dbo.A AS a\nJOIN dbo.B AS b ON b.AId = a.Id\nJOIN dbo.C AS c ON c.BId = b.Id;"},{"text":"In `UPDATE ... FROM`, update through the alias.","sql":"UPDATE o SET o.Status = 'shipped'\nFROM dbo.Orders AS o\nJOIN dbo.Shipments AS s ON s.OrderId = o.OrderId;"}],"diagnostic":"-- List the aliases and table names actually in scope for the failing query,\n-- then check every column reference uses one of them.\n-- In a stored procedure, extract the query text to read it directly:\nSELECT OBJECT_NAME(object_id) AS proc_name\nFROM sys.sql_modules WHERE definition LIKE N'%Orders.OrderId%';\n-- Which queries reference the old table name after an alias was introduced?\nSELECT OBJECT_SCHEMA_NAME(m.object_id) AS schema_name, OBJECT_NAME(m.object_id) AS name, o.type_desc\nFROM sys.sql_modules AS m\nJOIN sys.objects AS o ON o.object_id = m.object_id\nWHERE m.definition LIKE N'%WHERE Orders.%' OR m.definition LIKE N'%SELECT Orders.%';","alternatives":"Give every table an alias from the start and write all column references through it. When a join order makes an ON clause need a table that comes later, restructure the join or move that condition into the WHERE clause, which is evaluated after all joins.","details":[],"details_title":null,"repro":"SELECT Orders.OrderId FROM (VALUES (1)) AS o(OrderId);  -- Msg 4104","repro_note":null,"related":["sql-server/207","sql-server/208","sql-server/209","postgresql/42P01","mysql/1054"],"sqlly":"SQLly maps the server's message back onto the line in your script and highlights the `t.Column` reference that failed to bind, so a mistyped alias is visible where it happened.","faqs":[{"question":"Does the alias rule apply to the table's own name too?","answer":"Yes. FROM dbo.Orders o means the table is reachable only as o in this query. dbo.Orders.OrderId fails with 4104 because SQL Server treats it as a three-part identifier for a table named Orders that is not in scope, not as the aliased table."},{"question":"Why does this only break in the ON clause and not in WHERE?","answer":"An ON clause runs while its join is being processed, so it can only see tables joined up to that point. WHERE runs after the FROM is complete and sees every table. Moving the condition to WHERE usually resolves it, though for OUTER joins the placement changes the semantics, so restructure carefully."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4104","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4121","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot find column or function","description":"A call like schema.function() couldn't be resolved to a column method or user-defined function: wrong schema, a typo, or a function that isn't deployed.","body":{"code":"4121","slug":"4121","name":null,"message":"Cannot find either column \"%.*ls\" or the user-defined function or aggregate \"%.*ls\", or the name is ambiguous.","group":"objects","severity":16,"sql_state":null,"summary":"A call like schema.function() couldn't be resolved to a column method or user-defined function: wrong schema, a typo, or a function that isn't deployed.","meaning":"SQL Server raises 4121 when an expression of the form `name.something(...)` can't be bound to a column method or a user-defined function or aggregate. Scalar user-defined functions must be called with at least a two-part name such as `dbo.MyFunction()`, and 4121 usually means that two-part name points at the wrong schema or at a function that doesn't exist there.","causes":["The function exists in another schema or database than the one named.","A typo in the function name, or the function wasn't deployed."],"fix":[{"text":"Find the function and its schema.","sql":"SELECT SCHEMA_NAME(schema_id) AS schema_name, name, type_desc\nFROM sys.objects WHERE type IN ('FN', 'IF', 'TF', 'FS', 'FT', 'AF') AND name = N'FormatName';"},{"text":"Call it with the correct schema-qualified name.","sql":"SELECT dbo.FormatName(FirstName, LastName) FROM dbo.People;"}],"diagnostic":"-- Search every schema for the function name\nSELECT SCHEMA_NAME(schema_id) AS schema_name, name, type_desc\nFROM sys.objects\nWHERE type IN ('FN', 'IF', 'TF', 'FS', 'FT', 'AF')\n  AND name LIKE N'%FormatName%';\n-- No rows means it is not in this database at all: wrong database\n-- context or it was never deployed. Rows in another schema mean the\n-- caller used the wrong schema prefix. For scalar UDFs the rule is\n-- strict: schema-qualified two-part name is required.","alternatives":"Call the function with its real two-part name, or deploy it into the schema the callers expect. If the code was written against another database, switch context with USE or use a three-part name. A CLR function also needs its assembly present, so a restored database on a new server can lose the function even though the T-SQL objects moved with it.","details":[],"details_title":null,"repro":"-- Scratch DB repro: function exists in one schema, called under another\nCREATE FUNCTION dbo.FormatName(@First nvarchar(50), @Last nvarchar(50))\nRETURNS nvarchar(101)\nAS\nBEGIN\n    RETURN @First + N' ' + @Last;\nEND\nGO\n-- This raises 4121: there is no FormatName in the sales schema\nSELECT sales.FormatName(N'A', N'B');\nGO\nDROP FUNCTION dbo.FormatName;","repro_note":null,"related":["sql-server/2812","sql-server/208","sql-server/207","postgresql/42883"],"sqlly":"Query sys.objects for the name in SQLly's grid; the type_desc column tells you whether the server has the function at all, and in which schema it actually lives.","faqs":[{"question":"Why can't I call a scalar function without the schema prefix, like a stored procedure?","answer":"Stored procedures fall back to the caller's default schema, but scalar function calls must be schema-qualified. A bare call such as FormatName(...) fails with 195 ('FormatName' is not a recognized built-in function name). A prefix that is not a schema, such as sales.FormatName(...) or FirstName.FormatName(...), is parsed as a column or type method and produces 4121 when nothing matches."},{"question":"The function shows in SSMS but the query still fails. What else should I check?","answer":"Check which database your query window is pointed at; the object browser may be showing a different database than the one your session is in. Then confirm the schema prefix matches, since two schemas can hold functions with the same name."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4121","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4145","corpus":"errors","engine":"sql-server","language":"en","title":"Non-boolean expression in a condition","description":"WHERE, HAVING, IF, WHILE, ON or CASE WHEN got a value instead of a true/false condition, such as WHERE IsActive instead of WHERE IsActive = 1.","body":{"code":"4145","slug":"4145","name":null,"message":"An expression of non-boolean type specified in a context where a condition is expected, near '%.*ls'.","group":"syntax","severity":15,"sql_state":null,"summary":"WHERE, HAVING, IF, WHILE, ON or CASE WHEN got a value instead of a true/false condition, such as WHERE IsActive instead of WHERE IsActive = 1.","meaning":"T-SQL has no boolean column type that can stand alone as a condition. Clauses that need a predicate (`WHERE`, `ON`, `HAVING`, `IF`, `WHILE`, `CASE WHEN`) require a comparison or an expression such as `EXISTS`, `IN` or `LIKE`. A bare column, variable or function result fails with 4145.","causes":["Treating a `bit` column as a boolean: `WHERE IsActive` (valid in MySQL, and in PostgreSQL only for a `boolean` column, not `bit`; T-SQL rejects it).","A bare column or variable on one side of AND or OR with no comparison, such as `WHERE Id = 1 AND IsActive`. A missing operator between two values (`WHERE Id 1`) or a doubled operator (`WHERE Id == 1`) fails with 102 instead.","Calling a scalar function that returns `bit` without comparing its result."],"fix":[{"text":"Compare explicitly.","sql":"SELECT * FROM dbo.Users WHERE IsActive = 1;\nIF dbo.IsWeekend(@d) = 1 PRINT 'weekend';"},{"text":"For dynamic conditions, build the full predicate, not just the column name.","sql":null}],"diagnostic":"-- A compile error leaves nothing in sys.dm_exec_query_stats, so the failing query cannot be looked up there.\n-- The column Msg 8120 names is the first select-list column that is neither grouped nor aggregated.\nSELECT CustomerId, Country, SUM(Total) AS total\nFROM dbo.Orders\nGROUP BY CustomerId;  -- Msg 8120 names Country: selected but not grouped","alternatives":"If the intent was rows where the flag is set, write WHERE flag = 1. If you meant the column must be nonzero, write WHERE col <> 0. In an EXISTS check, spell out SELECT 1 inside the subquery so the predicate is explicit.","details":[],"details_title":null,"repro":"DECLARE @flag bit = 1;\nIF @flag PRINT 'yes';  -- Msg 4145","repro_note":null,"related":["sql-server/102","postgresql/42804","mysql/1064"],"sqlly":"SQLly maps the error to the failing line of your script and shows the full message, so the condition SQL Server refused to treat as true or false is highlighted rather than buried.","faqs":[{"question":"Isn't BIT the SQL Server boolean type?","answer":"It holds 0, 1 and NULL, but T-SQL still requires an explicit comparison in every condition. WHERE bit_col alone fails with 4145."},{"question":"What about a column holding the string 'true'?","answer":"Same thing. There is no implicit conversion from a value to a predicate. Write WHERE status_col = 'true'."},{"question":"Why did this work in MySQL?","answer":"MySQL treats nonzero numbers as true in WHERE. SQL Server does not, so queries written with that habit need an explicit = 1 or <> 0."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4145","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4712","corpus":"errors","engine":"sql-server","language":"en","title":"Can't truncate a referenced table","description":"TRUNCATE TABLE isn't allowed on a table that a foreign key references, even if the child table is empty. Use DELETE or drop the constraint.","body":{"code":"4712","slug":"4712","name":null,"message":"Cannot truncate table '%.*ls' because it is being referenced by a FOREIGN KEY constraint.","group":"constraints","severity":16,"sql_state":null,"summary":"TRUNCATE TABLE isn't allowed on a table that a foreign key references, even if the child table is empty. Use DELETE or drop the constraint.","meaning":"`TRUNCATE TABLE` deallocates pages instead of deleting rows one by one. Microsoft documents that it can't be used on a table referenced by a FOREIGN KEY constraint, and the refusal happens whether or not child rows exist.","causes":["Truncating a parent table such as `Customers` that `Orders` references.","A reset script that truncates tables to reload test data."],"fix":[{"text":"Use `DELETE` instead (logged row by row, slower on big tables).","sql":"DELETE FROM dbo.Orders;\nDELETE FROM dbo.Customers;"},{"text":"Or drop the foreign keys, truncate, and recreate them.","sql":"ALTER TABLE dbo.Orders DROP CONSTRAINT FK_Orders_Customers;\nTRUNCATE TABLE dbo.Orders;\nTRUNCATE TABLE dbo.Customers;\nALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Customers\n    FOREIGN KEY (CustomerId) REFERENCES dbo.Customers (CustomerId);"}],"diagnostic":"-- Which foreign keys reference this table?\nSELECT fk.name AS foreign_key, OBJECT_SCHEMA_NAME(fk.parent_object_id) + N'.' + OBJECT_NAME(fk.parent_object_id) AS child_table\nFROM sys.foreign_keys fk\nWHERE fk.referenced_object_id = OBJECT_ID(N'dbo.Parent');","alternatives":"TRUNCATE the child tables first and the parent still refuses because the constraint object itself, not the child rows, is what TRUNCATE checks. So the real alternatives are DELETE (keep constraints in place), or drop and recreate the keys around the TRUNCATE. For huge tables where DELETE is too slow, the drop-truncate-recreate pattern in the fix is standard; script the keys first with the SSMS scripting wizard or sys.foreign_keys.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.Parent (Id int NOT NULL CONSTRAINT PK_Parent PRIMARY KEY);\nCREATE TABLE dbo.Child (Id int NOT NULL CONSTRAINT PK_Child PRIMARY KEY, ParentId int NULL,\n    CONSTRAINT FK_Child_Parent FOREIGN KEY (ParentId) REFERENCES dbo.Parent(Id));\nINSERT INTO dbo.Parent VALUES (1);\n-- Even with zero child rows this fails with 4712:\nTRUNCATE TABLE dbo.Parent;\nDELETE FROM dbo.Child;\nDELETE FROM dbo.Parent;\n-- DELETE works where TRUNCATE failed.","repro_note":null,"related":["sql-server/3726","sql-server/547","mysql/1701","oracle/ora-02266"],"sqlly":"SQLly's ER diagram shows the foreign keys into the table, so the child table that forces the DELETE route is visible before you rewrite the statement.","faqs":[{"question":"Does the foreign key have to be disabled instead of dropped?","answer":"No. Disabling with NOCHECK does not help; TRUNCATE still refuses while the constraint exists. You must actually drop it."},{"question":"Does TRUNCATE reset identity values?","answer":"Yes, TRUNCATE reseeds identity columns, DELETE does not. Factor that in when switching between them."},{"question":"Why is TRUNCATE faster than DELETE?","answer":"It deallocates whole pages with minimal logging instead of touching every row. That speed comes with a limitation: Microsoft documents that TRUNCATE TABLE can't be used on tables referenced by a FOREIGN KEY constraint."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4712","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/4922","corpus":"errors","engine":"sql-server","language":"en","title":"Objects access this column","description":"ALTER TABLE DROP COLUMN or ALTER COLUMN failed because other objects use the column. The 5074 messages before it list them.","body":{"code":"4922","slug":"4922","name":null,"message":"%ls %.*ls failed because one or more objects access this %S_MSG.","group":"objects","severity":16,"sql_state":null,"summary":"ALTER TABLE DROP COLUMN or ALTER COLUMN failed because other objects use the column. The 5074 messages before it list them.","meaning":"Error 4922 is the closing message of a failed `ALTER TABLE ... DROP COLUMN` or `ALTER COLUMN` when dependencies exist. Each dependent object is reported first with error 5074. Remove or change those objects and run the `ALTER TABLE` again.","causes":["Default constraints, indexes, user-created statistics, foreign keys or check constraints that use the column.","Schema-bound views or functions referencing the column."],"fix":[{"text":"Read the 5074 messages to see each dependent object, drop or alter them, then repeat the `ALTER TABLE`.","sql":null},{"text":"List objects that reference the column, including views, functions and check constraints.","sql":"SELECT OBJECT_NAME(referencing_id) AS referencing_object\nFROM sys.sql_expression_dependencies WHERE referenced_id = OBJECT_ID(N'dbo.Orders');"}],"diagnostic":"-- List every constraint, index and statistic built on the column.\nSELECT c.name AS constraint_or_index, c.type_desc, c.is_disabled\nFROM sys.index_columns ic\nJOIN sys.indexes c ON c.object_id = ic.object_id AND c.index_id = ic.index_id\nWHERE ic.object_id = OBJECT_ID(N'dbo.Cust')\nUNION ALL\nSELECT dc.name, 'DEFAULT_CONSTRAINT', 0\nFROM sys.default_constraints dc\nWHERE dc.parent_object_id = OBJECT_ID(N'dbo.Cust') AND dc.parent_column_id = COLUMNPROPERTY(dc.parent_object_id, N'Email', 'ColumnId')\nUNION ALL\nSELECT fk.name, 'FOREIGN_KEY', fk.is_disabled\nFROM sys.foreign_keys fk\nJOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id\nWHERE fkc.parent_object_id = OBJECT_ID(N'dbo.Cust') AND fkc.parent_column_id = COLUMNPROPERTY(fkc.parent_object_id, N'Email', 'ColumnId');\n-- Schema-bound views and functions:\nSELECT OBJECT_NAME(referencing_id) AS referencing_object\nFROM sys.sql_expression_dependencies\nWHERE referenced_id = OBJECT_ID(N'dbo.Cust');","alternatives":"If you only need the column out of the way, create a new table without it, copy the rows, then use sp_rename to swap the names. The old table's indexes, defaults and statistics go with it, so recreate each one on the new table. A foreign key from another table to the old table blocks the DROP TABLE with 3726, so drop that foreign key first.","details":[],"details_title":null,"repro":"-- Scratch database\nCREATE TABLE dbo.Cust (Id int NOT NULL CONSTRAINT PK_Cust PRIMARY KEY, Email nvarchar(200) NOT NULL);\nCREATE INDEX IX_Cust_Email ON dbo.Cust(Email);\nALTER TABLE dbo.Cust ADD CONSTRAINT DF_Cust_Email DEFAULT ('') FOR Email;\nGO\n-- Both an index and a default constraint use the column, so this fails:\nALTER TABLE dbo.Cust DROP COLUMN Email;\n-- Messages: 5074 per dependent object, then 4922.","repro_note":null,"related":["sql-server/5074","sql-server/3726"],"sqlly":"SQLly's grid turns the dependency hunt into one query: sys.sql_expression_dependencies filtered on the column's object lists the views and procedures that still reference it.","faqs":[{"question":"Does DROP COLUMN drop the default constraint automatically?","answer":"No. Any default constraint on the column blocks the drop, whether it was named, written inline in CREATE TABLE, or added with ALTER TABLE ADD. Drop it first with ALTER TABLE ... DROP CONSTRAINT, then drop the column. A system-named default appears in the 5074 message as DF__<table>__<column>__<hash>, and its name is in sys.default_constraints."},{"question":"Why does ALTER COLUMN fail with 4922 too?","answer":"Only some changes do. Narrowing an indexed column, changing the type of an indexed column, or changing the type of a foreign key column fails with 4922. Widening an indexed, defaulted, checked or statistics column does not fail. When it does fail, drop the dependent objects, change the type, then rebuild them."},{"question":"Can statistics block the drop?","answer":"Yes. Auto-created statistics are dropped with the column, but user-created ones named in the 5074 messages must be dropped yourself."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/4922","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/5030","corpus":"errors","engine":"sql-server","language":"en","title":"Database couldn't be exclusively locked","description":"An ALTER DATABASE operation such as a rename or collation change needs exclusive access, but other sessions are using the database.","body":{"code":"5030","slug":"5030","name":null,"message":"The database %.*ls could not be exclusively locked to perform the operation.","group":"objects","severity":16,"sql_state":null,"summary":"An ALTER DATABASE operation such as a rename or collation change needs exclusive access, but other sessions are using the database.","meaning":"Some database-level changes, such as `ALTER DATABASE ... MODIFY NAME` or changing the database collation, require that no other session is using the database. If one is, SQL Server waits about 20 seconds and then raises 5030.","causes":["Other connections to the database, including your own query window or Object Explorer.","Background tasks or applications that keep connections open."],"fix":[{"text":"Take the database into single-user mode for the change.","sql":"USE master;\nALTER DATABASE SalesDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nALTER DATABASE SalesDb MODIFY NAME = SalesDb2025;\nALTER DATABASE SalesDb2025 SET MULTI_USER;"},{"text":"Schedule the change in a maintenance window, since `ROLLBACK IMMEDIATE` rolls back other users' open transactions and disconnects their sessions.","sql":null}],"diagnostic":"-- Who holds sessions in the database:\nSELECT session_id, login_name, program_name, status\nFROM sys.dm_exec_sessions\nWHERE database_id = DB_ID(N'SalesDb');\n\n-- Any long-running transaction holding locks on it:\nSELECT t.session_id, t.transaction_id, at.name AS tran_name,\n       DATEDIFF(minute, at.transaction_begin_time, SYSDATETIME()) AS tran_age_min\nFROM sys.dm_tran_session_transactions t\nJOIN sys.dm_tran_active_transactions at ON at.transaction_id = t.transaction_id\nWHERE t.session_id IN (\n    SELECT session_id FROM sys.dm_exec_sessions WHERE database_id = DB_ID(N'SalesDb'));\n\n-- Your own current database, since it counts too:\nSELECT DB_NAME();","alternatives":"If the database cannot go single-user, some changes avoid the exclusive lock: adding files and changing the recovery model run fine with other sessions connected. Turning READ_COMMITTED_SNAPSHOT on or off is not one of them. Without a termination clause it waits for other sessions to leave and then succeeds, with no 5030. With WITH ROLLBACK IMMEDIATE it succeeds and disconnects every open connection to the database. A rename has no workaround except single-user mode or doing it in a window when nobody is connected.","details":[],"details_title":null,"repro":"-- Rename a database while another session holds it open.\nCREATE DATABASE ScratchDb;\n\n-- Connection 2:\nUSE ScratchDb;  -- keep open\n\n-- Connection 1:\nALTER DATABASE ScratchDb MODIFY NAME = ScratchDb2;\n-- Msg 5030, Level 16, State 2: The database ScratchDb could not be exclusively locked to perform the operation.\n-- It fails after about 20 seconds of waiting, not immediately.\n\n-- Single-user mode fixes it:\nUSE master;\nALTER DATABASE ScratchDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nALTER DATABASE ScratchDb MODIFY NAME = ScratchDb2;\nALTER DATABASE ScratchDb2 SET MULTI_USER;\nDROP DATABASE ScratchDb2;","repro_note":null,"related":["sql-server/3101","sql-server/3702","sql-server/1222"],"sqlly":"Check SQLly's activity monitor first: it lists the server's sessions with their login, program and current query, and a kill from that view is often faster than hunting spids in a query window.","faqs":[{"question":"What database operations need exclusive access like this?","answer":"Renaming with MODIFY NAME and changing the collation fail with 5030 while another session is connected. Moving to single-user or emergency states also needs the database to be free, but it waits for the other session to leave instead of raising 5030. Routine settings such as compatibility level or auto-grow options do not need it."},{"question":"The alter worked before but fails now. What changed?","answer":"A new connection source: a deployed app pool, a monitoring agent, or an open SSMS window on that database. The session list query names it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/5030","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/5074","corpus":"errors","engine":"sql-server","language":"en","title":"Object is dependent on column","description":"ALTER TABLE couldn't drop a column or change its type because an index, constraint, statistic or computed column depends on it. Drop that object first.","body":{"code":"5074","slug":"5074","name":null,"message":"The %S_MSG '%.*ls' is dependent on %S_MSG '%.*ls'.","group":"objects","severity":16,"sql_state":null,"summary":"ALTER TABLE couldn't drop a column or change its type because an index, constraint, statistic or computed column depends on it. Drop that object first.","meaning":"SQL Server won't drop or alter a column while other objects rely on it. Error 5074 names the dependent object, such as a default constraint, an index or a statistics object. It is usually followed by 4922, which reports that the `ALTER TABLE` failed.","causes":["A default constraint on the column (they are created automatically with system-generated names when you use `DEFAULT`).","An index, unique constraint, foreign key or statistics object that includes the column.","A computed column or a schema-bound view that references it."],"fix":[{"text":"Find default constraints on the column.","sql":"SELECT dc.name FROM sys.default_constraints AS dc\nJOIN sys.columns AS c ON c.object_id = dc.parent_object_id AND c.column_id = dc.parent_column_id\nWHERE dc.parent_object_id = OBJECT_ID(N'dbo.Orders') AND c.name = N'Status';"},{"text":"Drop the dependent object named in the message, then alter the column.","sql":"ALTER TABLE dbo.Orders DROP CONSTRAINT DF__Orders__Status__1A2B3C4D;\nALTER TABLE dbo.Orders DROP COLUMN Status;"},{"text":"Name default constraints explicitly when you create them, so scripts don't depend on generated names.","sql":null}],"diagnostic":"-- Everything that depends on the column, by object type\nDECLARE @t sysname = N'dbo.Orders', @c sysname = N'Status';\nSELECT 'default constraint' AS dep, dc.name\nFROM sys.default_constraints AS dc\nJOIN sys.columns AS c ON c.object_id = dc.parent_object_id AND c.column_id = dc.parent_column_id\nWHERE dc.parent_object_id = OBJECT_ID(@t) AND c.name = @c\nUNION ALL\nSELECT 'index', i.name\nFROM sys.indexes AS i\nJOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id\nJOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id\nWHERE i.object_id = OBJECT_ID(@t) AND c.name = @c\nUNION ALL\nSELECT 'statistics', s.name\nFROM sys.stats AS s\nJOIN sys.stats_columns AS sc ON sc.object_id = s.object_id AND sc.stats_id = s.stats_id\nJOIN sys.columns AS c ON c.object_id = sc.object_id AND c.column_id = sc.column_id\nWHERE s.object_id = OBJECT_ID(@t) AND c.name = @c;\n-- Also check computed columns referencing it:\nSELECT name FROM sys.computed_columns\nWHERE object_id = OBJECT_ID(@t) AND definition LIKE N'%' + @c + N'%';","alternatives":"Drop the named dependent object first, then alter the column, as the fix shows. When the constraint name is system-generated, look it up in sys.default_constraints and build the DROP dynamically. If you only need the column out of new rows rather than gone from history, consider marking it unused in application code and leaving the schema alone, or schedule the drop for a maintenance window since dropping statistics can change query plans.","details":[],"details_title":null,"repro":"-- Scratch DB repro: default constraint blocks DROP COLUMN\nCREATE TABLE dbo.Orders (\n    OrderId int NOT NULL PRIMARY KEY,\n    Status nvarchar(20) NOT NULL DEFAULT N'New'\n);\nGO\n-- Raises 5074: the object 'DF__Orders__Status__xxxx' is dependent on column 'Status'\nALTER TABLE dbo.Orders DROP COLUMN Status;\nGO\nDECLARE @df sysname = (\n    SELECT dc.name FROM sys.default_constraints AS dc\n    WHERE dc.parent_object_id = OBJECT_ID(N'dbo.Orders')\n);\nEXEC(N'ALTER TABLE dbo.Orders DROP CONSTRAINT ' + @df);\nALTER TABLE dbo.Orders DROP COLUMN Status;\nGO\n-- the table stays; only the Status column is removed","repro_note":null,"related":["sql-server/4922","sql-server/3726","postgresql/2BP01"],"sqlly":"Query the table's indexes, constraints and computed columns in SQLly's grid (sys.indexes, sys.default_constraints, sys.computed_columns); the defaults, indexes, statistics and computed columns end up in one result; foreign keys and schema-bound views need a separate check.","faqs":[{"question":"What is the weird name of the constraint in the message?","answer":"When you write DEFAULT in a column definition without naming it, SQL Server generates a name like DF__Orders__Status__1A2B3C4D. The hash suffix varies per table, which is why scripts that hardcode it break across environments. Name constraints explicitly at creation to keep names predictable."},{"question":"I dropped the index but still get 5074. What am I missing?","answer":"Dropping an index also drops the statistics it created, so those never block the column. A statistic you created yourself with CREATE STATISTICS on the column does block it, and the error names it. Auto-created statistics do not block DROP COLUMN. Each failed attempt names one dependent it found, so drop those one at a time. The diagnostic query does not cover foreign keys or schema-bound views; check for those separately."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/5074","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/512","corpus":"errors","engine":"sql-server","language":"en","title":"Subquery returned more than 1 value","description":"A subquery used as a single value (after =, <, > or in SET) returned several rows. Make it return one row, or use IN, EXISTS or a join.","body":{"code":"512","slug":"512","name":null,"message":"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.","group":"data","severity":16,"sql_state":null,"summary":"A subquery used as a single value (after =, <, > or in SET) returned several rows. Make it return one row, or use IN, EXISTS or a join.","meaning":"A subquery in a place that expects one value, such as `WHERE x = (SELECT ...)`, `SET @v = (SELECT ...)` or a column in the select list, must return at most one row. If it returns two or more at run time, SQL Server raises 512. The query may work for months and then fail once the data contains a duplicate.","causes":["The subquery's filter isn't unique, for example looking up a customer by name when two customers share it.","A trigger written for single-row changes that does `SELECT @id = (SELECT id FROM inserted)`, failing on multi-row inserts or updates.","Duplicate rows appearing in a lookup table that was assumed to be unique."],"fix":[{"text":"If any matching row will do, use `IN` or `EXISTS` instead of `=`.","sql":"SELECT * FROM dbo.Orders\nWHERE CustomerId IN (SELECT CustomerId FROM dbo.Customers WHERE Country = 'NL');"},{"text":"If you need exactly one value, say which with `TOP (1)` and `ORDER BY`, or an aggregate.","sql":"SELECT @lastOrder = (SELECT TOP (1) OrderId FROM dbo.Orders WHERE CustomerId = @c ORDER BY OrderDate DESC);"},{"text":"Rewrite triggers to work on the whole `inserted` set with a join.","sql":"UPDATE c SET c.LastOrderAt = i.OrderDate\nFROM dbo.Customers AS c\nJOIN inserted AS i ON i.CustomerId = c.CustomerId;"},{"text":"Find the duplicates that broke the assumption, and add a unique constraint if the column should be unique.","sql":"SELECT Name, COUNT(*) FROM dbo.Customers GROUP BY Name HAVING COUNT(*) > 1;"}],"diagnostic":"-- If the error came from a trigger, list triggers on the table involved and inspect their bodies for scalar subqueries on 'inserted' or 'deleted'.\nSELECT t.name AS trigger_name, OBJECT_NAME(t.parent_id) AS table_name\nFROM sys.triggers t WHERE t.is_disabled = 0;\nEXEC sp_helptext N'dbo.trg_CustomerUpdate';\n-- If it came from a query, replace the failing scalar subquery with a count to see how many rows it actually returns.\nSELECT CustomerId, COUNT(*) FROM dbo.Customers WHERE Name = N'Contoso' GROUP BY CustomerId;\n-- Check whether a lookup assumed unique has duplicates.\nSELECT Name, COUNT(*) FROM dbo.Customers GROUP BY Name HAVING COUNT(*) > 1;","alternatives":"Instead of TOP (1) with an arbitrary ORDER BY, an aggregate like MAX or MIN states the intent better and never fails. If any row will do, EXISTS is usually clearer than IN with a subquery, and SQL Server compiles both to the same semi-join plan, and a JOIN handles the multi-row case without any single-value assumption.","details":[],"details_title":null,"repro":"SELECT (SELECT v FROM (VALUES (1), (2)) AS t(v));  -- Msg 512","repro_note":null,"related":["sql-server/8120","postgresql/21000","mysql/1242","oracle/ora-01427"],"sqlly":"Run the subquery by itself in SQLly's grid and COUNT the rows; the number that comes back is the whole story, and a TOP (1) or an aggregate in the editor fixes it.","faqs":[{"question":"The subquery worked for months. Why did it break today?","answer":"The data changed, not the code. The subquery returns one row for every matching row, and today's insert added a second match, such as a duplicate customer name. That is why 512 often appears only after the data changes."},{"question":"Is TOP (1) without ORDER BY a safe fix?","answer":"No. Without ORDER BY the row chosen is arbitrary and can change between executions. If you use TOP (1), always specify which row you want with ORDER BY, or use an aggregate."},{"question":"Why does my trigger fail only on bulk operations?","answer":"Triggers fire once per statement, not per row. A scalar assignment like SELECT @id = (SELECT ... FROM inserted) works on single-row changes and raises 512 on multi-row ones. Rewrite the trigger to operate on the whole inserted set with a join."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/512","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/5120","corpus":"errors","engine":"sql-server","language":"en","title":"Unable to open the physical file","description":"SQL Server couldn't open a database file (.mdf, .ndf or .ldf), typically because the service account has no permission or the file is in use.","body":{"code":"5120","slug":"5120","name":null,"message":"Unable to open the physical file \"%.*ls\". Operating system error %d: \"%ls\".","group":"backup","severity":16,"sql_state":null,"summary":"SQL Server couldn't open a database file (.mdf, .ndf or .ldf), typically because the service account has no permission or the file is in use.","meaning":"When attaching a database, restoring, or bringing a database online, the SQL Server service opens its data and log files. Error 5120 reports that one couldn't be opened, with the operating system error: On Windows, 5 is access denied, 32 is the file being used by another process, and 2 or 3 means the path doesn't exist. On Linux a missing file or directory reports 2, and a file still held by a live database reports 5.","causes":["Operating system error 5: the SQL Server service account lacks permission on the file, often after copying `.mdf` files from elsewhere.","Operating system error 32 (Windows): another SQL Server instance or process has the file open. On Linux the same situation reports 5.","The path is wrong or the drive isn't available to the service.","Attaching a read-only file or one on removable media."],"fix":[{"text":"Grant the SQL Server service account full control on the files and folder (find the account in `sys.dm_server_services`).","sql":null},{"text":"Make sure no other instance uses the files; detach them there first.","sql":null},{"text":"Attach using the correct paths.","sql":"CREATE DATABASE SalesDb ON\n    (FILENAME = N'D:\\Data\\SalesDb.mdf'),\n    (FILENAME = N'D:\\Data\\SalesDb_log.ldf')\nFOR ATTACH;"}],"diagnostic":"-- The OS error code in the message narrows it: 5 access denied, 32 file in\n-- use, 2/3 missing path.\n\n-- Which account needs the permission (Windows; no engine row is listed on Linux):\nSELECT service_account FROM sys.dm_server_services WHERE servicename LIKE 'SQL Server (%';\n\n-- Is another instance holding the file (error 32)? From a shell on the server:\n-- openfiles /query   (requires maintain objects list enabled)\n-- or Process Explorer: search for the .mdf file name.\n\n-- Database state and file locations for a database that is attached (a failed attach creates no rows):\nSELECT name, state_desc FROM sys.databases WHERE name = N'SalesDb';\nSELECT name, physical_name, state_desc\nFROM sys.master_files WHERE database_id = DB_ID(N'SalesDb');","alternatives":"If the files came from another machine and ownership is tangled, take fresh copies as the service account (or grant it full control on the whole folder). For a one-time import of foreign .mdf files, rebuilding the database from scripts or a BACPAC is often faster than fighting permissions.","details":[],"details_title":null,"repro":"-- Attach a file at a path that does not exist:\nCREATE DATABASE AttachTest ON\n    (FILENAME = N'C:\\Temp\\does_not_exist.mdf')\nFOR ATTACH;\n-- Msg 5120, Level 16: Unable to open the physical file \"<path>\". Operating system error 2: \"2(The system cannot find the file specified.)\".\n-- A C:\\ path on a Linux instance reports Msg 5133 (Directory lookup failed) instead.\n\n-- Access denied repro: copy a detached .mdf somewhere the service account\n-- cannot read, detach it first so the service is not holding it:\nCREATE DATABASE ScratchDb;\nEXEC sp_detach_db N'ScratchDb';\n-- move C:\\...ScratchDb.mdf to a folder with no service-account permission,\nCREATE DATABASE ScratchDb ON\n    (FILENAME = N'<new_path>\\ScratchDb.mdf'),\n    (FILENAME = N'<new_path>\\ScratchDb_log.ldf')\nFOR ATTACH;\n-- Operating system error 5.\n\nDROP DATABASE ScratchDb;  -- once attached, or delete the files by hand","repro_note":null,"related":["sql-server/3201","sql-server/3013","sql-server/9001"],"sqlly":"SQLly shows the operating-system error next to the file name.","faqs":[{"question":"I copied a detached .mdf from another server and now attach fails with error 5. Why?","answer":"The copy landed without the SQL Server service account's permissions, and the source server had them. Grant the local service account full control on the file and its folder, then attach again."},{"question":"Can I just take ownership of the files with my admin account?","answer":"That does not help: the service account is the one that opens them. Your account owning the files changes nothing about the service's access."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/5120","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/515","corpus":"errors","engine":"sql-server","language":"en","title":"Cannot insert the value NULL into column","description":"An INSERT or UPDATE left a NOT NULL column without a value. The message names the column, the table, and which statement failed.","body":{"code":"515","slug":"515","name":null,"message":"Cannot insert the value NULL into column '%.*ls', table '%.*ls'; column does not allow nulls. %ls fails.","group":"constraints","severity":16,"sql_state":null,"summary":"An INSERT or UPDATE left a NOT NULL column without a value. The message names the column, the table, and which statement failed.","meaning":"A column declared `NOT NULL` must always have a value. If an `INSERT` doesn't list the column and it has no default, or an `UPDATE` sets it to NULL, SQL Server stops the statement with 515.","causes":["The `INSERT` column list leaves out a `NOT NULL` column that has no `DEFAULT`.","A variable or parameter passed to the column is NULL.","An `INSERT ... SELECT` whose source has NULLs, often from an outer join.","A new `NOT NULL` column was added without a default, and old code doesn't supply it."],"fix":[{"text":"Provide a value for the column, or wrap possibly-NULL inputs.","sql":"DECLARE @CustomerId int = 7, @Status varchar(20) = NULL;\nINSERT INTO dbo.Orders (CustomerId, Status, CreatedAt)\nVALUES (@CustomerId, COALESCE(@Status, 'new'), SYSUTCDATETIME());"},{"text":"If the column should get a value automatically, add a default constraint.","sql":"ALTER TABLE dbo.Orders ADD CONSTRAINT DF_Orders_CreatedAt DEFAULT (SYSUTCDATETIME()) FOR CreatedAt;"},{"text":"Find the source rows with NULLs before an `INSERT ... SELECT`.","sql":"SELECT * FROM staging.Orders WHERE Status IS NULL;"}],"diagnostic":"-- Which NOT NULL columns on the table have no default and no identity?\nSELECT c.name, TYPE_NAME(c.user_type_id) AS type_name,\n       c.is_identity, dc.definition AS default_definition\nFROM sys.columns AS c\nLEFT JOIN sys.default_constraints AS dc\n    ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id\nWHERE c.object_id = OBJECT_ID(N'dbo.Orders')\n  AND c.is_nullable = 0\n  AND dc.object_id IS NULL\n  AND c.is_identity = 0;\n-- For INSERT ... SELECT, find the source rows that would deliver NULL\nSELECT * FROM staging.Orders WHERE Status IS NULL;","alternatives":"If the column should fill itself, add a DEFAULT constraint so callers stop supplying it. If NULL is a legitimate state for the data, alter the column to allow NULL instead of forcing a placeholder value like empty string or zero.","details":[],"details_title":null,"repro":"CREATE TABLE #n (a int NOT NULL, b int NULL);\nINSERT INTO #n (b) VALUES (1);  -- Msg 515: Cannot insert the value NULL into column 'a' ...\nDROP TABLE #n;","repro_note":null,"related":["sql-server/547","sql-server/2627","postgresql/23502","mysql/1048","mysql/1364","oracle/ora-01400","sqlite/sqlite-constraint-notnull"],"sqlly":"SQLly's editor highlights the statement's line when the INSERT fails, and Validate SQL (Cmd+Shift+V or Ctrl+Shift+V) re-checks the fixed column list against the table's schema without executing anything.","faqs":[{"question":"How is 515 different from 547?","answer":"547 is a FOREIGN KEY or CHECK constraint violation. 515 is the NOT NULL property on a single column. Both come with 3621 saying the statement was terminated."},{"question":"I added a NOT NULL column and old code now fails. Why?","answer":"ALTER TABLE ... ADD without a DEFAULT on a NOT NULL column succeeds only on an empty table. On a table with rows, SQL Server rejects the ALTER with Msg 4901. A 515 appears when the column was added to an empty table (or its default was later dropped) and old INSERTs that leave it out now fail. Add a DEFAULT constraint or update the insert code."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/515","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/53","corpus":"errors","engine":"sql-server","language":"en","title":"Network-related or instance-specific","description":"The client couldn't reach SQL Server at all: wrong server or instance name, the service is stopped, TCP/IP is disabled, or a firewall blocks the port.","body":{"code":"53","slug":"53","name":null,"message":"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)","group":"connection","severity":null,"sql_state":null,"summary":"The client couldn't reach SQL Server at all: wrong server or instance name, the service is stopped, TCP/IP is disabled, or a firewall blocks the port.","meaning":"Error 53 comes from the client's network layer, not from SQL Server. It is the Windows error \"The network path was not found\", and it means the client never got as far as talking to the database engine, so no login was attempted.\n\nThe same family of failures shows up under other numbers depending on the client library: error 26 (Error Locating Server/Instance Specified) when a named instance can't be found, 10060 when the connection attempt times out, 11001 when the host name doesn't resolve, and \"actively refused\" when nothing listens on the port.","causes":["The server name or instance name in the connection string is wrong, or points to another environment.","The SQL Server service is not running.","TCP/IP is disabled for the instance in SQL Server Configuration Manager, which is the default on Express.","A firewall blocks TCP 1433 (or the instance's port), or UDP 1434 that the SQL Server Browser service uses to tell clients a named instance's port.","The SQL Server Browser service is stopped, so a named instance on a dynamic port can't be located.","The host name doesn't resolve, or resolves to a stale address."],"fix":[{"text":"Check that the service is running, on the server, in SQL Server Configuration Manager (SQL Server Services) or the Services console.","sql":null},{"text":"Connect with an explicit TCP address and port to take name resolution and the Browser service out of the picture: `tcp:192.168.1.101,1433` (or the instance's port). If that works, the problem is the name, the instance lookup, or UDP 1434.","sql":null},{"text":"Find the port the instance really listens on from its error log.","sql":"EXEC sys.xp_readerrorlog 0, 1, N'Server is listening on';"},{"text":"Enable TCP/IP under SQL Server Network Configuration, Protocols for the instance, then restart the SQL Server service.","sql":null},{"text":"Allow the port through the server's firewall and any network firewall, and UDP 1434 if you connect to a named instance by name. Start the SQL Server Browser service for named instances on dynamic ports, or give the instance a static port.","sql":null},{"text":"Test plain TCP reachability from the client with `Test-NetConnection server -Port 1433` (PowerShell) or `nc -vz server 1433`.","sql":null}],"diagnostic":"-- Is the engine service running at all?\nSELECT servicename, status_desc, startup_type_desc FROM sys.dm_server_services;\n-- Which ports did this instance register at startup?\nEXEC sys.xp_readerrorlog 0, 1, N'Server is listening on';\n-- Is TCP/IP enabled for this instance? xp_instance_regread maps the default-instance\n-- path to the instance you are connected to; look for the Enabled value in the result.\nEXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\\Microsoft\\Microsoft SQL Server\\MSSQLSERVER\\MSSQLServer\\SuperSocketNetLib\\Tcp', N'Enabled';\n-- Named instances answer on UDP 1434 via the Browser service; check it from a shell: sc query \"SQLBrowser\"","alternatives":"When you only need to check reachability, Test-NetConnection on the client (Test-NetConnection host -Port 1433) tells you whether the port is open without any SQL tooling. Connecting by IP and port instead of a name also removes DNS and the Browser service from the diagnosis.","details":[],"details_title":null,"repro":"-- 53 is a client-side failure: nothing reached the engine. Reproduce the parts from a shell:\n-- 1) Host does not resolve (SQL Network Interfaces error 26 or 11001):\n--    sqlcmd -S no-such-host-xyz -Q \"SELECT 1\"\n-- 2) Host resolves but the port is refused (service stopped or firewall):\n--    sqlcmd -S \"tcp:localhost,14331\" -Q \"SELECT 1\"     -- error 10061\n-- 3) Via Named Pipes (Windows ODBC/SNAC clients only; go-sqlcmd on macOS rejects np: with a URL parse error):\n--    sqlcmd -S np:localhost -Q \"SELECT 1\"              -- Windows ODBC clients: error 53 \"The network path was not found\"","repro_note":null,"related":["sql-server/18456","sql-server/4060","postgresql/08001","postgresql/08006","mysql/2002","mysql/2003","oracle/ora-12541"],"sqlly":"SQLly's connection test reports whether the server was reachable, the round-trip time and the exact error the driver returned, so you can tell a network failure like this one from a login failure (18456) before you start changing settings.","faqs":[{"question":"Does error 53 mean my password is wrong?","answer":"No. The client never reached SQL Server, so credentials weren't checked yet. Fix the network path first; a wrong password shows up as error 18456."},{"question":"Why can I connect on the server itself but not from my machine?","answer":"Local connections use shared memory, which skips the network. Remote connections need TCP/IP enabled, the right port and an open firewall."},{"question":"Can I fix error 53 with a query once I get connected?","answer":"Sometimes, for the parts that live in SQL Server: you can check sys.dm_server_services for the service state if you connect to another instance on the same box, but TCP settings and the Browser service are Configuration Manager and Windows settings, not server configuration."},{"question":"Does error 53 mean the server is down?","answer":"Not necessarily. It means the client could not establish a session at all. Common non-down causes are a typo in the server or instance name, TCP/IP disabled for the instance, a stopped SQL Server Browser, or a firewall rule that only allows port 1433 when the instance uses a dynamic port."},{"question":"Why does connecting with the instance name fail but IP,port works?","answer":"That pattern points at name resolution or the instance lookup: DNS can't resolve the host, or the SQL Server Browser service is stopped so the client can't learn the named instance's port. IP and port skips both steps."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/53","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/547","corpus":"errors","engine":"sql-server","language":"en","title":"Statement conflicted with a constraint","description":"An INSERT, UPDATE, DELETE or ALTER TABLE ... ADD CONSTRAINT broke a FOREIGN KEY or CHECK constraint: a child without a parent, a parent with children, or a failed check.","body":{"code":"547","slug":"547","name":null,"message":"The %ls statement conflicted with the %ls constraint \"%.*ls\". The conflict occurred in database \"%.*ls\", table \"%.*ls\"%ls%.*ls%ls.","group":"constraints","severity":16,"sql_state":null,"summary":"An INSERT, UPDATE, DELETE or ALTER TABLE ... ADD CONSTRAINT broke a FOREIGN KEY or CHECK constraint: a child without a parent, a parent with children, or a failed check.","meaning":"Error 547 covers two kinds of constraint. With a `FOREIGN KEY`, it means the statement would leave a reference pointing nowhere: inserting or updating a child row whose parent doesn't exist, or deleting or changing a parent that child rows still use. With a `CHECK` constraint, it means a row failed the constraint's condition. The message names the statement type, the constraint, and the database, table and column involved.","causes":["Inserting a child row with a foreign key value that has no matching parent row (wrong id, or the parent isn't inserted yet).","Deleting a parent row, or changing its key, while child rows reference it.","A value that fails a `CHECK` constraint, such as a negative quantity.","Adding a foreign key or check constraint to a table whose existing data already violates it (`ALTER TABLE ... ADD CONSTRAINT`).","Loading tables in the wrong order: children before parents."],"fix":[{"text":"Read the constraint name in the message, then see what it enforces.","sql":"SELECT fk.name, OBJECT_NAME(fk.parent_object_id) AS child_table,\n       OBJECT_NAME(fk.referenced_object_id) AS parent_table,\n       fk.delete_referential_action_desc\nFROM sys.foreign_keys AS fk WHERE fk.name = N'FK_Orders_Customers';"},{"text":"For an insert, make sure the parent exists first, or insert parents before children.","sql":"SELECT * FROM dbo.Customers WHERE CustomerId = 42;"},{"text":"For a delete, remove or reassign the child rows first, or define the key with `ON DELETE CASCADE` if deleting children with the parent is what you want.","sql":"DELETE FROM dbo.Orders WHERE CustomerId = 42;\nDELETE FROM dbo.Customers WHERE CustomerId = 42;"},{"text":"When adding a constraint to existing data, find the rows that break it.","sql":"SELECT o.*\nFROM dbo.Orders AS o\nLEFT JOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.CustomerId IS NOT NULL AND c.CustomerId IS NULL;"}],"diagnostic":"-- What kind of constraint failed, and what does it enforce?\nSELECT o.name, o.type_desc,\n       OBJECT_SCHEMA_NAME(o.parent_object_id) AS on_table\nFROM sys.objects AS o\nWHERE o.object_id = OBJECT_ID(N'FK_Orders_Customers');\n-- For a foreign key: which child rows have no matching parent (orphans)?\nSELECT o.CustomerId, COUNT(*) AS orphaned_rows\nFROM dbo.Orders AS o\nLEFT JOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId\nWHERE o.CustomerId IS NOT NULL AND c.CustomerId IS NULL\nGROUP BY o.CustomerId;","alternatives":"For parent deletes you intend to keep, declare the key with ON DELETE CASCADE so children go with the parent, or use ON DELETE SET NULL where a dangling reference makes sense. For bulk loads, loading with the constraint disabled (WITH NOCHECK) and validating afterwards is a workaround, but rows you miss stay invalid forever, so follow up with a check.","details":[],"details_title":null,"repro":"CREATE TABLE #p (id int PRIMARY KEY);\nCREATE TABLE #c (id int, CHECK (id > 0));\nINSERT INTO #c VALUES (-1);  -- Msg 547: The INSERT statement conflicted with the CHECK constraint ...\nDROP TABLE #c; DROP TABLE #p;","repro_note":"Temp tables can't have foreign keys, so the repro uses a CHECK constraint; a FOREIGN KEY violation raises the same error number.","related":["sql-server/2627","sql-server/515","sql-server/3726","postgresql/23503","postgresql/23514","mysql/1452","mysql/1451","oracle/ora-02291","oracle/ora-02292"],"sqlly":"SQLly's ER diagram draws the foreign keys between tables, so you can see which parent a constraint points to and which tables reference the row you're deleting.","faqs":[{"question":"How do I delete a row that other tables reference?","answer":"Delete or update the referencing rows first, or change the foreign key to ON DELETE CASCADE or ON DELETE SET NULL if that matches the data's meaning. Disabling the constraint leaves orphaned rows behind."},{"question":"Can I add the constraint anyway and ignore the bad rows?","answer":"ALTER TABLE ... WITH NOCHECK ADD CONSTRAINT skips validation of existing data, and SQL Server marks the constraint as not trusted. New writes are checked, but the optimizer may ignore the constraint, so plan to clean the orphans and re-validate."},{"question":"The message says DELETE conflicted but I only inserted rows. What happened?","answer":"Look for a trigger or a cascade chain: a delete inside a trigger, or ON DELETE CASCADE from a third table, can run a delete that hits the constraint. The constraint name in the message points at the table where it fired."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/547","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/6401","corpus":"errors","engine":"sql-server","language":"en","title":"No transaction or savepoint found","description":"ROLLBACK TRANSACTION name named a savepoint or transaction that doesn't exist, often a misspelling or a savepoint that was never set.","body":{"code":"6401","slug":"6401","name":null,"message":"Cannot roll back %.*ls. No transaction or savepoint of that name was found.","group":"transactions","severity":16,"sql_state":null,"summary":"ROLLBACK TRANSACTION name named a savepoint or transaction that doesn't exist, often a misspelling or a savepoint that was never set.","meaning":"`ROLLBACK TRANSACTION name` rolls back to the savepoint (or outermost named transaction) with that name. If no savepoint or transaction of that name exists in the current transaction, SQL Server raises 6401. With no transaction open at all, the same statement raises 3903 instead: \"The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.\" Rolling back to a savepoint doesn't end the transaction; only an unnamed `ROLLBACK` or the outermost name does.","causes":["A typo in the savepoint name, or a `SAVE TRANSACTION` that was skipped by control flow.","Naming an inner `BEGIN TRANSACTION name` in `ROLLBACK`; only the outermost transaction's name or a savepoint name is valid.","The savepoint was already consumed: rolling back to a savepoint discards it and any savepoint saved after it, so a second rollback to the same name, or to a later savepoint, raises 6401. An earlier error that ends the whole transaction gives 3903 instead (or 3931 when the transaction is uncommittable)."],"fix":[{"text":"Set the savepoint before the work you may need to undo, and roll back to the same name. Check @@ERROR after each statement: it reflects only the statement that ran last, so a failed statement followed by a successful one is not rolled back by that check.","sql":"BEGIN TRANSACTION;\nSAVE TRANSACTION BeforeImport;\n-- work\nIF @@ERROR <> 0 ROLLBACK TRANSACTION BeforeImport;\nCOMMIT TRANSACTION;"},{"text":"Check `XACT_STATE()` first: if it's -1, only a full `ROLLBACK` is possible.","sql":null}],"diagnostic":"-- How many transactions does this session hold, and is it doomed?\nSELECT @@TRANCOUNT AS open_transactions, XACT_STATE() AS state;\n-- List savepoints is not possible directly, but you can see whether the\n-- session has an active transaction at all:\nSELECT session_id, open_transaction_count\nFROM sys.dm_exec_sessions\nWHERE session_id = @@SPID;\n-- XACT_STATE() = -1 means an uncommittable transaction from an earlier\n-- error: only a full ROLLBACK works, and a rollback to any name fails.","alternatives":"Issue SAVE TRANSACTION with the exact name before the work you may want to undo, and use the same spelling in the rollback. If the transaction is uncommittable, use a full ROLLBACK and retry. In application code, keep transaction naming consistent between the save and rollback calls, ideally through shared constants.","details":[],"details_title":null,"repro":"-- Scratch DB repro: rollback to a savepoint that was never saved\nBEGIN TRANSACTION;\n-- There is no SAVE TRANSACTION BeforeImport anywhere\nROLLBACK TRANSACTION BeforeImport; -- raises 6401\nROLLBACK; -- clean up so the session is not left in a transaction","repro_note":null,"related":["sql-server/3903","sql-server/266","sql-server/3930","postgresql/3B001"],"sqlly":"SQLly maps SQL Server's line number onto your whole script and highlights the statement that failed, so the savepoint name that doesn't match its BEGIN TRANSACTION is easy to spot.","faqs":[{"question":"Can I roll back to a named inner transaction, like BEGIN TRANSACTION Step1?","answer":"Only the outermost transaction's name works as a rollback target; ROLLBACK TRANSACTION Step1 where Step1 is a nested BEGIN TRANSACTION name raises 6401 in that situation. For partial undo inside a transaction, use SAVE TRANSACTION and roll back to the savepoint name."},{"question":"Does rolling back to a savepoint commit the rest?","answer":"No. ROLLBACK TRANSACTION savepoint undoes only the work done after that savepoint; work done before it is kept, the transaction stays open, and the savepoint itself is consumed. You still need a later COMMIT or full ROLLBACK."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/6401","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/701","corpus":"errors","engine":"sql-server","language":"en","title":"Insufficient memory in resource pool","description":"SQL Server couldn't get the memory it needed for a query in this resource pool. The server, pool or a memory-hungry workload is short of memory.","body":{"code":"701","slug":"701","name":null,"message":"There is insufficient system memory in resource pool '%ls' to run this query.","group":"resources","severity":19,"sql_state":null,"summary":"SQL Server couldn't get the memory it needed for a query in this resource pool. The server, pool or a memory-hungry workload is short of memory.","meaning":"Error 701 means a memory allocation failed: SQL Server needed memory for the query and the resource pool (usually `default` or `internal`) couldn't provide it. It points at memory pressure on the instance, not a bug in the query itself, though one query with a huge memory grant can be the cause.","causes":["`max server memory` set too low for the workload, or the machine itself low on memory.","A Resource Governor pool with a tight `MAX_MEMORY_PERCENT`.","Memory-optimized (In-Memory OLTP) tables growing beyond what the pool allows.","Queries with very large memory grants for sorts and hash joins, often from bad row estimates.","Other processes on the server taking memory, or a memory leak in a component loaded into SQL Server."],"fix":[{"text":"Check the memory configuration.","sql":"SELECT name, value_in_use FROM sys.configurations WHERE name IN (N'max server memory (MB)', N'min server memory (MB)');"},{"text":"See which memory clerks use the most memory.","sql":"SELECT TOP (10) type, SUM(pages_kb) / 1024 AS mb\nFROM sys.dm_os_memory_clerks GROUP BY type ORDER BY mb DESC;"},{"text":"Look for queries with large memory grants.","sql":"SELECT session_id, requested_memory_kb, granted_memory_kb, query_cost\nFROM sys.dm_exec_query_memory_grants ORDER BY requested_memory_kb DESC;"},{"text":"Raise `max server memory` if the host has room, or add memory, and tune the queries with the largest grants (better indexes and up-to-date statistics shrink sorts and hashes).","sql":null}],"diagnostic":"-- Top memory consumers right now (clerks, aggregated)\nSELECT TOP 10 type, SUM(pages_kb)/1024 AS mb\nFROM sys.dm_os_memory_clerks\nGROUP BY type ORDER BY mb DESC;\n-- Queries holding big memory grants\nSELECT session_id, requested_memory_kb, granted_memory_kb, used_memory_kb\nFROM sys.dm_exec_query_memory_grants ORDER BY granted_memory_kb DESC;\n-- Any external pressure? Look for RESOURCE_SEMAPHORE waits (waiting for a grant)\nSELECT wait_type, waiting_tasks_count, wait_time_ms\nFROM sys.dm_os_wait_stats WHERE wait_type LIKE 'RESOURCE_SEMAPHORE%';\n-- Current setting\nSELECT name, value_in_use FROM sys.configurations WHERE name LIKE '%server memory%';","alternatives":"Running heavy reports off a replica, or in a maintenance window, moves the pressure off business hours. Resource Governor (Enterprise or Developer edition on SQL Server 2022 and earlier, and Standard as well from SQL Server 2025) can cap the memory a workload pool can grab so one query cannot starve the rest, and batching very large ETL operations keeps each request's grant small.","details":[],"details_title":null,"repro":"-- 701 needs genuine memory pressure, so drill it on a throwaway instance only.\n-- The deterministic path is a Resource Governor pool too small for the\n-- memory-optimized tables charged to it (In-Memory OLTP memory is charged to\n-- the pool the database is bound to, not to the query's workload group):\nCREATE RESOURCE POOL pool_tiny WITH MAX_MEMORY_PERCENT = 1;\nGO\nCREATE DATABASE Scratch701 ON PRIMARY\n    (NAME = Scratch701, FILENAME = 'C:\\Temp\\Scratch701.mdf'),\n  FILEGROUP Scratch701_mem CONTAINS MEMORY_OPTIMIZED_DATA\n    (NAME = Scratch701_mem, FILENAME = 'C:\\Temp\\Scratch701_mem');\nGO\nEXEC sys.sp_xtp_bind_db_resource_pool N'Scratch701', N'pool_tiny';\nALTER DATABASE Scratch701 SET OFFLINE WITH ROLLBACK IMMEDIATE;\nALTER DATABASE Scratch701 SET ONLINE;\nGO\nUSE Scratch701;\nCREATE TABLE dbo.Filler (id int IDENTITY PRIMARY KEY NONCLUSTERED,\n                         payload char(4000) NOT NULL)\n    WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY);\n-- Insert in a loop until the pool cap stops you:\n--   INSERT INTO dbo.Filler (payload) VALUES (REPLICATE('x', 4000));\n-- On a small instance, 1% of memory fills within a few thousand rows and the\n-- insert fails with 701 naming pool_tiny.\n-- Cleanup: DROP DATABASE Scratch701; then ALTER RESOURCE GOVERNOR DISABLE;\n-- and DROP RESOURCE POOL pool_tiny;","repro_note":null,"related":["sql-server/8645","sql-server/8623","postgresql/53200","oracle/ora-04031"],"sqlly":"SQLly's activity monitor shows running queries with their waits, and the execution plan view flags the oversized estimates that produce huge memory grants, the usual culprits behind 701.","faqs":[{"question":"Is this a bug in my query?","answer":"Rarely by itself. Error 701 means the pool could not satisfy an allocation, which points at instance-wide pressure. One query with an enormous memory grant can still be the trigger, which is what the dm_exec_query_memory_grants query checks."},{"question":"Should I restart SQL Server?","answer":"It clears memory, but you lose the evidence. Capture the clerk and grant queries above first, then restart if you must. If the pressure returns within hours, the restart treated the symptom."},{"question":"Does lowering max server memory help?","answer":"It can help when SQL Server is competing with other software on the same box, because it reserves memory for the OS. It does not help when SQL Server itself needs more than it has, which is a case for more RAM or smaller grants."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/701","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/7202","corpus":"errors","engine":"sql-server","language":"en","title":"Could not find server in sys.servers","description":"A four-part name or OPENQUERY referred to a linked server that isn't defined on this instance, or the name is spelled differently.","body":{"code":"7202","slug":"7202","name":null,"message":"Could not find server '%.*ls' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.","group":"objects","severity":11,"sql_state":null,"summary":"A four-part name or OPENQUERY referred to a linked server that isn't defined on this instance, or the name is spelled differently.","meaning":"A four-part name such as `SERVER1.SalesDb.dbo.Orders`, or `OPENQUERY(SERVER1, ...)`, uses a linked server defined in `sys.servers`. If no linked server has that name, SQL Server raises 7202.","causes":["The linked server was never created on this instance, for example after moving a database to a new server.","The linked server is defined under a different name (an alias, or `SERVER\\INSTANCE`).","A database name accidentally written as a four-part name, adding an extra prefix."],"fix":[{"text":"List the linked servers defined here.","sql":"SELECT name, product, provider, data_source FROM sys.servers WHERE is_linked = 1;"},{"text":"Create the linked server, then set up its login mapping.","sql":"EXEC master.dbo.sp_addlinkedserver @server = N'SERVER1', @srvproduct = N'SQL Server';\nEXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'SERVER1', @useself = N'True';"},{"text":"If the object is on this server, use a three-part name instead.","sql":null}],"diagnostic":"-- Is the name registered at all? Four-part names match case-insensitively on the registered name.\nSELECT name, is_linked, is_remote_login_enabled, is_data_access_enabled FROM sys.servers;\n-- If it exists but the query still fails, the error is different (login or provider), not 7202.\n-- OPENQUERY uses the same registered name:\nSELECT name FROM sys.servers WHERE is_linked = 1;","alternatives":"If the remote instance should not be a permanent linked server, use OPENROWSET with a full connection string for a one-off query, no registration needed. The caller needs the Ad Hoc Distributed Queries server configuration enabled before OPENROWSET works, because it is off by default.","details":[],"details_title":null,"repro":"-- Scratch database, no linked servers defined\nSELECT * FROM OTHERSERVER.db.dbo.Thing;\n-- Fails with 7202: could not find server 'OTHERSERVER' in sys.servers.\n-- Add it, then query an object that exists there (the Thing query fails with 7314 until db.dbo.Thing exists):\nEXEC sys.sp_addlinkedserver @server = N'OTHERSERVER', @srvproduct = N'', @provider = N'MSOLEDBSQL', @datasrc = N'localhost';\nSELECT name, is_linked FROM sys.servers;","repro_note":null,"related":["sql-server/208","sql-server/53"],"sqlly":"Query sys.servers in SQLly's grid; if the linked server is missing from the result, the four-part name was never going to work until someone adds it with sp_addlinkedserver.","faqs":[{"question":"The server is registered under one name but my query uses another. Which one counts?","answer":"The name in sys.servers, exactly as registered (comparisons are case-insensitive). Use sp_addlinkedserver's @server value, or add an alias under the name your queries expect."},{"question":"Does 7202 mean the remote server is down?","answer":"No. It means the name is not defined on this instance at all. Connection failures after registration give different errors."},{"question":"Do linked servers exist per database?","answer":"No. sys.servers is per instance, so a linked server defined once is visible from every database on it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/7202","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8114","corpus":"errors","engine":"sql-server","language":"en","title":"Error converting data type","description":"SQL Server couldn't convert a value from one data type to another, often a varchar to numeric conversion or a parameter of the wrong type.","body":{"code":"8114","slug":"8114","name":null,"message":"Error converting data type %ls to %ls.","group":"data","severity":16,"sql_state":null,"summary":"SQL Server couldn't convert a value from one data type to another, often a varchar to numeric conversion or a parameter of the wrong type.","meaning":"Error 8114 is a general conversion failure, raised for example when a string can't be converted to `numeric` or `decimal`, or when a value passed to a stored procedure parameter doesn't fit the parameter's type. The message names the source and target types (`Error converting data type varchar to numeric`).","causes":["Converting text that isn't a valid number, such as `'1,234.50'` or `'12abc'`, to `decimal` or `numeric`.","Passing a string to a numeric procedure parameter: `EXEC dbo.SetPrice @Price = 'free'`.","Regional formatting: a decimal comma (`'12,5'`) where SQL Server expects a decimal point."],"fix":[{"text":"Find the values that don't convert.","sql":"SELECT Amount FROM staging.Payments WHERE TRY_CONVERT(decimal(18, 2), Amount) IS NULL AND Amount IS NOT NULL;"},{"text":"Clean formatting before converting, or parse with a culture.","sql":"SELECT TRY_PARSE('12,5' AS decimal(18, 2) USING 'de-DE');"},{"text":"Pass parameters with the right types from the application instead of strings.","sql":null}],"diagnostic":"-- Find the strings that are not valid numbers (SQL Server 2012+)\nSELECT pk, text_col,\n       TRY_CONVERT(decimal(18,2), text_col) AS parsed\nFROM dbo.MyTable\nWHERE TRY_CONVERT(decimal(18,2), text_col) IS NULL AND text_col IS NOT NULL;\n\n-- See what statement a session ran (replace spid with an integer session id, for example from sys.dm_exec_sessions; the 8114 message does not include one)\nDBCC INPUTBUFFER(spid);\n\n-- Compare against the parameter types the procedure expects\nSELECT p.name AS parameter, t.name AS type_name, p.precision, p.scale\nFROM sys.parameters p\nJOIN sys.types t ON t.user_type_id = p.user_type_id\nWHERE p.object_id = OBJECT_ID(N'dbo.MyProc');","alternatives":"Clean the text before converting: strip thousands separators and spaces, and normalize the decimal separator, or fix the client to send numbers with a period and no grouping. On SQL Server 2012 and later, `TRY_CONVERT` or `TRY_CAST` returns NULL instead of raising, which lets a query skip or flag bad rows.","details":[],"details_title":null,"repro":"SELECT CAST('12abc' AS decimal(10, 2));  -- Msg 8114: Error converting data type varchar to numeric.","repro_note":null,"related":["sql-server/245","sql-server/8115","postgresql/22P02","mysql/1366","oracle/ora-01722"],"sqlly":"SQLly's execution plan findings flag implicit conversions in a plan, which is often where a varchar meets a numeric and fails as 8114 instead of returning rows.","faqs":[{"question":"Why is '1,234.50' rejected?","answer":"SQL Server does not accept thousands separators when it converts text to a number: CAST('1,234.50' AS decimal(10, 2)) raises error 8114. A bare 1,234.50 in a query is not a literal: SELECT 1,234.50 returns two columns, 1 and 234.50. Remove the comma first, or store numbers in numeric columns so no text parsing happens."},{"question":"Is ISNUMERIC enough to validate input?","answer":"No. ISNUMERIC returns 1 for values like '1e5', currency symbols and other formats that CONVERT may still reject or read differently. Use TRY_CONVERT and check for NULL instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8114","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8115","corpus":"errors","engine":"sql-server","language":"en","title":"Arithmetic overflow error converting","description":"A number is too big for the target data type, for example a value over 2,147,483,647 into int, or more digits than a decimal's precision allows.","body":{"code":"8115","slug":"8115","name":null,"message":"Arithmetic overflow error converting %ls to data type %ls.","group":"data","severity":16,"sql_state":null,"summary":"A number is too big for the target data type, for example a value over 2,147,483,647 into int, or more digits than a decimal's precision allows.","meaning":"Each numeric type has a range: `tinyint` 0 to 255, `smallint` -32,768 to 32,767, `int` up to 2,147,483,647, and `decimal(p, s)` at most p digits with s after the decimal point. Converting a value that doesn't fit raises 8115 when the target is decimal or numeric, or when a bigint is converted to int. An int that doesn't fit a tinyint or smallint raises 220 instead, such as `Msg 220 ... value = 300`. A common surprise is `COUNT(*)` or `SUM()` over an `int` column exceeding the `int` range on big tables.","causes":["Inserting or converting a value that is larger than the column type allows.","`SUM()` of an `int` column whose total passes 2,147,483,647; the result type is `int`.","`COUNT(*)` on more than about 2.1 billion rows (use `COUNT_BIG`).","Converting to a `decimal` with too few digits, such as 1234.5 into `decimal(4,1)`.","An identity column of type `int` that has run out of values."],"fix":[{"text":"Aggregate in a wider type.","sql":"SELECT SUM(CAST(Quantity AS bigint)) AS total, COUNT_BIG(*) AS row_count FROM dbo.OrderLines;"},{"text":"Widen the column to `bigint` or a larger `decimal`.","sql":"ALTER TABLE dbo.Metrics ALTER COLUMN Value decimal(18, 4) NOT NULL;"},{"text":"Check how close an identity column is to its limit.","sql":"SELECT IDENT_CURRENT('dbo.Events') AS current_identity;"}],"diagnostic":"-- Check the declared types you are inserting into or summing\nSELECT c.name, t.name AS type_name, c.precision, c.scale\nFROM sys.columns c\nJOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID(N'dbo.MyTable');\n\n-- Find which rows would overflow an int-typed column on insert\nSELECT pk, big_value\nFROM dbo.Staging\nWHERE TRY_CONVERT(int, big_value) IS NULL AND big_value IS NOT NULL;\n\n-- Identity close to exhaustion: compare last assigned value to the type's max\nSELECT IDENT_CURRENT(N'dbo.MyTable') AS current_seed;\nSELECT MAX(id) FROM dbo.MyTable;","alternatives":"Widen the column or variable: `bigint` for large counts and ids, or `decimal(p,s)` with enough digits for totals. Cast the inputs of a `SUM` to `bigint` before aggregating, and use `COUNT_BIG(*)` when a table can pass 2.1 billion rows.","details":[],"details_title":null,"repro":"SELECT CAST(300 AS tinyint);  -- Msg 220 for a constant tinyint (and for an int column cast to tinyint); decimal and numeric overflow is 8115:\nSELECT CAST(1234.5 AS decimal(4, 1));  -- Msg 8115","repro_note":null,"related":["sql-server/220","sql-server/8114","sql-server/245","postgresql/22003","mysql/1264","oracle/ora-01438"],"sqlly":"Run the failing expression over the real rows in SQLly's grid with TRY_CAST and the NULLs mark where the target type runs out of room (a NULL source also shows as NULL).","faqs":[{"question":"Why does SUM fail when the column values are small?","answer":"SUM over an int column returns int, so the running total overflows even though no single value does. Cast first: SUM(CAST(col AS bigint))."},{"question":"Can I recover an identity column that ran out of values?","answer":"You have to change the column to a wider type, typically bigint, which on most versions means rebuilding or recreating the table, or migrate to a new table with a fresh sequence. DBCC CHECKIDENT can reseed, but only to a value the type still allows."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8115","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8117","corpus":"errors","engine":"sql-server","language":"en","title":"Operand data type invalid for operator","description":"An operator got a type that doesn't support it, such as SUM, AVG, MIN, MAX, STDEV or unary minus on bit, or arithmetic between two text, ntext, xml or image values.","body":{"code":"8117","slug":"8117","name":null,"message":"Operand data type %ls is invalid for %ls operator.","group":"data","severity":16,"sql_state":null,"summary":"An operator got a type that doesn't support it, such as SUM, AVG, MIN, MAX, STDEV or unary minus on bit, or arithmetic between two text, ntext, xml or image values.","meaning":"Each operator works on certain data types. Error 8117 names the type and the operator that don't go together, for example `Operand data type bit is invalid for sum operator` or `Operand data type varchar is invalid for avg operator` when averaging a text column.","causes":["`SUM()` or `AVG()` over a `bit` column (bit is an exact numeric, but SQL Server rejects it for SUM, AVG, MIN, MAX and STDEV).","Aggregating a numeric value stored as text with `SUM()` or `AVG()`. Plain arithmetic such as `'1' + 1` converts implicitly and does not raise 8117.","Aggregating legacy `text`, `ntext` or `image` columns with `SUM()` or `AVG()`. Comparisons and `ORDER BY` raise 402 and 306 instead."],"fix":[{"text":"Cast to a numeric type before aggregating.","sql":"SELECT SUM(CAST(IsActive AS int)) AS active_count FROM dbo.Users;"},{"text":"Convert text columns holding numbers to a numeric type, or convert with `TRY_CONVERT` inside the aggregate.","sql":"SELECT AVG(TRY_CONVERT(decimal(18, 2), Amount)) FROM staging.Payments;"},{"text":"Replace `text` and `ntext` columns with `varchar(max)` and `nvarchar(max)`.","sql":null}],"diagnostic":"-- Confirm the data type the message complained about; the message names the type and operator.\nSELECT c.name, t.name AS type_name FROM sys.columns c JOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID(N'dbo.Users') AND c.name = N'IsActive';\n-- For an expression in a view or query, check the types of every operand you aggregate.\nSELECT t.name AS type_name FROM sys.types t WHERE t.name IN ('bit', 'text', 'ntext', 'image');\n-- Quick sanity check of the same expression on one row:\nSELECT TOP (1) IsActive FROM dbo.Users;","alternatives":"For bit sums, COUNT(CASE WHEN IsActive = 1 THEN 1 END) is often clearer than SUM(CAST(... AS int)) and needs no cast. For text columns holding numbers, the real fix is changing the column type to a numeric one; TRY_CONVERT inside the aggregate is a patch that leaves the bad schema in place.","details":[],"details_title":null,"repro":"SELECT SUM(b) FROM (VALUES (CAST(1 AS bit))) AS t(b);  -- Msg 8117","repro_note":null,"related":["sql-server/245","sql-server/8114","postgresql/42883"],"sqlly":"Check the column's data type with a query against sys.columns in SQLly's grid; SUM over a bit column and arithmetic on text are the usual offenders behind 8117.","faqs":[{"question":"Why can't I SUM a bit column? It looks like a number.","answer":"bit holds only 0, 1, and NULL, and SQL Server rejects it in SUM, AVG, MIN, MAX and STDEV even though Learn classes it as an exact numeric. Cast it to int for the aggregate, or express the intent with COUNT(CASE ...), which also makes partial counts easier."},{"question":"Is error 8117 the same as error 257?","answer":"They overlap. 257 fires on implicit conversion not allowed between two types, often in comparisons; 8117 fires when an operator such as SUM, AVG, or arithmetic gets an unsupported operand type. If the message names an operator, 8117 is the one."},{"question":"How do I replace a text column without breaking old code?","answer":"Add a varchar(max) or nvarchar(max) column, copy data with a CONVERT in batches, update the queries that use it, then drop the old text column. READTEXT, WRITETEXT and UPDATETEXT on the legacy types stop working once the column is gone, so find those first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8117","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8118","corpus":"errors","engine":"sql-server","language":"en","title":"Aggregate without GROUP BY","description":"The SELECT mixes an aggregate such as COUNT(*) with a plain column and has no GROUP BY at all. Add a GROUP BY or aggregate the column.","body":{"code":"8118","slug":"8118","name":null,"message":"Column '%.*ls.%.*ls' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.","group":"syntax","severity":16,"sql_state":null,"summary":"The SELECT mixes an aggregate such as COUNT(*) with a plain column and has no GROUP BY at all. Add a GROUP BY or aggregate the column.","meaning":"A query with an aggregate and no `GROUP BY` returns a single row for the whole table. Any non-aggregated column in the select list would have to be one value out of many, so SQL Server rejects it. On SQL Server 2022 that rejection is Msg 8120; Msg 8118 is documented for the same shape but was not raised by any query shape tested.","causes":["Writing `SELECT name, COUNT(*) FROM ...` and forgetting `GROUP BY name`.","Wanting the total next to each row, which needs a window aggregate rather than a plain one."],"fix":[{"text":"Group by the non-aggregated columns.","sql":"SELECT type, COUNT(*) AS n FROM sys.objects GROUP BY type;"},{"text":"To show a total on every row, use a window aggregate.","sql":"SELECT name, COUNT(*) OVER () AS total_objects FROM sys.objects;"}],"diagnostic":"-- Shape check: which select items have no aggregate around them?\n-- Run the aggregate-only version first; if it returns one row, the plain\n-- columns are what triggered 8118.\nSELECT COUNT(*) FROM your_table;  -- OK\n-- SELECT name, COUNT(*) FROM your_table;  -- error 8120","alternatives":"If you wanted one summary row, remove the plain columns. If you wanted per-group rows, add a GROUP BY. If you wanted each row beside its group total, use a window function: SELECT name, COUNT(*) OVER () FROM your_table.","details":[],"details_title":null,"repro":"SELECT name, COUNT(*) FROM sys.objects;  -- Msg 8120 on SQL Server 2022","repro_note":null,"related":["sql-server/8120","postgresql/42803","oracle/ora-00937"],"sqlly":"SQLly's IntelliSense lists the real columns of each table as you type, which makes it easy to see the plain column that needs to join the GROUP BY or move inside an aggregate.","faqs":[{"question":"Why is one aggregate enough to change the whole query?","answer":"Without GROUP BY, an aggregate collapses everything into a single row. A plain column would need to be one value out of the whole table, so SQL Server refuses instead of guessing."},{"question":"How is this different from 8120?","answer":"A query with aggregates and no GROUP BY raises 8120 on SQL Server 2022. 8120 also fires when a GROUP BY exists but a selected column is missing from it. Msg 8118 has the same no-GROUP-BY meaning in its documented text but was not reproduced on 2022."},{"question":"Can I get each row plus the table total in one query?","answer":"Yes, with a window function: COUNT(*) OVER () computes the total per row without collapsing anything."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8118","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8120","corpus":"errors","engine":"sql-server","language":"en","title":"Column not in GROUP BY or aggregate","description":"A column in SELECT is neither in GROUP BY nor inside an aggregate like SUM or MAX, so SQL Server can't tell which row's value to show.","body":{"code":"8120","slug":"8120","name":null,"message":"Column '%.*ls.%.*ls' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.","group":"syntax","severity":16,"sql_state":null,"summary":"A column in SELECT is neither in GROUP BY nor inside an aggregate like SUM or MAX, so SQL Server can't tell which row's value to show.","meaning":"With `GROUP BY`, each output row stands for a group of input rows. A selected column must either be one of the grouping columns or be aggregated; otherwise there could be many different values per group. SQL Server enforces this strictly (unlike older MySQL modes, which picked an arbitrary value).","causes":["Adding a column to `SELECT` and forgetting to add it to `GROUP BY`.","Wanting a value from \"the latest row per group\", which a plain `GROUP BY` can't express.","Grouping by an expression but selecting the underlying column."],"fix":[{"text":"Add the column to `GROUP BY` if it identifies the group.","sql":"SELECT CustomerId, Country, SUM(Total) AS total\nFROM dbo.Orders\nGROUP BY CustomerId, Country;"},{"text":"Aggregate it if any one value per group is fine.","sql":"SELECT CustomerId, MAX(OrderDate) AS last_order\nFROM dbo.Orders\nGROUP BY CustomerId;"},{"text":"For the whole row of the latest order per customer, use a window function.","sql":"SELECT *\nFROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate DESC) AS rn\n      FROM dbo.Orders AS o) AS x\nWHERE rn = 1;"}],"diagnostic":"-- List each select column and mark whether it is grouped or aggregated\nSELECT name, aggregate_function, is_grouped\nFROM (VALUES ('region', 'COUNT', 1), ('city', 'MAX', 1), ('street', NULL, 0))\n     AS audit(name, aggregate_function, is_grouped)\nWHERE is_grouped = 0;  -- these are the columns that must join the GROUP BY\n-- See what GROUP BY currently lists\nSELECT text FROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle)\nWHERE text LIKE '%GROUP BY%';","alternatives":"If you want one representative value per group, wrap the column in MIN() or MAX(). If you want the detail rows back, drop the GROUP BY and aggregate in a join or a window function like ROW_NUMBER() OVER (PARTITION BY ...).","details":[],"details_title":null,"repro":"SELECT name, type, COUNT(*) FROM sys.objects GROUP BY type;  -- Msg 8120 for 'sys.objects.name'","repro_note":null,"related":["sql-server/8118","postgresql/42803","mysql/1055","oracle/ora-00979"],"sqlly":"Run the query without the GROUP BY in SQLly's grid first: the result header shows every column you asked for, which makes the one that needs an aggregate or a GROUP BY term obvious.","faqs":[{"question":"Which column is the problem?","answer":"The message names the first offending column. Any column in the select list that is neither in the GROUP BY list nor wrapped in an aggregate triggers this."},{"question":"Can I group by a column that isn't selected?","answer":"Yes. The GROUP BY list and the select list do not have to match. A column in GROUP BY may be absent from SELECT, but the reverse is what error 8120 forbids."},{"question":"Why is SQL Server stricter than MySQL here?","answer":"Because the unaggregated column could hold a different value in every row of the group, so any single answer would be arbitrary. MySQL's old permissive mode picked one; SQL Server makes you decide."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8120","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8134","corpus":"errors","engine":"sql-server","language":"en","title":"Divide by zero error encountered","description":"An expression divided by zero. Guard the divisor with NULLIF so the result is NULL instead of an error.","body":{"code":"8134","slug":"8134","name":null,"message":"Divide by zero error encountered.","group":"data","severity":16,"sql_state":null,"summary":"An expression divided by zero. Guard the divisor with NULLIF so the result is NULL instead of an error.","meaning":"Integer and decimal division by zero is an error in SQL Server (with the default `ARITHABORT` and `ANSI_WARNINGS` settings), and it stops the statement. It often appears only for some rows, such as a ratio where the denominator is occasionally zero.","causes":["Computing a ratio or percentage where the denominator can be 0.","A `CASE` that doesn't protect every path, or a filter that SQL Server evaluates after the division rather than before."],"fix":[{"text":"Turn a zero divisor into NULL with `NULLIF`.","sql":"SELECT Clicks * 1.0 / NULLIF(Impressions, 0) AS ctr FROM dbo.Ads;"},{"text":"Or decide what the result should be with `CASE`, or `ISNULL(... , 0)` around the `NULLIF` version.","sql":"SELECT ISNULL(Clicks * 1.0 / NULLIF(Impressions, 0), 0) AS ctr FROM dbo.Ads;"},{"text":"Don't rely on `WHERE Impressions <> 0` to protect a division in the select list of the same query; SQL Server may evaluate expressions in any order. Put the guard in the expression itself.","sql":null}],"diagnostic":"-- Find candidate zero denominators in the columns your expression divides by.\nSELECT COUNT(*) FROM dbo.Ads WHERE Impressions = 0;\n-- On SQL Server 2012 and later, run the query with TRY_CAST-style protection removed and use the actual division to locate failing rows:\nSELECT KeyCol FROM dbo.Ads WHERE Impressions = 0 OR ImpressionShots = 0;\n-- Check the session settings, because with ARITHABORT OFF and ANSI_WARNINGS OFF division by zero returns NULL instead of erroring.\nSELECT name, value_in_use FROM sys.configurations\nWHERE name IN ('user options');\nSELECT @@OPTIONS & 64 AS ansi_warnings_on, @@OPTIONS & 128 AS arithabort_on;","alternatives":"NULLIF is the standard guard, but you can also pre-aggregate so the divisor is never a raw row value, or compute the ratio in a view once with the guard built in so callers can't forget it. On 2012+, IIF(Impressions = 0, NULL, Clicks * 1.0 / Impressions) reads more explicitly than NULLIF if that matters to your team.","details":[],"details_title":null,"repro":"SELECT 1 / 0;  -- Msg 8134","repro_note":null,"related":["sql-server/8115","postgresql/22012","oracle/ora-01476"],"sqlly":"Guard the divisor with NULLIF in SQLly's editor and rerun; the grid then shows NULLs where the division failed, and ISNULL around the expression closes the gap.","faqs":[{"question":"Why did my WHERE clause not stop the divide by zero?","answer":"SQL Server does not guarantee that a filter is evaluated before expressions in the select list. Row-level filters and expression order are optimized independently, so a zero row can still reach the division. Put NULLIF in the expression itself."},{"question":"Should the result be NULL or 0 when the divisor is zero?","answer":"NULL is usually the honest answer: a ratio with zero impressions is undefined, not zero percent. Wrap with ISNULL(..., 0) only when a consumer genuinely requires a number, such as a report cell that cannot show NULL."},{"question":"Can I turn divide-by-zero off globally?","answer":"With SET ARITHABORT OFF and SET ANSI_WARNINGS OFF, x/0 returns NULL, but this is fragile: those settings change plans, affect indexed view inserts, and any client with different settings behaves differently. Guarding the expression with NULLIF is the durable fix."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8134","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8144","corpus":"errors","engine":"sql-server","language":"en","title":"Too many arguments specified","description":"A call passed more arguments than the procedure or function defines, often because the code and the deployed procedure are different versions.","body":{"code":"8144","slug":"8144","name":null,"message":"Procedure or function %.*ls has too many arguments specified.","group":"objects","severity":16,"sql_state":null,"summary":"A call passed more arguments than the procedure or function defines, often because the code and the deployed procedure are different versions.","meaning":"SQL Server matches arguments to the parameters a procedure or function declares. If a call supplies more values than there are parameters, it fails with 8144. It usually means the caller expects a newer (or older) version of the procedure than the one in the database.","causes":["The application was updated to pass a new parameter, but the procedure change wasn't deployed to this database.","Calling a procedure with the same name in a different schema or database that has fewer parameters.","An extra comma-separated value in a hand-written `EXEC` call."],"fix":[{"text":"Check the parameters the procedure actually has.","sql":"SELECT name, TYPE_NAME(user_type_id) AS type_name, is_output\nFROM sys.parameters WHERE object_id = OBJECT_ID(N'dbo.SaveOrder') ORDER BY parameter_id;"},{"text":"Deploy the matching version of the procedure, or remove the extra arguments from the call.","sql":"EXEC dbo.SaveOrder @CustomerId = 42, @Total = 99.50;"},{"text":"Name arguments in calls (`@Param = value`), which makes mismatches obvious.","sql":null}],"diagnostic":"-- Compare what the caller passes with what the procedure declares. First list the real parameters.\nSELECT p.name, TYPE_NAME(p.user_type_id) AS type_name, p.is_output, p.has_default_value\nFROM sys.parameters p WHERE p.object_id = OBJECT_ID(N'dbo.SaveOrder') ORDER BY p.parameter_id;\n-- If several schemas or databases could hold a same-named procedure, check which one your connection resolves to.\nSELECT s.name AS schema_name, o.name, o.modify_date\nFROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id\nWHERE o.name = N'SaveOrder' AND o.type = 'P';\n-- A recent modify_date close to the app deploy often explains a version mismatch.","alternatives":"If you control the procedure, give the new parameter a default value so older callers keep working during a rollout: @Priority int = 1. If you don't control it, drop the extra argument until the procedure is deployed. Named arguments make these mismatches obvious immediately instead of positional guessing.","details":[],"details_title":null,"repro":"-- Scratch DB: a procedure with two parameters, called with three.\nCREATE DATABASE Scratch8144;\nGO\nUSE Scratch8144;\nGO\nCREATE PROCEDURE dbo.SaveOrder @CustomerId int, @Total decimal(10,2) AS SELECT @CustomerId, @Total;\nGO\nEXEC dbo.SaveOrder @CustomerId = 42, @Total = 99.50, @Priority = 1;  -- Msg 8144: Procedure or function SaveOrder has too many arguments specified.\nGO\nUSE master;\nDROP DATABASE Scratch8144;","repro_note":null,"related":["sql-server/8145","sql-server/8146","sql-server/2812","postgresql/42883","mysql/1318"],"sqlly":"Query sys.parameters in SQLly's grid to get the procedure's deployed signature, then fix the call in the editor to match it argument for argument.","faqs":[{"question":"The procedure definitely has that parameter on my dev machine. Why does prod fail?","answer":"The deploy didn't reach this database, or the caller is pointed at a copy with an older procedure version. Compare sys.parameters between environments and check modify_date; a missed migration is the usual culprit."},{"question":"Can I call with extra arguments that have defaults?","answer":"Defaults let you omit arguments, not add them. If you pass more arguments than the procedure declares, the call fails with 8144. If you pass a name the procedure doesn't declare while the argument count still fits, it fails with 8145 instead."},{"question":"How is 8144 different from 8145?","answer":"8144 is too many arguments by count; 8145 is a named argument that matches no parameter name. They often share the same root cause, a version mismatch, but 8145 usually means a typo or rename."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8144","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8145","corpus":"errors","engine":"sql-server","language":"en","title":"Is not a parameter for procedure","description":"A named argument (@Name = value) doesn't match any parameter of the procedure. Usually a typo or a version mismatch between code and database.","body":{"code":"8145","slug":"8145","name":null,"message":"%.*ls is not a parameter for procedure %.*ls.","group":"objects","severity":16,"sql_state":null,"summary":"A named argument (@Name = value) doesn't match any parameter of the procedure. Usually a typo or a version mismatch between code and database.","meaning":"When arguments are passed by name, each name must match one of the procedure's declared parameters. Error 8145 names the argument that isn't recognized.","causes":["A misspelled parameter name.","The parameter was renamed or removed in the deployed procedure, or hasn't been added yet.","Calling the wrong procedure of a similar name."],"fix":[{"text":"List the procedure's real parameter names.","sql":"SELECT name FROM sys.parameters WHERE object_id = OBJECT_ID(N'dbo.SaveOrder') ORDER BY parameter_id;"},{"text":"Correct the argument name or deploy the matching procedure version.","sql":null}],"diagnostic":"-- List the parameter names the procedure actually has and compare spelling, including case-insensitive typos like @CustomerID vs @CustomerId.\nSELECT p.name, TYPE_NAME(p.user_type_id) AS type_name\nFROM sys.parameters p WHERE p.object_id = OBJECT_ID(N'dbo.SaveOrder') ORDER BY p.parameter_id;\n-- Check whether a same-named procedure in another schema is being called by mistake.\nSELECT OBJECT_SCHEMA_NAME(OBJECT_ID(N'dbo.SaveOrder')) AS resolved_schema;\n-- If the parameter was renamed recently, the source control history for the procedure definition will show when.","alternatives":"Passing arguments positionally (EXEC dbo.SaveOrder 42) sidesteps name mismatches but hides typos and breaks when parameters are added, so it trades one failure for another. The durable options are fixing the name in the caller or adding a default-valued parameter so both old and new callers work during a deploy.","details":[],"details_title":null,"repro":"-- Scratch DB: pass a named argument the procedure doesn't declare.\nCREATE DATABASE Scratch8145;\nGO\nUSE Scratch8145;\nGO\nCREATE PROCEDURE dbo.SaveOrder @CustomerId int AS SELECT @CustomerId;\nGO\nEXEC dbo.SaveOrder @CustomerID = 42;  -- Msg 8145: The parameter @CustomerID is not a parameter for procedure SaveOrder.\nGO\nUSE master;\nDROP DATABASE Scratch8145;","repro_note":null,"related":["sql-server/8144","sql-server/8146","sql-server/2812"],"sqlly":"The grid output of sys.parameters or sp_helptext in SQLly's editor shows the parameter names as deployed, so the misspelled @Name in the call is a one-line fix.","faqs":[{"question":"Is parameter matching case-sensitive?","answer":"No, T-SQL identifiers follow the database's collation, so @CustomerID and @CustomerId are the same name on most servers. If you get 8145, the problem is almost never casing; it's a different word or a missing parameter."},{"question":"How is this different from error 8144?","answer":"8145 names a specific argument that matches no declared parameter; 8144 just says the call supplied too many arguments. Both usually trace back to the same thing: the code and the deployed procedure are different versions."},{"question":"Why does my ORM-generated call hit this after a deploy?","answer":"The model in the ORM still has the old or new parameter set while the database has the other one. Regenerate or update the model after the procedure deploy, and keep procedure definitions and ORM mappings in the same migration so they can't drift."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8145","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8146","corpus":"errors","engine":"sql-server","language":"en","title":"Procedure has no parameters","description":"Arguments were passed to a stored procedure that takes none. The caller and the deployed procedure don't agree on its definition.","body":{"code":"8146","slug":"8146","name":null,"message":"Procedure %.*ls has no parameters and arguments were supplied.","group":"objects","severity":16,"sql_state":null,"summary":"Arguments were passed to a stored procedure that takes none. The caller and the deployed procedure don't agree on its definition.","meaning":"A procedure declared without parameters can't accept any arguments. Passing one raises 8146, which usually means the procedure in this database is an older or different version than the caller expects.","causes":["Parameters were added to the procedure in development but not deployed here.","A procedure with the same name but no parameters exists in the schema being resolved."],"fix":[{"text":"Check the definition that is deployed.","sql":"EXEC sp_helptext 'dbo.RefreshCache';"},{"text":"Deploy the version with parameters, or call it without arguments.","sql":null}],"diagnostic":"-- Count the parameters the deployed procedure actually has\nSELECT p.name, COUNT(pa.parameter_id) AS parameter_count\nFROM sys.procedures AS p\nLEFT JOIN sys.parameters AS pa ON pa.object_id = p.object_id\nWHERE p.name = N'RefreshCache'\nGROUP BY p.name;\n-- Zero means the deployed copy has no parameters. Compare with\n-- sys.parameters in the environment where the call was written.\n-- Also check whether a synonym redirects the name somewhere else:\nSELECT name, base_object_name FROM sys.synonyms WHERE name = N'RefreshCache';","alternatives":"If the parameterless copy is stale, deploy the parameterized version from source control instead of editing the database by hand. If the caller is wrong, drop the argument from the call. A synonym pointing at another database's procedure can also explain a mismatch, so check sys.synonyms before redeploying.","details":[],"details_title":null,"repro":"-- Scratch DB repro: procedure without parameters, called with one\nCREATE PROCEDURE dbo.RefreshCache\nAS\nBEGIN\n    SET NOCOUNT ON;\n    SELECT 1 AS cache_ok;\nEND\nGO\n-- This call raises 8146: Procedure RefreshCache has no parameters and arguments were supplied.\nEXEC dbo.RefreshCache @Minutes = 30;\nGO\nDROP PROCEDURE dbo.RefreshCache;","repro_note":null,"related":["sql-server/8144","sql-server/8145"],"sqlly":"Compare the deployed definition with the call: sp_helptext in SQLly's grid shows the procedure as it exists on the server, which settles who is out of date, the code or the database.","faqs":[{"question":"The procedure has parameters on my dev server. Why does it fail in production?","answer":"The deployed definition in production is a different, older copy. SQL Server resolves the name to the procedure in the current database, and that copy was created without parameters. Deploy the current definition and the error goes away."},{"question":"Can I add a parameter to a procedure without dropping it?","answer":"Yes. ALTER PROCEDURE, or CREATE OR ALTER PROCEDURE, replaces the definition in place, so you don't have to drop it first. Include the full parameter list in that statement, because the list you write becomes the procedure's parameter list. A plain CREATE PROCEDURE on an existing name fails with error 2714, \"There is already an object named '...' in the database.\""}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8146","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8152","corpus":"errors","engine":"sql-server","language":"en","title":"String or binary data truncated","description":"A value is longer than the column it's going into, so SQL Server stops the INSERT or UPDATE instead of cutting it. Newer versions name the column (2628).","body":{"code":"8152","slug":"8152","name":null,"message":"String or binary data would be truncated.","group":"data","severity":16,"sql_state":null,"summary":"A value is longer than the column it's going into, so SQL Server stops the INSERT or UPDATE instead of cutting it. Newer versions name the column (2628).","meaning":"With the default SET ANSI_WARNINGS ON, SQL Server won't silently shorten data; with SET ANSI_WARNINGS OFF an INSERT or UPDATE truncates without error. If a string or binary value is longer than the target column, for example 60 characters into a `varchar(50)`, the statement fails. Error 8152 doesn't say which column or row; that made it hard to debug, so SQL Server 2019 introduced error 2628, which names the table, column and the truncated value. 2628 is the default only at database compatibility level 150 and above; below that, 8152 is still raised.","causes":["Data longer than the column's declared length, often from user input or an import.","A column that is too narrow for real data, such as `nvarchar(50)` for e-mail addresses or names.","An `INSERT ... SELECT` whose columns are in a different order than the target's column list, so a long column lands in a short one.","A variable declared longer than the column it is inserted into, such as a `varchar(20)` variable inserted into a `varchar(3)` column. A variable declared too short truncates silently on assignment and the INSERT still succeeds."],"fix":[{"text":"On SQL Server 2019 and later, get error 2628 with the column and value instead. It is ON by default, but it only changes the error at database compatibility level 150 and above. At level 140 or lower the error stays 8152.","sql":"ALTER DATABASE SCOPED CONFIGURATION SET VERBOSE_TRUNCATION_WARNINGS = ON;"},{"text":"Compare the source lengths with the target columns to find the culprit.","sql":"SELECT MAX(LEN(Email)) AS max_email, MAX(LEN(Name)) AS max_name FROM staging.Customers;\nSELECT name, max_length, TYPE_NAME(user_type_id) AS type_name\nFROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.Customers');"},{"text":"Widen the column if the data is legitimate.","sql":"ALTER TABLE dbo.Customers ALTER COLUMN Email nvarchar(320) NOT NULL;"},{"text":"Or shorten on purpose where truncation is acceptable.","sql":"INSERT INTO dbo.Notes (Summary) SELECT LEFT(Body, 200) FROM staging.Notes;"},{"text":"Always name the target columns in `INSERT ... SELECT` so the order can't drift.","sql":null}],"diagnostic":"-- Which column is too narrow? Compare the widest source value with each target width\nSELECT c.name, c.max_length, TYPE_NAME(c.user_type_id) AS type_name\nFROM sys.columns AS c\nWHERE c.object_id = OBJECT_ID(N'dbo.Customers');\nSELECT MAX(LEN(Email)) AS max_email_len, MAX(LEN(Name)) AS max_name_len\nFROM staging.Customers;\n-- On 2019+ (compat level 150+) error 2628 names the column by default. On 2016 SP2 CU6+ and 2017 CU12+ the same detail is available behind trace flag 460:\n-- DBCC TRACEON(460);","alternatives":"Where truncation is acceptable, cut on purpose with LEFT(col, n) or CAST to the target type so the intent is visible in the code. For imports, pre-check the source with MAX(LEN()) per column and widen the table before the load instead of letting the batch fail halfway.","details":[],"details_title":null,"repro":"CREATE TABLE #t (code varchar(3));\nINSERT INTO #t VALUES ('ABCD');  -- 2628 at compatibility level 150+ (SQL Server 2019+); 8152 at level 140 or lower\nDROP TABLE #t;","repro_note":null,"related":["sql-server/2628","sql-server/245","postgresql/22001","mysql/1406","oracle/ora-12899"],"sqlly":"When SQLly's CSV import creates a new table, its `CREATE TABLE` script sizes each text column from the longest value in the file, rounded up to `NVARCHAR(50)`, `NVARCHAR(255)`, `NVARCHAR(1000)` or `NVARCHAR(MAX)`, so the imported rows fit.","faqs":[{"question":"How do I find which column is being truncated?","answer":"On SQL Server 2019 or later at compatibility level 150, the error becomes 2628 and names the table, column and value. On older versions, compare MAX(LEN(...)) of each source column with the target column lengths."},{"question":"Can I make SQL Server truncate silently instead?","answer":"SET ANSI_WARNINGS OFF makes inserts truncate without error, but it also changes other behavior and isn't allowed with indexed views or computed column indexes. Prefer an explicit LEFT() where truncation is intended."},{"question":"The error gives no clue which column overflowed. How do I find it?","answer":"On SQL Server 2019 or later you should get error 2628 with the column and value instead, either by default at compat level 150+ or with VERBOSE_TRUNCATION_WARNINGS = ON. On 2016 SP2 CU6+ and 2017 CU12+ enable trace flag 460. Otherwise compare MAX(LEN()) of the source against sys.columns.max_length column by column."},{"question":"Why does SET on a variable truncate silently, while an INSERT of a too-long variable fails?","answer":"Assignment to a variable truncates without error, and an INSERT of that already-truncated variable succeeds, so a too-short variable hides the problem. Error 8152/2628 appears only when a variable (or expression) longer than the target column is inserted."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8152","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8169","corpus":"errors","engine":"sql-server","language":"en","title":"Conversion to uniqueidentifier failed","description":"A string converted to uniqueidentifier isn't a valid GUID: wrong length, stray characters, or an empty string.","body":{"code":"8169","slug":"8169","name":null,"message":"Conversion failed when converting from a character string to uniqueidentifier.","group":"data","severity":16,"sql_state":null,"summary":"A string converted to uniqueidentifier isn't a valid GUID: wrong length, stray characters, or an empty string.","meaning":"A `uniqueidentifier` string must be in the `8-4-4-4-12` hyphenated form (36 characters), optionally wrapped in braces (38 characters). A bare 32-digit string fails to convert with 8169, and so do an empty string, a string with leading spaces or quotes, or a string shorter than 36 characters. Characters after the 36th, including trailing spaces, are ignored rather than rejected.","causes":["Empty strings or placeholder text in a column of GUIDs stored as `varchar`.","Comparing a `uniqueidentifier` column with a string that isn't a GUID, which forces a conversion of the string.","GUIDs with extra characters, such as quotes or whitespace copied along with the value."],"fix":[{"text":"Find the values that aren't valid GUIDs.","sql":"SELECT RawId FROM staging.Items WHERE TRY_CONVERT(uniqueidentifier, RawId) IS NULL AND RawId IS NOT NULL;"},{"text":"Convert empty strings to NULL before converting.","sql":"SELECT TRY_CONVERT(uniqueidentifier, NULLIF(LTRIM(RTRIM(RawId)), '')) FROM staging.Items;"}],"diagnostic":"-- List the values that fail the GUID format check before converting anything.\nSELECT RawId, LEN(RawId) AS length\nFROM staging.Items\nWHERE TRY_CONVERT(uniqueidentifier, NULLIF(LTRIM(RTRIM(RawId)), '')) IS NULL\n  AND RawId IS NOT NULL;\n-- Check the actual length distribution; valid hyphenated GUIDs are 36 characters and braced ones 38; a bare 32-digit value fails the conversion.\nSELECT LEN(RawId) AS length, COUNT(*) AS rows FROM staging.Items GROUP BY LEN(RawId) ORDER BY length;\n-- If a uniqueidentifier column is being compared to a string parameter, confirm which column forces the conversion.\nSELECT c.name, t.name AS type_name FROM sys.columns c JOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID(N'dbo.Items') AND t.name = 'uniqueidentifier';","alternatives":"Use TRY_CONVERT or TRY_CAST, which return NULL instead of raising on bad input, available since SQL Server 2012. For bulk loads, clean the staging column with NULLIF and TRIM first, or convert in a separate flagged step so bad rows are rejected with a report rather than aborting the load.","details":[],"details_title":null,"repro":"SELECT CAST('not-a-guid' AS uniqueidentifier);  -- Msg 8169","repro_note":null,"related":["sql-server/245","sql-server/8114","postgresql/22P02"],"sqlly":"Isolate the bad values from SQLly's editor with TRY_CONVERT(uniqueidentifier, the_column); the grid lists them, and the row count tells you whether this is one typoed row or a load gone wrong.","faqs":[{"question":"What exactly counts as a valid uniqueidentifier string?","answer":"The 8-4-4-4-12 hyphenated form (36 characters), optionally wrapped in braces. A bare 32-digit string fails. NULL is fine; an empty string itself fails the conversion, which surprises people loading CSV files where blanks became empty strings."},{"question":"Can I convert between uniqueidentifier and binary?","answer":"Yes, a uniqueidentifier converts to and from binary(16). Some teams store GUIDs as binary(16) for storage size; note the byte ordering of a GUID string does not match its binary layout in a way useful for sorting."},{"question":"Why does my lookup fail only for one row?","answer":"Almost always one bad value: a truncated GUID, quotes or leading spaces pasted along with it, or an empty string in an otherwise GUID-shaped column. List the failures with TRY_CONVERT before fixing the query."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8169","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8178","corpus":"errors","engine":"sql-server","language":"en","title":"Parameterized query expects a parameter","description":"A parameterized query (sp_executesql) declares a parameter that the call didn't supply, usually a NULL value the client library left out.","body":{"code":"8178","slug":"8178","name":null,"message":"The parameterized query '%.*ls' expects the parameter '%.*ls', which was not supplied.","group":"objects","severity":16,"sql_state":null,"summary":"A parameterized query (sp_executesql) declares a parameter that the call didn't supply, usually a NULL value the client library left out.","meaning":"Client libraries send parameterized SQL through `sp_executesql` with a list of declared parameters and their values. If a declared parameter has no value, SQL Server raises 8178. In .NET a classic cause is setting a parameter's value to `null`, which means \"not supplied\"; a database NULL must be `DBNull.Value`.","causes":["A parameter value of `null` in ADO.NET instead of `DBNull.Value`.","A parameter declared in the SQL text but never added to the command.","A mismatch between parameter names in the SQL and those added to the command."],"fix":[{"text":"Pass `DBNull.Value` for NULLs in ADO.NET, or let the library do it (for example Dapper converts `null` for you).","sql":null},{"text":"Make sure every `@parameter` in the SQL text has a value, with matching names.","sql":null},{"text":"In T-SQL, supply every declared parameter.","sql":"EXEC sys.sp_executesql\n    N'SELECT * FROM dbo.Orders WHERE CustomerId = @c AND Status = @s',\n    N'@c int, @s varchar(20)',\n    @c = 42, @s = NULL;"}],"diagnostic":"-- The message names the missing parameter. Compare it with what was actually sent: enable sp_executesql capture briefly with a SQL Trace / Extended Events session on rpc_completed and read the statement field plus the parameter assignments.\nCREATE EVENT SESSION [cap] ON SERVER\nADD EVENT sqlserver.rpc_completed (ACTION(sqlserver.client_app_name))\nADD TARGET package0.ring_buffer;\nALTER EVENT SESSION [cap] ON SERVER STATE = START;\n-- Run the failing operation, then inspect the session data and drop it:\nALTER EVENT SESSION [cap] ON SERVER STATE = STOP;\nDROP EVENT SESSION [cap] ON SERVER;\n-- On the code side, list the parameters the command actually has (the pattern below is C#, for reference):\n-- foreach (var p in cmd.Parameters) Console.WriteLine(p.ParameterName);","alternatives":"A stored procedure call enforces the same rule but raises a different error: an omitted parameter gives 201 (\"Procedure or function '<name>' expects parameter '@s', which was not supplied.\"), not 8178. Passing @s = NULL explicitly is accepted. If the code may legitimately omit parameters, build the parameter list and the SQL text from the same source so they cannot drift, or use a library that maps C# null to DBNull automatically.","details":[],"details_title":null,"repro":"Plain T-SQL reproduces it: EXEC sys.sp_executesql N'SELECT @a AS a, @b AS b', N'@a int, @b int', @a = 1; raises 8178 at severity 16 because @b is declared but not supplied. Passing @b = NULL is accepted, since a NULL is a supplied value.","repro_note":null,"related":["sql-server/8144","sql-server/8145"],"sqlly":"For a stored procedure call, sys.parameters lists its declared parameters, so compare those with the call. An ad-hoc sp_executesql batch has no catalog object, so compare the declaration string passed as @params with the values actually supplied.","faqs":[{"question":"Why does null fail but DBNull.Value works?","answer":"In ADO.NET, a C# null parameter value means the parameter was never supplied, so it is not sent to SQL Server at all. DBNull.Value is the representation of a database NULL and gets sent."},{"question":"Does this affect Dapper or Entity Framework?","answer":"Both translate C# null into DBNull for you, so the error usually points at hand-written DbCommand code or a parameter name that does not match the SQL text."},{"question":"Can I reproduce it in plain T-SQL?","answer":"Yes. Leave a declared parameter out of the call, for example EXEC sys.sp_executesql N'SELECT @a AS a, @b AS b', N'@a int, @b int', @a = 1;, and SQL Server raises 8178 at severity 16. Passing @b = NULL instead is accepted, because NULL is a supplied value."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8178","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/823","corpus":"errors","engine":"sql-server","language":"en","title":"Operating system returned an I/O error","description":"Windows or Linux reported an error when SQL Server read or wrote a database file. Treat it as a storage failure and check database integrity.","body":{"code":"823","slug":"823","name":null,"message":"The operating system returned error %ls to SQL Server during a %S_MSG at offset %#016I64x in file '%ls'. Additional messages in the SQL Server error log and operating system error log may provide more detail. This is a severe system-level error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.","group":"integrity","severity":24,"sql_state":null,"summary":"Windows or Linux reported an error when SQL Server read or wrote a database file. Treat it as a storage failure and check database integrity.","meaning":"Error 823 means the read or write call itself failed at the operating system level, and the message includes the OS error code. Unlike 824, where data came back but was wrong, here the I/O request didn't complete. It is severity 24 and threatens database integrity.","causes":["Disk or storage hardware failures, bad sectors, or a disconnected SAN or network volume.","Driver or firmware problems in the storage stack.","The volume holding the files went offline or was dismounted."],"fix":[{"text":"Check the operating system and hardware logs for disk errors at the same time.","sql":null},{"text":"Run a consistency check once storage is stable.","sql":"DBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS, ALL_ERRORMSGS;"},{"text":"Restore damaged pages or the database from backup if CHECKDB reports errors, and move the database to healthy storage.","sql":null}],"diagnostic":"-- Confirm which file failed and when, from the error log. The 823 message names the file, offset and OS error code.\nEXEC xp_readerrorlog 0, 1, N'823';\n-- Check that the database files are where SQL Server expects them and whether any volume is missing.\nSELECT name, physical_name, type_desc, state_desc, size * 8 / 1024 AS size_mb\nFROM sys.database_files;\n-- Once storage is stable, check whether any pages were damaged.\nDBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS, ALL_ERRORMSGS;","alternatives":"There is no workaround for failed storage; the fix is on the hardware side. What you can change is your exposure: alerts on error 823 and 825, verified backups, and moving data and log files onto separate healthy volumes.","details":[],"details_title":null,"repro":"-- Error 823 is a real storage failure. You cannot trigger it with T-SQL alone.\n-- The closest safe drill is a restore drill: prove you can recover instead of trying to break a disk.\n-- 1. Confirm you have a recent full backup.\nSELECT database_name, type, backup_finish_date\nFROM msdb.dbo.backupset\nWHERE database_name = DB_NAME()\nORDER BY backup_finish_date DESC;\n-- 2. Restore that backup to a scratch database and run CHECKDB on it, so you know the recovery path works before you ever need it.","repro_note":null,"related":["sql-server/824","sql-server/825","sql-server/9001","sqlite/sqlite-ioerr"],"sqlly":"SQLly's grid makes the history easy to share: run the xp_readerrorlog search and copy the results out for whoever owns the storage, before you run CHECKDB.","faqs":[{"question":"Can I just run CHECKDB with REPAIR_ALLOW_DATA_LOSS and move on?","answer":"Only after storage is fixed and backups are confirmed. Repair deletes data when it can't rebuild it, so if the disk is still failing you can lose more. Backup restore plus repair is the safe order."},{"question":"The error happened once and hasn't come back. Ignore it?","answer":"No. A single 823 is often the first sign of a dying disk or flaky path. Check hardware logs and run DBCC CHECKDB; treat silence afterward with suspicion."},{"question":"Does an 823 on the log file differ from one on a data file?","answer":"Both are storage failures, but a log 823 (often followed by 9001 or 9004) can block all writes to the database and can make tail-of-log backup impossible, so it is usually the more urgent case."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/823","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/824","corpus":"errors","engine":"sql-server","language":"en","title":"Logical consistency-based I/O error","description":"A page read from disk failed SQL Server's checks (bad checksum, torn page, wrong page ID). This is database corruption: run DBCC CHECKDB now.","body":{"code":"824","slug":"824","name":null,"message":"SQL Server detected a logical consistency-based I/O error: %ls. It occurred during a %S_MSG of page %S_PGID in database ID %d at offset %#016I64x in file '%ls'. Additional messages in the SQL Server error log or operating system error log may provide more detail. This is a severe error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see https://go.microsoft.com/fwlink/?linkid=2252374.","group":"integrity","severity":24,"sql_state":null,"summary":"A page read from disk failed SQL Server's checks (bad checksum, torn page, wrong page ID). This is database corruption: run DBCC CHECKDB now.","meaning":"SQL Server verifies each page as it reads it, using the page checksum (or torn-page detection) and the page header. Error 824 means the read itself succeeded but the content is wrong: the data on disk is damaged. It is a severity 24 error, written to the error log, and the page is recorded in `msdb.dbo.suspect_pages`. The usual cause is the storage stack (disk, controller, drivers, SAN), not SQL Server.","causes":["Faulty disks, controllers, firmware or storage drivers writing or returning bad data.","Power loss or a storage failure in the middle of a write without write-through protection.","File system filter drivers (antivirus, backup tools) interfering with database files.","Memory errors on the server corrupting pages before they were written."],"fix":[{"text":"Run a full consistency check to see the extent of the damage.","sql":"DBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS, ALL_ERRORMSGS;"},{"text":"See which pages were flagged.","sql":"SELECT * FROM msdb.dbo.suspect_pages;"},{"text":"The safe fix is restoring from backup. With the full recovery model and an unbroken log chain you can restore just the damaged pages.","sql":"RESTORE DATABASE SalesDb PAGE = '1:57' FROM DISK = N'D:\\Backup\\SalesDb.bak' WITH NORECOVERY;\n-- then restore subsequent log backups, back up the tail of the log, and restore it WITH RECOVERY"},{"text":"Check the storage: Windows event logs, hardware diagnostics, firmware and driver versions. Corruption comes back if the cause isn't fixed.","sql":null},{"text":"`DBCC CHECKDB ... REPAIR_ALLOW_DATA_LOSS` is a last resort when no backup exists, because it deletes whatever it can't repair.","sql":null}],"diagnostic":"-- Start with a full consistency check; it maps every damaged allocation:\nDBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS, ALL_ERRORMSGS;\n\n-- Which pages are already flagged, and when:\nSELECT DB_NAME(database_id) AS database_name, file_id, page_id,\n       error_type, last_update_date\nFROM msdb.dbo.suspect_pages\nWHERE database_id = DB_ID(N'SalesDb');\n\n-- How many 824s, and do they grow? Growing means the storage fault is live:\nEXEC sys.sp_readerrorlog 0, 1, N'824';\n\n-- Check the page checksum setting (WITH CHECKSUM backups and PAGE_VERIFY):\nSELECT name, page_verify_option_desc\nFROM sys.databases WHERE name = N'SalesDb';\n\n-- One object or many? CHECKDB output names the table and index per error.\n-- Damage confined to one index can be repaired by rebuilding that index\n-- offline after confirming the pages read clean on a retry.","alternatives":"With a good backup chain, restore the damaged pages (RESTORE ... PAGE = 'file:page') plus subsequent log backups, which needs the full recovery model. Without one, extract what you can to a new database (BCP out tables that read clean) before any REPAIR_ALLOW_DATA_LOSS run, since that repair deletes rows and can drop whole objects.","details":[],"details_title":null,"repro":"-- Real 824s need genuinely corrupt storage, which you must never fake on a server you keep.\n-- The safe drill proves the recovery path instead of the failure:\n-- 1. Confirm a recent full backup exists.\nSELECT TOP (5) type, backup_finish_date FROM msdb.dbo.backupset\nWHERE database_name = DB_NAME() ORDER BY backup_finish_date DESC;\n-- 2. RESTORE it as a scratch database (WITH MOVE) and run DBCC CHECKDB on the copy,\n--    so the day a real 824 lands you already know restore + CHECKDB works end to end.","repro_note":null,"related":["sql-server/823","sql-server/825","sql-server/9001","postgresql/XX001","sqlite/sqlite-corrupt"],"sqlly":"From SQLly's editor, run CHECKDB and the suspect_pages query in tabs; the grid results make the damaged page list easy to copy out for the storage team.","faqs":[{"question":"Is error 824 a SQL Server bug?","answer":"Almost never. SQL Server is reporting that the page it read doesn't match what it wrote, which points to the I/O path: storage hardware, drivers or filter drivers."},{"question":"Can I keep running on a database with 824 errors?","answer":"Only the pages that fail reads are suspect (some may be fine), so the database often stays up, but every query touching them fails and the damage can spread if the storage fault is ongoing. Restore from backup as soon as you have identified the affected objects."},{"question":"Does rebuilding the index fix the corruption?","answer":"Sometimes, if the damaged pages belong to a nonclustered index and the underlying table reads clean: rebuilding rewrites the index from the table. It does nothing for clustered index or data-page corruption, and CHECKDB output tells you which case you have."},{"question":"Torn pages versus checksums: which should I use?","answer":"CHECKSUM. It is the default for new databases and catches far more than torn-page detection. Set PAGE_VERIFY CHECKSUM if the database is on TORN_PAGE_DETECTION or NONE. Pages receive their checksum when they are next written to disk, not when a backup runs, so the protection builds up as data is written."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/824","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/825","corpus":"errors","engine":"sql-server","language":"en","title":"Read retry succeeded after failing","description":"A read failed and then succeeded on retry. Nothing failed for the user yet, but it's an early warning of failing storage.","body":{"code":"825","slug":"825","name":null,"message":"A read of the file '%ls' at offset %#016I64x succeeded after failing %d time(s) with error: %ls. Additional messages in the SQL Server error log and operating system error log may provide more detail. This error condition threatens database integrity and must be corrected. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.","group":"integrity","severity":10,"sql_state":null,"summary":"A read failed and then succeeded on retry. Nothing failed for the user yet, but it's an early warning of failing storage.","meaning":"When a read fails with an 823 or 824 condition, SQL Server retries it up to four times. If a retry succeeds, the query continues and SQL Server logs 825 at severity 10. Users don't see an error, which makes 825 easy to miss, but it means the storage is returning errors and real 823/824 failures may follow.","causes":["Disks or storage paths that are beginning to fail.","Intermittent driver, firmware or network storage problems."],"fix":[{"text":"Set up an alert for error 825 so it isn't missed.","sql":"EXEC msdb.dbo.sp_add_alert @name = N'Error 825 - read retry', @message_id = 825, @severity = 0, @include_event_description_in = 1;"},{"text":"Run `DBCC CHECKDB` and investigate the storage before it gets worse.","sql":"DBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS;"},{"text":"Make sure recent backups exist and are restorable.","sql":null}],"diagnostic":"-- See whether this server has logged 825s and when they started.\nEXEC xp_readerrorlog 0, 1, N'825';\nEXEC xp_readerrorlog 1, 1, N'825';\n-- If retries point at one file, look at that file's volume; if they are spread out, suspect a shared component like a controller or SAN path.\nSELECT name, physical_name, type_desc FROM sys.database_files;\n-- Then run a full consistency check to confirm no page was returned damaged.\nDBCC CHECKDB (N'SalesDb') WITH NO_INFOMSGS, ALL_ERRORMSGS;","alternatives":"There is no application-side workaround because nothing has failed yet. The useful alternative is monitoring: an alert on message 825 turns this quiet warning into a page before it becomes an 823.","details":[],"details_title":null,"repro":"-- Error 825 requires failing storage, so it cannot be reproduced with T-SQL on a healthy system.\n-- Read retry is built in (SQL Server 2005+): up to four retries per failed read, an 825\n-- logged at severity 10 when a retry succeeds, an 823 or 824 when none do. There is no\n-- configuration option or trace flag to turn it on; do not go looking for one.\n-- What is worth drilling instead: confirm an alert exists so a retry is never silently missed.\nSELECT name FROM msdb.dbo.sysalerts WHERE message_id = 825;","repro_note":null,"related":["sql-server/824","sql-server/823"],"sqlly":"An 825 appears in SQLly's output with its full text and severity, and a query against msdb.dbo.alerts in the grid confirms an alert actually exists to catch the next one.","faqs":[{"question":"The retry succeeded, so is anything actually wrong?","answer":"Something is wrong. A healthy disk doesn't need retries. The data is fine this time, but Microsoft notes the disk problem could cause data loss or database corruption if it is not resolved."},{"question":"How many retries does SQL Server do?","answer":"Up to four retries on a failed read. If all of them fail you get an 823 or 824 instead; if any succeeds you get an 825 logged at severity 10."},{"question":"Should I alert on 825 even though it's severity 10?","answer":"Yes. This is one of the few low-severity errors that deserves an alert, because it predicts a real outage. Paul Randal treats it as an early failure signal, since it is the only notification of a read retry."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/825","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8623","corpus":"errors","engine":"sql-server","language":"en","title":"Query processor ran out of resources","description":"The optimizer gave up building a plan, usually for a query with a huge IN list, thousands of UNIONs or very deeply nested expressions.","body":{"code":"8623","slug":"8623","name":null,"message":"The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.","group":"resources","severity":16,"sql_state":null,"summary":"The optimizer gave up building a plan, usually for a query with a huge IN list, thousands of UNIONs or very deeply nested expressions.","meaning":"Error 8623 means the query was too complex for the optimizer to compile, not that data was too large. It is typically caused by generated SQL: an `IN (...)` list with tens of thousands of values, a very long chain of `OR` or `UNION ALL`, or many tables and partitions in one statement.","causes":["An ORM or application building `WHERE id IN (...)` with a very large list of literals or parameters.","Thousands of `UNION ALL` branches or `OR` conditions generated in a loop.","Queries over views nested many levels deep that expand to a very large number of tables."],"fix":[{"text":"Load the values into a temp table or table-valued parameter and join to it.","sql":"CREATE TABLE #ids (id int PRIMARY KEY);\nINSERT INTO #ids (id) VALUES (1), (2), (3);  -- or bulk insert / TVP\nSELECT o.* FROM dbo.Orders AS o JOIN #ids AS i ON i.id = o.OrderId;"},{"text":"Pass a delimited list and split it on the server.","sql":"SELECT o.* FROM dbo.Orders AS o\nJOIN STRING_SPLIT(@idList, ',') AS s ON o.OrderId = CAST(s.value AS int);"},{"text":"Simplify deeply nested views, or materialize intermediate results into temp tables.","sql":null}],"diagnostic":"-- How big is the statement actually getting? Length and token count of the batch:\nSELECT LEN(@sql);  -- run in the app context, or log it from the application side\n\n-- If the failure comes from a view, count what it expands to:\nSELECT COUNT(*) AS table_count\nFROM sys.sql_expression_dependencies\nWHERE referencing_id = OBJECT_ID(N'dbo.MyDeepView');\n\n-- Catch the failing batch: extended events or the error log record the text\n-- around the 8623. In the app, log the generated SQL before sending it;\n-- the IN-list count is usually obvious there.","alternatives":"Table-valued parameters avoid string building entirely and stay under the complexity limits at far larger sizes. For ORMs, most have a batching option that splits huge IN lists into chunks of a few thousand.","details":[],"details_title":null,"repro":"-- An IN list this large is enough on most builds:\nDECLARE @sql nvarchar(max) = N'SELECT COUNT(*) FROM dbo.Orders WHERE OrderId IN (';\nDECLARE @i int = 1;\nWHILE @i <= 50000\nBEGIN\n    SET @sql = @sql + CASE WHEN @i > 1 THEN N',' ELSE N'' END + CAST(@i AS nvarchar(10));\n    SET @i = @i + 1;\nEND\nSET @sql = @sql + N')';\nEXEC sys.sp_executesql @sql;\n-- The exact list size that fails varies with the rest of the query and the\n-- SQL Server version, so scale the count down until it compiles.\n\n-- Scratch setup for the query itself:\n-- CREATE TABLE dbo.Orders (OrderId int PRIMARY KEY, CustomerID int);","repro_note":null,"related":["sql-server/701","sql-server/8645"],"sqlly":"SQLly's editor runs the reworked query, temp table instead of a thousand-item IN list, in the same tab, and the execution plan view shows the simpler plan the optimizer can actually build.","faqs":[{"question":"Is there a hard limit on the number of values in an IN list?","answer":"No documented number. The limit is on optimizer complexity, so it depends on the whole statement: joins, subqueries, and view expansion all count. The same 10,000 values that fail in one query may compile in another."},{"question":"Does a temp table join perform worse than the IN list?","answer":"Usually the opposite at this scale. A join to an indexed temp table gives the optimizer a real cardinality estimate, and the plan survives plan cache reuse. A giant literal list bloats the batch and the plan."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8623","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8645","corpus":"errors","engine":"sql-server","language":"en","title":"Timeout waiting for memory resources","description":"A query waited too long for a memory grant to run its sorts or hashes and gave up. Too many large queries are competing for workspace memory.","body":{"code":"8645","slug":"8645","name":null,"message":"A timeout occurred while waiting for memory resources to execute the query in resource pool '%ls' (%ld). Rerun the query.","group":"resources","severity":17,"sql_state":null,"summary":"A query waited too long for a memory grant to run its sorts or hashes and gave up. Too many large queries are competing for workspace memory.","meaning":"Before running, queries that sort or hash ask for a memory grant. If not enough memory is free, they wait in a queue (the `RESOURCE_SEMAPHORE` wait type). When the wait exceeds the query's grant timeout, it fails with 8645. The usual root cause is a few queries asking for far more memory than they need.","causes":["Several concurrent queries with large memory grants, often from bad cardinality estimates.","Missing indexes that force large sorts or hash joins.","A low `max server memory` setting or a Resource Governor limit."],"fix":[{"text":"See who is waiting for and who is holding memory grants.","sql":"SELECT session_id, requested_memory_kb, granted_memory_kb, wait_time_ms, query_cost\nFROM sys.dm_exec_query_memory_grants ORDER BY requested_memory_kb DESC;"},{"text":"Tune the queries with the biggest grants: add indexes that remove sorts, update statistics, avoid `SELECT *` with wide columns in sorted results.","sql":null},{"text":"Cap per-query grants with a hint as a stopgap (SQL Server 2012 SP3 and later).","sql":"SELECT * FROM dbo.BigTable ORDER BY SomeColumn OPTION (MAX_GRANT_PERCENT = 10);"}],"diagnostic":"-- Who is waiting for a grant and how long:\nSELECT session_id, requested_memory_kb, granted_memory_kb,\n       wait_time_ms, dop, plan_handle\nFROM sys.dm_exec_query_memory_grants\nORDER BY requested_memory_kb DESC;\n\n-- The SQL text behind each waiting session:\nSELECT r.session_id, t.text, r.wait_type, r.wait_time\nFROM sys.dm_exec_requests r\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t\nWHERE r.wait_type = 'RESOURCE_SEMAPHORE';\n\n-- Historical grant waits, to tell chronic pressure from a one-off:\nSELECT wait_type, waiting_tasks_count, wait_time_ms, max_wait_time_ms\nFROM sys.dm_os_wait_stats\nWHERE wait_type IN ('RESOURCE_SEMAPHORE', 'RESOURCE_SEMAPHORE_QUERY_COMPILE');\n\n-- Resource Governor check: a workload group cap also causes this.\nSELECT group_id, name, request_max_memory_grant_percent\nFROM sys.resource_governor_workload_groups;","alternatives":"Run heavy reports outside peak hours, or route them to a readable secondary with an AG. Resource Governor can cap grant sizes for a specific workload group if you cannot change the queries.","details":[],"details_title":null,"repro":"-- Simulate memory pressure: lower max server memory so grants queue up.\nEXEC sp_configure 'show advanced options', 1; RECONFIGURE;\nEXEC sp_configure 'max server memory', 1024; RECONFIGURE;\n\n-- Large sorts in parallel from several sessions can then hit the grant queue.\n-- Run this from several concurrent connections on a copy of a wide table:\nSELECT CustomerID, COUNT(*)\nFROM dbo.Orders\nGROUP BY CustomerID\nORDER BY COUNT(*) DESC\nOPTION (MAXDOP 4);\n\n-- Watch the queue while they run:\nSELECT session_id, wait_type, wait_time\nFROM sys.dm_exec_requests\nWHERE wait_type LIKE 'RESOURCE_SEMAPHORE%';\n\n-- Clean up:\nEXEC sp_configure 'max server memory', 2147483647; RECONFIGURE;\n-- On a small test box a single big sort may fail with 8645 once the grant\n-- timeout is exceeded; on a box with lots of RAM it may take reduced memory\n-- pressure to see the wait at all.","repro_note":null,"related":["sql-server/701","sql-server/8623"],"sqlly":"SQLly's execution plan view flags table scans, missing indexes and estimates that diverge from actual row counts, the usual reasons behind oversized memory grants.","faqs":[{"question":"Why does a query ask for gigabytes of memory to sort a few million rows?","answer":"The estimate is wrong. If SQL Server thinks the sort will see far more rows or much wider rows than it does, it requests a matching grant. Stale statistics or parameter sniffing are the usual reasons for a wrong estimate."},{"question":"Does the query fail immediately?","answer":"No. It first queues as a RESOURCE_SEMAPHORE wait. 8645 only fires when the wait outlasts the query's grant timeout, which grows with the query cost. The failed wait is often minutes after the query started."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8645","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/8672","corpus":"errors","engine":"sql-server","language":"en","title":"MERGE touched the same row twice","description":"In a MERGE, one target row matched more than one source row, so it would be updated twice. Make the source unique on the join key.","body":{"code":"8672","slug":"8672","name":null,"message":"The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.","group":"syntax","severity":16,"sql_state":null,"summary":"In a MERGE, one target row matched more than one source row, so it would be updated twice. Make the source unique on the join key.","meaning":"`MERGE` requires that each target row match at most one source row when a `WHEN MATCHED THEN UPDATE` action applies. If the `ON` condition lets two source rows match the same target row, SQL Server can't decide which update to apply and fails with 8672. A `WHEN MATCHED THEN DELETE` with duplicate matches does not raise 8672 on SQL Server 2022 (RTM-CU28); the target row is deleted once.","causes":["Duplicate keys in the source table or staging data.","An `ON` clause that doesn't cover the full key, such as joining on customer only when the key is customer plus date."],"fix":[{"text":"Find the duplicate keys in the source.","sql":"SELECT CustomerId, COUNT(*) FROM staging.Customers GROUP BY CustomerId HAVING COUNT(*) > 1;"},{"text":"Deduplicate the source in a CTE before merging, keeping the row you want.","sql":"WITH src AS (\n    SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY UpdatedAt DESC) AS rn\n    FROM staging.Customers\n)\nMERGE dbo.Customers AS t\nUSING (SELECT * FROM src WHERE rn = 1) AS s ON t.CustomerId = s.CustomerId\nWHEN MATCHED THEN UPDATE SET t.Name = s.Name\nWHEN NOT MATCHED THEN INSERT (CustomerId, Name) VALUES (s.CustomerId, s.Name);"},{"text":"Make the `ON` condition match the full key.","sql":null}],"diagnostic":"-- Which join keys are duplicated in the source?\nSELECT s.CustomerId, COUNT(*) AS source_rows\nFROM staging.Customers AS s\nGROUP BY s.CustomerId\nHAVING COUNT(*) > 1;\n-- Only a duplicated key that also exists in the target hits the same target\n-- row twice (with WHEN MATCHED UPDATE). Also check the ON clause: if the real key\n-- is (CustomerId, OrderDate) but you join on CustomerId alone, a customer with\n-- two orders triggers the error, because CustomerId alone is not unique in the table.","alternatives":"Deduplicate the source with ROW_NUMBER() in a CTE and merge from the ranked result. If duplicates are expected data, aggregate them in the source first so each key appears once. Skipping MERGE does not help by itself: an UPDATE ... FROM join over duplicate keys raises no error and updates each target row from an arbitrary matching source row. Deduplicate first either way.","details":[],"details_title":null,"repro":"-- Scratch DB repro: duplicate keys in the MERGE source\nCREATE TABLE dbo.Customers (CustomerId int NOT NULL PRIMARY KEY, Name nvarchar(100) NULL);\nGO\nCREATE SCHEMA staging;\nGO\nCREATE TABLE staging.Customers (CustomerId int, Name nvarchar(100), UpdatedAt datetime2);\nINSERT INTO dbo.Customers VALUES (1, N'Old name');\nINSERT INTO staging.Customers VALUES (1, N'From batch A', '2026-01-01'), (1, N'From batch B', '2026-01-02');\nGO\n-- Raises 8672: the MERGE statement attempted to UPDATE or DELETE the same row more than once\nMERGE dbo.Customers AS t\nUSING staging.Customers AS s ON t.CustomerId = s.CustomerId\nWHEN MATCHED THEN UPDATE SET t.Name = s.Name;\nGO\nDROP TABLE dbo.Customers;\nDROP TABLE staging.Customers;","repro_note":null,"related":["sql-server/2627","sql-server/512","postgresql/21000"],"sqlly":"Find the duplicate source keys with a GROUP BY HAVING COUNT(*) > 1 run in SQLly's grid; the repeated keys land in the result where you can decide how to deduplicate.","faqs":[{"question":"Which source row wins if I deduplicate?","answer":"Whichever your ORDER BY picks. ROW_NUMBER() OVER (PARTITION BY key ORDER BY UpdatedAt DESC) with rn = 1 keeps the newest row. For WHEN MATCHED THEN UPDATE, MERGE never chooses between duplicate matches; that is why it refuses to run. A WHEN MATCHED THEN DELETE with duplicate matches runs without error and deletes the row once."},{"question":"Does this error change any data?","answer":"No. The target keeps its original rows, including keys that did not duplicate, because the statement fails as a whole. Inside an explicit transaction, the same error rolls back the whole transaction, so work done earlier in that transaction is lost too."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/8672","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/9001","corpus":"errors","engine":"sql-server","language":"en","title":"The log for database is not available","description":"SQL Server lost access to the database's transaction log, usually because of an I/O failure on the log file, and took the database offline.","body":{"code":"9001","slug":"9001","name":null,"message":"The log for database '%.*ls' is not available. Check the operating system error log for related error messages. Resolve any errors and restart the database.","group":"integrity","severity":21,"sql_state":null,"summary":"SQL Server lost access to the database's transaction log, usually because of an I/O failure on the log file, and took the database offline.","meaning":"Every change goes through the transaction log, so when SQL Server can't read or write the log it can't safely continue. Error 9001 (severity 21) takes the database out of service. The operating system error that caused it is in the error log just before 9001.","causes":["The disk or volume holding the log file failed or became unavailable.","Storage errors while writing the log.","A TDE or EKM key-access failure that makes the log unreadable."],"fix":[{"text":"Check the SQL Server error log and the operating system event log for the I/O error that preceded 9001, and fix the storage.","sql":null},{"text":"Once the storage is healthy, try to bring the database back online. `WITH ROLLBACK IMMEDIATE` discards open transactions.","sql":"ALTER DATABASE SalesDb SET OFFLINE WITH ROLLBACK IMMEDIATE;\nALTER DATABASE SalesDb SET ONLINE;"},{"text":"Run `DBCC CHECKDB` afterwards. If the log is damaged, restore from backup.","sql":null},{"text":"If `AUTO_CLOSE` is on, turn it off.","sql":"ALTER DATABASE SalesDb SET AUTO_CLOSE OFF;"}],"diagnostic":"-- Find the OS error that caused it; it sits immediately before 9001 in the error log.\nEXEC xp_readerrorlog 0, 1, N'9001';\nEXEC xp_readerrorlog 0, 1, N'Operating system error';\n-- Check the database state and the log file's expected location.\nSELECT name, state_desc, log_reuse_wait_desc FROM sys.databases WHERE name = N'SalesDb';\nSELECT name, physical_name, size * 8 / 1024 AS size_mb FROM sys.master_files WHERE database_id = DB_ID(N'SalesDb') AND type_desc = 'LOG';\n-- If AUTO_CLOSE contributed, you'll see it here (0 means off).\nSELECT is_auto_close_on FROM sys.databases WHERE name = N'SalesDb';","alternatives":"While the log is unavailable there is no write workaround; the database refuses changes by design. If the log device is unrecoverable, restore from backup rather than trying to force the database online with a damaged log, which risks permanent data loss.","details":[],"details_title":null,"repro":"-- A real 9001 needs a failed log device, which you should never fake on a production system.\n-- On a disposable local instance, taking the log's volume away while the database is offline does NOT produce 9001. It raises OS error 2 at startup, Msg 5181 and Msg 5069, and leaves the database in RECOVERY_PENDING. 9001 needs the log to fail while the database is running, which cannot be reproduced safely:\n-- 1. Note the log file location.\nSELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID(N'SalesDb') AND type_desc = 'LOG';\n-- 2. Take the database offline, rename or disconnect the log's volume, then try SET ONLINE.\n-- 3. Restore the volume and SET ONLINE again. Do this only on a scratch instance.","repro_note":null,"related":["sql-server/9002","sql-server/823","sql-server/824","sql-server/5120"],"sqlly":"Run the sys.databases and xp_readerrorlog checks from SQLly's editor; both results land in the grid where you can copy them for the storage or HA team.","faqs":[{"question":"Is 9001 the same as a full transaction log (error 9002)?","answer":"No. 9002 means the log is full: low disk space, a file size limit (MAXSIZE), or a log reuse wait such as an open transaction or a missing log backup. 9001 means SQL Server could not read or write the log at all, usually because of an I/O error or a TDE/EKM key failure. A full log can lead to 9001 when the rollback fails, so fix 9002 first. Full logs have space workarounds; failed logs need storage repair or restore."},{"question":"The storage came back but the database is still offline. What now?","answer":"Try ALTER DATABASE ... SET ONLINE. If it comes back damaged or refuses to recover, restore from backup. Run DBCC CHECKDB once it is up, and don't trust a database that recovered from a damaged log without a check."},{"question":"Why does AUTO_CLOSE matter?","answer":"With AUTO_CLOSE on, a database closes after the last connection ends and must reopen its log on the next connection. On a server with flaky storage, a reopen that hits an I/O error can surface as 9001. A missing log volume at reopen does not: it raises OS error 2 and Msg 5181 and leaves the database in RECOVERY_PENDING. It should be off on shared production servers."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/9001","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/9002","corpus":"errors","engine":"sql-server","language":"en","title":"Transaction log for database is full","description":"The database's log file is full and can't grow, so writes fail. The message's reason (LOG_BACKUP, ACTIVE_TRANSACTION...) says what keeps the log from being reused.","body":{"code":"9002","slug":"9002","name":null,"message":"The transaction log for database '%.*ls' is full due to '%.*ls' and the holdup lsn is %S_LSN.","group":"resources","severity":17,"sql_state":null,"summary":"The database's log file is full and can't grow, so writes fail. The message's reason (LOG_BACKUP, ACTIVE_TRANSACTION...) says what keeps the log from being reused.","meaning":"SQL Server writes every change to the transaction log before it changes data. Log space is reused only once nothing still needs it: in the full recovery model that means after a log backup, and in every model the oldest open transaction, replication or an availability group replica can hold it. If the log can't be reused and can't grow (it hit its maximum size or the disk is full), every write fails with 9002.\n\nThe message names the reason, which is the same value as `log_reuse_wait_desc` in `sys.databases`. On SQL Server 2022 the message also names the holdup LSN (`and the holdup lsn is (7:132:1)`); on 2019 and earlier it ends after the reason.","causes":["`LOG_BACKUP`: the database is in the full or bulk-logged recovery model and log backups aren't being taken.","`ACTIVE_TRANSACTION`: a long-running or forgotten open transaction pins the log.","`REPLICATION` or `AVAILABILITY_REPLICA`: a log reader or a secondary replica has fallen behind.","The log file has a fixed maximum size, or the disk holding it is full.","A single huge transaction, such as deleting millions of rows in one statement."],"fix":[{"text":"See why the log can't be reused.","sql":"SELECT name, recovery_model_desc, log_reuse_wait_desc FROM sys.databases WHERE name = N'SalesDb';"},{"text":"For `LOG_BACKUP`, take a log backup (and schedule them).","sql":"BACKUP LOG SalesDb TO DISK = N'D:\\Backup\\SalesDb_log.trn';"},{"text":"For `ACTIVE_TRANSACTION`, find the oldest open transaction and get it committed or rolled back.","sql":"DBCC OPENTRAN (N'SalesDb');"},{"text":"Give the log room: let it grow, or add a second log file on another disk.","sql":"ALTER DATABASE SalesDb MODIFY FILE (NAME = SalesDb_log, MAXSIZE = UNLIMITED, FILEGROWTH = 512MB);"},{"text":"Break huge data changes into batches so each transaction is small.","sql":"WHILE 1 = 1\nBEGIN\n    DELETE TOP (10000) FROM dbo.EventLog WHERE CreatedAt < '2024-01-01';\n    IF @@ROWCOUNT = 0 BREAK;\nEND;"},{"text":"If you don't need point-in-time restore for this database, the simple recovery model reuses log space after each checkpoint.","sql":"ALTER DATABASE SalesDb SET RECOVERY SIMPLE;"}],"diagnostic":"-- Why is the log not reusing space? This matches the message reason.\nSELECT name, recovery_model_desc, log_reuse_wait_desc FROM sys.databases WHERE name = DB_NAME();\n-- How full is the log right now? (SQL Server 2012 and later)\nSELECT total_log_size_in_bytes/1048576.0 AS total_mb, used_log_space_in_percent FROM sys.dm_db_log_space_usage;\n-- Who is holding the log back?\nDBCC OPENTRAN;  -- oldest open transaction\nSELECT host_name, program_name, login_time, last_request_start_time\nFROM sys.dm_exec_sessions WHERE is_user_process = 1 ORDER BY last_request_start_time;\nDBCC SQLPERF(LOGSPACE);  -- percent used per database","alternatives":"If the database is a dev copy, switching to the simple recovery model frees log space at every checkpoint and no log backups are needed. For large one-off operations, doing them in batches with a log backup in between (full recovery) or after each batch (simple recovery) keeps the log small.","details":[],"details_title":null,"repro":"-- Scratch database with a 4 MB log cap, full recovery, no log backups\nCREATE DATABASE err9002 ON (NAME = err9002, FILENAME = 'C:\\temp\\err9002.mdf', SIZE = 8MB)\nLOG ON (NAME = err9002_log, FILENAME = 'C:\\temp\\err9002.ldf', SIZE = 4MB, MAXSIZE = 4MB, FILEGROWTH = 0);\nALTER DATABASE err9002 SET RECOVERY FULL;\nUSE err9002;\nCREATE TABLE t (id INT IDENTITY, filler CHAR(3000) DEFAULT 'x');\n-- Log reuse is now ACTIVE_TRANSACTION/NOTHING_BACKED_UP; keep inserting\n-- and the log hits its cap: INSERT INTO t DEFAULT VALUES; (run in a loop)\n-- Cleanup: DROP DATABASE err9002;","repro_note":null,"related":["sql-server/1105","sql-server/1101","sql-server/9001","postgresql/53100","oracle/ora-00257","oracle/ora-30036"],"sqlly":"Query sys.databases and sys.dm_db_log_space_usage from SQLly's editor and read log_reuse_wait_desc straight out of the grid, which is the fastest way to see what is holding the log full.","faqs":[{"question":"Should I shrink the log file after fixing 9002?","answer":"Only if it grew far beyond its normal size because of a one-off event. Shrinking a log that regularly needs that space just makes it grow again, which costs time while writes wait."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/9002","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sql-server/916","corpus":"errors","engine":"sql-server","language":"en","title":"Login can't access the database","description":"The login connected to the server but has no user in this database and no guest access, so it can't use the database in the current security context.","body":{"code":"916","slug":"916","name":null,"message":"The server principal \"%.*ls\" is not able to access the database \"%.*ls\" under the current security context.","group":"permissions","severity":14,"sql_state":null,"summary":"The login connected to the server but has no user in this database and no guest access, so it can't use the database in the current security context.","meaning":"A login gets into a database through a database user mapped to it, through a Windows group, or through the `guest` user if guest is enabled. Error 916 means none of those apply for this database. It often appears in SSMS when Object Explorer tries to read properties of every database, including ones you aren't a user in.","causes":["The login has no database user in that database.","The database was restored from another server and its user is orphaned (its SID doesn't match the login).","Code switches to the database with `USE`, or a cross-database query or view touches a database the login can't access.","Running under `EXECUTE AS USER`, which is scoped to the current database, then touching another database."],"fix":[{"text":"Create a user for the login in the database and grant it a role.","sql":"USE SalesDb;\nCREATE USER app_user FOR LOGIN app_user;\nALTER ROLE db_datareader ADD MEMBER app_user;"},{"text":"If the database came from another server, remap the orphaned user to the login.","sql":"USE SalesDb;\nALTER USER app_user WITH LOGIN = app_user;"},{"text":"List orphaned users in the current database.","sql":"SELECT dp.name\nFROM sys.database_principals dp\nLEFT JOIN sys.server_principals sp ON sp.sid = dp.sid\nWHERE dp.type IN ('S', 'U') AND sp.sid IS NULL AND dp.authentication_type_desc = 'INSTANCE';"}],"diagnostic":"-- From inside the target database: does a user map to this login, and is it orphaned?\nUSE SalesDb;\nSELECT dp.name AS db_user, dp.type_desc, dp.sid,\n       sp.name AS server_login\nFROM sys.database_principals dp\nLEFT JOIN sys.server_principals sp ON sp.sid = dp.sid\nWHERE dp.type IN ('S','U');\n-- A row with a NULL server_login whose authentication_type_desc is INSTANCE is an orphaned user (guest and the system users also show NULL and are not orphans) (database from another\n-- server). No row at all for the login's sid means there is no mapping, and\n-- guest is the only remaining path:\nSELECT name, type_desc, authentication_type_desc FROM sys.database_principals WHERE name = 'guest';\n-- Also check which databases the login CAN enter, to compare:\nSELECT d.name, state_desc FROM sys.databases d\nWHERE HAS_DBACCESS(d.name) = 1 ORDER BY d.name;","alternatives":"Granting access through a Windows group is the lower-maintenance path: add the group as a user once and manage membership in Active Directory instead of creating a user per login. If the error appears only in SSMS Object Explorer, it is often harmless noise from enumerating databases you aren't a user in; filter the explorer or ignore it.","details":[],"details_title":null,"repro":"-- Reproduce on a scratch instance: a login with no user in the database.\nUSE master;\nIF DB_ID('scratch_916') IS NULL CREATE DATABASE scratch_916;\nIF NOT EXISTS (SELECT 1 FROM sys.sql_logins WHERE name = 'scratch_916_login')\n    CREATE LOGIN scratch_916_login WITH PASSWORD = N'Scratch-916!', CHECK_POLICY = OFF;\nGO\n-- The login gets in (no default database problem) but has no user in scratch_916.\n-- From a shell:\n--   sqlcmd -S localhost -U scratch_916_login -P 'Scratch-916!' -d scratch_916 -Q \"SELECT 1\"\n-- fails with 916. Connecting without -d succeeds, because master's guest user\n-- is enabled by default, so the login lands in master as guest.\n-- Cleanup:\nDROP LOGIN scratch_916_login; DROP DATABASE scratch_916;","repro_note":null,"related":["sql-server/4060","sql-server/229","sql-server/18456"],"sqlly":"The database name comes back inside the error from SQLly's connection test, so it is obvious which saved connection points at a database this login cannot enter.","faqs":[{"question":"Why does 916 appear all over SSMS when I expand Databases?","answer":"Object Explorer queries every database, including ones your login has no user in. Each of those raises 916. It doesn't mean anything is broken; it means you can't see into those databases, which is often intended."},{"question":"What is the difference between 4060 and 916?","answer":"4060 fails at login time: the connection asked to open the database and couldn't. 916 happens after you're connected to the server, when code or a tool tries to use a database the login can't enter."},{"question":"What is the guest user and should I enable it?","answer":"guest is a built-in database user that lets any server login use the database when it has no mapping of its own. It is disabled in user databases by default. Enabling it grants broad access and is rarely the right fix for 916; create a proper user instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sql-server/916","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-abort","corpus":"errors","engine":"sqlite","language":"en","title":"query aborted","description":"An operation stopped before finishing, usually by request: an sqlite3_exec() callback returned non-zero, or a ROLLBACK may fail a pending read or write.","body":{"code":"SQLITE_ABORT","slug":"sqlite-abort","name":"4","message":"query aborted","group":"primary","severity":null,"sql_state":null,"summary":"An operation stopped before finishing, usually by request: an sqlite3_exec() callback returned non-zero, or a ROLLBACK may fail a pending read or write.","meaning":"`SQLITE_ABORT` (4) means an operation was cut short. The SQLite documentation lists two everyday cases: the callback passed to `sqlite3_exec()` returned non-zero, which tells SQLite to stop; or a `ROLLBACK` ran on the same connection while a read or write was pending, in which case the pending statement may fail with `SQLITE_ABORT` or the extended `SQLITE_ABORT_ROLLBACK`.","causes":["A row callback in `sqlite3_exec()` returned non-zero.","A `ROLLBACK` on the connection while another statement on it was still being stepped. A pending read fails only if the rolled-back transaction changed the schema; the SQLite docs say a pending write always fails.","A `RAISE(ABORT, ...)` in a trigger, which reports as a constraint error with the trigger's message."],"fix":[{"text":"If you use `sqlite3_exec()` with a callback, make sure it returns 0 to continue.","sql":null},{"text":"Finish or reset open statements before rolling back, and don't issue `ROLLBACK` from one part of the program while another is still reading on the same connection.","sql":null}],"diagnostic":"-- If a trigger may be raising ABORT, list triggers on the table and look for RAISE(ABORT,...):\nSELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND sql LIKE '%RAISE%';","alternatives":"If the abort came from a rollback you issued, treat the statement and any transaction state as finished and restart the work. There is no way to resume a statement after SQLITE_ABORT.","details":[],"details_title":null,"repro":"-- Needs a host-language hook, so it is not reproducible with sequential SQL: a callback passed\n-- to sqlite3_exec() that returns non-zero, or a ROLLBACK issued while another statement on the\n-- same connection is mid-read (that variant reports as SQLITE_ABORT_ROLLBACK, 516).","repro_note":null,"related":["sqlite/sqlite-abort-rollback","sqlite/sqlite-interrupt","sqlite/sqlite-locked"],"sqlly":"SQLly highlights the statement that failed in the editor and keeps it in query history, so re-running it once the callback or rollback that stopped it is fixed takes a click.","faqs":[{"question":"I got SQLITE_ABORT but I never cancelled anything.","answer":"Something on the same connection rolled back while a statement was still running, or a sqlite3_exec() callback returned non-zero. Check that only one thread drives a connection at a time."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-abort","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-abort-rollback","corpus":"errors","engine":"sqlite","language":"en","title":"statement aborted by ROLLBACK","description":"A statement failed because the transaction it was running in was rolled back while it was still pending, for example by a ROLLBACK on the same connection.","body":{"code":"SQLITE_ABORT_ROLLBACK","slug":"sqlite-abort-rollback","name":"516","message":"abort due to ROLLBACK","group":"extended","severity":null,"sql_state":null,"summary":"A statement failed because the transaction it was running in was rolled back while it was still pending, for example by a ROLLBACK on the same connection.","meaning":"`SQLITE_ABORT_ROLLBACK` (516) means a statement was aborted because the transaction that was active when it started was rolled back. Pending writes always fail this way after a rollback; a pending read fails only if the schema changed inside the transaction being rolled back. The text is `abort due to ROLLBACK`.","causes":["Calling `ROLLBACK` while a write on the same connection is still pending, or while a read is pending and the transaction changed the schema.","An error elsewhere that made the application (or SQLite, for example after an `INTERRUPT` or `ON CONFLICT ROLLBACK`) roll back the transaction."],"fix":[{"text":"Finish or reset all statements on a connection before rolling back its transaction.","sql":null},{"text":"Look for the earlier error that triggered the rollback and fix that; this error is a consequence.","sql":null}],"diagnostic":"-- The database state confirms the consequence: after this error the connection is back in\n-- autocommit mode (sqlite3_get_autocommit() returns 1, conn.in_transaction in Python is False).\n-- The cause is up a level: find the ROLLBACK, the ON CONFLICT ROLLBACK clause, or the error\n-- handler that rolled back while a statement was still active.","alternatives":"Re-run the transaction from the start after a rollback: pending writes, and pending reads when the transaction changed the schema, are unusable. Find and fix the earlier error that caused the rollback.","details":[],"details_title":null,"repro":"-- Needs a statement still being stepped while another call rolls back the\n-- transaction, so it is not reproducible with sequential SQL alone.","repro_note":null,"related":["sqlite/sqlite-abort","sqlite/sqlite-locked","sqlite/sqlite-interrupt","postgresql/25P02"],"sqlly":"After the rollback, query history keeps the aborted statement so re-running the transaction from its start is a click rather than a retype.","faqs":[{"question":"Are my uncommitted writes saved anywhere after this?","answer":"No. The transaction was rolled back; its writes are gone."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-abort-rollback","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-auth","corpus":"errors","engine":"sqlite","language":"en","title":"authorization denied","description":"The application's authorizer callback rejected the SQL statement while it was being prepared.","body":{"code":"SQLITE_AUTH","slug":"sqlite-auth","name":"23","message":"authorization denied","group":"primary","severity":null,"sql_state":null,"summary":"The application's authorizer callback rejected the SQL statement while it was being prepared.","meaning":"`SQLITE_AUTH` (23) is returned when an authorizer callback, installed with `sqlite3_set_authorizer()`, denies a table, column, `ATTACH` or other database action. A denied function call is the exception: SQLite reports it as `SQLITE_ERROR` (1) with the text `not authorized to use function: <name>`. Applications use authorizers to sandbox SQL from untrusted sources, for example to allow only reads or to block certain tables or functions. The error comes from your application's policy, not from file permissions.","causes":["The application (or a framework it uses) installed an authorizer that denies the operation, such as writes, `ATTACH` or a particular table.","Running user-supplied SQL through a sandboxed connection."],"fix":[{"text":"Check what the authorizer allows and run the statement on a connection that permits it, if that is intended.","sql":null},{"text":"If you wrote the authorizer, log the action code and arguments it receives to see which part of the statement was denied.","sql":null}],"diagnostic":"-- The authorizer is application code, so turn on logging in it: sqlite3_set_authorizer()\n-- receives the action code and the names of the objects each statement touches, and returning\n-- SQLITE_DENY for one becomes this error. The schema itself looks normal from SQL.","alternatives":"If the denial is not intended, run the statement on a connection without the authorizer, or adjust the authorizer to return SQLITE_OK for that action code.","details":[],"details_title":null,"repro":"-- Not reproducible in plain SQL: SQLITE_AUTH (23) requires an authorizer callback\n-- installed with sqlite3_set_authorizer() that returns SQLITE_DENY for the action.","repro_note":null,"related":["sqlite/sqlite-readonly","sqlite/sqlite-perm"],"sqlly":"SQLly sets no authorizer on its connections, so running the denied statement from a fresh SQLly tab tells you whether the denial really comes from the application's policy.","faqs":[{"question":"Is this a file permission problem?","answer":"No. A file the process cannot open gives SQLITE_CANTOPEN (14), and a write to a read-only file gives SQLITE_READONLY (8). SQLITE_AUTH comes from the application's own authorizer callback."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-auth","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-busy","corpus":"errors","engine":"sqlite","language":"en","title":"database is locked","description":"Another connection holds a lock SQLite needs, usually a writer in another process. Set a busy timeout, keep write transactions short, or switch to WAL mode.","body":{"code":"SQLITE_BUSY","slug":"sqlite-busy","name":"5","message":"database is locked","group":"primary","severity":null,"sql_state":null,"summary":"Another connection holds a lock SQLite needs, usually a writer in another process. Set a busy timeout, keep write transactions short, or switch to WAL mode.","meaning":"SQLite allows one writer at a time per database file. When a connection needs a lock that another connection (in the same or another process) holds, the call fails with `SQLITE_BUSY` and the message `database is locked`, unless a busy handler is set, in which case SQLite retries for up to the timeout first. That retry does not happen when a transaction that already read the database tries to upgrade to a write while another connection holds the write lock: SQLite returns SQLITE_BUSY at once, whatever the timeout.\n\nBy default there is no busy handler, so the failure is immediate. In rollback-journal mode readers also block a writer from committing, and a writer blocks new readers while it commits; WAL mode lets readers and one writer work at the same time.","causes":["Two processes or threads write to the same database at the same time, with no busy timeout set.","A long write transaction holds the lock while others wait, and so does a transaction that has read the database and was never committed (a bare `BEGIN` holds nothing until its first statement).","A transaction that has already read the database (for example `BEGIN` followed by a `SELECT`) tries to upgrade to a write while another connection holds the write lock. It gets `SQLITE_BUSY` at once in either journal mode, and the busy timeout is not applied. In WAL mode, if the other connection has committed since the read snapshot began, the upgrade returns `SQLITE_BUSY_SNAPSHOT` (extended code 517), and a retry in the same transaction cannot succeed.","An open cursor or unfinished statement in your own program keeps a read transaction open.","The database file is on a network file system whose locking doesn't work reliably."],"fix":[{"text":"Set a busy timeout so SQLite waits and retries instead of failing at once. Most bindings expose it (Python's `sqlite3` waits 5 seconds by default; raise it with `sqlite3.connect(path, timeout=30)`). In SQL:","sql":"PRAGMA busy_timeout = 5000;  -- milliseconds"},{"text":"Switch the database to write-ahead logging, so readers no longer block the writer and the writer doesn't block readers.","sql":"PRAGMA journal_mode = WAL;"},{"text":"Start write transactions with `BEGIN IMMEDIATE`, which takes the write lock up front. A busy connection then waits at `BEGIN` (where the timeout applies) instead of failing halfway through.","sql":"BEGIN IMMEDIATE;\nUPDATE counters SET n = n + 1 WHERE name = 'visits';\nCOMMIT;"},{"text":"Keep transactions short, commit promptly, and finish or reset every statement (close cursors) so no connection holds a lock longer than it needs.","sql":null},{"text":"Keep the database on a local disk, not a network share.","sql":null}],"diagnostic":"-- Check the journal mode; rollback-journal databases serialize readers and writers far more than WAL does:\nPRAGMA journal_mode;\n-- A busy timeout of zero means every collision fails immediately:\nPRAGMA busy_timeout;\n-- On WAL mode, a checkpoint blocked by a long reader leaves checkpointed below log. PASSIVE reports busy 0 in that case; RESTART, FULL and TRUNCATE report busy 1:\nPRAGMA wal_checkpoint(PASSIVE);","alternatives":"Route all writes through one connection or a small queue and most contention disappears. If a reader-to-writer upgrade keeps failing, start the transaction with BEGIN IMMEDIATE instead of a deferred one.","details":[],"details_title":null,"repro":"-- Connection 1 (for example the sqlite3 shell), setup first:\nCREATE TABLE t(x);\nBEGIN IMMEDIATE;\nINSERT INTO t VALUES (1);\n-- Connection 2, same file, no busy timeout:\nINSERT INTO t VALUES (2);   -- Runtime error near line 1: database is locked (5)","repro_note":"Use two separate connections to the same scratch database file. Run the CREATE TABLE on connection 1 before opening connection 2.","related":["sqlite/sqlite-locked","sqlite/sqlite-busy-snapshot","sqlite/sqlite-busy-timeout","postgresql/55P03","mysql/1205","sql-server/1222"],"sqlly":"SQLly can mark a connection read-only, so a tab kept open to inspect a file never takes its write lock. A per-connection statement timeout also stops one of your own long statements from holding the file longer than planned.","faqs":[{"question":"What is the difference between SQLITE_BUSY and SQLITE_LOCKED?","answer":"`SQLITE_BUSY` means another database connection, usually in another process, holds a conflicting lock. `SQLITE_LOCKED` means the conflict is inside your own connection or between connections sharing a cache, for example dropping a table while a statement is still reading it."},{"question":"Does WAL mode get rid of database is locked?","answer":"It removes most reader-writer conflicts, but there is still only one writer at a time, so concurrent writers still need a busy timeout."},{"question":"Does busy_timeout fix everything?","answer":"No. It helps when a transaction waits for the write lock at its first write. It does not help when a transaction that already read the database tries to upgrade to a write: SQLite returns SQLITE_BUSY at once, which is also how it avoids the deadlock where two deferred transactions both wait to upgrade. Start such transactions with BEGIN IMMEDIATE, and keep write transactions short as well."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-busy","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-busy-recovery","corpus":"errors","engine":"sqlite","language":"en","title":"another process is recovering the WAL","description":"Another process is recovering a WAL-mode database after a crash. With no busy timeout set, SQLite doesn't wait and the statement fails. It clears after recovery.","body":{"code":"SQLITE_BUSY_RECOVERY","slug":"sqlite-busy-recovery","name":"261","message":"database is locked","group":"extended","severity":null,"sql_state":null,"summary":"Another process is recovering a WAL-mode database after a crash. With no busy timeout set, SQLite doesn't wait and the statement fails. It clears after recovery.","meaning":"`SQLITE_BUSY_RECOVERY` (261) is an extended `SQLITE_BUSY` code for WAL-mode databases: an operation couldn't continue because another process is busy recovering the database file after a crash. Recovery rebuilds the WAL index from the WAL file and normally takes a moment.","causes":["A process using the database crashed or was killed, and the next connection is recovering the WAL.","A very large WAL file, which makes recovery take longer."],"fix":[{"text":"Retry after a short wait, or set a busy timeout so SQLite waits for you.","sql":"PRAGMA busy_timeout = 5000;"},{"text":"Keep the WAL small with regular checkpoints, so recovery after a crash is quick.","sql":"PRAGMA wal_checkpoint(TRUNCATE);"}],"diagnostic":"PRAGMA journal_mode;   -- must report wal for this code to be possible\n-- While it happens, look at the files beside the database: a large app.db-wal means the\n-- recovering process has more work to do. In the shell: ls -l app.db-wal app.db-shm","alternatives":"Set PRAGMA busy_timeout so the recovering connection is waited for, and keep the WAL small with periodic wal_checkpoint(TRUNCATE) so recovery stays short.","details":[],"details_title":null,"repro":"-- Not safely reproducible in SQL: it needs a process killed while a WAL-mode\n-- database was open, then a new connection racing the WAL recovery.","repro_note":null,"related":["sqlite/sqlite-busy","sqlite/sqlite-busy-snapshot"],"sqlly":"Nothing in SQLly speeds up WAL recovery; give it a moment, then re-run the failed statement from query history once the database answers again.","faqs":[{"question":"Is my data lost after a crash triggers recovery?","answer":"No. Recovery rebuilds the WAL index from the WAL file; transactions already committed in the WAL are preserved."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-busy-recovery","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-busy-snapshot","corpus":"errors","engine":"sqlite","language":"en","title":"stale read can't become a write","description":"In WAL mode, a transaction that started by reading tried to write after another connection had already changed the database. Waiting won't help; restart the transaction.","body":{"code":"SQLITE_BUSY_SNAPSHOT","slug":"sqlite-busy-snapshot","name":"517","message":"database is locked","group":"extended","severity":null,"sql_state":null,"summary":"In WAL mode, a transaction that started by reading tried to write after another connection had already changed the database. Waiting won't help; restart the transaction.","meaning":"`SQLITE_BUSY_SNAPSHOT` (517) happens only on WAL-mode databases. A read transaction sees a snapshot of the database. If it then tries to write, SQLite must upgrade it to a write transaction, but if another connection committed changes after the snapshot was taken, the earlier reads are out of date and the upgrade is refused.\n\nUnlike plain `SQLITE_BUSY`, a busy timeout doesn't fix this: the transaction must be rolled back and run again from the start.","causes":["`BEGIN` (deferred) followed by `SELECT` and then `UPDATE`, while another process commits in between.","Long read transactions in an application that later decides to write."],"fix":[{"text":"Start transactions that will write with `BEGIN IMMEDIATE`, so the write lock is taken before any reads.","sql":"BEGIN IMMEDIATE;\nSELECT balance FROM accounts WHERE id = 1;\nUPDATE accounts SET balance = balance - 10 WHERE id = 1;\nCOMMIT;"},{"text":"When it does happen, roll back and retry the whole transaction.","sql":"ROLLBACK;"}],"diagnostic":"-- Confirm the database is in WAL mode, where snapshot upgrades happen:\nPRAGMA journal_mode;","alternatives":"Split the work: run the reads, end that transaction, then start a fresh BEGIN IMMEDIATE, re-read what the write depends on, and write. For contended rows, add a version column and make the write conditional on it (UPDATE ... WHERE id = ? AND version = ?), running the read and the conditional write as separate autocommit statements; zero rows updated then means another connection got there first and the read has to be redone. Inside an open deferred BEGIN, the same UPDATE fails with SQLITE_BUSY_SNAPSHOT instead of returning zero rows.","details":[],"details_title":null,"repro":"-- Two connections on a WAL-mode database. Setup, once, on either connection:\nPRAGMA journal_mode = WAL;\nCREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER);\nINSERT INTO accounts VALUES (1, 100);\n-- A: BEGIN;\n-- A: SELECT count(*) FROM accounts;\n-- B: UPDATE accounts SET balance = 0; COMMIT;\n-- A: UPDATE accounts SET balance = balance - 10;\n-- Error on A: database is locked (the sqlite3 shell prints code 5; the C API and drivers report SQLITE_BUSY_SNAPSHOT, 517)","repro_note":"Connection A and connection B are two separate sqlite3 shells on the same scratch file. Run the setup, then keep A's transaction open while B commits.","related":["sqlite/sqlite-busy","sqlite/sqlite-busy-recovery","postgresql/40001","sql-server/3960","oracle/ora-08177"],"sqlly":"Retry from query history after restructuring the batch to start with BEGIN IMMEDIATE; a fresh run takes a fresh snapshot, so the stale one can't block it.","faqs":[{"question":"Will a busy timeout fix this?","answer":"No. Waiting does not help here: another connection committed after your snapshot, so the transaction must be rolled back and rerun. A busy timeout does clear plain SQLITE_BUSY for a single autocommit statement, but SQLite skips the busy handler inside an open read transaction."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-busy-snapshot","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-busy-timeout","corpus":"errors","engine":"sqlite","language":"en","title":"blocking file lock timed out","description":"A blocking POSIX file lock request in SQLite's VFS layer timed out. Only builds compiled with SQLITE_ENABLE_SETLK_TIMEOUT return it.","body":{"code":"SQLITE_BUSY_TIMEOUT","slug":"sqlite-busy-timeout","name":"773","message":"database is locked","group":"extended","severity":null,"sql_state":null,"summary":"A blocking POSIX file lock request in SQLite's VFS layer timed out. Only builds compiled with SQLITE_ENABLE_SETLK_TIMEOUT return it.","meaning":"The SQLite documentation describes `SQLITE_BUSY_TIMEOUT` (773) as a blocking POSIX advisory file lock request that failed because of a timeout. Blocking locks are only available when SQLite is compiled with `SQLITE_ENABLE_SETLK_TIMEOUT`. That is necessary but not sufficient, and most applications never see this code; they get plain `SQLITE_BUSY` when a lock can't be taken.","causes":["Another connection held the lock for longer than the configured wait, on a build that uses blocking locks."],"fix":[{"text":"Handle it like `SQLITE_BUSY`: keep write transactions short, use WAL mode, and retry.","sql":null},{"text":"Raise the wait time if the lock holder is expected to take a while.","sql":"PRAGMA busy_timeout = 10000;"}],"diagnostic":"PRAGMA compile_options;   -- look for ENABLE_SETLK_TIMEOUT; if it is absent, 773 cannot occur\nPRAGMA busy_timeout;   -- what your binding actually set, if anything","alternatives":"Unless you know your build was compiled with SQLITE_ENABLE_SETLK_TIMEOUT, treat this exactly like plain SQLITE_BUSY: set busy_timeout, keep write transactions short, and retry on failure.","details":[],"details_title":null,"repro":"-- Not reproducible on ordinary builds: the blocking lock wait behind this code needs the\n-- SQLITE_ENABLE_SETLK_TIMEOUT compile-time option. Everyone else gets plain SQLITE_BUSY (5).","repro_note":null,"related":["sqlite/sqlite-busy","sqlite/sqlite-busy-snapshot"],"sqlly":"SQLly shows the engine's message with the failed statement; if you really run a SQLITE_ENABLE_SETLK_TIMEOUT build, the wait is tuned with PRAGMA busy_timeout from a query tab.","faqs":[{"question":"Why do I see SQLITE_BUSY instead of this code?","answer":"Blocking lock waits need the compile-time option, and a build that has it can still return SQLITE_BUSY. With no busy handler, SQLite returns SQLITE_BUSY at once; with busy_timeout set, SQLite's busy handler retries until the timeout."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-busy-timeout","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-cantopen","corpus":"errors","engine":"sqlite","language":"en","title":"unable to open database file","description":"SQLite couldn't open the database file or one of its temporary files: a wrong path, a missing directory, a permissions problem, or a path that is a directory.","body":{"code":"SQLITE_CANTOPEN","slug":"sqlite-cantopen","name":"14","message":"unable to open database file","group":"primary","severity":null,"sql_state":null,"summary":"SQLite couldn't open the database file or one of its temporary files: a wrong path, a missing directory, a permissions problem, or a path that is a directory.","meaning":"`SQLITE_CANTOPEN` (14) means the operating system refused to open a file SQLite needed. That is usually the main database file, but it can also be a temporary file. SQLite creates a new database file when the path doesn't exist, so this error usually means the directory is missing or not writable, not that the file is missing.\n\nExtended codes narrow it down, for example `SQLITE_CANTOPEN_ISDIR` (the path is a directory) and `SQLITE_CANTOPEN_FULLPATH` (the full path couldn't be resolved).","causes":["The directory in the path doesn't exist; SQLite creates files, not directories.","A relative path resolved against an unexpected working directory, for example in a service or a test runner.","No permission to read the file, or to create it in that directory.","The path points at a directory (`SQLITE_CANTOPEN_ISDIR`).","No directory SQLite tries for temporary files is usable, so a temporary file can't be created. A missing or unwritable TMPDIR on its own is skipped, because SQLite falls back to /var/tmp, /usr/tmp, /tmp and then the current directory.","Too many open files in the process."],"fix":[{"text":"Use an absolute path and make sure every directory in it exists.","sql":null},{"text":"Check permissions on the file and its directory for the user the program runs as.","sql":null},{"text":"If temporary files are the problem, point SQLite at a writable directory with the `SQLITE_TMPDIR` or `TMPDIR` environment variable, or keep temporary storage in memory.","sql":"PRAGMA temp_store = MEMORY;"},{"text":"In the `sqlite3` shell, confirm what was opened.","sql":".databases"}],"diagnostic":"-- Confirm which file the connection tried to open:\nPRAGMA database_list;\n-- In the shell, test the path directly: sqlite3 /exact/path/file.db 'PRAGMA user_version;'\n-- Check the temp directory SQLite needs for temp files: PRAGMA temp_store_directory; (deprecated but shows intent) or echo $TMPDIR","alternatives":"Use an absolute path built from the application's data directory rather than the process working directory, which differs between services, test runners and terminals.","details":[],"details_title":null,"repro":"sqlite3 /no/such/dir/app.db 'SELECT 1;'\n-- Error: unable to open database \"/no/such/dir/app.db\": unable to open database file   (the directory is missing; SQLite creates files, not directories)\nmkdir -p /no/such/dir && sqlite3 /no/such/dir/app.db 'PRAGMA user_version;'   -- succeeds and creates the file","repro_note":null,"related":["sqlite/sqlite-readonly","sqlite/sqlite-perm","sqlite/sqlite-notadb","sqlite/sqlite-cantopen-isdir"],"sqlly":"The connection editor shows the exact path SQLly was given, so a missing directory or a stray relative path is usually visible at a glance; fixing it there repairs the connection for every query tab.","faqs":[{"question":"Why can't SQLite create the missing directories for me?","answer":"SQLite opens files, it does not manage paths. Every directory in the path must already exist. Write access to the directory is needed to create a new file or to write to one; an existing file can still be opened and read from a read-only directory."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-cantopen","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-cantopen-isdir","corpus":"errors","engine":"sqlite","language":"en","title":"the path is a directory","description":"SQLite was asked to open a database at a path that is a directory, not a file.","body":{"code":"SQLITE_CANTOPEN_ISDIR","slug":"sqlite-cantopen-isdir","name":"526","message":"unable to open database file","group":"extended","severity":null,"sql_state":null,"summary":"SQLite was asked to open a database at a path that is a directory, not a file.","meaning":"`SQLITE_CANTOPEN_ISDIR` (526) is an extended `SQLITE_CANTOPEN` code for a path that is really a directory. SQLite raises it on Windows; on macOS (SQLite 3.51.0 and 3.54.1 tested) and in the Unix code paths of the SQLite source, the same mistake is reported as plain `SQLITE_CANTOPEN` (14). A path built from a folder setting with the file name missing is the usual cause.","causes":["A configuration value that holds the data directory instead of the database file path.","Joining paths in a way that drops the file name."],"fix":[{"text":"Pass the full path to the database file, including its name, for example `/var/lib/app/app.db` rather than `/var/lib/app`.","sql":null}],"diagnostic":"-- Check what the path actually points at. On macOS or Linux, file /path/to/app.db prints\n-- 'directory' for this case, and ls -ld shows it directly.\nPRAGMA database_list;   -- what the connection did manage to open, if anything","alternatives":"If a config value legitimately holds the data directory, append the database file name in one place, for example a single path-joining helper, so the file name cannot get dropped elsewhere.","details":[],"details_title":null,"repro":"-- On macOS, opening a directory path fails with plain SQLITE_CANTOPEN (14); SQLITE_CANTOPEN_ISDIR is raised on Windows:\nATTACH DATABASE '/tmp' AS not_a_db;  -- unable to open database: /tmp","repro_note":null,"related":["sqlite/sqlite-cantopen","sqlite/sqlite-notadb"],"sqlly":"The path in SQLly's connection editor shows whether a directory slipped in where the file name belongs; appending the name there fixes every query tab at once.","faqs":[{"question":"Can I point SQLite at a folder and have it open all databases in it?","answer":"No. A database connection opens exactly one file per attached name. Attach each file separately with its full path."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-cantopen-isdir","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint","corpus":"errors","engine":"sqlite","language":"en","title":"constraint failed","description":"An INSERT, UPDATE or DELETE broke a constraint: UNIQUE, PRIMARY KEY, NOT NULL, CHECK or FOREIGN KEY. The message and extended code name which one.","body":{"code":"SQLITE_CONSTRAINT","slug":"sqlite-constraint","name":"19","message":"constraint failed","group":"primary","severity":null,"sql_state":null,"summary":"An INSERT, UPDATE or DELETE broke a constraint: UNIQUE, PRIMARY KEY, NOT NULL, CHECK or FOREIGN KEY. The message and extended code name which one.","meaning":"`SQLITE_CONSTRAINT` (19) means a statement would have broken one of the table's rules, so SQLite stopped it. The generic text is `constraint failed`, but the message usually names the rule and column, such as `UNIQUE constraint failed: users.email`, and the extended code tells you the kind: `SQLITE_CONSTRAINT_UNIQUE`, `_PRIMARYKEY`, `_NOTNULL`, `_CHECK`, `_FOREIGNKEY`, `_DATATYPE` (STRICT tables) or `_TRIGGER` (a `RAISE()` in a trigger).\n\nBy default the failing statement is undone (conflict mode `ABORT`) but earlier statements in the same transaction are kept.","causes":["A duplicate value in a primary key or unique column.","A NULL in a `NOT NULL` column, often because the insert left the column out and it has no default.","A value that fails a `CHECK` expression.","A child row whose parent doesn't exist, with `PRAGMA foreign_keys = ON`.","A value of the wrong type in a `STRICT` table."],"fix":[{"text":"Read the message or the extended code to see which constraint failed, then look at the table definition.","sql":"SELECT sql FROM sqlite_schema WHERE name = 'users';"},{"text":"For duplicates you want to merge or skip, use an upsert or a conflict clause.","sql":"INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada')\nON CONFLICT (email) DO UPDATE SET name = excluded.name;"},{"text":"For the other constraints, fix the data you are writing: supply the missing value, insert the parent row first, or correct the value that fails the check.","sql":null}],"diagnostic":"-- The error message already names the constraint and column. To see the full rule set:\nSELECT sql FROM sqlite_schema WHERE name = 'users';","alternatives":"If a duplicate should update the existing row, use INSERT ... ON CONFLICT (email) DO UPDATE. If it should be skipped, use INSERT OR IGNORE.","details":[],"details_title":null,"repro":"CREATE TABLE users (email TEXT UNIQUE);\nINSERT INTO users VALUES ('ada@example.com');\nINSERT INTO users VALUES ('ada@example.com');\n-- Runtime error: UNIQUE constraint failed: users.email (19)","repro_note":null,"related":["sqlite/sqlite-constraint-unique","sqlite/sqlite-constraint-primarykey","sqlite/sqlite-constraint-notnull","sqlite/sqlite-constraint-check","sqlite/sqlite-constraint-foreignkey","sqlite/sqlite-constraint-datatype"],"sqlly":"When an edit in SQLly's data grid fails a constraint, the change is staged as pending and the engine's message names the table and column, so you can fix that one cell and reapply instead of starting over.","faqs":[{"question":"Does a failed insert roll back my whole transaction?","answer":"No. In the default ABORT conflict mode only the failing statement is undone; statements that already ran in the same transaction stay, and the transaction remains open until you COMMIT or ROLLBACK."},{"question":"How do I find out which constraint failed from code?","answer":"Read the error message, which names the rule and column for unique, NOT NULL and CHECK failures (a foreign key failure only says FOREIGN KEY constraint failed), or the extended result code (SQLITE_CONSTRAINT_UNIQUE, _PRIMARYKEY, _NOTNULL, _CHECK, _FOREIGNKEY, _DATATYPE, _TRIGGER), which tells you the kind."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-check","corpus":"errors","engine":"sqlite","language":"en","title":"CHECK constraint failed","description":"A row failed a CHECK expression on the table. The message names the constraint, or shows the expression when the constraint has no name.","body":{"code":"SQLITE_CONSTRAINT_CHECK","slug":"sqlite-constraint-check","name":"275","message":"CHECK constraint failed: price_positive","group":"extended","severity":null,"sql_state":null,"summary":"A row failed a CHECK expression on the table. The message names the constraint, or shows the expression when the constraint has no name.","meaning":"`SQLITE_CONSTRAINT_CHECK` (275) means a value made a `CHECK` expression false. Name your constraints (`CONSTRAINT price_positive CHECK (price > 0)`) so the message tells you which rule failed; for an unnamed constraint recent versions of SQLite print the expression instead.\n\nA CHECK that evaluates to NULL passes, so `CHECK (price > 0)` doesn't reject a NULL price.","causes":["A value outside the allowed range or list.","Text that doesn't match a pattern such as `CHECK (email LIKE '%@%')`.","A CHECK written to emulate an enum or boolean, given an unexpected value."],"fix":[{"text":"Look at the constraint definition.","sql":"SELECT sql FROM sqlite_schema WHERE name = 'products';"},{"text":"Fix the value, or change the rule if the data is right and the rule is wrong. SQLite can't alter a CHECK in place; rebuild the table with the new definition.","sql":null},{"text":"Name constraints so failures are easy to read.","sql":"CREATE TABLE products (\n    id    INTEGER PRIMARY KEY,\n    price REAL NOT NULL CONSTRAINT price_positive CHECK (price > 0)\n);"}],"diagnostic":"-- Read the CHECK expressions on the table:\nSELECT sql FROM sqlite_schema WHERE name = 'products';\n-- Then test the failing value against each expression in a plain SELECT.","alternatives":"If the data is valid and the rule is wrong, the table must be rebuilt: SQLite cannot alter a CHECK in place. Create the new definition, copy rows over, drop and rename.","details":[],"details_title":null,"repro":"CREATE TABLE products (price REAL CHECK (price > 0));\nINSERT INTO products VALUES (-1);\n-- Runtime error: CHECK constraint failed: price > 0 (275; sqlite3 CLI prints the primary code 19)","repro_note":null,"related":["sqlite/sqlite-constraint","postgresql/23514","mysql/3819","sql-server/547"],"sqlly":"The table's CHECK expressions are in the definition SQLly's schema browser shows, and you can test a rejected value against them in the query editor without touching any data.","faqs":[{"question":"Does NULL pass a CHECK constraint?","answer":"Yes. A CHECK that evaluates to NULL passes, so CHECK (price > 0) accepts a NULL price. Add NOT NULL if that matters."},{"question":"Why doesn't the error name my constraint?","answer":"It does if you named it with CONSTRAINT. Unnamed CHECKs are reported by expression text, which recent SQLite versions print instead."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-check","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-datatype","corpus":"errors","engine":"sqlite","language":"en","title":"value doesn't fit a STRICT column","description":"A STRICT table rejected a value that cannot be losslessly converted to the column's declared type, such as non-numeric text in an INTEGER column.","body":{"code":"SQLITE_CONSTRAINT_DATATYPE","slug":"sqlite-constraint-datatype","name":"3091","message":"cannot store TEXT value in INTEGER column t.qty","group":"extended","severity":null,"sql_state":null,"summary":"A STRICT table rejected a value that cannot be losslessly converted to the column's declared type, such as non-numeric text in an INTEGER column.","meaning":"`STRICT` tables (SQLite 3.37 and later) enforce column types: an `INTEGER` column only accepts integers (or text and reals that convert to an integer without loss), `TEXT` stores numbers as text, and so on. A value that doesn't fit fails with `SQLITE_CONSTRAINT_DATATYPE` (3091). Ordinary tables use type affinity instead and store the value anyway.","causes":["Inserting a string such as `'12 pcs'` into an `INTEGER` column of a STRICT table.","A driver binding numbers as text, or dates as a type the column doesn't accept."],"fix":[{"text":"Convert the value before storing it, or bind it with the right type.","sql":"INSERT INTO t (qty) VALUES (CAST('12' AS INTEGER));"},{"text":"If a column must hold mixed types, declare it `ANY` in the STRICT table.","sql":null}],"diagnostic":"-- Confirm the table is STRICT and see the declared type of each column:\nSELECT sql FROM sqlite_schema WHERE name = 't';\nPRAGMA table_info(t);","alternatives":"If a column must hold mixed types in a STRICT table, declare it ANY. If most values are one type but a few are not, it is often cleaner to keep the column typed and store the odd values in a separate ANY column.","details":[],"details_title":null,"repro":"CREATE TABLE t (qty INTEGER) STRICT;\nINSERT INTO t VALUES ('abc');  -- cannot store TEXT value in INTEGER column t.qty","repro_note":null,"related":["sqlite/sqlite-mismatch","sqlite/sqlite-constraint","postgresql/22P02","mysql/1366","sql-server/245"],"sqlly":"The table definition in SQLly's schema browser shows the STRICT option and each column's declared type, so the accepted types are visible before you write the insert.","faqs":[{"question":"Can I convert an existing table to STRICT?","answer":"No. There is no ALTER TABLE for it. Rebuild: create the new table with STRICT, copy the rows across, and swap the names inside a transaction, cleaning any values that would not fit first."},{"question":"Why does '12' work but '12 pcs' fail in an INTEGER column?","answer":"STRICT tables accept text that converts to an integer without loss, so '12' is stored as the integer 12. '12 pcs' contains characters after the number that are not part of a numeric literal, so it cannot convert losslessly and is rejected. Leading and trailing spaces are ignored, so ' 12 ' is also stored as 12."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-datatype","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-foreignkey","corpus":"errors","engine":"sqlite","language":"en","title":"FOREIGN KEY constraint failed","description":"A write would leave a child row pointing at a parent that doesn't exist, or delete a parent that still has children. Foreign keys must be switched on per connection.","body":{"code":"SQLITE_CONSTRAINT_FOREIGNKEY","slug":"sqlite-constraint-foreignkey","name":"787","message":"FOREIGN KEY constraint failed","group":"extended","severity":null,"sql_state":null,"summary":"A write would leave a child row pointing at a parent that doesn't exist, or delete a parent that still has children. Foreign keys must be switched on per connection.","meaning":"`SQLITE_CONSTRAINT_FOREIGNKEY` (787) means a foreign key check failed. SQLite only enforces foreign keys on connections that run `PRAGMA foreign_keys = ON`; it is off by default for backward compatibility, which is why the same insert can succeed in one tool and fail in another.\n\nThe message doesn't say which key failed. `PRAGMA foreign_key_check` lists every violating row.","causes":["Inserting a child row whose parent id doesn't exist.","Deleting a parent row that still has children, without `ON DELETE CASCADE` or `SET NULL`. Changing a parent key that children still reference needs `ON UPDATE CASCADE` or `ON UPDATE SET NULL`, because the ON DELETE action does not apply to updates.","Loading tables in the wrong order: children before parents.","Deferred constraints (`DEFERRABLE INITIALLY DEFERRED`) failing at `COMMIT`."],"fix":[{"text":"Find the rows that break a foreign key.","sql":"PRAGMA foreign_key_check;\nPRAGMA foreign_key_list(orders);"},{"text":"Insert parents before children, or delete children before parents.","sql":null},{"text":"For bulk loads, defer checking to the end of the transaction.","sql":"BEGIN;\nPRAGMA defer_foreign_keys = ON;\n-- load tables in any order\nCOMMIT;"},{"text":"If deleting a parent should remove its children, declare the action on the foreign key.","sql":"CREATE TABLE orders (\n    id          INTEGER PRIMARY KEY,\n    customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE CASCADE\n);"}],"diagnostic":"-- The message names no key, so ask the database which rows are broken:\nPRAGMA foreign_key_check;   -- table, rowid, parent table and fkid (index of the failing foreign key, same as foreign_key_list's id), for every violation\nPRAGMA foreign_keys;   -- 0 means enforcement is off and this error cannot come from this connection","alternatives":"For dumps and bulk loads, PRAGMA defer_foreign_keys = ON inside the transaction is usually simpler than reordering statements. For validation jobs that should report all problems at once rather than failing on the first row, run PRAGMA foreign_key_check and work from its output.","details":[],"details_title":null,"repro":"PRAGMA foreign_keys = ON;\nCREATE TABLE p (id INTEGER PRIMARY KEY);\nCREATE TABLE c (pid INTEGER REFERENCES p(id));\nINSERT INTO c VALUES (1);  -- Runtime error: FOREIGN KEY constraint failed (19)","repro_note":null,"related":["sqlite/sqlite-constraint","postgresql/23503","mysql/1452","mysql/1451","sql-server/547","oracle/ora-02291","oracle/ora-02292"],"sqlly":"SQLly's ER diagram draws the foreign keys between your SQLite tables, so you can see which parent a failing insert depends on.","faqs":[{"question":"Why are foreign keys not enforced in my SQLite database?","answer":"Enforcement is per connection and off by default. Each connection has to run PRAGMA foreign_keys = ON, and it cannot be changed inside a transaction."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-foreignkey","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-notnull","corpus":"errors","engine":"sqlite","language":"en","title":"NOT NULL constraint failed","description":"An INSERT or UPDATE tried to store NULL in a NOT NULL column, often because the column was left out and has no default. The message names it.","body":{"code":"SQLITE_CONSTRAINT_NOTNULL","slug":"sqlite-constraint-notnull","name":"1299","message":"NOT NULL constraint failed: users.name","group":"extended","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE tried to store NULL in a NOT NULL column, often because the column was left out and has no default. The message names it.","meaning":"`SQLITE_CONSTRAINT_NOTNULL` (1299) means a `NOT NULL` column would have received NULL. That happens when you pass NULL explicitly, and also when an `INSERT` leaves out a `NOT NULL` column that has no `DEFAULT`, because the missing column gets NULL.","causes":["The `INSERT` column list leaves out a required column with no default.","The application passed NULL or None for a value it didn't have.","Adding a `NOT NULL` column in a table rebuild without filling it for existing rows."],"fix":[{"text":"Supply a value for the column, or give it a default.","sql":"INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada');"},{"text":"Check which columns are required.","sql":"PRAGMA table_info(users);  -- notnull = 1, dflt_value"},{"text":"To add a required column to an existing table, give it a default so existing rows get a value.","sql":"ALTER TABLE users ADD COLUMN status TEXT NOT NULL DEFAULT 'active';"}],"diagnostic":"-- The message names the table and column. See whether other columns are required and whether\n-- they have defaults, since a left-out column with no default becomes NULL:\nPRAGMA table_info(users);   -- notnull = 1 marks the strict columns; dflt_value shows the fallback","alternatives":"If the column is genuinely optional, drop the NOT NULL or give it a DEFAULT rather than passing empty strings to dodge the constraint. An empty string satisfies NOT NULL but is not the same as NULL and will surprise later queries.","details":[],"details_title":null,"repro":"CREATE TABLE users (email TEXT, name TEXT NOT NULL);\nINSERT INTO users (email) VALUES ('a@x');  -- Runtime error near line 2: NOT NULL constraint failed: users.name (19)","repro_note":null,"related":["sqlite/sqlite-constraint","postgresql/23502","mysql/1048","sql-server/515","oracle/ora-01400"],"sqlly":"SQLly's data grid stages edits as pending changes and shows the engine's message when applying them fails, so you can fill the one cell that needs the value and reapply.","faqs":[{"question":"Why does the INSERT fail when I never passed NULL?","answer":"An INSERT that leaves out a column without a DEFAULT fills that column with NULL, which then hits the constraint. Check PRAGMA table_info to see which columns are notnull and which have defaults."},{"question":"How do I find rows that would break a new NOT NULL rule during a table rebuild?","answer":"Before copying rows, run SELECT count(*) FROM old WHERE col IS NULL. Decide whether to backfill, default, or reject those rows first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-notnull","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-primarykey","corpus":"errors","engine":"sqlite","language":"en","title":"PRIMARY KEY constraint failed","description":"An INSERT or UPDATE would duplicate a primary key value. SQLite's message still says UNIQUE constraint failed and names the key column.","body":{"code":"SQLITE_CONSTRAINT_PRIMARYKEY","slug":"sqlite-constraint-primarykey","name":"1555","message":"UNIQUE constraint failed: orders.id","group":"extended","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE would duplicate a primary key value. SQLite's message still says UNIQUE constraint failed and names the key column.","meaning":"`SQLITE_CONSTRAINT_PRIMARYKEY` (1555) is the extended code for a duplicate primary key. The message text is the same as for any unique violation, `UNIQUE constraint failed: table.column`, so the extended code is how a program tells the two apart.\n\nFor an `INTEGER PRIMARY KEY` column you can leave the value out (or pass NULL) and SQLite assigns the next rowid, which avoids most collisions.","causes":["Inserting an explicit id that already exists.","Copying rows between databases with their ids, where the ranges overlap.","Generating ids in the application with a scheme that can repeat."],"fix":[{"text":"Let SQLite assign `INTEGER PRIMARY KEY` values by leaving the column out.","sql":"INSERT INTO orders (total) VALUES (19.99);\nSELECT last_insert_rowid();"},{"text":"When merging data, upsert on the key or skip existing rows.","sql":"INSERT INTO orders (id, customer_id, total)\nSELECT id, customer_id, total FROM other.orders WHERE true\nON CONFLICT (id) DO NOTHING;"}],"diagnostic":"-- Find the row that already holds the key:\nSELECT * FROM orders WHERE id = 1;","alternatives":"For INTEGER PRIMARY KEY columns, leave the id out of the INSERT and let SQLite assign the next rowid. When merging two databases, remap ids into a free range or upsert on a natural key instead of copying ids directly.","details":[],"details_title":null,"repro":"CREATE TABLE orders (id INTEGER PRIMARY KEY, total REAL);\nINSERT INTO orders VALUES (1, 9.99);\nINSERT INTO orders VALUES (1, 5.00);  -- Runtime error near line 3: UNIQUE constraint failed: orders.id (19)","repro_note":null,"related":["sqlite/sqlite-constraint-unique","sqlite/sqlite-mismatch","sqlite/sqlite-constraint","postgresql/23505","mysql/1062"],"sqlly":"In SQLly's data grid you can filter to the id the message names and see the row that already holds it, and the message shown matches SQLite's UNIQUE wording even though the code is the primary-key one.","faqs":[{"question":"Why does the message say UNIQUE constraint failed when the problem is the primary key?","answer":"A primary key is checked as a unique key: a non-integer primary key gets an automatic unique index, while an INTEGER PRIMARY KEY is the rowid and has no separate index. Either way the message text is identical to any unique violation. Only the extended result code (1555 versus 2067) tells the two apart, which is what makes this code useful to programs."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-primarykey","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-trigger","corpus":"errors","engine":"sqlite","language":"en","title":"RAISE() in a trigger aborted it","description":"A trigger called RAISE(ABORT, ...), RAISE(FAIL, ...) or RAISE(ROLLBACK, ...) and stopped the statement. The message is the text the trigger passed to RAISE.","body":{"code":"SQLITE_CONSTRAINT_TRIGGER","slug":"sqlite-constraint-trigger","name":"1811","message":"n must not be negative","group":"extended","severity":null,"sql_state":null,"summary":"A trigger called RAISE(ABORT, ...), RAISE(FAIL, ...) or RAISE(ROLLBACK, ...) and stopped the statement. The message is the text the trigger passed to RAISE.","meaning":"`SQLITE_CONSTRAINT_TRIGGER` (1811) means a `RAISE()` function inside a trigger fired. Triggers use it to enforce rules a CHECK can't express, such as rules that look at other tables. The error message is the text given to `RAISE`, so a well-written trigger tells you exactly what was wrong.","causes":["The data broke a business rule enforced by a trigger.","A trigger left over from an older version of the schema, enforcing a rule that no longer applies."],"fix":[{"text":"Read the message and find the trigger that raised it.","sql":"SELECT name, sql FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = 'orders';"},{"text":"Fix the data, or drop and recreate the trigger if the rule is outdated.","sql":"DROP TRIGGER IF EXISTS orders_no_negative_total;"}],"diagnostic":"-- The message text is whatever the trigger passed to RAISE(). List the triggers that could\n-- have raised it:\nSELECT name, sql FROM sqlite_schema WHERE type = 'trigger' AND sql LIKE '%RAISE(%';","alternatives":"If the rule only looks at the row being written, a CHECK constraint is simpler: it sits inside the CREATE TABLE next to the column it guards, with no separate trigger to find or order. Keep triggers for rules that need other tables or aggregate state.","details":[],"details_title":null,"repro":"CREATE TABLE t (n INTEGER);\nCREATE TRIGGER t_positive BEFORE INSERT ON t WHEN NEW.n < 0\nBEGIN SELECT RAISE(ABORT, 'n must not be negative'); END;\nINSERT INTO t VALUES (-1);  -- Runtime error near line 4: n must not be negative (19)","repro_note":null,"related":["sqlite/sqlite-constraint","sqlite/sqlite-abort","oracle/ora-04088"],"sqlly":"The message is the trigger's own text, and SQLly shows it with the failing statement highlighted; the trigger's SQL is in the schema browser next to its table.","faqs":[{"question":"What is the difference between RAISE(ABORT, ...), RAISE(FAIL, ...) and RAISE(ROLLBACK, ...)?","answer":"ABORT undoes the current statement and leaves the transaction open. FAIL stops at the offending row but keeps earlier rows of the statement. ROLLBACK undoes the whole transaction. A fourth form, RAISE(IGNORE), silently skips the row instead of raising an error."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-trigger","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-constraint-unique","corpus":"errors","engine":"sqlite","language":"en","title":"UNIQUE constraint failed","description":"An INSERT or UPDATE would duplicate a value in a UNIQUE column or unique index. The message names the table and column.","body":{"code":"SQLITE_CONSTRAINT_UNIQUE","slug":"sqlite-constraint-unique","name":"2067","message":"UNIQUE constraint failed: users.email","group":"extended","severity":null,"sql_state":null,"summary":"An INSERT or UPDATE would duplicate a value in a UNIQUE column or unique index. The message names the table and column.","meaning":"SQLite returns `SQLITE_CONSTRAINT_UNIQUE` (2067) when a write would create two rows with the same value in a `UNIQUE` constraint or unique index. The message lists the columns, as `table.column`, comma-separated for a multi-column key. Duplicate primary keys are reported with `SQLITE_CONSTRAINT_PRIMARYKEY` but use the same message text.\n\nNULLs don't count as duplicates: a unique column can hold any number of NULLs.","causes":["Inserting a row that already exists, for example re-running an import.","Two values that differ only in case, in a column declared `COLLATE NOCASE`.","An `UPDATE` that sets the column to a value another row already has."],"fix":[{"text":"Find the existing row.","sql":"SELECT * FROM users WHERE email = 'ada@example.com';"},{"text":"Update the existing row instead, with an upsert (SQLite 3.24 and later).","sql":"INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada')\nON CONFLICT (email) DO UPDATE SET name = excluded.name;"},{"text":"Or skip duplicates on purpose.","sql":"INSERT OR IGNORE INTO users (email, name) VALUES ('ada@example.com', 'Ada');"}],"diagnostic":"-- The message names the columns. Find the row that already holds the value:\nSELECT rowid, * FROM users WHERE email = 'ada@example.com';\n-- For a multi-column key, match every column the message lists:\nSELECT rowid, * FROM memberships WHERE user_id = 7 AND role = 'admin';","alternatives":"For import jobs, staging the incoming rows in a temp table and merging with one INSERT ... SELECT ... WHERE true ON CONFLICT statement keeps the dedup logic in a single place. The WHERE clause is required: without it SQLite reports a syntax error near DO.","details":[],"details_title":null,"repro":"CREATE TABLE users (email TEXT UNIQUE);\nINSERT INTO users VALUES ('a@x');\nINSERT INTO users VALUES ('a@x');  -- Runtime error: UNIQUE constraint failed: users.email (19)","repro_note":null,"related":["sqlite/sqlite-constraint-primarykey","sqlite/sqlite-constraint","postgresql/23505","mysql/1062","sql-server/2627","sql-server/2601","oracle/ora-00001"],"sqlly":"When a grid edit or CSV import hits a duplicate in SQLly, the engine's message names the table and column; filtering the data grid to that value shows the row already holding it.","faqs":[{"question":"What is the difference between INSERT OR REPLACE and an upsert?","answer":"`INSERT OR REPLACE` deletes the conflicting row and inserts a new one, so columns you didn't supply are reset. Delete triggers fire only when `PRAGMA recursive_triggers` is on, and foreign key actions fire when `PRAGMA foreign_keys` is on. An upsert with `ON CONFLICT DO UPDATE` changes the existing row in place."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-constraint-unique","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-corrupt","corpus":"errors","engine":"sqlite","language":"en","title":"database disk image is malformed","description":"SQLite found the database file's structure damaged. Stop writing to it, take a copy, and recover what you can with the .recover command or from a backup.","body":{"code":"SQLITE_CORRUPT","slug":"sqlite-corrupt","name":"11","message":"database disk image is malformed","group":"primary","severity":null,"sql_state":null,"summary":"SQLite found the database file's structure damaged. Stop writing to it, take a copy, and recover what you can with the .recover command or from a backup.","meaning":"`SQLITE_CORRUPT` (11) means SQLite read something in the file that doesn't fit its format: a broken page, a bad pointer, an index entry with no matching row. SQLite doesn't corrupt files on its own in normal use; the SQLite documentation (\"How To Corrupt An SQLite Database File\") lists what does: files copied while a transaction is open, broken file locking (often on network file systems), deleting a hot journal, hardware or storage faults, `PRAGMA synchronous=OFF`, bugs in SQLite itself, and writes into the file by other code.\n\n`SQLITE_CORRUPT_INDEX` is a special case where only an index is damaged and `REINDEX` may fix it.","causes":["Copying or backing up the database file while it was being written, which can leave half-applied changes in the copy, or copying a WAL-mode database without its `-wal` file, which silently drops the transactions that were only in the `-wal`.","Deleting a `-journal` or `-wal` file left after a crash. A deleted hot journal can leave half-applied changes that `PRAGMA integrity_check` still reports as ok.","A network file system or container volume with unreliable locking, letting two writers in at once.","Disk, memory or power failures, or a storage layer that ignores fsync.","Another part of the program writing to the file directly through an open file descriptor."],"fix":[{"text":"Stop writing to the database and make a copy of the file and any `-wal` and `-journal` files before you try anything.","sql":null},{"text":"Measure the damage.","sql":"PRAGMA integrity_check;"},{"text":"If `integrity_check` names only an index (for example `row 2 missing from index`), rebuild it. If `REINDEX` itself fails with `database disk image is malformed (11)`, the index pages are damaged, so go to the recovery step.","sql":"REINDEX;"},{"text":"Otherwise recover the data into a new file with the `sqlite3` shell's `.recover` command, then check the result: `sqlite3 broken.db .recover | sqlite3 recovered.db`.","sql":null},{"text":"Restore from a backup if the recovery is incomplete, and make future backups with `VACUUM INTO` or the backup API rather than copying the file while it is in use.","sql":"VACUUM INTO '/backups/app-2026-11-09.db';"}],"diagnostic":"-- Run the integrity checker. quick is faster and checks most of the file:\nPRAGMA quick_check;\n-- Full check on a copy if you need certainty:\nPRAGMA integrity_check;","alternatives":"Restore from a backup taken with the .backup command or the backup API, which do not copy half-written state on a live database; while a writer holds the lock, `.backup` can fail with `database is locked` instead, so retry once the writer finishes. A file-level copy taken while SQLite was writing is often the corruption itself, so don't retry that method.","details":[],"details_title":null,"repro":"sqlite3 scratch.db 'CREATE TABLE t(x); INSERT INTO t VALUES (1);'\ncp scratch.db broken.db\nprintf 'XXXX' | dd of=broken.db bs=1 seek=4096 conv=notrunc   -- scramble the start of the copy's page 2\nsqlite3 broken.db 'PRAGMA integrity_check;'\n-- Error: stepping, database disk image is malformed (11)","repro_note":"Page 2 starts at byte 4096 with the default page size. Corrupt a scratch copy only; the printf overwrites 4 bytes in place.","related":["sqlite/sqlite-notadb","sqlite/sqlite-ioerr","sqlite/sqlite-busy","sql-server/824"],"sqlly":"Copy the damaged file first and inspect only the copy. The SQLly read-only setting blocks SQL writes but not SQLite's hot-journal rollback, which runs when the file is opened and changes its bytes, so keep the original, and any -journal or -wal beside it, untouched until recovery is done. Whatever still loads shows up in the schema browser and the data grid.","faqs":[{"question":"Can SQLite recover the file by itself?","answer":"Sometimes. The .recover command in the shell salvages what it can into a new database, but expect some loss. Copy the damaged file first."},{"question":"I copied the .db file and now it's corrupt. Why?","answer":"A plain copy taken while the database was writing can hold half-applied changes, and integrity_check can still pass on it. A copy of a WAL-mode database made without its -wal file is valid but silently lacks the transactions still in that file. Use the backup API or stop all writers first."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-corrupt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-corrupt-index","corpus":"errors","engine":"sqlite","language":"en","title":"index entry missing","description":"SQLite found an index that is missing an entry for a row. Running REINDEX may repair it, if nothing else in the file is damaged.","body":{"code":"SQLITE_CORRUPT_INDEX","slug":"sqlite-corrupt-index","name":"779","message":"database disk image is malformed","group":"extended","severity":null,"sql_state":null,"summary":"SQLite found an index that is missing an entry for a row. Running REINDEX may repair it, if nothing else in the file is damaged.","meaning":"`SQLITE_CORRUPT_INDEX` (779) is a special case of `SQLITE_CORRUPT`: an entry is or was missing from an index. Because indexes can be rebuilt from their tables, the SQLite documentation notes that `REINDEX` may fix the problem as long as there is no other damage.\n\nA common cause is changing a collation or a function used by an index (for example after upgrading an extension) so that existing index entries no longer sort the way SQLite expects.","causes":["A custom collation or deterministic function used by an index changed its behavior.","General file damage that happened to hit an index page."],"fix":[{"text":"Rebuild the indexes, then check the whole file.","sql":"REINDEX;\nPRAGMA integrity_check;"},{"text":"If the integrity check still reports problems, treat it as `SQLITE_CORRUPT`: copy the file and recover with `.recover`.","sql":null}],"diagnostic":"-- integrity_check names the index that has the problem, for example \"row 30 missing from index my_index\":\nPRAGMA integrity_check;","alternatives":"If REINDEX clears integrity_check, you are done. If it does not, the damage goes beyond the index: restore from a backup, or use .recover in the sqlite3 CLI to build a new file from whatever is readable.","details":[],"details_title":null,"repro":"-- Not reproducible from SQL alone: the sqlite3 CLI cannot register a collation.\n# Python, on a scratch file only:\n# c = sqlite3.connect('scratch.db'); c.create_collation('v385coll', lambda a, b: (a < b) - (a > b))\n# c.execute('CREATE TABLE t(id INTEGER PRIMARY KEY, x TEXT)'); c.execute('CREATE INDEX i ON t(x COLLATE v385coll)')\n# c.executemany('INSERT INTO t(x) VALUES (?)', [(s,) for s in 'abcdefgh']); c.commit()\n# reopen, then register v385coll as lambda a, b: (b < a) - (b > a)\n# UPDATE t SET x = 'zz' WHERE id = 3   -> SQLITE_CORRUPT_INDEX (779)","repro_note":null,"related":["sqlite/sqlite-corrupt","sqlite/sqlite-error-missing-collseq"],"sqlly":"REINDEX and PRAGMA integrity_check run fine from SQLly's query editor, and re-opening the table in the data grid afterwards shows reads coming back clean.","faqs":[{"question":"Why did this appear after an upgrade?","answer":"Indexes store entries in collation order. If a custom collation or a user-defined function used by the index now sorts differently, existing entries no longer match what SQLite expects, and lookups that use that collation find gaps. Rebuilding the index re-sorts everything."},{"question":"Is rebuilding an index safe?","answer":"Yes. An index is derived data; REINDEX rebuilds it from the table rows. It cannot lose table data, and it is the right first step before assuming the file is truly corrupt. REINDEX can still fail: if the new collation makes two stored values equal under a UNIQUE index, it stops with \"UNIQUE constraint failed\" and leaves the table rows as they were."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-corrupt-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-error","corpus":"errors","engine":"sqlite","language":"en","title":"SQL logic error","description":"SQLite's generic error code: a syntax error, a missing table or column, or another problem with the SQL. The real reason is in the error message, not the code.","body":{"code":"SQLITE_ERROR","slug":"sqlite-error","name":"1","message":"SQL logic error","group":"primary","severity":null,"sql_state":null,"summary":"SQLite's generic error code: a syntax error, a missing table or column, or another problem with the SQL. The real reason is in the error message, not the code.","meaning":"`SQLITE_ERROR` (1) is the code SQLite uses when no more specific code applies. Almost every mistake in the SQL itself lands here: a typo, a table or column that doesn't exist, a table that already exists, a wrong number of values. The generic text is `SQL logic error`; the message from `sqlite3_errmsg()` says what actually went wrong, for example `no such table: users`, `no such column: emial`, `near \"FORM\": syntax error` or `table users already exists`.\n\nBecause one code covers so many problems, always log and read the message.","causes":["A syntax error: `near \"...\": syntax error` points at the token where parsing failed.","`no such table`: the table name is misspelled, the table lives in a database file that isn't attached to this connection, or the program opened a different (often new and empty) database file than you think.","`no such column`: a misspelled column. A string literal in double quotes doesn't produce this error by default: if no column matches, SQLite reads it as a string.","`table ... already exists` from a `CREATE TABLE` without `IF NOT EXISTS`.","Using syntax or functions that your SQLite version is too old to support, such as `RETURNING` (3.35) or window functions (3.25)."],"fix":[{"text":"Read the full message and fix what it names. Check the schema you are actually connected to:","sql":"SELECT name, type FROM sqlite_schema ORDER BY name;\nPRAGMA table_info(users);"},{"text":"If a table is missing, check which file is open. A relative path opens a file relative to the process's working directory, and opening a path that doesn't exist creates a new empty database.","sql":"PRAGMA database_list;"},{"text":"Use single quotes for string literals and double quotes only for identifiers.","sql":"SELECT * FROM users WHERE status = 'active';"},{"text":"Check the library version when newer syntax fails.","sql":"SELECT sqlite_version();"}],"diagnostic":"-- The message names the token and object. Check what actually exists in the database you are connected to:\nSELECT name, type FROM sqlite_master WHERE type IN ('table','view') ORDER BY name;\n-- Check a specific table's columns before writing a query against it:\nPRAGMA table_info(my_table);","alternatives":"If a table or column is genuinely missing, decide whether a migration should create it rather than working around the query. For double-quoted strings that get read as column names, switch to single quotes for literals.","details":[],"details_title":null,"repro":"SELECT * FROM no_such_table;   -- Parse error near line 1: no such table: no_such_table","repro_note":null,"related":["sqlite/sqlite-schema","sqlite/sqlite-cantopen","sql-server/208","postgresql/42P01","mysql/1146","oracle/ora-00942"],"sqlly":"When a statement fails, SQLly highlights the token SQLite complained about and moves the editor to it. Validate SQL (Cmd+Shift+V on macOS, Ctrl+Shift+V elsewhere) checks a query against the connection's schema without running it and marks unknown tables and columns.","faqs":[{"question":"Why does my string in double quotes fail?","answer":"SQLite treats a double-quoted name as an identifier when a column matches. If none matches, SQLite reads it as a string literal, a misfeature kept for compatibility and present in default builds. It can be disabled at compile time with -DSQLITE_DQS=0 or at run time with sqlite3_db_config. Use single quotes for string values and double quotes only for identifiers."},{"question":"The table exists but SQLite says it doesn't. Why?","answer":"You are probably connected to a different database file, or the file that holds the table isn't attached to this connection. An attached table is found without a prefix. Qualify it (backup.users) only when the same name also exists in main, which is searched first, or to be explicit."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-error","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-error-missing-collseq","corpus":"errors","engine":"sqlite","language":"en","title":"no such collation sequence","description":"The SQL, or the schema it touches, uses a collation this connection doesn't have, usually a custom collation registered by another application.","body":{"code":"SQLITE_ERROR_MISSING_COLLSEQ","slug":"sqlite-error-missing-collseq","name":"257","message":"no such collation sequence: unicode_ci","group":"extended","severity":null,"sql_state":null,"summary":"The SQL, or the schema it touches, uses a collation this connection doesn't have, usually a custom collation registered by another application.","meaning":"`SQLITE_ERROR_MISSING_COLLSEQ` (257) means a statement couldn't be prepared because a collating sequence it names isn't registered on this connection. SQLite has three built-in collations, `BINARY`, `NOCASE` and `RTRIM`; anything else must be registered by the application with `sqlite3_create_collation()`. A database created by an app that registers its own collation can't be fully used by tools that don't.","causes":["The schema declares a column or index with a custom collation, such as one from an ICU extension or an application.","The extension that provides the collation isn't loaded in this tool or program."],"fix":[{"text":"Find where the collation is used.","sql":"SELECT name, sql FROM sqlite_schema WHERE sql LIKE '%COLLATE%';"},{"text":"Load the extension or register the collation in your program before running the statement.","sql":null},{"text":"Or rebuild the table so the affected column declares a built-in collation, if the custom one isn't needed. Copy the rows into a new table, then rename it.","sql":"CREATE TABLE users_new (id INTEGER PRIMARY KEY, name TEXT COLLATE NOCASE);\nINSERT INTO users_new SELECT id, name FROM users;\nDROP TABLE users;\nALTER TABLE users_new RENAME TO users;\nCREATE INDEX idx_users_name ON users(name);"}],"diagnostic":"-- Find every column and index that references a collation:\nSELECT name, sql FROM sqlite_schema WHERE sql LIKE '%COLLATE%';","alternatives":"If the custom collation is not needed, rebuild the table so the column declares a built-in one (BINARY, NOCASE or RTRIM); otherwise load the extension that registers it before using the database.","details":[],"details_title":null,"repro":"-- On a scratch connection with no custom collations loaded:\nCREATE TABLE t (name TEXT COLLATE unicode_ci);\n-- Prepare error: no such collation sequence: unicode_ci (257)","repro_note":null,"related":["sqlite/sqlite-error","sqlite/sqlite-schema"],"sqlly":"SQLly's schema browser shows table definitions, where the COLLATE clauses naming the missing collation live, so you can see every column and index that depends on it before rebuilding any.","faqs":[{"question":"Which collations are built in?","answer":"Only BINARY, NOCASE and RTRIM. Every other name, including ICU collations, must be registered by the application with sqlite3_create_collation()."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-error-missing-collseq","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-full","corpus":"errors","engine":"sqlite","language":"en","title":"database or disk is full","description":"A write failed because the disk, or the partition used for temporary files, ran out of space, or the database hit its max_page_count limit.","body":{"code":"SQLITE_FULL","slug":"sqlite-full","name":"13","message":"database or disk is full","group":"primary","severity":null,"sql_state":null,"summary":"A write failed because the disk, or the partition used for temporary files, ran out of space, or the database hit its max_page_count limit.","meaning":"`SQLITE_FULL` (13) means SQLite couldn't finish a write for lack of space. The SQLite documentation points out a common surprise: the space can run out in the temporary directory rather than where the database lives, because large sorts, index builds and `VACUUM` write temporary files, and the temp partition may be much smaller.\n\nThe same code is returned when the database reaches the page limit set with `PRAGMA max_page_count`.","causes":["The disk holding the database, its journal or its WAL file is full.","The temporary directory is on a small partition (for example a small `/tmp`), and a big `ORDER BY`, `CREATE INDEX` or `VACUUM` filled it.","`PRAGMA max_page_count` caps the database size.","A WAL file that has grown very large because checkpoints can't complete."],"fix":[{"text":"Free space on the volume, or move the database to a larger one.","sql":null},{"text":"Point temporary files at a larger directory with the `SQLITE_TMPDIR` or `TMPDIR` environment variable, or keep them in memory if the data fits.","sql":"PRAGMA temp_store = MEMORY;"},{"text":"Check and raise the page limit if one is set.","sql":"PRAGMA max_page_count;\nPRAGMA max_page_count = 2147483646;"},{"text":"In WAL mode, run a checkpoint to shrink the WAL once readers are done.","sql":"PRAGMA wal_checkpoint(TRUNCATE);"}],"diagnostic":"-- How full is the database now, and is a page cap set?\nPRAGMA page_count;\nPRAGMA max_page_count;\nPRAGMA freelist_count; -- pages already free inside the file\n-- In the shell, check the volume holding the db and its temp dir: df -h .","alternatives":"VACUUM returns free pages to the operating system, but it needs free disk space of up to twice the size of the database, so free disk first. If max_page_count was set deliberately, raise it or split the data across an attached database.","details":[],"details_title":null,"repro":"sqlite3 scratch.db 'PRAGMA max_page_count = 2;\nCREATE TABLE t(x);\nINSERT INTO t VALUES (zeroblob(1000000));'\n-- Error: stepping, database or disk is full (13)","repro_note":null,"related":["sqlite/sqlite-ioerr","sql-server/1105","sql-server/9002","oracle/ora-01653"],"sqlly":"SQLly's disk usage view reports a SQLite database's size and how much of it is reclaimable free pages, so you can see what VACUUM would give back before running it. Deleting the rows you no longer need and then running VACUUM is one way to shrink the file for good.","faqs":[{"question":"Why does deleting rows not shrink the file?","answer":"Deleted pages go on the freelist for reuse but stay in the file. VACUUM rebuilds the database and actually shrinks it."},{"question":"Can a full temp directory cause SQLITE_FULL?","answer":"Yes. Large sorts, CREATE INDEX and VACUUM write temp files. If the temp directory sits on a small partition, the write fails even though the database volume has space."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-full","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-interrupt","corpus":"errors","engine":"sqlite","language":"en","title":"interrupted","description":"A running statement was stopped by sqlite3_interrupt(), usually because the user or the application cancelled it.","body":{"code":"SQLITE_INTERRUPT","slug":"sqlite-interrupt","name":"9","message":"interrupted","group":"primary","severity":null,"sql_state":null,"summary":"A running statement was stopped by sqlite3_interrupt(), usually because the user or the application cancelled it.","meaning":"`SQLITE_INTERRUPT` (9) is what a statement returns after `sqlite3_interrupt()` was called on its connection. Applications call it to cancel long queries, often from another thread when the user presses Cancel or a timeout fires. If the interrupted statement was an INSERT, UPDATE or DELETE inside an explicit transaction, SQLite rolls back the entire transaction automatically, so that transaction's uncommitted writes are gone and have to be run again.","causes":["The user cancelled the query in the application.","The application's own timeout called `sqlite3_interrupt()`.","A progress handler that returns non-zero, which also interrupts the statement."],"fix":[{"text":"If you cancelled on purpose, nothing is wrong. Check whether a transaction is still open before continuing (conn.in_transaction in Python). An interrupted INSERT, UPDATE or DELETE has already rolled it back, so a ROLLBACK then fails with \"cannot rollback - no transaction is active\"; an interrupted SELECT leaves the transaction open, so roll that one back or commit it.","sql":"ROLLBACK;"},{"text":"If a timeout interrupted a query that should finish, make it faster: check the plan and add an index for the filter or join.","sql":"EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 42;\nCREATE INDEX idx_orders_customer ON orders(customer_id);"}],"diagnostic":"-- No pragma shows an interrupt, since it comes from the host. Check your code for sqlite3_interrupt calls, progress handlers returning non-zero, and query timeouts.\n-- After an interrupt, check whether a transaction is still open before doing more writes, for example conn.in_transaction in Python.","alternatives":"Treat the interrupted statement as failed and re-run it. If interrupts happen without the user asking, look for a watchdog or timeout in the application that calls sqlite3_interrupt.","details":[],"details_title":null,"repro":"import sqlite3, threading\nconn = sqlite3.connect('scratch.db')\nthreading.Timer(0.5, conn.interrupt).start()\nconn.execute('WITH RECURSIVE c(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM c) SELECT count(*) FROM c')\n# sqlite3.OperationalError: interrupted","repro_note":"conn.interrupt() is Python's handle on sqlite3_interrupt(); the unbounded recursive query runs long enough to lose the race.","related":["sqlite/sqlite-abort","postgresql/57014","mysql/3024","sql-server/3621"],"sqlly":"Cancelling a query in SQLly interrupts the running SQLite statement, so a long query stops at its next check instead of finishing in the background. SQLly can also stop a statement that runs past the connection's statement timeout.","faqs":[{"question":"Was my data lost after SQLITE_INTERRUPT?","answer":"Committed data is untouched. The interrupted statement is undone, and if it was an INSERT, UPDATE or DELETE inside an explicit transaction, SQLite rolls back the whole transaction automatically, so that transaction's uncommitted writes are gone and have to be re-run."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-interrupt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-ioerr","corpus":"errors","engine":"sqlite","language":"en","title":"disk I/O error","description":"The operating system reported an I/O error while SQLite read, wrote, synced or locked a file. The extended code says which operation failed.","body":{"code":"SQLITE_IOERR","slug":"sqlite-ioerr","name":"10","message":"disk I/O error","group":"primary","severity":null,"sql_state":null,"summary":"The operating system reported an I/O error while SQLite read, wrote, synced or locked a file. The extended code says which operation failed.","meaning":"`SQLITE_IOERR` (10) means a file operation failed at the operating-system level. SQLite has many extended codes for it, such as `SQLITE_IOERR_READ`, `SQLITE_IOERR_WRITE`, `SQLITE_IOERR_FSYNC`, `SQLITE_IOERR_SHORT_READ` (fewer bytes than requested, for example a truncated file) and `SQLITE_IOERR_LOCK`. A full disk normally gives `SQLITE_FULL` instead.\n\nThe extended code is the best clue, so enable extended result codes or read them with `sqlite3_extended_errcode()`.","causes":["Failing or disconnected storage: a removed USB drive, an unmounted network share, a bad disk.","A network file system or sync folder that doesn't support the locking or syncing SQLite needs.","Antivirus or backup software holding or changing the file.","The file was truncated or replaced underneath an open connection. In a local test, truncating a rollback-mode database file under an open connection reported SQLITE_CORRUPT rather than an I/O error."],"fix":[{"text":"Read the extended code to see which operation failed, and check the operating system's logs for disk errors.","sql":null},{"text":"Keep the database on a local disk. If it must be shared, don't share the file: put a server in front of it.","sql":null},{"text":"Exclude the database, `-journal`, `-wal` and `-shm` files from antivirus scanning and file-sync tools.","sql":null},{"text":"After any I/O error, check the file before trusting it.","sql":"PRAGMA integrity_check;"}],"diagnostic":"-- The extended code tells you which low-level call failed: SQLITE_IOERR_READ (266), SQLITE_IOERR_WRITE (778), SQLITE_IOERR_SHORT_READ (522), SQLITE_IOERR_FSYNC (1034). Log the extended code, not just the base code.\n-- Rule out the file location first:\nPRAGMA database_list;\n-- In the shell, confirm the OS can still reach the file: ls -l and df -h on its volume","alternatives":"Move the database off network file systems and sync folders to local storage. If the disk is failing, copy the database and its WAL file to healthy storage before doing anything else.","details":[],"details_title":null,"repro":"-- Device-level failure, so there is no script that raises it honestly: the OS has to fail a\n-- read, write, sync or lock on the file (a pulled USB drive, an unmounted network share, a\n-- dying disk). Reproducing it means failing the storage underneath a live database.","repro_note":null,"related":["sqlite/sqlite-full","sqlite/sqlite-corrupt","sqlite/sqlite-ioerr-short-read","sqlite/sqlite-cantopen","sql-server/823"],"sqlly":"SQLly shows SQLite's message with the failed statement, and once the file has moved to healthy storage, updating the path in the connection editor and reconnecting is all it takes.","faqs":[{"question":"Why is SQLITE_IOERR common on network drives?","answer":"SQLite needs working byte-range locks and reliable fsync. Some network filesystems do not provide them reliably, so writes that look fine can fail or corrupt the file."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-ioerr","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-ioerr-short-read","corpus":"errors","engine":"sqlite","language":"en","title":"read returned fewer bytes","description":"A read in SQLite's VFS layer got fewer bytes than it asked for. The file may be truncated, but a truncated file usually reports SQLITE_CORRUPT (11) rather than this code.","body":{"code":"SQLITE_IOERR_SHORT_READ","slug":"sqlite-ioerr-short-read","name":"522","message":"disk I/O error","group":"extended","severity":null,"sql_state":null,"summary":"A read in SQLite's VFS layer got fewer bytes than it asked for. The file may be truncated, but a truncated file usually reports SQLITE_CORRUPT (11) rather than this code.","meaning":"`SQLITE_IOERR_SHORT_READ` (522) is an extended `SQLITE_IOERR` code: a read couldn't get as many bytes as requested. The SQLite documentation says this might be due to a truncated file.","causes":["The file was truncated by an interrupted copy, download or sync.","Another process truncated the file while it was open. That usually surfaces as SQLITE_CORRUPT (11), not this code."],"fix":[{"text":"Compare the file's size with the original or with a backup, and re-copy it.","sql":null},{"text":"Integrity check fails on a truncated file with `database disk image is malformed` and lists nothing. Recover what remains into a new file with `.recover`.","sql":"PRAGMA integrity_check;"}],"diagnostic":"-- Reads fewer bytes than the header promises, so this confirms the damage:\nPRAGMA integrity_check;","alternatives":"There is no SQL fix for a truncated file. Restore the database from a known-good copy, or if you have no backup, the .recover command in the sqlite3 CLI can salvage whatever is still readable into a new database file.","details":[],"details_title":null,"repro":"-- Not reproducible through ordinary SQL on the stock unix VFS: it zero-fills a short read and\n-- carries on, so a truncated file surfaces as SQLITE_CORRUPT (11) instead (a copy truncated to\n-- 100 bytes reports malformed on its first query). SQLITE_IOERR_SHORT_READ is what a VFS layer\n-- returns when it reports the shortfall itself, typically a custom or wrapped VFS.","repro_note":null,"related":["sqlite/sqlite-ioerr","sqlite/sqlite-corrupt"],"sqlly":"This is a file problem, not a query problem: restore or re-copy the file, then reconnect in SQLly and check the tables load in the sidebar.","faqs":[{"question":"Can SQLite repair a truncated file on its own?","answer":"No. The short read is not returned to your query: it fails with SQLITE_CORRUPT (11), \"database disk image is malformed\". Repair means restoring a backup or dumping what remains with .recover into a fresh file."},{"question":"Why did this start after I synced or copied the database?","answer":"Copying or syncing a database file while a connection is writing produces partial copies. Stop the writers, or use the backup API or the .backup command, which copy a consistent file."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-ioerr-short-read","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-locked","corpus":"errors","engine":"sqlite","language":"en","title":"database table is locked","description":"A write couldn't continue because of a conflict inside the same connection or shared cache, such as dropping a table a statement is still reading.","body":{"code":"SQLITE_LOCKED","slug":"sqlite-locked","name":"6","message":"database table is locked","group":"primary","severity":null,"sql_state":null,"summary":"A write couldn't continue because of a conflict inside the same connection or shared cache, such as dropping a table a statement is still reading.","meaning":"`SQLITE_LOCKED` (6) means the conflict is within your own connection, or between connections sharing a cache, not with another process. The classic example from the SQLite documentation is a `DROP TABLE` while another statement on the same connection is still reading that table: dropping it would pull the table out from under the reader.\n\nThis is different from `SQLITE_BUSY`, which means another connection, usually in another process, holds a lock. Waiting doesn't fix `SQLITE_LOCKED`; finishing the other statement does.","causes":["Running `DROP TABLE` while a `SELECT` on the same connection hasn't been stepped to the end or reset. In the same situation, `ALTER TABLE ... ADD COLUMN`, `ALTER TABLE ... RENAME`, `ALTER TABLE ... DROP COLUMN` and `CREATE INDEX` succeeded in testing.","Shared-cache mode, where one connection modifying a table blocks others sharing the cache (`SQLITE_LOCKED_SHAREDCACHE`)."],"fix":[{"text":"Finish, reset or finalize every statement before changing the schema. In Python, fetch all rows or close the cursor first.","sql":null},{"text":"Read the rows you need into memory first, then run the DDL or the writes.","sql":"-- read first\nSELECT id FROM staging;\n-- then, after the reader is done:\nDROP TABLE staging;"},{"text":"Avoid shared-cache mode unless you need it. SQLite discourages it; WAL mode is the usual way to get concurrent readers.","sql":null}],"diagnostic":"-- In your code, check for statements you fetched only some rows from. In the sqlite3 shell this is rare, so the cause is almost always an unclosed cursor in the application.\n-- Shared-cache mode makes LOCKED far more likely, and journal mode has nothing to do with it; check the open flags or connection URI for cache=shared.","alternatives":"Fetch all rows or close the cursor before writing to or altering the same table. If you must iterate and write at once, collect the keys you need, finish the read, then write in a second statement.","details":[],"details_title":null,"repro":"import sqlite3\nconn = sqlite3.connect('scratch.db')\nconn.execute('CREATE TABLE t(x)')\nconn.executemany('INSERT INTO t VALUES (?)', [(i,) for i in range(1000)])\nconn.commit()\ncur = conn.execute('SELECT * FROM t')\ncur.fetchone()                       # stepped into the middle, cursor still open\nconn.execute('DROP TABLE t')\n# sqlite3.OperationalError: database table is locked","repro_note":"The drop fails only while the cursor is mid-read; fetch all rows or close it and the same DROP succeeds.","related":["sqlite/sqlite-busy","sqlite/sqlite-abort-rollback"],"sqlly":"The conflict is inside the connection, so this is usually an application bug; when it appears in SQLly the failed statement is highlighted, and query history keeps it so you can re-run it after the blocking cursor is closed.","faqs":[{"question":"Will a busy timeout fix SQLITE_LOCKED?","answer":"No. The busy handler is for conflicts with other connections (SQLITE_BUSY). SQLITE_LOCKED is a conflict inside your own connection or shared cache, so the fix is to finish or reset the statement that is in the way."},{"question":"Why does DROP TABLE fail while the same SELECT works alone?","answer":"A SELECT you have not stepped to completion or reset still holds a read lock inside your own connection. Finish it, or reset and finalize it, then run the DDL."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-locked","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-locked-sharedcache","corpus":"errors","engine":"sqlite","language":"en","title":"table locked in shared cache","description":"In shared-cache mode, another connection sharing the same cache is modifying the data this connection needs, so access is blocked.","body":{"code":"SQLITE_LOCKED_SHAREDCACHE","slug":"sqlite-locked-sharedcache","name":"262","message":"database table is locked","group":"extended","severity":null,"sql_state":null,"summary":"In shared-cache mode, another connection sharing the same cache is modifying the data this connection needs, so access is blocked.","meaning":"`SQLITE_LOCKED_SHAREDCACHE` (262) only occurs in shared-cache mode, where several connections in one process share a page cache. While one of them is modifying a record, the others are blocked from it so they never see a half-finished change.","causes":["Opening connections with `cache=shared` (often an in-memory database shared between connections) and writing from one while reading from another."],"fix":[{"text":"Open each connection without cache=shared so it gets its own cache, and use WAL mode so readers and writers do not block each other. Shared-cache mode is discouraged for most uses. Setting WAL while cache=shared is still set does not clear this error.","sql":"PRAGMA journal_mode = WAL;"},{"text":"If you need shared cache, coordinate access in the application, or use `sqlite3_unlock_notify()` to wait for the lock to be released.","sql":null}],"diagnostic":"-- Only possible when connections were opened with cache=shared, so start there: check the\n-- open flags or the connection URI in your code. SQL alone cannot see the other connection's\n-- statement; the message names the table, and your own logs name the thread writing it.","alternatives":"Drop cache=shared and use WAL mode instead; SQLite itself discourages shared cache for most uses. If you must keep it, serialize access or use sqlite3_unlock_notify().","details":[],"details_title":null,"repro":"-- Needs shared-cache mode, not plain SQL:\n-- two connections on the same file with cache=shared, one writing a row while\n-- the other reads it, gives SQLITE_LOCKED_SHAREDCACHE (262).","repro_note":null,"related":["sqlite/sqlite-locked","sqlite/sqlite-busy"],"sqlly":"SQLly opens standard connections and does not enable shared cache, so a setup that depends on cache=shared has to be reproduced in the application that uses it.","faqs":[{"question":"Does a busy timeout help here?","answer":"Not reliably. sqlite3_busy_timeout does not wait for shared-cache table locks; the intended mechanism is sqlite3_unlock_notify()."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-locked-sharedcache","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-mismatch","corpus":"errors","engine":"sqlite","language":"en","title":"datatype mismatch","description":"One of the few places SQLite is strict about types: most often, setting a rowid or INTEGER PRIMARY KEY column to something that isn't an integer.","body":{"code":"SQLITE_MISMATCH","slug":"sqlite-mismatch","name":"20","message":"datatype mismatch","group":"primary","severity":null,"sql_state":null,"summary":"One of the few places SQLite is strict about types: most often, setting a rowid or INTEGER PRIMARY KEY column to something that isn't an integer.","meaning":"SQLite normally lets you store any value in any column. `SQLITE_MISMATCH` (20) is returned in the few cases where it insists on a type. The one the SQLite documentation calls out is the rowid: a table's rowid, and a column declared `INTEGER PRIMARY KEY` (which is an alias for it), must hold an integer. Setting it to text such as `'abc'` or a non-integral real fails with `datatype mismatch`; NULL is allowed and picks the next free integer.\n\nIn a `STRICT` table, a value that cannot be converted to the column type is reported as `SQLITE_CONSTRAINT_DATATYPE` (for example `cannot store TEXT value in INTEGER column t.x`). An `INTEGER PRIMARY KEY` column in a `STRICT` table still reports `SQLITE_MISMATCH`.","causes":["Inserting a non-integer value, such as a UUID string, into an `INTEGER PRIMARY KEY` column.","Updating `rowid` to a text value.","Migrating a schema from another database where the id column was text, but declaring it `INTEGER PRIMARY KEY` in SQLite."],"fix":[{"text":"Insert integers (or NULL to let SQLite assign one) into `INTEGER PRIMARY KEY` columns.","sql":"INSERT INTO users (id, name) VALUES (NULL, 'Ada');"},{"text":"If the key really is text, declare it as a text primary key instead.","sql":"CREATE TABLE users (\n    id   TEXT PRIMARY KEY,\n    name TEXT NOT NULL\n);"}],"diagnostic":"-- Check whether the id column is an INTEGER PRIMARY KEY (an alias for the rowid):\nPRAGMA table_info(users);\n-- pk = 1 with type INTEGER means integer values only; NULL picks the next rowid automatically.","alternatives":"If the key is a text value such as a UUID string, declare the column TEXT PRIMARY KEY instead, or keep the integer id and store the UUID in a separate unique column.","details":[],"details_title":null,"repro":"CREATE TABLE t (id INTEGER PRIMARY KEY);\nINSERT INTO t VALUES ('abc');   -- Runtime error near line 2: datatype mismatch (20)","repro_note":null,"related":["sqlite/sqlite-constraint-datatype","sqlite/sqlite-constraint-primarykey","sql-server/245","postgresql/22P02"],"sqlly":"SQLly's schema browser shows a table's definition, so you can check whether the id column is an INTEGER PRIMARY KEY before writing code that puts anything else in it.","faqs":[{"question":"Why is INTEGER PRIMARY KEY stricter than every other column?","answer":"In a rowid table it is an alias for the rowid, and the rowid must be an integer. In a WITHOUT ROWID table it is an ordinary column, and text is accepted. Other columns accept any storage class unless the table is STRICT."},{"question":"How is this different from a STRICT table type error?","answer":"Ordinary columns in a STRICT table report SQLITE_CONSTRAINT_DATATYPE, with a message such as cannot store TEXT value in INTEGER column t.x. An INTEGER PRIMARY KEY column in a STRICT table still reports SQLITE_MISMATCH."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-mismatch","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-misuse","corpus":"errors","engine":"sqlite","language":"en","title":"bad parameter or other API misuse","description":"The program called an SQLite function in an undefined way, such as using a statement after finalizing it. It is a bug in the calling code.","body":{"code":"SQLITE_MISUSE","slug":"sqlite-misuse","name":"21","message":"bad parameter or other API misuse","group":"primary","severity":null,"sql_state":null,"summary":"The program called an SQLite function in an undefined way, such as using a statement after finalizing it. It is a bug in the calling code.","meaning":"`SQLITE_MISUSE` (21) means the application used the SQLite API incorrectly. SQLite tries to detect misuse but, as its documentation stresses, detection is not guaranteed, so the same bug can also crash or corrupt memory. Any `SQLITE_MISUSE` is a bug to fix, not a condition to handle.","causes":["Using a prepared statement after `sqlite3_finalize()`, or a connection after `sqlite3_close()`.","Using one connection or statement from two threads at the same time in multi-thread mode. Sequential use from different threads is safe, and serialized mode (`SQLITE_OPEN_FULLMUTEX`) makes concurrent use safe.","Calling `sqlite3_step()` again after it returned an error without resetting the statement.","Passing a NULL or invalid connection handle."],"fix":[{"text":"Find the call that returned the code and check the object's life cycle: prepare, bind, step, reset or finalize, and never use it after finalizing.","sql":null},{"text":"Give each thread its own connection, or open connections with `SQLITE_OPEN_FULLMUTEX` (serialized mode), and don't use one statement from two threads at once.","sql":null},{"text":"In higher-level bindings, look for objects used after their connection was closed, for example a cursor kept after `close()`.","sql":null}],"diagnostic":"-- Nothing in the database causes this, so there is no pragma to run. In code, log the\n-- prepare/bind/step/reset/finalize life cycle around the failing call and look for an object\n-- used after close or finalize. Good bindings raise their own clearer error first, for\n-- example Python's ProgrammingError: Cannot operate on a closed cursor.","alternatives":"Treat every SQLITE_MISUSE as a bug in the application or binding: log the call site, and check the prepare/bind/step/reset/finalize life cycle and connection lifetime around it.","details":[],"details_title":null,"repro":"-- Not reproducible in SQL: SQLITE_MISUSE comes from misusing the C API or a binding,\n-- for example sqlite3_step() after sqlite3_finalize().","repro_note":null,"related":["sqlite/sqlite-range","sqlite/sqlite-schema"],"sqlly":"This is a bug in the program embedding SQLite, not in the SQL; SQLly's error panel shows the engine's own message, which keeps a misuse report from being mistaken for a query problem.","faqs":[{"question":"Can I catch and ignore SQLITE_MISUSE?","answer":"No. SQLite only detects some misuse, and the same mistake can crash or corrupt memory elsewhere. Fix the call, don't handle the code."},{"question":"I use Python or Node and a connection or cursor fails after I closed it. Is my SQL wrong?","answer":"No, the SQL is fine. A connection or cursor is being used after it was closed, or from the wrong thread."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-misuse","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-nomem","corpus":"errors","engine":"sqlite","language":"en","title":"out of memory","description":"SQLite couldn't allocate memory it needed to continue. Usually the process is out of memory, or a heap limit was set too low.","body":{"code":"SQLITE_NOMEM","slug":"sqlite-nomem","name":"7","message":"out of memory","group":"primary","severity":null,"sql_state":null,"summary":"SQLite couldn't allocate memory it needed to continue. Usually the process is out of memory, or a heap limit was set too low.","meaning":"`SQLITE_NOMEM` (7) means an internal call to `sqlite3_malloc()` or `sqlite3_realloc()` failed when the memory was required to continue. SQLite is designed to fail cleanly here, rolling back the statement without corrupting the database.","causes":["The process or container hit its memory limit.","A hard heap limit set with `sqlite3_hard_heap_limit64()` or `PRAGMA hard_heap_limit`. A soft heap limit (`sqlite3_soft_heap_limit64()` or `PRAGMA soft_heap_limit`) only makes SQLite shrink its cache and does not cause this error.","A query building a huge in-memory result: a sort or `GROUP BY` without an index, or `temp_store = MEMORY` with a large intermediate result.","A very large `cache_size` setting."],"fix":[{"text":"Check memory limits on the process or container, and any heap limit the application sets.","sql":"PRAGMA soft_heap_limit;\nPRAGMA hard_heap_limit;"},{"text":"Let large temporary results go to disk instead of memory, and reduce the page cache if it is very large.","sql":"PRAGMA temp_store = FILE;\nPRAGMA cache_size = -2000;  -- about 2 MB, the upstream default"},{"text":"Add indexes so sorts and groupings don't need to hold everything in memory.","sql":null}],"diagnostic":"-- Check the heap limits the application or embedder may have set. 0 means no limit:\nPRAGMA hard_heap_limit;\n-- Check the page cache setting; a huge cache_size grows memory per connection:\nPRAGMA cache_size;","alternatives":"If a single query is the problem, add an index so the sort or GROUP BY can stream instead of buffering, or lower temp_store back to the default file-based mode.","details":[],"details_title":null,"repro":"-- Not reliably reproducible from SQL: it takes a process genuinely out of heap or an\n-- application-set limit. Setting a small PRAGMA hard_heap_limit inside a tool such as the\n-- sqlite3 shell does not trigger it; the limit has to come from the embedding program\n-- (sqlite3_hard_heap_limit64()) or the container.","repro_note":null,"related":["sqlite/sqlite-full","sql-server/701","oracle/ora-04031"],"sqlly":"Trim the query and retry: query history keeps the failing statement, so adding a LIMIT and re-running is a small edit (a LIMIT bounds an ORDER BY sort but does not shrink a GROUP BY), and the schema browser's index list shows whether the columns behind a big sort or GROUP BY are indexed.","faqs":[{"question":"Can a query really use unbounded memory?","answer":"Only with temp_store=MEMORY. A sort or GROUP BY without a usable index buffers rows, and temp_store=MEMORY keeps those buffers in RAM instead of a temp file, so they can grow until the heap limit. With the default temp_store they spill to a temp file and need far less heap. The page cache is capped by cache_size, so a large cache_size raises the per-connection ceiling."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-nomem","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-notadb","corpus":"errors","engine":"sqlite","language":"en","title":"file is not a database","description":"The file opened doesn't look like an SQLite database: it's another kind of file, it's encrypted, or its header is damaged.","body":{"code":"SQLITE_NOTADB","slug":"sqlite-notadb","name":"26","message":"file is not a database","group":"primary","severity":null,"sql_state":null,"summary":"The file opened doesn't look like an SQLite database: it's another kind of file, it's encrypted, or its header is damaged.","meaning":"`SQLITE_NOTADB` (26) means the file's header doesn't match SQLite's format. Every non-empty SQLite database file starts with the 16 bytes `SQLite format 3` followed by a zero byte. Opening a file only reads it lazily, so the error usually appears on the first query rather than at open time.","causes":["The path points at a different kind of file, such as a CSV, a SQL dump or a database from another engine.","The database is encrypted (SQLCipher or another encryption extension) and was opened without the key, or with a library that has no encryption support.","The file was damaged at the start, for example by an interrupted download or copy.","A text SQL dump was given where a database file was expected; load it with the shell instead."],"fix":[{"text":"Check the first bytes of the file. On macOS or Linux: `head -c 16 app.db` should print `SQLite format 3`.","sql":null},{"text":"If the database is encrypted, open it with the matching library and key.","sql":null},{"text":"If the file is a SQL dump, build a database from it: `sqlite3 new.db < dump.sql`.","sql":null},{"text":"If the header is damaged, try the `.recover` command or restore a backup.","sql":null}],"diagnostic":"-- In the sqlite3 shell, check the 16-byte header:\nSELECT substr(hex(readfile('app.db')), 1, 32);\n-- '53514C69746520666F726D6174203300' is 'SQLite format 3' plus a zero byte.\n-- Anything else means the file is not a plain SQLite database (it may be encrypted).","alternatives":"If the file is a SQL dump rather than a database, build a real database from it with `sqlite3 new.db < dump.sql`. If it is encrypted, open it with the matching library and key.","details":[],"details_title":null,"repro":"-- Not reproducible with SQL on a valid database. In the shell:\n--   echo 'not a database' > fake.db\n--   sqlite3 fake.db 'SELECT 1;'\n-- Error: in prepare, file is not a database (26)","repro_note":null,"related":["sqlite/sqlite-corrupt","sqlite/sqlite-cantopen"],"sqlly":"SQLly's connection editor shows the path you are opening, which is usually the whole diagnosis: check it against the file you meant, since a CSV, a SQL dump or another engine's database all fail the same way.","faqs":[{"question":"Why does opening the file succeed but the first query fail?","answer":"SQLite reads the header lazily, so a wrong file is usually caught by the first statement, not by the open call."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-notadb","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-perm","corpus":"errors","engine":"sqlite","language":"en","title":"access permission denied","description":"SQLite couldn't give a new database the requested access mode. Ordinary file-system permission failures usually show up as SQLITE_CANTOPEN or SQLITE_READONLY instead.","body":{"code":"SQLITE_PERM","slug":"sqlite-perm","name":"3","message":"access permission denied","group":"primary","severity":null,"sql_state":null,"summary":"SQLite couldn't give a new database the requested access mode. Ordinary file-system permission failures usually show up as SQLITE_CANTOPEN or SQLITE_READONLY instead.","meaning":"The SQLite documentation defines `SQLITE_PERM` (3) narrowly: the requested access mode for a newly created database could not be provided. In practice it is rare, and permission problems on existing files usually show up as `SQLITE_READONLY` or `SQLITE_CANTOPEN` instead.","causes":["Creating a database in a location where the process may create the file but not with the requested mode.","A custom VFS or sandbox (for example on mobile platforms) refusing the requested access."],"fix":[{"text":"Create the database in a directory the process fully owns, such as the application's data directory.","sql":null},{"text":"Check the open flags and any URI parameters such as `mode=`, and make sure they match what the platform allows.","sql":null}],"diagnostic":"-- Outside SQLite, check the file and its directory. SQLite needs to create journal files next to the database:\n-- shell: ls -l /path/to/dir/ ; touch /path/to/dir/.write-test && rm /path/to/dir/.write-test\nPRAGMA database_list; -- confirm which file the connection actually opened","alternatives":"Move the database into a directory the process owns, such as the application data directory. On mobile platforms, use the sandbox path the platform gives you instead of a shared location.","details":[],"details_title":null,"repro":"-- Not reproducible from plain SQL: SQLITE_PERM (3) needs the open call itself to request an\n-- access mode the operating system will not grant for a new file, which lives in the open\n-- flags or mode= URI parameters, not in any statement.","repro_note":null,"related":["sqlite/sqlite-readonly","sqlite/sqlite-cantopen"],"sqlly":"SQLly's connection editor keeps the database path in one place, so you can confirm which file the connection asked for and sort out permissions before reopening it.","faqs":[{"question":"The file is writable but writes still fail. Why?","answer":"SQLite also writes a rollback journal next to the database, so the directory must be writable too. If it is not, the write fails with SQLITE_READONLY (8); the extended code is SQLITE_READONLY_DIRECTORY (1544), not SQLITE_PERM."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-perm","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-protocol","corpus":"errors","engine":"sqlite","language":"en","title":"locking protocol","description":"In WAL mode, a connection lost the race to start a transaction many times over several seconds and gave up. Very rare; a sign of heavy write contention.","body":{"code":"SQLITE_PROTOCOL","slug":"sqlite-protocol","name":"15","message":"locking protocol","group":"primary","severity":null,"sql_state":null,"summary":"In WAL mode, a connection lost the race to start a transaction many times over several seconds and gave up. Very rare; a sign of heavy write contention.","meaning":"The SQLite documentation describes `SQLITE_PROTOCOL` (15) as a problem with the file locking protocol, currently only returned in WAL mode when starting a transaction. When two connections race to start a transaction, the loser backs off and retries; if the same connection keeps losing for several seconds, it returns `SQLITE_PROTOCOL`. It should appear only with many processes competing hard to write the same database.","causes":["Many processes writing the same WAL-mode database at once.","File locking that misbehaves."],"fix":[{"text":"Reduce the number of concurrent writers: give one process ownership of writes and have the others hand it their requests.","sql":null},{"text":"Keep the database on a local disk with working locks.","sql":null},{"text":"Treat it like `SQLITE_BUSY`: retry the transaction after a short pause.","sql":null}],"diagnostic":"-- Confirm WAL mode, since SQLITE_PROTOCOL is a WAL contention error:\nPRAGMA journal_mode;\n-- Count connections if you can; many processes writing the same WAL file at once is the trigger.","alternatives":"Set a busy timeout so writers wait instead of racing for the WAL lock, or make a single process the only writer and let the rest queue their requests. Both remove the SQLITE_BUSY errors that the same contention causes.","details":[],"details_title":null,"repro":"-- Not safely scriptable: it takes several processes racing hard to start transactions on the\n-- same WAL-mode database for several seconds. Under everyday contention SQLite either waits\n-- (busy timeout) or reports SQLITE_BUSY (5) instead.","repro_note":null,"related":["sqlite/sqlite-busy","sqlite/sqlite-busy-snapshot"],"sqlly":"SQLly's read-only mode sets `PRAGMA query_only` for each run, so a read-only run cannot take a write lock.","faqs":[{"question":"How is this different from SQLITE_BUSY?","answer":"SQLITE_PROTOCOL happens only in WAL mode, when two connections race to start a transaction and the same connection keeps losing for several seconds. SQLITE_BUSY is the general lock-busy case in both journal modes."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-protocol","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-range","corpus":"errors","engine":"sqlite","language":"en","title":"column index out of range","description":"A parameter number passed to an sqlite3_bind function, or a column number passed to an sqlite3_column function, is outside the valid range.","body":{"code":"SQLITE_RANGE","slug":"sqlite-range","name":"25","message":"column index out of range","group":"primary","severity":null,"sql_state":null,"summary":"A parameter number passed to an sqlite3_bind function, or a column number passed to an sqlite3_column function, is outside the valid range.","meaning":"`SQLITE_RANGE` (25) means a bind or column index doesn't exist in the statement. Parameter numbers start at 1, and the highest is the number of `?` placeholders (or the largest `?NNN`). Language bindings report the same mistake when you pass more values than the statement has placeholders, for example Python's `Incorrect number of bindings supplied`.","causes":["Binding parameter 0, or one more parameter than the statement has.","Passing a list of values that doesn't match the number of `?` placeholders.","Reading a column index beyond the number of result columns.","Putting `?` inside quotes, where it is a literal question mark, not a placeholder."],"fix":[{"text":"Count the placeholders and pass exactly that many values. Bind indexes start at 1.","sql":null},{"text":"Use named parameters to avoid counting mistakes.","sql":"SELECT * FROM users WHERE email = :email AND status = :status;"},{"text":"Never quote a placeholder: write `WHERE name = ?`, not `WHERE name = '?'`.","sql":null}],"diagnostic":"-- In code, ask the statement what it expects: sqlite3_bind_parameter_count() returns the\n-- number of placeholders, and sqlite3_bind_parameter_index(stmt, ':name') resolves a named\n-- one. Python's error names both numbers: Incorrect number of bindings supplied. The current\n-- statement uses 1, and there are 2 supplied.","alternatives":"Use named parameters (:name) instead of positional ? so the count and order don't matter, and a missing named value is reported by name (Python: \"You did not supply a value for binding parameter :status.\"). Python silently ignores extra dict keys, so check the dict yourself.","details":[],"details_title":null,"repro":"CREATE TABLE t (name TEXT);\nSELECT * FROM t WHERE name = ?;\n-- The SQL alone runs fine in the shell. Binding index 2 to this one-placeholder\n-- statement with sqlite3_bind_* gives SQLITE_RANGE (25). Python rejects two values\n-- before binding, with a ProgrammingError instead.","repro_note":null,"related":["sqlite/sqlite-misuse","sqlite/sqlite-error","oracle/ora-01008"],"sqlly":"SQLly highlights the failed statement, and query history keeps it so you can recount placeholders against the values you passed and re-run.","faqs":[{"question":"Do bind indexes start at 0 or 1?","answer":"At 1. Parameter 0 is out of range."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-range","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-readonly","corpus":"errors","engine":"sqlite","language":"en","title":"attempt to write a readonly database","description":"The connection can't write: the file or its directory isn't writable, the database was opened read-only, or SQLite can't create its journal file.","body":{"code":"SQLITE_READONLY","slug":"sqlite-readonly","name":"8","message":"attempt to write a readonly database","group":"primary","severity":null,"sql_state":null,"summary":"The connection can't write: the file or its directory isn't writable, the database was opened read-only, or SQLite can't create its journal file.","meaning":"`SQLITE_READONLY` (8) is returned when a statement tries to change data the connection has no write permission for. Writing needs permission on the database file and also on its directory, because SQLite creates a journal (`-journal`) or WAL (`-wal`, `-shm`) file beside it.\n\nExtended codes say why: `SQLITE_READONLY_DIRECTORY` (no permission to create the journal), `SQLITE_READONLY_DBMOVED` (the file was moved or deleted while open), `SQLITE_READONLY_ROLLBACK` (a hot journal needs rolling back but the database is read-only), and others.","causes":["The database file is owned by another user or mounted read-only, typical for a web server user or a file inside an app bundle.","The directory isn't writable, so SQLite can't create the journal file even though the file itself is.","The connection was opened read-only (`SQLITE_OPEN_READONLY`, `?mode=ro` URI, or `PRAGMA query_only = ON`).","The file was moved, renamed or deleted while the connection was open (`SQLITE_READONLY_DBMOVED`)."],"fix":[{"text":"Give the process write permission on the file and on its directory. On Linux and macOS check with `ls -l` on both, then fix ownership or mode.","sql":null},{"text":"Check whether the connection itself is read-only.","sql":"PRAGMA query_only;\nPRAGMA database_list;"},{"text":"Open the database read-write: drop `mode=ro` from the URI or the read-only flag from the open call.","sql":null},{"text":"If the file was moved while open, close the connection and open it again at its new path.","sql":null}],"diagnostic":"-- Confirm the connection can't write because of its own settings:\nPRAGMA query_only;\n-- Check the file is where you think it is and the connection still points at it:\nPRAGMA database_list;\n-- In the shell: ls -l /path/to/db.db /path/to/dir","alternatives":"If you only meant to read, open with mode=ro and stop attempting writes. If writes are expected, fix permissions on both the file and its directory, since SQLite needs the directory for journal files.","details":[],"details_title":null,"repro":"cp app.db ro.db && chmod 444 ro.db\nsqlite3 ro.db 'CREATE TABLE t(x);'\n-- Runtime error near line 1: attempt to write a readonly database (8)\nchmod 644 ro.db   -- restore","repro_note":"Run against a scratch copy, not the original file.","related":["sqlite/sqlite-cantopen","sqlite/sqlite-perm","sqlite/sqlite-readonly-dbmoved","sqlite/sqlite-readonly-rollback","postgresql/25006"],"sqlly":"SQLly can mark a connection as Production, which blocks statements other than SELECT until you unlock writes for 1, 5 or 15 minutes. That block is SQLly's own refusal, not this engine error, so a SQLite file you only want to inspect can't be changed by accident.","faqs":[{"question":"What is SQLITE_READONLY_DBMOVED?","answer":"The database file was renamed or deleted while the connection was open, so SQLite refuses writes to protect integrity. Reopen the file at its new path."},{"question":"Why does this happen inside app bundles or on web servers?","answer":"Deployed files are often owned by root or the packager, and the server user can read but not write them. Copy the database to a writable data directory at first run."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-readonly","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-readonly-dbmoved","corpus":"errors","engine":"sqlite","language":"en","title":"database file moved while open","description":"The database file was moved, renamed or deleted after it was opened, so SQLite refuses to write to it to avoid corrupting it.","body":{"code":"SQLITE_READONLY_DBMOVED","slug":"sqlite-readonly-dbmoved","name":"1032","message":"attempt to write a readonly database","group":"extended","severity":null,"sql_state":null,"summary":"The database file was moved, renamed or deleted after it was opened, so SQLite refuses to write to it to avoid corrupting it.","meaning":"`SQLITE_READONLY_DBMOVED` (1032) means the database can't be modified because the file has moved since it was opened. If SQLite kept writing and the process crashed, its rollback journal would sit under the old name and couldn't be used to repair the file, so it stops writes instead.","causes":["Renaming, moving or replacing the database file while a program has it open.","Deleting the file (for example a cleanup job or a test teardown) while a connection is still open.","Atomic file replacement by deployment or sync tools."],"fix":[{"text":"Close all connections before moving or replacing the file, then reopen it at the new path.","sql":null},{"text":"To swap in a new database, restore into the open connection with the backup API instead of replacing the file on disk.","sql":null}],"diagnostic":"-- Compare the path SQLite has for this connection with where the file actually is now:\nPRAGMA database_list;","alternatives":"If the application itself moves or replaces the file, close every connection first. To swap in fresh data without downtime, copy the new database into the open connection with the backup API instead of touching the file on disk.","details":[],"details_title":null,"repro":"import os, sqlite3\nconn = sqlite3.connect('scratch.db')\nos.rename('scratch.db', 'scratch-moved.db')\nconn.execute('INSERT INTO t VALUES (1)')\n# sqlite3.OperationalError: attempt to write a readonly database\n# e.sqlite_errorname == 'SQLITE_READONLY_DBMOVED' and e.sqlite_errorcode == 1032","repro_note":"scratch.db already contains a table t. Verified on macOS. Linux was not run. On Windows the rename of an open file fails at the OS level instead (not run).","related":["sqlite/sqlite-readonly","sqlite/sqlite-cantopen"],"sqlly":"Closing and reopening the connection in SQLly clears the error only once the connection points at the new location. SQLly reopens the path stored in the connection profile, and reopening the old path creates an empty database there while the real file sits at the new one. Point the connection profile at the new location, then reconnect.","faqs":[{"question":"Can I keep using the connection if I rename the file back?","answer":"Yes, if the file goes back to the path it was opened at, the same connection can write again. Closing and reopening is the reliable path, because it works from any location. A connection whose file was moved, deleted, or replaced by a different file at its path keeps failing with SQLITE_READONLY_DBMOVED."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-readonly-dbmoved","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-readonly-directory","corpus":"errors","engine":"sqlite","language":"en","title":"can't create the journal file","description":"The database file is writable but its directory isn't, so SQLite can't create the journal file it needs before writing.","body":{"code":"SQLITE_READONLY_DIRECTORY","slug":"sqlite-readonly-directory","name":"1544","message":"attempt to write a readonly database","group":"extended","severity":null,"sql_state":null,"summary":"The database file is writable but its directory isn't, so SQLite can't create the journal file it needs before writing.","meaning":"`SQLITE_READONLY_DIRECTORY` (1544) means the process lacks permission to create a journal file in the database's directory, and creating one is required before any write. This is the common case where a file has write permission but its folder does not.","causes":["The directory is owned by another user or is read-only, for example a system directory or an app bundle.","A container volume mounted with a writable file but a read-only parent."],"fix":[{"text":"Give the process write permission on the directory, or move the database to a directory it owns.","sql":null},{"text":"In WAL mode the `-wal` and `-shm` files are created there too. If they do not already exist, the directory must be writable so SQLite can create them. A read-only WAL database whose -wal and -shm files already exist can still be read and written.","sql":null}],"diagnostic":"-- The directory, not the file, is usually the blocker. On macOS or Linux check both:\nls -ld /path/to/dir /path/to/dir/app.db\ntouch /path/to/dir/.write-test && rm /path/to/dir/.write-test   -- fails here means the directory is read-only\nPRAGMA database_list;   -- confirm which directory the connection uses","alternatives":"Moving the database to a directory the process owns beats loosening permissions on a system directory. In containers, mount the volume so the database user can write the directory itself, since SQLite also creates journal files there.","details":[],"details_title":null,"repro":"mkdir /tmp/ro-dir && cp app.db /tmp/ro-dir/app.db && chmod a-w /tmp/ro-dir\nsqlite3 /tmp/ro-dir/app.db 'CREATE TABLE t(x);'\n-- Error: stepping, attempt to write a readonly database (8)\n-- Python sqlite3 reports sqlite_errorcode 1544, sqlite_errorname SQLITE_READONLY_DIRECTORY; the CLI shows only the primary code 8.\nchmod u+w /tmp/ro-dir   -- put it back","repro_note":"The file is writable; only the directory is not, which blocks the -journal file. Run on a scratch copy.","related":["sqlite/sqlite-readonly","sqlite/sqlite-cantopen"],"sqlly":"In the default rollback-journal mode, reading still works in this state, so SQLly's schema browser and data grid keep working for inspection; writes resume once the directory is writable or the database has moved somewhere the process owns.","faqs":[{"question":"Why can I read the database but not write to it?","answer":"In the default rollback-journal mode, reading only touches the database file. Before any write, SQLite creates a journal (-journal) in the same directory. If the directory is not writable, no write can proceed even though the file itself is writable. In WAL mode, SQLite also needs the -wal and -shm files; if they do not exist and the directory is not writable, even reads fail with SQLITE_READONLY_DIRECTORY (1544)."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-readonly-directory","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-readonly-rollback","corpus":"errors","engine":"sqlite","language":"en","title":"hot journal can't be rolled back","description":"The database has a hot journal left by a crash that must be rolled back, but the connection can't write, so the database can't be read.","body":{"code":"SQLITE_READONLY_ROLLBACK","slug":"sqlite-readonly-rollback","name":"776","message":"attempt to write a readonly database","group":"extended","severity":null,"sql_state":null,"summary":"The database has a hot journal left by a crash that must be rolled back, but the connection can't write, so the database can't be read.","meaning":"`SQLITE_READONLY_ROLLBACK` (776) means the database file has a hot journal: a `-journal` file from a transaction that was interrupted by a crash. SQLite has to roll that journal back before anyone can read consistent data, and rolling back needs write access, which this connection doesn't have.","causes":["A program crashed mid-transaction, and the database is now being opened read-only or by a user without write permission.","The database and its journal were copied to read-only media."],"fix":[{"text":"Open the database once with a user and mode that can write, so SQLite rolls the journal back; after that it can be opened read-only again.","sql":null},{"text":"Never delete the `-journal` file to get around this: it holds the data needed to undo the interrupted transaction, and deleting it can corrupt the database.","sql":null}],"diagnostic":"-- After opening once with write access, confirm the rollback finished cleanly:\nPRAGMA integrity_check;","alternatives":"If the database sits on read-only media on purpose, you cannot read from it at all while the hot journal exists. Copy the database and its -journal file to writable storage and open the copy read-write once, so SQLite can roll the journal back there.","details":[],"details_title":null,"repro":"-- Not reproducible in a tidy script: it needs a process killed mid-transaction on a\n-- rollback-journal database (leaving a hot -journal file), then a read-only or unprivileged\n-- open of that file. The first connection that can write rolls the journal back and the\n-- error stops appearing.","repro_note":null,"related":["sqlite/sqlite-readonly","sqlite/sqlite-corrupt"],"sqlly":"Once a writable connection has rolled the hot journal back, SQLly's schema browser and data grid are a quick way to confirm the recovered data is all there.","faqs":[{"question":"Is it safe to delete the -journal file to get past this?","answer":"No. The journal holds the changes needed to undo an interrupted transaction. Deleting it can leave part of the interrupted change on disk for good, and integrity_check may still pass. Let SQLite roll it back from a writable connection instead."},{"question":"How do I prevent this?","answer":"It comes from a crash mid-transaction, so the real fix is that the machine or process should not die with writes in flight. The journal mechanism itself is doing its job; you just need one writable open to complete recovery."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-readonly-rollback","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-schema","corpus":"errors","engine":"sqlite","language":"en","title":"database schema has changed","description":"A prepared statement went stale after a schema change and SQLite didn't re-prepare it. Legacy sqlite3_prepare() never does; v2 and v3 retry SQLITE_MAX_SCHEMA_RETRY times.","body":{"code":"SQLITE_SCHEMA","slug":"sqlite-schema","name":"17","message":"database schema has changed","group":"primary","severity":null,"sql_state":null,"summary":"A prepared statement went stale after a schema change and SQLite didn't re-prepare it. Legacy sqlite3_prepare() never does; v2 and v3 retry SQLITE_MAX_SCHEMA_RETRY times.","meaning":"`SQLITE_SCHEMA` (17) means the schema changed between preparing a statement and running it, for example another connection added an index or altered a table. Statements prepared with `sqlite3_prepare_v2()` (what nearly every modern binding uses) are re-prepared automatically, up to 50 times by default, so you only see this error with the legacy `sqlite3_prepare()` or when re-preparing keeps failing. With the legacy interface, `sqlite3_step()` returns a generic SQLITE_ERROR and the SQLITE_SCHEMA code comes from `sqlite3_reset()`.","causes":["Using the legacy `sqlite3_prepare()` interface, which doesn't re-prepare on schema changes.","Another connection changing the schema constantly while statements are being prepared and run.","A schema change that makes the statement invalid, for example dropping a column it uses. With the legacy interface this reports SQLITE_SCHEMA from sqlite3_reset(); with sqlite3_prepare_v2() or sqlite3_prepare_v3() it reports SQLITE_ERROR (1) with the message \"no such column: a\"."],"fix":[{"text":"Prepare statements with `sqlite3_prepare_v2()` or `sqlite3_prepare_v3()` so SQLite re-prepares them for you.","sql":null},{"text":"If you get this from a statement cache, finalize the cached statement and prepare it again after a schema change.","sql":null},{"text":"Run schema migrations while the application is idle, not while other connections are executing statements.","sql":null}],"diagnostic":"-- You usually cannot see this from SQL alone. Check in code: is the binding using sqlite3_prepare() (legacy) instead of sqlite3_prepare_v2()/v3()?\n-- Read the schema version counter that moves when another connection changes the main schema:\nPRAGMA schema_version;","alternatives":"The practical fix is to prepare with the v2 or v3 API so SQLite re-prepares automatically, and to run migrations while the app is idle. Most modern bindings already use v2 or v3, so this error usually points at hand-written C or an old wrapper.","details":[],"details_title":null,"repro":"-- Not reachable through sqlite3_prepare_v2()/v3: SQLite re-prepares silently, up to\n-- SQLITE_MAX_SCHEMA_RETRY (50) times. It only surfaces with the legacy sqlite3_prepare()\n-- API in hand-written C, or when a schema change keeps invalidating the statement.","repro_note":null,"related":["sqlite/sqlite-error","sqlite/sqlite-misuse"],"sqlly":"Every run in SQLly prepares the statement against the current schema, so re-running from query history replaces a stale prepared statement with a fresh one.","faqs":[{"question":"I never changed the schema. Why did I get this?","answer":"Some other connection did, even a transient one such as a migration tool or an ALTER from another thread. PRAGMA schema_version changes on any accepted schema change to the main database. A CREATE TEMP TABLE on another connection leaves it unchanged and does not cause this error."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-schema","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"errors/sqlite/sqlite-toobig","corpus":"errors","engine":"sqlite","language":"en","title":"string or blob too big","description":"A string, BLOB or SQL statement was larger than SQLite's limit, 1,000,000,000 bytes by default, or a lower limit set by the application.","body":{"code":"SQLITE_TOOBIG","slug":"sqlite-toobig","name":"18","message":"string or blob too big","group":"primary","severity":null,"sql_state":null,"summary":"A string, BLOB or SQL statement was larger than SQLite's limit, 1,000,000,000 bytes by default, or a lower limit set by the application.","meaning":"`SQLITE_TOOBIG` (18) is returned when a string or BLOB exceeds the maximum length, set at compile time with `SQLITE_MAX_LENGTH` (default 1,000,000,000 bytes) or lowered at run time with `sqlite3_limit(db, SQLITE_LIMIT_LENGTH, ...)`. An oversized SQL statement gets the same error; its limit is `SQLITE_MAX_SQL_LENGTH` / `SQLITE_LIMIT_SQL_LENGTH`. A row larger than the length limit also fails.","causes":["Storing a very large file or document in a single BLOB or TEXT value.","Building one huge SQL statement, such as a multi-row `INSERT` with millions of literal values.","An application or binding that lowered the limit with `sqlite3_limit()`.","A `group_concat()` or string concatenation that grows past the limit."],"fix":[{"text":"Store large files outside the database and keep their paths, or split the content into chunks across rows.","sql":null},{"text":"Insert many rows with one prepared statement executed repeatedly, with bound parameters, instead of a single enormous statement.","sql":"INSERT INTO items (id, name) VALUES (?, ?);  -- prepare once, bind and run per row"},{"text":"Check whether your binding sets a lower length limit, and raise it if appropriate.","sql":null}],"diagnostic":"-- How big is the value that failed? For a blob already in a table:\nSELECT length(data) FROM t WHERE rowid = 1;\n-- For a statement that fails, check how many bytes of SQL text you are sending:\n-- in a host language, len(sql_text.encode(\"utf-8\")) against the SQLITE_MAX_SQL_LENGTH limit (default 1,000,000,000 bytes).","alternatives":"Store big files on disk or in object storage and keep the path in the database, or split the content into chunks of a few MB across rows.","details":[],"details_title":null,"repro":"CREATE TABLE t (data BLOB);\nINSERT INTO t VALUES (zeroblob(3000000000));   -- over every possible SQLITE_MAX_LENGTH (a 32-bit setting, 1,000,000,000 by default)\n-- Runtime error near line 2: string or blob too big (18)","repro_note":null,"related":["sqlite/sqlite-range","sql-server/8152","mysql/1153"],"sqlly":"Keep the big file out of the database and store its path instead; SQLly's data grid exports query results to a file, which is often where an oversized blob should have lived in the first place.","faqs":[{"question":"What is the actual maximum size of a string or blob?","answer":"1,000,000,000 bytes by default, set at compile time with SQLITE_MAX_LENGTH or changed at run time with sqlite3_limit(db, SQLITE_LIMIT_LENGTH, ...)."},{"question":"Why did my giant INSERT fail with this error even though no value looks that big?","answer":"The whole SQL statement counts too. SQLITE_MAX_SQL_LENGTH caps the statement text at 1,000,000,000 bytes by default, and a statement needs roughly 100 million short literals, or one enormous string literal, to reach it."}],"aliases":[]},"source_url":"https://sqlly.app/errors/sqlite/sqlite-toobig","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
