brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ANALYZE SELECT runs the query and shows real row counts next to the database estimates

Database
~/tips/tip-database-mariadb-analyze-select

ANALYZE SELECT * FROM orders WHERE customer = 'ann';

Runs a query and prints the plan with actual rows read beside the optimizer's guess.

EXPLAIN shows what the optimizer expects to happen. When a query is slow anyway, I want to know what really happened, and MariaDB has a statement for that.

ANALYZE SELECT * FROM orders WHERE customer = 'ann';

The output has the same columns as EXPLAIN plus a few that start with r_. rows is the estimate, r_rows is what was actually read, and r_filtered is the share of rows that survived the WHERE. When rows says 10 and r_rows says 400000, the optimizer worked with bad statistics, and ANALYZE TABLE orders is the first thing I’d try.

A low r_filtered on a big table means the server reads lots of rows only to throw them away, which usually points at a missing or unused index. For more detail, ANALYZE FORMAT=JSON SELECT ... adds timings per step.

Unlike EXPLAIN, this executes the statement. For a SELECT that is fine. ANALYZE UPDATE and ANALYZE DELETE exist too, and they really change your data. Wrap those in a transaction and roll back, or run them on a copy. MySQL has a similar feature under another name, EXPLAIN ANALYZE, with different output.

Further reading: ANALYZE statement

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link