MySQL Cheatsheet
Dense quick reference for MySQL 8.4 LTS (InnoDB): connect, define, query, index, lock, monitor, back up, and wire it into Go and Laravel. Chapters behind it: MySQL storage engines, Indexing, Isolation levels, Locks & concurrency.
How to use this page
- This is a lookup page: find the task in the first column, copy the command, and read the note before running it on production.
- For why, and for query and index examples, read the chapters linked in the summary above and the SQL Queries & Indexes Cheatsheet.
- Written for MySQL 8.4 LTS; anything marked with a version (for example 8.0+) is absent below that version.
Page map
| Section | Use it when |
|---|---|
| Connection | Connecting, TLS, login paths and checking the connection |
| Meta-commands (mysql client) | Meta-commands in the mysql client: SHOW statements, pager, source |
| DDL | Creating and altering tables, online DDL and partitions |
| DML | Inserts, upserts, CTEs, windows, JSON and pagination |
| Indexes | Choosing, building and auditing indexes |
| Transactions & isolation | Isolation levels, row and named locks, timeouts and retries |
| Admin & monitoring | Threads, locks, statements, sizes, replication and the slow log |
| Diagnostic queries | Long SQL moved out of the tables, ready to paste |
| Config knobs | Defaults and sizing hints for the main settings |
| Backup & restore | Dumps, restores, clone and point-in-time recovery |
| Users, roles & grants | Accounts, grants, roles and resource limits |
| Common errors | Error numbers and what to do about them |
| Go snippets | database/sql driver, DSN parameters and transactions |
| Laravel snippets | Config, raw queries, locks, upsert and read replicas |
| References | Official documentation |
Connection
| Task | Command | Notes |
|---|---|---|
| Connect with flags | mysql -h db.example.com -P 3306 -u app -p shop | -p with no value prompts for the password; no space between -p and an inline password |
| Secure connection | mysql -h db -u app -p --ssl-mode=VERIFY_IDENTITY shop | Modes: DISABLED, PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY |
| Run one statement | mysql -e "select now()" shop | -e executes and exits |
| Run a file | mysql shop < schema.sql | Add --force to continue after errors |
| Script-friendly output | mysql -B -N -e "select id,email from users" shop | -B batch tab-separated, -N skips column names |
| Vertical output | mysql -e "select * from users limit 1\G" shop | \G ends the statement with a vertical layout |
| Credentials without a password flag | mysql_config_editor set --login-path=prod --host=db --user=app --password then mysql --login-path=prod | Stored encrypted in ~/.mylogin.cnf |
| Charset | mysql --default-character-set=utf8mb4 shop | Use utf8mb4, not the legacy utf8 alias |
| Unix socket | mysql -S /var/run/mysqld/mysqld.sock -u root -p | Local connections skip TCP |
| Check connection | select current_user(), database(), version(), @@hostname; | current_user() is the account that matched, user() the one you asked for |
Meta-commands (mysql client)
| Task | Command | Notes |
|---|---|---|
| List databases | show databases; | |
| Switch database | use shop; | Or \u shop |
| List tables | show tables; / show full tables where table_type = 'BASE TABLE'; | |
| Describe table | describe users; / show columns from users; | Short form desc |
| Show DDL | show create table users\G | Authoritative: engine, charset, constraints |
| Show indexes | show index from users; | Cardinality and visibility |
| Show variables | show variables like 'innodb%'; / show global variables like 'max_conn%'; | % wildcard; SESSION vs GLOBAL scope |
| Show status counters | show global status like 'Threads%'; | Counters since start |
| Show warnings | show warnings; | Run right after a statement that reports a note |
| Pager | pager less -S / nopager | Wide result sets |
| Tee output / status | tee /tmp/out.log / notee; status (\s) | status prints connection info and uptime |
| Run a file | source /path/file.sql or \. file.sql | |
| Switch user | connect or \r | Reconnects with the current settings |
| Help | help contents / \h | |
| Quit | exit / \q |
DDL
| Task | Command | Notes |
|---|---|---|
| Create table | see Diagnostic queries | InnoDB and utf8mb4 are the defaults in 8.4 |
| Add / drop column | alter table orders add column note varchar(255) null; / drop column note; | Add algorithm=instant where supported to avoid a rebuild |
| Online DDL | alter table orders add index idx_u (user_id), algorithm=inplace, lock=none; | Fails loudly if the combination is not allowed, which is the point |
| Change type | alter table orders modify total decimal(14,2) not null; | Many type changes rebuild the table |
| Rename | rename table orders to sales; / alter table t rename column a to b; | rename table is atomic and can swap two tables |
| Primary / unique | alter table t add primary key (id); / add unique key uq_email (email); | InnoDB clusters rows by the primary key |
| Foreign key | alter table orders add constraint fk_u foreign key (user_id) references users(id) on delete restrict; | Needs an index on the referencing column (created automatically) |
| Check constraint | alter table orders add constraint pos check (total >= 0); | Enforced from 8.0.16 |
| Default expression | create table t (id char(36) default (uuid())); | Expression defaults go in parentheses |
| Generated column | alter table orders add column gross decimal(12,2) generated always as (total * 1.2) stored; | virtual computes on read and can be indexed |
| Enum / set | status enum('new','paid') not null | Appending a value at the end is an instant change |
| JSON column | data json | Index with a generated column or a functional index |
| Range partition | see Diagnostic queries | The partition key must be in every unique key |
| List / hash / key | partition by list (region) / partition by hash (id) partitions 8 / partition by key (id) | |
| Partition maintenance | alter table ev drop partition p1; / reorganize partition pmax into (...) | drop partition is a fast delete |
| Temporary table | create temporary table t (...) | Per session |
| Drop / truncate | drop table if exists t; / truncate table t; | truncate resets AUTO_INCREMENT and commits implicitly |
| DDL transactions | DDL causes an implicit commit | Atomic DDL in 8.0+ means a single DDL is all-or-nothing, but not part of your transaction |
DML
| Task | Command | Notes |
|---|---|---|
| Insert, fetch id | insert into users (email) values ('a@x.io'); select last_insert_id(); | MySQL has no RETURNING; drivers expose LastInsertId |
| Multi-row insert | insert into t (a,b) values (1,'x'),(2,'y'); | Batch for throughput |
| Upsert | insert into kv (k,v) values ('a',1) as new on duplicate key update v = new.v; | Alias form; the VALUES(col) function is deprecated |
| Insert ignore | insert ignore into kv (k,v) values ('a',1); | Turns errors into warnings, which can hide real problems |
| Replace | replace into kv (k,v) values ('a',1); | Deletes then inserts, fires delete triggers and changes ids |
| Update with join | update orders o join payments p on p.order_id = o.id set o.status='paid'; | Multi-table update syntax |
| Delete with join | delete s from sessions s join users u on u.id = s.user_id where u.banned; | Names the table to delete from |
| Update limit | update jobs set state='x' where state='new' order by id limit 10; | ORDER BY and LIMIT allowed on single-table update and delete |
| CTE | with recent as (select * from orders where created_at > now() - interval 1 day) select count(*) from recent; | Since 8.0 |
| Recursive CTE | with recursive t(n) as (select 1 union all select n+1 from t where n < 5) select * from t; | Bounded by cte_max_recursion_depth (default 1000) |
| Window function | select *, row_number() over (partition by user_id order by created_at desc) rn from orders; | Latest-per-group: filter rn = 1 in an outer query |
| Running total | sum(total) over (order by created_at rows between unbounded preceding and current row) | Also lag, lead, rank, ntile |
| JSON access | select data->'$.a.b', data->>'$.a.b' from docs; | -> returns JSON, ->> unquoted text |
| JSON search | select * from docs where json_contains(data, '"admin"', '$.roles'); | Also json_extract, json_search, member of |
| JSON modify | update docs set data = json_set(data, '$.a', 2); | json_insert, json_replace, json_remove |
| JSON table | select * from json_table(@j, '$[*]' columns (id int path '$.id')) t; | Turns JSON into rows |
| Keyset pagination | select * from orders where (created_at, id) < (?, ?) order by created_at desc, id desc limit 50; | Beats OFFSET on deep pages |
| Explain | explain analyze select ...; | analyze runs the query; plain explain format=tree does not |
| Bulk load | load data local infile 'u.csv' into table users fields terminated by ',' ignore 1 lines; | Needs local_infile enabled on both sides |
| GROUP BY / HAVING, window and pagination patterns | SQL Queries & Indexes Cheatsheet | worked examples with plan lines |
Indexes
| Task | Command | Notes |
|---|---|---|
| Create | create index idx_o_u on orders (user_id, created_at); | B-tree; leftmost-prefix rule applies |
| Online create | alter table orders add index idx_o_u (user_id), algorithm=inplace, lock=none; | Concurrent DML allowed for secondary indexes |
| Unique | create unique index uq_email on users (email); | |
| Descending | create index idx on orders (user_id, created_at desc); | Real descending indexes since 8.0 |
| Prefix | create index idx on docs (title(32)); | Required for TEXT/BLOB, may not cover the query |
| Functional | create index idx on users ((lower(email))); | Double parentheses; query must use the same expression |
| Covering | create index idx on orders (user_id, total); | No INCLUDE; add trailing columns; Extra: Using index in EXPLAIN |
| Full-text | create fulltext index ft on docs (title, body); then match(title, body) against ('x' in natural language mode) | InnoDB full-text |
| Invisible | alter table orders alter index idx_o_u invisible; | Test dropping an index safely, then drop index |
| Drop | drop index idx_o_u on orders; | |
| Index sizes | see Diagnostic queries | size is in pages |
| Unused indexes | select * from sys.schema_unused_indexes; | Based on performance_schema counters since startup |
| Redundant indexes | select * from sys.schema_redundant_indexes; | Includes the dominating index and a ready DROP statement |
| Tables without a PK | see Diagnostic queries | Every InnoDB table should have a primary key |
| Refresh statistics | analyze table orders; | Updates index cardinality |
| Worked examples | SQL Queries & Indexes Cheatsheet | composite order, sort path, "is the index used?", GROUP BY / HAVING |
Transactions & isolation
| Task | Command | Notes |
|---|---|---|
| Start | start transaction; / begin; | start transaction with consistent snapshot; pins the snapshot at once |
| Read-only | start transaction read only; | Slightly cheaper; read write is the default |
| Set level (next txn) | set transaction isolation level serializable; | Applies to the next transaction only |
| Set level (session) | set session transaction isolation level read committed; | GLOBAL for new connections |
| Levels | read uncommitted, read committed, repeatable read (default), serializable | Variable is transaction_isolation |
| Autocommit | set autocommit = 0; | Default is 1; each statement commits by itself |
| Savepoints | savepoint a; rollback to savepoint a; release savepoint a; | |
| Commit / rollback | commit; / rollback; | |
| Row lock | select * from accounts where id = 1 for update; | Locks index records; gap locks under REPEATABLE READ |
| Shared lock | select * from accounts where id = 1 for share; | Replaces the old LOCK IN SHARE MODE |
| Fail fast | select ... for update nowait; | Error 3572 if the row is locked |
| Queue worker | select * from jobs where state='new' order by id limit 10 for update skip locked; | 8.0+; skipped rows are not locked or returned |
| Lock only one table | for update of orders | Required when joining |
| Named lock | select get_lock('invoice-42', 5); ... select release_lock('invoice-42'); | Application-level, returns 1 on success |
| Table lock | lock tables t write; ... unlock tables; | Rarely right with InnoDB |
| Global read lock | flush tables with read lock; | Blocks writes server-wide |
| Lock wait timeout | set session innodb_lock_wait_timeout = 5; | Default 50 seconds; error 1205 |
| Retry rule | Retry on 1213 (deadlock) and sometimes 1205 | Retry the whole transaction |
| Current locks | select * from performance_schema.data_locks; | One row per held or requested lock |
Admin & monitoring
| Task | Command | Notes |
|---|---|---|
| Running threads | show full processlist; | Same data in information_schema.processlist and performance_schema.processlist |
| Long running | see Diagnostic queries | |
| Kill | kill query 123; / kill 123; | kill query stops the statement, kill closes the connection |
| Who blocks whom | select * from sys.innodb_lock_waits\G | Shows waiting and blocking queries and a sql_kill_blocking_query |
| Raw lock waits | select * from performance_schema.data_lock_waits; | Join with data_locks |
| Open transactions | see Diagnostic queries | Old trx_started means a long transaction |
| Top statements | see Diagnostic queries | Timers are picoseconds |
| Friendlier top list | see Diagnostic queries | sys schema formats times |
| Full table scans | select * from sys.statements_with_full_table_scans limit 10; | |
| Reset digests | truncate table performance_schema.events_statements_summary_by_digest; | |
| InnoDB status | show engine innodb status\G | Sections: LATEST DETECTED DEADLOCK, TRANSACTIONS, BUFFER POOL AND MEMORY |
| Last deadlock | Look in LATEST DETECTED DEADLOCK | Set innodb_print_all_deadlocks=ON to log every one |
| Buffer pool hit | show global status like 'Innodb_buffer_pool_read%'; | reads / read_requests should be near zero |
| Table sizes | see Diagnostic queries | Estimates; run analyze table first |
| Database size | see Diagnostic queries | |
| Connections | see Diagnostic queries | Compare with max_connections |
| Replica status | show replica status\G | Check Replica_IO_Running, Replica_SQL_Running, Seconds_Behind_Source, Last_Error |
| Source status | show binary log status; | Replaces SHOW MASTER STATUS |
| Replication threads | select * from performance_schema.replication_applier_status_by_worker; | Per-worker applier errors and lag |
| Binary logs | show binary logs; | purge binary logs before '2026-11-01'; |
| Slow query log | set global slow_query_log = on; set global long_query_time = 0.5; | Writes to slow_query_log_file |
Diagnostic queries
Long queries moved out of the tables above, in table order; each table row points here.
Create table. InnoDB and utf8mb4 are the defaults in 8.4.
CREATE TABLE orders (
id bigint unsigned AUTO_INCREMENT PRIMARY KEY,
user_id bigint unsigned NOT NULL,
total decimal(12,2) NOT NULL DEFAULT 0,
created_at datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;Range partition. The partition key must be in every unique key.
CREATE TABLE ev (
id bigint,
at datetime NOT NULL,
PRIMARY KEY (id, at)
) PARTITION BY RANGE (to_days(at)) (
PARTITION p1 VALUES LESS THAN (to_days('2026-12-01')),
PARTITION pmax VALUES LESS THAN MAXVALUE
);Index sizes. size is in pages.
SELECT index_name, round(stat_value * @@innodb_page_size / 1024 / 1024) mb
FROM mysql.innodb_index_stats
WHERE database_name = 'shop' AND table_name = 'orders' AND stat_name = 'size';Tables without a PK. Every InnoDB table should have a primary key.
SELECT t.table_schema, t.table_name
FROM information_schema.tables t
LEFT JOIN information_schema.table_constraints c
ON c.table_schema = t.table_schema
AND c.table_name = t.table_name
AND c.constraint_type = 'PRIMARY KEY'
WHERE t.table_type = 'BASE TABLE'
AND c.constraint_name IS NULL
AND t.table_schema NOT IN ('mysql','sys','information_schema','performance_schema');Long running.
SELECT id, user, time, state, left(info,80)
FROM information_schema.processlist
WHERE command <> 'Sleep'
ORDER BY time DESC;Open transactions. Old trx_started means a long transaction.
SELECT trx_id, trx_started, trx_mysql_thread_id, trx_rows_locked
FROM information_schema.innodb_trx
ORDER BY trx_started;Top statements. Timers are picoseconds.
SELECT digest_text, count_star, round(sum_timer_wait/1e12,2) total_s, round(avg_timer_wait/1e9,2) avg_ms
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC
LIMIT 10;Friendlier top list. sys schema formats times.
SELECT query, exec_count, total_latency, avg_latency
FROM sys.statement_analysis
LIMIT 10;Table sizes. Estimates; run analyze table first.
SELECT table_name, round((data_length+index_length)/1024/1024) mb
FROM information_schema.tables
WHERE table_schema = 'shop'
ORDER BY mb DESC
LIMIT 10;Database size.
SELECT table_schema, round(sum(data_length+index_length)/1024/1024) mb
FROM information_schema.tables
GROUP BY 1;Connections. Compare with max_connections.
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';Role. Roles must be activated.
CREATE ROLE 'readonly';
GRANT SELECT ON shop.* TO 'readonly';
GRANT 'readonly' TO 'app'@'10.%';
SET DEFAULT ROLE ALL TO 'app'@'10.%';Config knobs
| Task | Command | Notes |
|---|---|---|
innodb_buffer_pool_size | Default 128MB | Resizable online; the 50 to 75 percent of RAM sizing rule is not verified |
innodb_redo_log_capacity | Default 100MB | Replaces innodb_log_file_size; the 1-8GB sizing advice is not verified |
innodb_flush_log_at_trx_commit | Default 1 | 1 is fully durable; 2 flushes once per second to the OS |
sync_binlog | Default 1 | Keep 1 with the above for crash-safe replication |
max_connections | Default 151 | Raise only with enough memory; use a pooler or a per-app limit |
innodb_lock_wait_timeout | Default 50 (seconds) | Lower for interactive apps |
transaction_isolation | Default REPEATABLE-READ | READ-COMMITTED reduces gap locking |
innodb_io_capacity | Default 10000 (8.4) | innodb_io_capacity_max defaults to twice this value |
tmp_table_size | Default 16MB | Per in-memory temp table; with max_heap_table_size |
max_allowed_packet | Default 64MB | Raise for large blobs or bulk inserts |
binlog_expire_logs_seconds | Default 2592000 (30 days) | Match your backup and replica catch-up window |
wait_timeout | Default 28800 (8 hours) | Pool max lifetime must be shorter |
long_query_time | Default 10 | Lower to 0.5 or 1; with slow_query_log=ON |
slow_query_log | Default OFF | Turn on in production |
character_set_server | Default utf8mb4 | Pair with collation_server, for example utf8mb4_0900_ai_ci |
Backup & restore
| Task | Command | Notes |
|---|---|---|
| Consistent logical dump | mysqldump --single-transaction --routines --triggers --events shop > shop.sql | --single-transaction gives an InnoDB snapshot without locking |
| All databases | mysqldump --all-databases --single-transaction > all.sql | Includes the mysql system schema |
| With binlog position | mysqldump --single-transaction --source-data=2 shop > shop.sql | Replaces the old --master-data; records the coordinates for a new replica |
| Schema only | mysqldump --no-data shop > schema.sql | |
| One table | mysqldump --single-transaction shop orders > orders.sql | |
| Compressed stream | mysqldump --single-transaction shop | gzip > shop.sql.gz | |
| Restore | mysql shop < shop.sql / gunzip -c shop.sql.gz | mysql shop | Create the database first |
| GTID dumps | --set-gtid-purged=OFF | Use when restoring into a server with its own GTIDs |
| Physical copy | Clone plugin: clone local data directory = '/backup/clone'; | Needs install plugin clone soname 'mysql_clone.so' |
| Point in time | mysqlbinlog --start-datetime='2026-11-25 10:00:00' binlog.000042 | mysql | Replay binary logs after restoring a full dump |
Users, roles & grants
| Task | Command | Notes |
|---|---|---|
| Create user | create user 'app'@'10.%' identified by 'secret'; | The host part is part of the identity |
| Grant | grant select, insert, update, delete on shop.* to 'app'@'10.%'; | Since 8.0 grant does not create users |
| Show grants | show grants for 'app'@'10.%'; | |
| Revoke | revoke insert on shop.* from 'app'@'10.%'; | |
| Role | see Diagnostic queries | Roles must be activated |
| Require TLS | alter user 'app'@'10.%' require ssl; | |
| Change password | alter user 'app'@'10.%' identified by 'new'; | Default plugin is caching_sha2_password |
| Resource limits | alter user 'app'@'10.%' with max_user_connections 20; | |
| Lock / drop | alter user 'x'@'%' account lock; / drop user 'x'@'%'; | |
| Grant option | grant select on shop.* to 'a'@'%' with grant option; | Lets the user pass the privilege on |
| Who am I | select current_user(), @@global.version; |
Common errors
| Task | Command | Notes |
|---|---|---|
| 1062 ER_DUP_ENTRY (23000) | Duplicate entry for key | Use ON DUPLICATE KEY UPDATE or map to 409 |
| 1213 ER_LOCK_DEADLOCK (40001) | Deadlock found; try restarting transaction | Order locks consistently; retry the transaction |
| 1205 ER_LOCK_WAIT_TIMEOUT (HY000) | Lock wait timeout exceeded | Find the blocker in sys.innodb_lock_waits |
| 3572 ER_LOCK_NOWAIT (HY000) | Statement aborted because lock(s) could not be acquired immediately | NOWAIT hit; retry later |
| 1452 ER_NO_REFERENCED_ROW_2 (23000) | Cannot add or update a child row | Parent row missing |
| 1451 ER_ROW_IS_REFERENCED_2 (23000) | Cannot delete or update a parent row | Child rows exist |
| 1045 ER_ACCESS_DENIED_ERROR (28000) | Access denied for user | Check host part of the account and auth plugin |
| 1040 ER_CON_COUNT_ERROR (08004) | Too many connections | Pool, or raise max_connections |
| 1049 ER_BAD_DB_ERROR (42000) | Unknown database | |
| 1146 ER_NO_SUCH_TABLE (42S02) | Table does not exist | |
| 1054 ER_BAD_FIELD_ERROR (42S22) | Unknown column | |
| 1064 ER_PARSE_ERROR (42000) | You have an error in your SQL syntax | |
| 1406 ER_DATA_TOO_LONG (22001) | Data too long for column | Strict mode turns truncation into an error |
| 2006 / 2013 (client) | MySQL server has gone away / Lost connection during query | Check wait_timeout, max_allowed_packet, restarts |
Go snippets
// go get github.com/go-sql-driver/mysql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
db, err := sql.Open("mysql", "app:secret@tcp(db:3306)/shop?parseTime=true&loc=UTC&charset=utf8mb4&collation=utf8mb4_0900_ai_ci&timeout=5s&readTimeout=30s")
if err != nil { return err }
db.SetConnMaxLifetime(3 * time.Minute) // below wait_timeout and proxy idle limits
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
if err := db.PingContext(ctx); err != nil { return err }
// Query one row
var email string
err = db.QueryRowContext(ctx, "select email from users where id = ?", id).Scan(&email)
// Query many rows
rows, err := db.QueryContext(ctx, "select id, email from users where active = ?", 1)
if err != nil { return err }
defer rows.Close()
for rows.Next() { /* rows.Scan(...) */ }
// Transaction
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
if err != nil { return err }
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "update accounts set balance = balance - ? where id = ?", amt, from); err != nil { return err }
return tx.Commit()| Task | Command | Notes |
|---|---|---|
| DSN shape | user:password@tcp(host:3306)/dbname?param=value | Param values must be URL-escaped, for example loc=Europe%2FBerlin |
| Time values | parseTime=true | Returns time.Time instead of bytes; add loc= |
| Timeouts | timeout (dial), readTimeout, writeTimeout | Duration strings such as 5s |
| Duplicate key | var me *mysql.MySQLError; errors.As(err, &me); me.Number == 1062 | Compare against error numbers |
| Multi statements | multiStatements=true | Off by default; widens SQL-injection impact |
| Placeholders | interpolateParams=true | Client-side interpolation, saves a round trip |
Laravel snippets
// config/database.php (env: DB_CONNECTION=mysql, DB_URL=mysql://app:secret@db:3306/shop)
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix_indexes' => true,
'strict' => true,
],
$rows = DB::select('select * from users where active = ?', [1]);
DB::statement('drop table temp_users');
DB::transaction(function () {
DB::update('update accounts set balance = balance - 10 where id = ?', [1]);
}, attempts: 3);
$acct = DB::table('accounts')->where('id', $id)->lockForUpdate()->first(); // inside a transaction
$rows = DB::table('posts')->where('votes', '>', 100)->sharedLock()->get();| Task | Command | Notes |
|---|---|---|
| Raw read / write | DB::select(), DB::insert(), DB::update(), DB::delete(), DB::statement() | Always bind values with ? |
| Manual transaction | DB::beginTransaction(); DB::commit(); DB::rollBack(); | DB::transaction($cb, $attempts) retries on deadlock |
| Pessimistic locks | ->lockForUpdate() / ->sharedLock() | Map to FOR UPDATE and the shared lock clause; only valid inside a transaction |
| Upsert | DB::table('kv')->upsert($rows, ['k'], ['v']); | Generates ON DUPLICATE KEY UPDATE on MySQL |
| Log queries | DB::listen(fn ($q) => logger($q->sql, $q->bindings)); | Service provider |
| Read replicas | 'read' => ['host' => [...]], 'write' => ['host' => [...]], 'sticky' => true | sticky reads your own writes within the request |
References
- Connecting to the server and mysql client options
- INSERT ... ON DUPLICATE KEY UPDATE
- SET TRANSACTION and Locking reads (
NOWAIT,SKIP LOCKED) - Online DDL operations and Locking functions
- Statement summary tables, data_locks, sys schema views
- SHOW REPLICA STATUS
- InnoDB parameters, server system variables, binary log options
- mysqldump, GRANT
- Server error reference
- go-sql-driver/mysql README for DSN parameters
- Laravel 13 Database and Query Builder