sql Errors

119 error patterns

sql3 fixes

PostgreSQL JSONB extracting from scalar

ERROR:.*cannot extract elements from a scalar.*jsonb

  • Check value is an object/array before extraction: jsonb_typeof(col) = 'object'
  • Use COALESCE with '{}' for null/scalar values
sql3 fixes

PostgreSQL JSONB operator type mismatch

ERROR:.*operator does not exist.*jsonb @> text

  • Cast the right operand to jsonb: col @> '{"key": "val"}'::jsonb
  • Use ->> operator for text extraction instead of ->
sql3 fixes

PostgreSQL full-text search config not found

ERROR:.*text search configuration.*does not exist

  • Create the text search configuration or use a built-in one (english, simple)
  • Install the pg_catalog extension if using a custom configuration
sql3 fixes

PostgreSQL partition range overlap

ERROR:.*a]ttempt to create.*partition.*for values.*overlap

  • Ensure partition bounds don't overlap with existing partitions
  • Use FROM (value) TO (value) with non-overlapping ranges
sql3 fixes

PostgreSQL no matching partition for inserted row

ERROR:.*no partition of relation.*found for row

  • Create a partition covering the value range being inserted
  • Add a DEFAULT partition to catch unmatched rows
sql3 fixes

PostgreSQL logical replication slot not found

ERROR:.*logical replication.*slot.*does not exist

  • Create replication slot: SELECT pg_create_logical_replication_slot('name', 'pgoutput')
  • Check slot wasn't dropped: SELECT * FROM pg_replication_slots
sql3 fixes

PostgreSQL replication slot already active

ERROR:.*replication slot.*is active for PID

  • Terminate the existing connection using the slot
  • Wait for the current consumer to disconnect
sql3 fixes

PostgreSQL row-level security policy violation

ERROR:.*new row violates row-level security policy

  • Check RLS policy conditions match the current user's context
  • Verify SET SESSION current_user or app.current_tenant is set
sql3 fixes

PostgreSQL RLS infinite recursion

ERROR:.*infinite recursion detected in policy for relation

  • Use SECURITY DEFINER function to break the policy recursion
  • Add USING clause that doesn't reference the same table's RLS
sql3 fixes

PostgreSQL deadlock detected

ERROR:.*deadlock detected.*Process.*waits for.*blocked by process

  • Ensure transactions acquire locks in consistent order
  • Keep transactions short to minimize deadlock window
sql3 fixes

PostgreSQL serialization failure

ERROR:.*could not serialize access due to read/write dependencies

  • Implement retry logic for serialization failures (40001)
  • Reduce transaction isolation level if strict serializability isn't required
sql3 fixes

PostgreSQL statement timeout exceeded

ERROR:.*canceling statement due to statement timeout

  • Optimize the slow query (add indexes, rewrite)
  • Increase statement_timeout for specific session: SET statement_timeout = '60s'
sql3 fixes

MySQL recursive CTE exceeded execution time

MySQL.*Error 3988.*Recursive Common Table Expression.*exceeded.*max_execution_time

  • Add a recursion depth limit with a counter column
  • Set cte_max_recursion_depth to appropriate value
sql3 fixes

MySQL window function frame specification error

MySQL.*Error 4186.*Window function.*frame.*not allowed

  • Remove frame clause for functions that don't support it (ROW_NUMBER, RANK)
  • Use ROWS/RANGE BETWEEN correctly for aggregate window functions
sql3 fixes

MySQL JSON_TABLE invalid JSON argument

MySQL.*Error 3156.*Invalid JSON.*in argument.*to function.*json_table

  • Validate JSON column data: JSON_VALID(column)
  • Handle NULL values: IFNULL(json_col, '[]')
sql3 fixes

MySQL cannot make primary key invisible

MySQL.*Error 3171.*Cannot create.*invisible.*index.*primary key

  • Primary keys cannot be invisible - use a different index
  • Create a secondary unique index and make it invisible for testing
