tips
53 tips Database
One command, setting or habit at a time about Database: what it does, the line to copy and a caveat or two.
SQL shells 16
-
Records every query and result of an interactive session in a log file.
MariaDB [shop]> tee /tmp/fix-orders.log -
Sends query output through less without line wrapping, so wide tables stay aligned.
MariaDB [shop]> pager less -S -
Prints a complete CREATE TABLE statement with keys, engine and charset for one table.
SHOW CREATE TABLE orders\G -
Puts the login user, server host and current database in the client prompt.
mariadb --prompt='\u@\h [\d]> ' shop -
Stores the client login in a private file so commands and cron jobs need no -p.
cat > ~/.my.cnf <<'EOF' -
Prints the SQL that psql sends for backslash commands like \dt.
psql -E -d mydb -
Stores the single row of a query result in psql variables for later statements.
\gset -
Runs a SQL script as one transaction and stops at the first error, rolling everything back.
psql -1 -v ON_ERROR_STOP=1 -d appdb -f migrate.sql -
Starts psql without reading startup files, so scripts give the same output on every machine.
psql -X -d appdb -f report.sql -
Keeps an open psql transaction usable after one statement fails, instead of aborting all of it.
\set ON_ERROR_ROLLBACK interactive -
Prints the details of the current psql connection, so you know where a query is about to run.
postgres=# \conninfo -
Opens an SQLite database file in read-only mode, so a stray UPDATE or DELETE just returns an error.
sqlite3 -readonly db.sqlite -
Makes psql print wide query results one field per line, only when they do not fit.
\x auto -
Exports SQLite query results to a CSV file and imports a CSV back with the shell.
sqlite3 -header -csv app.db "SELECT id, email FROM users" > users.csv -
Shows disk usage per table, index and database from the psql prompt.
\dt+ -
Reruns the last PostgreSQL query at a fixed interval inside psql.
\watch 2
Backups and dumps 13
-
Pulls one database out of a full server dump without touching the others.
mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' -
Dumps only rows as INSERT IGNORE, so loading them adds missing rows and keeps the rest.
mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql -
Writes one INSERT per row so diff and grep show exactly which rows changed.
mariadb-dump --skip-extended-insert shop orders > orders.sql -
Makes a dump that creates and selects its own database when you restore it.
mariadb-dump --databases shop blog > shop-blog.sql -
Takes a fast physical backup of a live MariaDB server instead of a slow SQL dump.
mariadb-backup --backup --target-dir=/backup/full --user=root --password -
Writes a compact, consistent copy of a SQLite database to a new file.
sqlite3 app.db "VACUUM INTO '/backups/app-compact.db'" -
Dumps a PostgreSQL database but leaves out the rows of chosen tables while keeping their definitions.
pg_dump -Fc --exclude-table-data='app_log*' -f appdb.dump appdb -
Drops existing objects before a restore and skips the errors for objects that were never there.
pg_restore --clean --if-exists -d appdb appdb.dump -
Makes a consistent copy of a SQLite database file while it is still in use.
sqlite3 app.db ".backup /backup/app-$(date +%F).db" -
Speeds up PostgreSQL dumps and restores by processing several tables at once.
pg_dump -Fd -j 4 -f /backup/appdb.dir appdb -
Saves a PostgreSQL database as a compressed archive from which you can restore only chosen parts.
pg_dump -Fc -f appdb.dump appdb -
Writes only the table and routine definitions of a MySQL or MariaDB database, in a form that diffs cleanly.
mysqldump --no-data --routines --skip-dump-date mydb > schema.sql -
Dumps a MySQL or MariaDB database from one consistent snapshot so applications can keep writing during the backup.
mysqldump --single-transaction --routines --events mydb | gzip > mydb.sql.gz
Admin and checks 11
-
Shows which tables use the most disk space, data and indexes together, in megabytes.
SELECT table_schema, table_name, -
Compares a table on two servers with one number instead of dumping and diffing it.
CHECKSUM TABLE shop.orders; -
Uses the check script that ships in the MariaDB image instead of a hand-made mysqladmin line.
services: -
Has the official image run mariadb-upgrade and back up system tables after a version bump.
services: -
Checks how much reclaimable space a table holds before rebuilding it to shrink it.
SHOW TABLE STATUS LIKE 'orders'\G -
Finds which two transactions deadlocked and which rows they were both waiting for.
mariadb -e 'SHOW ENGINE INNODB STATUS\G' | grep -A 40 'LATEST DETECTED DEADLOCK' -
Rebuilds a new SQLite database from every readable page of a damaged file.
sqlite3 broken.db ".recover" | sqlite3 recovered.db -
Tests PostgreSQL availability without credentials and returns a script-friendly exit code.
pg_isready -h 127.0.0.1 -p 5432 -
Lists the exact privileges of one MySQL or MariaDB account so you can spot too-wide rights.
SHOW GRANTS FOR 'app'@'localhost'; -
Verifies the structure of a SQLite file and reports damage or broken foreign keys.
sqlite3 app.db "PRAGMA integrity_check;" -
Finds the PostgreSQL tables with the most dead rows and shows when they were last cleaned.
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;
Query tuning 8
-
Runs a query and prints the plan with actual rows read beside the optimizer's guess.
ANALYZE SELECT * FROM orders WHERE customer = 'ann'; -
Sets a time limit so a slow query is aborted instead of running for hours.
SET STATEMENT max_statement_time = 5 FOR -
Hides an index from the optimizer so you can see what breaks before you drop it.
ALTER TABLE orders ALTER INDEX idx_customer IGNORED; -
Counts the rows a query actually read, so full table scans stand out right away.
SHOW SESSION STATUS LIKE 'Handler_read%'; -
Starts logging slow statements on a running MySQL or MariaDB server and shows where the file lives.
SET GLOBAL slow_query_log = 'ON'; -
Shows whether SQLite reads a whole table or uses an index for a given query.
sqlite3 app.db "EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = '[email protected]';" -
Runs a PostgreSQL statement and reports real timings and cache reads for each plan step.
EXPLAIN (ANALYZE, BUFFERS) UPDATE orders SET paid = true WHERE id = 42; -
Lists every running thread of a MySQL or MariaDB server with its complete SQL text, and lets you stop one.
mysql -e 'SHOW FULL PROCESSLIST'
WP-CLI 4
-
Runs a SQL query against the WordPress database without needing the database password.
wp db query 'SELECT option_value FROM wp_options WHERE option_name="home"' --skip-column-names -
Searches every WordPress table for a string or regex and shows the table, column and row.
wp db search example.com -
Prints all custom fields (post meta) of a single post, optionally filtered by key.
wp post meta list 123 -
Counts the replacements WP-CLI would make in your WordPress database without changing anything.
wp search-replace 'http://old.example' 'https://new.example' --dry-run
Debugging 1
-
Turns on the WordPress database repair page at wp-admin/maint/repair.php, which needs no login.
define( 'WP_ALLOW_REPAIR', true );
Nothing in this filter yet.