Home / Guides / WordPress handbook / Chapter 08
WordPress handbook · Chapter 08 · Security
WordPress Database Security
The database is the site. Files can be reinstalled from WordPress.org; posts, users, orders and settings cannot. This chapter covers how WordPress talks to MySQL and MariaDB, how to limit what a compromised site can do to its database, how to keep it healthy as it grows, and how to look inside it without breaking it.
On this page
- MySQL, MariaDB and how WordPress connects
- Database users, privileges and credentials
- Table prefixes: why changing wp_ is not access control
- Backups and restoration
- Why direct SQL modifications are dangerous
- Database growth: transients, revisions, orphaned metadata and scheduled actions
- WooCommerce database tables
- Optimisation, corruption and connection failures
- Safe diagnostic SQL
- Database security checklist
MySQL, MariaDB and how WordPress connects
WordPress runs on MySQL or MariaDB. MariaDB forked from MySQL in 2009, and the two have since diverged in internals, but both remain compatible with WordPress's SQL. The WordPress Hosting Team currently recommends recent long-term releases (MySQL 8.4 LTS; MariaDB 10.11, 11.4 or 11.8 LTS) for new installations. Older versions keep working but miss performance and security fixes. Use InnoDB for every table. It supports transactions, row-level locking and crash recovery; old MyISAM tables lock the whole table on writes and corrupt more easily after crashes.
WordPress connects through the wpdb class using the DB_* constants in wp-config.php. DB_HOST may be localhost (Unix socket), 127.0.0.1 (TCP), localhost:/path/to/mysqld.sock, db.internal:3306, or a managed database endpoint. Every page load opens a connection, runs dozens to hundreds of queries, and closes it.
Database users, privileges and credentials
One user per site, one database per user
Each WordPress site should have its own database and its own database user, with privileges on that database only. Then a compromised site, or an SQL injection flaw in one of its plugins, cannot read or destroy other sites' data on the same server. Never connect WordPress as root or as a user granted ALL PRIVILEGES ON *.*.
Which privileges WordPress needs
Day to day, WordPress needs SELECT, INSERT, UPDATE and DELETE. But core updates, plugin installs and plugin updates create and alter tables, so they also need CREATE, ALTER, INDEX and DROP. Some plugins use CREATE TEMPORARY TABLES or LOCK TABLES. Removing schema privileges is possible for hardened sites where updates run under a separate, more privileged account, but it breaks dashboard updates in confusing ways. Most sites should grant the standard set on their own database only:
CREATE DATABASE example_wp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'example_wp_user'@'localhost' IDENTIFIED BY 'a-long-random-password';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP,
CREATE TEMPORARY TABLES, LOCK TABLES
ON example_wp.* TO 'example_wp_user'@'localhost';
-- Never: GRANT ALL PRIVILEGES ON *.* ... WITH GRANT OPTION
On shared hosting, the control panel's "MySQL Databases" tool creates exactly this kind of scoped user. The host bit to note is '@'localhost': the user can only connect from the server itself. A database listening on a public IP with users allowed from '%' (anywhere) is exposed to the internet's brute-force traffic. Keep the database bound to localhost or a private network, and firewall port 3306.
Credentials in wp-config.php
The database password sits in plain text in wp-config.php; PHP needs it. Protect it with file permissions, server deny rules and keeping it out of version control (Chapter 02). Rotate it after any compromise, staff change with server access, or accidental exposure:
- Create a new strong password for the database user (panel or
ALTER USER ... IDENTIFIED BY ...). - Immediately update
DB_PASSWORDinwp-config.php. The site shows "Error establishing a database connection" between these two steps, so do them back to back, or create a second user, switch, then drop the first. - Update any other tool that connects with those credentials (backup scripts, reporting tools).
Table prefixes: why changing wp_ is not access control
The table prefix ($table_prefix) exists so several WordPress installations can share one database. Changing it from wp_ to something random is often recommended as a security measure. It is not one, for three reasons:
- SQL injection does not need to guess. An attacker who can run SQL can list the tables (
SHOW TABLESorinformation_schema) in one query and read the prefix from the result. - It does not change who can connect or what they can do. Access control means credentials, privileges and network restrictions. A prefix is just a name.
- It only stops the crudest automated scripts that hard-code
wp_users, and those were unlikely to succeed for other reasons.
On a new installation, a non-default prefix costs nothing. On an existing site, changing it means renaming every table and updating prefixed option names and user meta keys (wp_user_roles, wp_capabilities, wp_user_level). Missing one of these locks every user out of wp-admin ("Sorry, you are not allowed to access this page"). The risk outweighs the benefit; spend the effort on updates, MFA and least-privilege database users instead.
Backups and restoration
Logical vs physical backups
- Logical backups (
mysqldump,mariadb-dump,wp db export, backup plugins) produce SQL statements. They are portable between versions and servers, and slower to restore for very large databases. - Physical/snapshot backups (host snapshots, Percona XtraBackup, Mariabackup, volume snapshots) copy data files. They are fast, but tied to the database version and configuration, and usually only available at host or root level.
For InnoDB, take logical dumps with --single-transaction so the dump is a consistent snapshot without locking tables while the shop keeps trading:
# WP-CLI (reads credentials from wp-config.php)
wp db export /home/example/backups/example-$(date +%F-%H%M).sql --single-transaction --quick
# Or directly (prompts for password; never put passwords on the command line on shared servers)
mysqldump --single-transaction --quick --routines --default-character-set=utf8mb4 \
-u example_wp_user -p example_wp | gzip > /home/example/backups/example-$(date +%F).sql.gz
A dump left in the web root (public_html/backup.sql) is a complete data breach waiting for someone to guess the name. Store backups outside the document root, copy them off-server, encrypt them if they contain personal data, and apply a retention policy.
Restoration
- Restore to staging first, unless production is already down and the backup is known good.
- Put the production site into maintenance mode if you are restoring over it, so new orders or comments are not written mid-restore (and record that anything written after the backup time will be lost).
- Import:
wp db import backup.sql(or the panel's import tool for small files; large files need the command line). - If the domain or path differs, run a serialization-aware search-replace (see below), then flush caches:
wp cache flush, plus the page cache and CDN. - Verify: log in, check recent content and orders, run
wp db check, and read the error log.
Test restores regularly. Common surprises: a backup that only contains some tables, character-set corruption (emoji or accents turned to "é"), dumps truncated by timeouts, and missing plugin tables.
Why direct SQL modifications are dangerous
Editing the database directly (phpMyAdmin, Adminer, the MySQL client) bypasses everything WordPress does to keep data consistent:
- Serialized data. Options and meta often hold PHP-serialized arrays that record string lengths. A plain
REPLACE()that changes a string's length leaves the length counter wrong; PHP cannot unserialize the value, and the setting silently reverts to defaults or widgets vanish. - Hooks are skipped. Changing an order status in SQL does not send emails, adjust stock, write order notes, update lookup tables or trigger webhooks. Deleting a post row leaves its meta, term relationships and comments orphaned.
- Caches go stale. With a persistent object cache, WordPress keeps serving the old value until the cache expires or is flushed.
- No undo. There is no trash and no revision. A
DELETEorUPDATEwithout the rightWHEREclause affects every row instantly. - Data model drift. WooCommerce, for example, stores orders in its own tables (HPOS) on modern stores, and may keep a synchronised copy in posts tables during migration. Editing one copy creates conflicts.
Prefer, in order: the WordPress admin; WP-CLI commands (which use WordPress APIs); plugin-provided tools; and only then SQL, after a backup, on staging first, wrapped in a transaction where possible, with a SELECT that previews exactly which rows will change. For URL changes, always use wp search-replace 'https://old.example' 'https://new.example' --dry-run first. It handles serialized data correctly. Then run it without --dry-run.
Database growth: transients, revisions, orphaned metadata and scheduled actions
| Source | What it is | How it grows | Safe management |
|---|---|---|---|
| Transients | Cached values with an expiry, stored in wp_options (rows named _transient_* and _transient_timeout_*) unless a persistent object cache is active | Expired transients are only deleted when read or by periodic clean-up; badly written plugins create unique transients per visitor or per URL | wp transient delete --expired; fix the plugin creating per-request transients; a persistent object cache moves them out of the database |
| Revisions | Copies of posts on each save (post_type = 'revision') | Unlimited by default; heavily edited pages accumulate hundreds | Limit with define( 'WP_POST_REVISIONS', 20 );. Delete old revisions with a maintained plugin or WP-CLI package after a backup |
| Auto-drafts and trash | Abandoned new-post screens, trashed items | Auto-drafts older than 7 days are cleaned by WordPress; trash empties after EMPTY_TRASH_DAYS (30) | Normally self-managing |
| Orphaned metadata | Rows in wp_postmeta / wp_usermeta / wp_commentmeta whose parent no longer exists, or that belong to uninstalled plugins | Direct SQL deletes, plugins that do not clean up on uninstall | Count first (queries below), back up, then remove using a maintained clean-up tool; review keys before deleting plugin meta |
| Autoloaded options | Options loaded on every request | Plugins storing large arrays or logs with autoload on | Identify the largest (query below), then fix at source or switch autoload off via the plugin. Site Health warns when autoloaded data is very large |
| Scheduled actions (Action Scheduler) | Background job queue used by WooCommerce and many plugins (wp_actionscheduler_actions, _logs) | Completed and failed actions are retained (completed actions are purged after 30 days by default); failing jobs can pile up in the hundreds of thousands | Tools → Scheduled Actions (or WooCommerce → Status → Scheduled Actions): look for failed and past-due actions; fix the cause; the retention period is filterable |
| Sessions | wp_woocommerce_sessions, plugin session tables | Expired sessions not cleaned when cron is broken | Fix WP-Cron; WooCommerce cleans expired sessions on schedule |
| Logs and statistics | Security, redirect-404, email and analytics plugins writing to their own tables | Every request or event adds rows | Configure retention in each plugin; disable database logging you do not use |
| Spam comments | wp_comments with comment_approved = 'spam' | Retained until deleted | Empty spam regularly; Akismet can discard the worst automatically |
WooCommerce database tables
WooCommerce adds its own tables (shown with the default wp_ prefix). Knowing them makes performance and data problems much easier to diagnose:
| Table(s) | Purpose |
|---|---|
wp_wc_orders, wp_wc_orders_meta, wp_wc_order_addresses, wp_wc_order_operational_data | High-Performance Order Storage (HPOS): orders in dedicated tables instead of posts and postmeta. Default for new stores since WooCommerce 8.2. Check WooCommerce → Settings → Advanced → Features to see whether a store uses HPOS and whether compatibility sync is on. |
wp_woocommerce_order_items, wp_woocommerce_order_itemmeta | Line items of each order (products, shipping, fees, taxes) |
wp_wc_product_meta_lookup, wp_wc_product_attributes_lookup | Denormalised lookup tables for fast filtering and sorting; can be regenerated from WooCommerce → Status → Tools |
wp_wc_order_stats, wp_wc_order_product_lookup, wp_wc_customer_lookup and related | Analytics tables; can be rebuilt via the analytics import tool |
wp_woocommerce_sessions | Cart sessions for guests and customers |
wp_actionscheduler_* | Background jobs (emails, webhooks, subscriptions renewals, analytics imports) |
wp_woocommerce_api_keys, wp_wc_webhooks | REST API keys (store the hashed key; review permissions and last access) and webhook definitions |
wp_woocommerce_payment_tokens, _tokenmeta | References to saved payment methods (tokens from the gateway, never full card numbers) |
wp_woocommerce_tax_rates, _tax_rate_locations, wp_woocommerce_shipping_zones and related | Tax and shipping configuration |
Never delete WooCommerce tables or rows by hand to "clean up". Use the tools under WooCommerce → Status → Tools, which know about dependencies and caches.
Optimisation, corruption and connection failures
Optimisation
"Optimise database" buttons usually run OPTIMIZE TABLE, which on InnoDB rebuilds the table to reclaim space. That locks or slows the table for the duration (seconds to many minutes on large tables) and temporarily needs free disk space roughly equal to the table size. It rarely makes a measurable performance difference. Real gains come from shrinking autoloaded options, pruning log tables, removing orphaned rows, adding indexes for slow queries the plugin developer confirms, and giving the database enough memory (innodb_buffer_pool_size, a host-level setting). Run rebuilds off-peak, after a backup, one large table at a time.
Corruption
Causes: disk-full events, server crashes or power loss (especially with MyISAM), failing storage, interrupted imports, and incompatible manual edits. Symptoms: "Table is marked as crashed", "Incorrect key file", errors for specific queries only, WordPress showing "One or more database tables are unavailable".
wp db checkrunsCHECK TABLEon all tables (read-only).wp db repairrunsREPAIR TABLE, which works for MyISAM. InnoDB tables do not support it; InnoDB corruption recovery is a host or DBA task (server-level recovery modes, restore from backup).- WordPress's built-in repair page is enabled with
define( 'WP_ALLOW_REPAIR', true );and found at/wp-admin/maint/repair.php. That page is accessible without logging in while the constant is set, so remove the line as soon as you are done. - Take a backup, even of a corrupted database, before attempting any repair.
Connection failures
"Error establishing a database connection" means PHP could not connect or authenticate, or (when shown inside wp-admin with a different message) connected but found tables missing or damaged. The full diagnostic procedure is in the Error Encyclopedia. The common causes, in order: wrong credentials or host after a migration or password change; the database server down or out of memory; max_connections reached under load; disk full; the database user lacking privileges on the database.
Safe diagnostic SQL
Every query below is a SELECT. It reads, it does not change anything. Replace wp_ with your prefix and example_wp with your database name. Run them on staging or during quiet periods on very large databases, since some scan whole tables. Clean-up should then be done with WordPress or WP-CLI tools, not by turning these into DELETE statements.
SELECT table_name,
ROUND((data_length + index_length) / 1024 / 1024, 1) AS size_mb,
table_rows,
engine
FROM information_schema.tables
WHERE table_schema = 'example_wp'
ORDER BY (data_length + index_length) DESC
LIMIT 20;
Look for unexpectedly large log, session, Action Scheduler or analytics tables, and for any table not using InnoDB.
SELECT COUNT(*) AS autoloaded_rows,
ROUND(SUM(LENGTH(option_value)) / 1024, 1) AS autoload_kb
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto');
WordPress 6.6 introduced the values on, off, auto, auto-on and auto-off alongside the legacy yes/no. A total of a few hundred KB is normal; several MB slows every uncached request.
SELECT option_name,
ROUND(LENGTH(option_value) / 1024, 1) AS size_kb,
autoload
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto')
ORDER BY LENGTH(option_value) DESC
LIMIT 25;
The option name prefix usually identifies the plugin. Raise large ones with the developer, or disable the feature that stores them.
SELECT post_type, post_status, COUNT(*) AS total
FROM wp_posts
WHERE post_type = 'revision' OR post_status = 'auto-draft'
GROUP BY post_type, post_status;
SELECT
SUM(option_name LIKE '\_transient\_timeout\_%' AND option_value < UNIX_TIMESTAMP()) AS expired_transients,
SUM(option_name LIKE '\_transient\_%' AND option_name NOT LIKE '\_transient\_timeout\_%') AS total_transients
FROM wp_options;
SELECT COUNT(*) AS orphaned_postmeta
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;
SELECT meta_key, COUNT(*) AS rows_count,
ROUND(SUM(LENGTH(meta_value)) / 1024 / 1024, 2) AS size_mb
FROM wp_postmeta
GROUP BY meta_key
ORDER BY SUM(LENGTH(meta_value)) DESC
LIMIT 25;
SELECT status, COUNT(*) AS total
FROM wp_actionscheduler_actions
GROUP BY status;
-- Most frequent failing hooks
SELECT hook, COUNT(*) AS failures
FROM wp_actionscheduler_actions
WHERE status = 'failed'
GROUP BY hook
ORDER BY failures DESC
LIMIT 15;
SELECT u.ID, u.user_login, u.user_email, u.user_registered
FROM wp_users u
JOIN wp_usermeta m ON m.user_id = u.ID
WHERE m.meta_key = 'wp_capabilities'
AND m.meta_value LIKE '%"administrator"%'
ORDER BY u.user_registered DESC;
The meta key includes the table prefix (wp_capabilities). Compare the result with wp user list --role=administrator. A user found by SQL but unknown to your team is a compromise indicator.
SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home', 'template', 'stylesheet', 'active_plugins', 'users_can_register', 'default_role');
Useful after migrations and during incident response: check that users_can_register and default_role have expected values.
Database security checklist
- Dedicated database and user per site; privileges scoped to that database only.
- WordPress never connects as root or a global user.
- Database bound to localhost/private network; port 3306 not open to the internet.
- Strong unique database password; rotated after staff or access changes.
- All tables use InnoDB and
utf8mb4. - Consistent automated backups stored off-server and outside the web root; restore tested this quarter.
- No SQL dumps or exports in the web root.
WP_ALLOW_REPAIRis not defined.- Autoloaded options total checked and within a reasonable size.
- Revisions limited; log and session tables have retention configured.
- Action Scheduler has no large backlog of failed or past-due actions.
- Database and server version are within vendor support.
Rather have someone else keep WordPress healthy?
Our managed hosting and care plans cover updates, backups, security monitoring and fixes like the ones in this handbook, so you can get on with running the business.
See Hosting & Care