sql3 fixes

MySQL clone plugin version mismatch

MySQL.*Error 3707.*Clone.*operation.*donor.*version.*mismatch

  • Ensure donor and recipient have same MySQL version (major.minor.patch)
  • Upgrade recipient to match donor version
sql3 fixes

PostgreSQL invalid jsonpath expression

PostgreSQL.*ERROR:.*jsonb_path_query.*invalid.*jsonpath

  • Validate jsonpath syntax: use $ for root, .key for access, [*] for arrays
  • Escape special characters in jsonpath strings
sql3 fixes

PostgreSQL ALTER TABLE blocked by pending triggers

PostgreSQL.*ERROR:.*cannot alter.*table.*because.*has pending trigger events

  • Commit or rollback the pending transaction first
  • Disable triggers temporarily: ALTER TABLE ... DISABLE TRIGGER ALL
sql3 fixes

PostgreSQL logical replication requires wal_level=logical

PostgreSQL.*ERROR:.*logical.*replication.*requires.*wal_level.*logical

  • Set wal_level = logical in postgresql.conf and restart
  • Verify with: SHOW wal_level
sql3 fixes

PostgreSQL partition constraint violated on UPDATE

PostgreSQL.*ERROR:.*partition constraint.*violated.*for relation

  • Enable partition row movement: SET enable_partition_pruning = on
  • Use ALTER TABLE ... ENABLE ROW MOVEMENT for the partitioned table
sql3 fixes

MySQL function missing DETERMINISTIC or NO SQL attribute

MySQL.*Error 1418.*This function has none of DETERMINISTIC.*NO SQL

  • Add DETERMINISTIC keyword if function always returns same output for same input
  • Add NO SQL or READS SQL DATA as appropriate
sql3 fixes

MySQL GTID consistency violation with temp tables

MySQL.*Error 3572.*Statement violates GTID consistency.*CREATE.*TEMPORARY

  • Avoid CREATE TEMPORARY TABLE in transactions with GTID mode
  • Use CREATE TABLE with session-scoped naming instead
sql3 fixes

MySQL table requires primary key (group replication)

MySQL.*Error 3098.*Table.*does not comply with the requirements.*primary key

  • Add a primary key to the table
  • Set sql_require_primary_key=OFF if not using group replication
sql3 fixes

PostgreSQL column does not exist

PostgreSQL.*ERROR:.*column.*of relation.*does not exist

  • Check column name for typos and case sensitivity (use double quotes for mixed case)
  • Run migrations to add the missing column
sql3 fixes

PostgreSQL exclusion constraint index missing

PostgreSQL.*ERROR:.*index.*does not exist.*for.*exclusion constraint

  • Install btree_gist or btree_gin extension for non-default operator support
  • Create the required operator class index first
sql3 fixes

MySQL incorrect value for column type

MySQL.*Error 1366.*Incorrect.*value.*for column.*at row

  • Validate data types before insertion
  • Set sql_mode to remove STRICT_TRANS_TABLES for lenient handling
sql3 fixes

PostgreSQL publication not found for logical replication

PostgreSQL.*ERROR:.*publication.*does not exist

  • Create publication: CREATE PUBLICATION pub_name FOR TABLE table1, table2
  • Use FOR ALL TABLES to replicate entire database
sql3 fixes

PostgreSQL disk space exhausted

PostgreSQL.*ERROR:.*could not extend file.*No space left on device

  • Free disk space: remove old WAL, temp files, unused indexes
  • Add tablespace on a different volume
sql3 fixes

PostgreSQL connection limit exceeded for role

PostgreSQL.*ERROR:.*too many connections for role

  • Increase CONNECTION LIMIT on the role: ALTER ROLE name CONNECTION LIMIT 200
  • Use connection pooling (PgBouncer) to reduce connection count
sql3 fixes

PostgreSQL insufficient privileges for GRANT

