Deleting a few thousand spam comments or old revisions leaves holes in the database tables, and the file on disk does not shrink by itself. wp db optimize is the one-line way to ask MySQL or MariaDB to tidy that up.
From the WordPress folder:
wp db optimize
It prints Success: Database optimized. when it is done. Under the hood it runs the mysqlcheck utility with --optimize=true, using the credentials from wp-config.php, so you do not type a password.
It makes the most sense after a big cleanup, for example after emptying the spam folder or running wp transient delete --expired. On a site that never deletes much, there is little to gain.
Caveats worth knowing before you run it on a production site:
- Optimizing can lock a table while it is rebuilt, so run it when the site is quiet.
- It needs enough free disk space, because a table may be copied during the rebuild.
- Take a dump first with
wp db export. The command is routine, but a backup costs one line.
Extra arguments are passed straight to mysqlcheck, and --defaults loads your MySQL option files, which are skipped by default.
Further reading: wp db optimize (WP-CLI handbook)