PostgreSQL.*ERROR:.*must be owner of.*to.*GRANT

  • Connect as the object owner or superuser to GRANT
  • Use ALTER ... OWNER TO to change ownership first
sql3 fixes

PostgreSQL all non-superuser connections used

PostgreSQL.*FATAL:.*remaining connection slots are reserved for.*superuser

  • Increase max_connections in postgresql.conf
  • Use connection pooling to reduce active connections
sql3 fixes

MySQL InnoDB lock wait timeout

MySQL.*Error 1205.*Lock wait timeout exceeded

  • Increase innodb_lock_wait_timeout for long transactions
  • Check SHOW ENGINE INNODB STATUS for lock details
sql3 fixes

MySQL index key too long

MySQL.*Error 1071.*Specified key was too long.*max key length is 3072 bytes

  • Use prefix index: CREATE INDEX idx ON table(col(191))
  • Reduce column size or use utf8mb3 instead of utf8mb4
sql3 fixes

MySQL row size exceeds maximum

MySQL.*Error 1118.*Row size too large.*The maximum row size.*8060

  • Use ROW_FORMAT=DYNAMIC or COMPRESSED for off-page storage
  • Convert large VARCHAR to TEXT (stored off-page)
sql3 fixes

MySQL JSON partial update failed

MySQL.*Error 3567.*JSON partial update.*cannot be applied

  • Use JSON_SET, JSON_REPLACE, JSON_REMOVE for partial updates
  • Ensure the target path exists for JSON_REPLACE
sql3 fixes

MySQL window function used in invalid context

MySQL.*Error 3719.*Definition of.*window.*is not allowed in this context

  • Window functions can't be in WHERE/HAVING - use subquery or CTE
  • Move window function to outer query: SELECT * FROM (SELECT ..., ROW_NUMBER() OVER() as rn ...)
sql3 fixes

PostgreSQL GIN index pending list too large for fast scan

PostgreSQL.*ERROR:.*GIN index.*pending list.*too large

  • Run VACUUM on the table to flush pending GIN entries
  • Increase gin_pending_list_limit for the index
sql3 fixes

PostgreSQL cannot create trigger on individual partition

PostgreSQL.*ERROR:.*cannot create.*trigger.*on.*partition.*directly

  • Create the trigger on the partitioned (parent) table instead
  • In PG 13+ triggers on parent propagate to partitions
sql3 fixes

PostgreSQL aggregate ORDER BY with DISTINCT conflict

PostgreSQL.*ERROR:.*aggregate.*ORDER BY.*not supported with DISTINCT

  • Remove DISTINCT or ORDER BY from the aggregate
  • Use a subquery to pre-sort/deduplicate before aggregating
sql3 fixes

MySQL recursive CTE reference error in subquery

MySQL.*Error 3732.*Subquery.*uses.*recursive CTE.*that.*not defined

  • Reference the CTE name directly, not via subquery wrapping
  • Ensure recursive CTE is defined before being referenced
sql3 fixes

MySQL foreign key prevents deletion

MySQL.*Error 3948.*cannot.*delete.*foreign key.*constraint

  • Delete child records first or use ON DELETE CASCADE
  • Temporarily: SET FOREIGN_KEY_CHECKS=0 (dangerous in production)
sql3 fixes

PostgreSQL RETURNING clause limitation in CTE

PostgreSQL.*ERROR:.*cannot use.*RETURNING.*in.*WITH.*query.*that.*modifies data

  • Move RETURNING to the main query, not the CTE
  • Use a separate query to fetch the affected rows
sql3 fixes

PostgreSQL operator class incompatible with data type

PostgreSQL.*ERROR:.*operator class.*does not accept data type

  • Use correct operator class for the data type (btree vs gin vs gist)
  • Cast the column to a supported type before indexing
sql3 fixes

MySQL value truncation error

MySQL.*Error 1292.*Truncated incorrect.*value

  • Check data fits within column constraints (length, type)
  • Set SQL mode to allow truncation if acceptable: ALLOW_INVALID_DATES
sql3 fixes

MySQL cannot modify column used in generated column

MySQL.*Error 3546.*Cannot.*change.*column.*used.*in.*generated.*column

  • Drop the generated column, modify the source column, then recreate generated column
  • Create new column and migrate data manually
sql3 fixes

PostgreSQL pg_trgm extension not installed

PostgreSQL.*ERROR:.*pg_trgm.*index.*not.*installed

  • Run CREATE EXTENSION pg_trgm
  • Ensure pg_trgm is in shared_preload_libraries for faster indexing
sql3 fixes

MySQL recursive CTE max recursion depth

MySQL.*Error 3637.*Recursive CTE.*max.*level.*reached

  • Set cte_max_recursion_depth = 10000 (or appropriate value)
  • Add recursion termination condition in WHERE clause
sql3 fixes

PostgreSQL cannot VACUUM partitioned table directly

PostgreSQL.*ERROR:.*cannot.*vacuum.*partitioned table.*directly

  • VACUUM individual partitions instead of the parent table
  • Use VACUUM with no table name to vacuum entire database
sql4 fixes

N+1 query problem detected

N\+1.*quer(y|ies)|SELECT.*executed (\d{2,})\s*times

  • Use eager loading: includes(:association) in Rails, with() in Laravel
  • Use JOIN to fetch related data in a single query
sql4 fixes

Sequential scan in EXPLAIN plan (missing index)

Seq Scan on.*cost=.*rows=

  • Add an index on the filtered/joined column
  • Check if the table statistics are stale: ANALYZE table_name
sql4 fixes

Index exists but not being used

Index.*not used|index.*ignored|full table scan

  • Check if a function wraps the indexed column (kills index usage)
  • Verify data types match — implicit casting prevents index use
sql3 fixes

Ambiguous column reference in JOIN

column.*is ambiguous|ambiguous column name

  • Prefix column with table alias: t.column_name
  • Add explicit table aliases to all tables in the query
sql4 fixes

Non-aggregated column missing from GROUP BY

column.*must appear in the GROUP BY clause|not.*aggregate.*or.*GROUP BY

  • Add the column to GROUP BY clause
  • Wrap the column in an aggregate function: MAX(), MIN(), ANY_VALUE()
sql3 fixes

Window function used in invalid clause

window function.*not allowed in (WHERE|GROUP BY|HAVING)

  • Wrap the query in a subquery/CTE and filter on the outer query
  • Use QUALIFY clause if your database supports it (BigQuery, Snowflake)
sql4 fixes

CTE recursion limit exceeded

maximum recursion.*exceeded|recursive query.*reached.*limit

  • Add a proper termination condition to the recursive member
  • Set higher limit: OPTION (MAXRECURSION n) in SQL Server
sql4 fixes

Database deadlock between transactions

deadlock detected|was deadlocked on.*resources

  • Access tables in a consistent order across transactions
  • Keep transactions short — minimize lock hold time
sql4 fixes

Scalar subquery returned multiple rows

subquery returns more than.*row|Scalar subquery produced more than one element

  • Add LIMIT 1 to the subquery if only one row is expected
  • Use IN or EXISTS instead of = for multi-row subqueries
sql4 fixes

Division by zero in SQL expression

division by zero

  • Use NULLIF: col / NULLIF(divisor, 0)
  • Add CASE WHEN divisor = 0 THEN NULL ELSE col/divisor END
sql4 fixes

String value exceeds column length

value too long for type.*varchar|string.*truncat

  • Increase column size: ALTER TABLE ALTER COLUMN col VARCHAR(longer)
  • Truncate input in application layer before insert
sql3 fixes

ORDER BY column not in GROUP BY or aggregate

cannot.*sort.*aggregate.*GROUP BY|ORDER BY.*not in.*GROUP BY

  • Add the ORDER BY column to GROUP BY
  • Wrap ORDER BY column in an aggregate function
sql4 fixes

Query execution timeout

statement timeout|query.*cancelled.*timeout

  • Add indexes on filtered and joined columns
  • Simplify the query — break into smaller steps with temp tables
sql4 fixes

NOT NULL constraint violation

INSERT.*violates not-null constraint|cannot insert NULL into

  • Provide a value for the required column in the INSERT
  • Add a DEFAULT value to the column definition
sql4 fixes

Table or relation does not exist

relation.*does not exist|Unknown table|table.*not found

  • Check the table name spelling and schema prefix
  • Run pending migrations to create the table
sql3 fixes

LATERAL join not supported or misused

LATERAL.*not supported|lateral.*subquer

  • Use CROSS APPLY / OUTER APPLY in SQL Server instead
  • Rewrite as a correlated subquery in the SELECT clause
sql4 fixes

Insufficient privileges on database object

permission denied for (table|relation|schema)

  • GRANT SELECT/INSERT/UPDATE on table TO role
  • Check the current user: SELECT current_user
sql3 fixes

Type mismatch in comparison operator

operator does not exist.*=.*|No operator matches the given name and argument type

  • Cast one side to match: column::text = $1 or CAST(col AS type)
  • Check parameter types match column types in the query
sql4 fixes

Unique constraint violation on insert/update

duplicate key value violates unique constraint

  • Use INSERT ... ON CONFLICT DO UPDATE (PostgreSQL upsert)
  • Use MERGE or INSERT ... ON DUPLICATE KEY UPDATE (MySQL)
sql4 fixes

Expensive correlated subquery or nested loop

correlated subquery.*performance|Nested Loop.*cost.*rows.*loops=(\d{3,})

  • Rewrite correlated subquery as a JOIN
  • Use a CTE to materialize the subquery result once
sql3 fixes

PostgreSQL deadlock detected

ERROR.*deadlock detected

  • Ensure all transactions access tables and rows in a consistent order
  • Reduce transaction duration by doing non-DB work outside the transaction
sql3 fixes

PostgreSQL serialization failure

ERROR.*could not serialize access due to concurrent update

  • Retry the transaction — serialization failures are expected in SERIALIZABLE isolation
  • Use SELECT ... FOR UPDATE to explicitly lock rows you intend to modify
sql3 fixes

PostgreSQL column does not exist

ERROR.*column "(.*)" does not exist

  • Check for case sensitivity — unquoted identifiers are lowercased: use double quotes for mixed-case columns
  • Verify the column exists in the correct table with \d tablename in psql
sql3 fixes

PostgreSQL table/relation not found

ERROR.*relation "(.*)" does not exist

  • Check the search_path: SET search_path TO my_schema, public
  • Verify the table exists and you're connected to the correct database
sql3 fixes

PostgreSQL permission denied

ERROR.*permission denied for (table|relation|schema) "(.*)"

  • Grant the required permission: GRANT SELECT, INSERT, UPDATE ON table TO role
  • Check if the role has USAGE permission on the schema: GRANT USAGE ON SCHEMA public TO role
sql3 fixes

pg_dump connection failure

pg_dump.*error.*connection.*refused|pg_dump.*could not connect

  • Verify PostgreSQL is running and accepting connections on the specified host/port
  • Check pg_hba.conf allows connections from the pg_dump client IP
sql3 fixes

PostgreSQL replication lag

replication.*lag|streaming replication.*behind

  • Check replica performance: SELECT now() - pg_last_xact_replay_timestamp() AS lag
  • Increase wal_keep_size or use replication slots to prevent WAL segment removal
sql3 fixes

PostgreSQL vacuum blocked or failing

ERROR.*canceling autovacuum.*lock conflict|VACUUM.*cannot.*lock

  • Reduce long-running transactions that hold locks preventing vacuum
  • Increase autovacuum_vacuum_cost_delay to reduce I/O impact or decrease it to vacuum faster
sql3 fixes

PostgreSQL varchar length exceeded

ERROR.*value too long for type character varying\((\d+)\)

  • Truncate the input value to fit the column's character limit
  • Alter the column to increase the length: ALTER TABLE t ALTER COLUMN c TYPE varchar(500)
sql3 fixes

PostgreSQL unique constraint violation

ERROR.*duplicate key value violates unique constraint

  • Use INSERT ... ON CONFLICT (column) DO UPDATE SET ... for upsert behavior
  • Check for race conditions in concurrent inserts — use advisory locks or serializable isolation
sql3 fixes

PostgreSQL out of shared memory for locks

ERROR.*out of shared memory.*lock table

  • Increase max_locks_per_transaction in postgresql.conf
  • Reduce the number of tables affected in a single transaction (partition operations are common culprits)
sql3 fixes

PostgreSQL connection limit reached

FATAL.*too many connections for role

  • Increase connection limit: ALTER ROLE myuser CONNECTION LIMIT 100
  • Use a connection pooler like PgBouncer to multiplex connections
sql3 fixes

PostgreSQL drop blocked by dependencies

ERROR.*cannot drop.*because other objects depend on it

  • Use CASCADE to drop dependent objects: DROP TABLE t CASCADE (review what will be dropped first)
  • Query pg_depend to see what depends on the object before dropping
sql3 fixes

PostgreSQL aborted transaction state

ERROR.*prepared transaction.*already exists|ERROR.*current transaction is aborted

  • Issue ROLLBACK to clear the aborted transaction state before new queries
  • Use SAVEPOINT within transactions to allow partial rollback without aborting the whole transaction
sql3 fixes

PostgreSQL shared memory allocation failure

ERROR.*could not resize shared memory segment.*No space left

  • Increase kernel shared memory limits: sysctl -w kernel.shmmax=17179869184
  • Check /dev/shm usage and increase its size in /etc/fstab
sql3 fixes

PostgreSQL type cast failure

ERROR.*invalid input syntax for type (uuid|integer|timestamp)

  • Validate and sanitize input data before inserting — ensure UUIDs/integers/timestamps are properly formatted
  • Use explicit type casting with error handling: CAST(value AS type) or value::type
sql3 fixes

pg_dump version mismatch with server

pg_dump.*aborting because of server version mismatch

  • Install pg_dump matching the server version — use the PostgreSQL apt/yum repo for that version
  • Use the pg_dump binary from the server's installation directory
sql3 fixes

PostgreSQL COPY command file permission error

ERROR.*could not open file.*for reading.*Permission denied

  • Use COPY ... FROM STDIN with psql's \copy command which runs as the client user, not postgres
  • Ensure the file is readable by the postgres system user when using server-side COPY
sql3 fixes

PostgreSQL index creation error

ERROR.*index.*already exists|ERROR.*cannot create index.*concurrently.*transaction

  • Use CREATE INDEX IF NOT EXISTS to avoid errors on existing indexes
  • CREATE INDEX CONCURRENTLY cannot run inside a transaction — remove BEGIN/COMMIT wrapper
sql3 fixes

PostgreSQL WAL segment removed before replica consumed it

ERROR.*WAL.*segment.*not found|requested WAL segment.*has already been removed

  • Use replication slots to retain WAL segments until replicas have consumed them
  • Increase wal_keep_size (or wal_keep_segments in older versions) to retain more WAL
sql3 fixes

MySQL max connections exceeded

Too many connections

  • Increase max_connections: SET GLOBAL max_connections = 500
  • Use connection pooling in the application to limit concurrent connections
sql3 fixes

MySQL InnoDB lock wait timeout

Lock wait timeout exceeded.*try restarting transaction

  • Retry the transaction — another transaction is holding a conflicting lock
  • Check blocking transactions: SELECT * FROM information_schema.INNODB_TRX
sql3 fixes

MySQL foreign key constraint violation on insert/update

Cannot add or update a child row.*foreign key constraint fails

  • Ensure the referenced parent row exists before inserting the child row
  • Check that the foreign key column values match the parent table's primary/unique key values exactly (type and value)
sql3 fixes

MySQL foreign key blocks parent row deletion

Cannot delete or update a parent row.*foreign key constraint fails

  • Delete or update child rows first before deleting the parent
  • Add ON DELETE CASCADE to the foreign key to auto-delete children
sql3 fixes

MySQL packet too large

Got a packet bigger than 'max_allowed_packet'

  • Increase max_allowed_packet: SET GLOBAL max_allowed_packet = 64*1024*1024
  • Break large INSERTs into smaller batches instead of one massive statement
sql3 fixes

MySQL binary logging unsafe statement

Binary logging not possible.*binlog_format.*STATEMENT.*unsafe

  • Switch to ROW-based replication: SET GLOBAL binlog_format = 'ROW'
  • Avoid non-deterministic functions (UUID(), NOW(), RAND()) in statements with STATEMENT format
sql3 fixes

MySQL replication SQL thread error

Slave.*SQL.*Error.*Could not execute.*event|Replica.*SQL.*Error

  • Check the exact error: SHOW SLAVE STATUS\G — look at Last_SQL_Error
  • Skip the problematic event if safe: SET GLOBAL sql_slave_skip_counter = 1; START SLAVE
sql3 fixes

MySQL table not found

Table '(.*)' doesn't exist

  • Check the database context: USE correct_database before the query
  • Verify table name case sensitivity — Linux MySQL is case-sensitive for table names by default
sql3 fixes

MySQL InnoDB deadlock

Deadlock found when trying to get lock.*try restarting transaction

  • Implement retry logic — InnoDB automatically rolls back the victim transaction
  • Access tables and rows in a consistent order across all transactions
sql3 fixes

MySQL table full - disk or tmp table limit

The table '(.*)' is full

  • Check disk space: df -h — free up space or add storage
  • For tmp tables: increase tmp_table_size and max_heap_table_size
sql3 fixes

MySQL access denied

Access denied for user '(.*)'@'(.*)'

  • Verify username, password, and host: mysql -u user -p -h host
  • Grant permissions: GRANT ALL ON database.* TO 'user'@'host' IDENTIFIED BY 'password'; FLUSH PRIVILEGES
sql3 fixes

MySQL character encoding mismatch

Incorrect string value.*for column '(.*)'

  • Convert column to utf8mb4: ALTER TABLE t MODIFY col VARCHAR(255) CHARACTER SET utf8mb4
  • Ensure connection charset matches: SET NAMES utf8mb4
sql3 fixes

MySQL InnoDB row size limit exceeded

Row size too large.*maximum row size.*InnoDB

  • Use DYNAMIC or COMPRESSED row format: ALTER TABLE t ROW_FORMAT=DYNAMIC
  • Change large VARCHAR columns to TEXT/BLOB which are stored off-page
sql3 fixes

MySQL replication IO thread error

Slave.*IO.*Error.*Got fatal error.*from master|Replica.*IO.*Error

  • Check network connectivity between master and replica
  • Verify replication user credentials and REPLICATION SLAVE grant on master
sql3 fixes

MySQL lock wait timeout during DDL or DML

ERROR 1205.*Lock wait timeout exceeded

  • Find the blocking transaction: SELECT * FROM information_schema.INNODB_LOCK_WAITS
  • Kill the blocking connection if it's idle: KILL <blocking_trx_id>
sql3 fixes

MySQL data truncation on insert/update

Data truncated for column '(.*)'

  • Check the column type and adjust input data to fit (e.g., truncate string, fix date format)
  • Alter column to accommodate larger values: ALTER TABLE t MODIFY col VARCHAR(500)
sql3 fixes

MySQL foreign key creation failure

ERROR.*Can't create table.*errno: 150|Foreign key constraint is incorrectly formed

  • Ensure parent and child columns have identical data types (including sign, length, and charset)
  • Both tables must use InnoDB engine for foreign keys
sql3 fixes

MySQL connection dropped - server gone away

ERROR.*server has gone away|MySQL server has gone away

  • Increase wait_timeout and interactive_timeout for long-idle connections
  • Implement connection pool health checks and reconnection logic in the application
sql3 fixes

MySQL duplicate key on insert

ERROR.*Duplicate entry '(.*)' for key '(.*)'

  • Use INSERT ... ON DUPLICATE KEY UPDATE to handle upserts
  • Use INSERT IGNORE to silently skip duplicates (data is discarded)
sql3 fixes

MySQL binary logging disabled or command restricted

ERROR.*The used command is not allowed with this MySQL version|binlog.*disabled

  • Enable binary logging: add log-bin=mysql-bin to my.cnf and restart MySQL
  • Set server-id to a unique value when enabling binlog: server-id=1
sql3 fixes

Database Connection Refused

connection refused|ECONNREFUSED|could not connect to server

  • Verify the database server is running: `systemctl status postgresql` or `docker ps`
  • Check host and port in your connection string — default PostgreSQL is 5432, MySQL is 3306
sql3 fixes

Database Query Timeout

statement timeout|query timeout|wait_timeout exceeded|Lock wait timeout exceeded

  • Add indexes on columns used in WHERE, JOIN, and ORDER BY clauses
  • Increase timeout setting: `SET statement_timeout = '60s'` (PostgreSQL) or `SET wait_timeout=28800` (MySQL)
sql3 fixes

Database Deadlock Detected

deadlock detected|Deadlock found when trying to get lock|was deadlocked on lock resources

  • Access tables in a consistent order across all transactions to prevent circular waits
  • Keep transactions short — move non-DB work outside the transaction block
sql3 fixes

Unique Constraint Violation

unique constraint|duplicate key value violates unique|Duplicate entry .* for key

  • Use `INSERT ... ON CONFLICT DO UPDATE` (PostgreSQL) or `INSERT ... ON DUPLICATE KEY UPDATE` (MySQL)
  • Check for race conditions — add application-level deduplication before inserting
sql3 fixes

Foreign Key Constraint Violation

foreign key constraint|violates foreign key|Cannot add or update a child row.*foreign key

  • Insert the parent record before the child record — ensure referenced row exists
  • When deleting, use CASCADE or delete child records first
sql3 fixes

SQL Syntax Error

syntax error at or near|You have an error in your SQL syntax.*near

  • Check for missing commas, unmatched quotes, or reserved words used as identifiers (wrap in double quotes or backticks)
  • Verify SQL dialect — PostgreSQL, MySQL, and SQL Server have different syntax for LIMIT, string concat, etc.
sql3 fixes

Table or Relation Not Found

relation .* does not exist|Table .* doesn't exist|Invalid object name

  • Check the schema/database context — use `SET search_path TO myschema` or fully qualify: `schema.table`
  • Run pending migrations: `npx prisma migrate deploy` or `alembic upgrade head`
sql3 fixes

Ambiguous Column Reference

column reference .* is ambiguous|ambiguous column name

  • Prefix the column with the table name or alias: `SELECT t1.id, t2.id FROM table1 t1 JOIN table2 t2`
  • Use explicit column lists instead of SELECT * in JOINs
sql3 fixes

Too Many Database Connections

too many connections|max_connections|Connection pool exhausted

  • Use a connection pooler like PgBouncer (PostgreSQL) or ProxySQL (MySQL) in front of the database
  • Ensure your app properly closes/releases connections — check for connection leaks in error paths
sql3 fixes

Database Migration Failed

migration failed|migrate.*error|Migration .* was not applied|MigrationError

  • Check if a previous partial migration left the DB in a dirty state — manually fix and mark as applied
  • Run `prisma migrate resolve` or manually update the migrations table to mark the failed migration