Analyze and Optimize Slow Database Queries
Slow database queries can significantly increase CPU usage and affect your site’s performance. Frappe Cloud provides tools to help you identify slow and frequently executed queries so you can optimize them and improve overall database efficiency.
Prerequisites
Advanced query optimization features, such as adding database indexes, require your site to be hosted on a Private Bench and running Frappe Version 14 or later.
View Slow Queries
MariaDB automatically tracks slow-running queries. You can review them from your site’s dashboard to identify queries that consume excessive CPU time.
- Open your Site in the Frappe Cloud dashboard.
- Navigate to the Analytics tab.
- Review the list of Slow Queries to identify queries that need optimization.
Analyze Frequently Executed Queries
Some queries may execute quickly but run so frequently that they still create unnecessary CPU load.
- Open your site’s Database Analyzer tab.
- Review frequently executed queries.
- Identify opportunities to optimize queries, reports, or custom code.
Optimize Queries with Database Indexes
Adding indexes to frequently filtered columns can significantly improve query performance. In many cases, composite indexes (indexes on multiple columns) perform better than single-column indexes.
View Existing Indexes
SHOW INDEXES FROM `tab<doctype_name>`;
Run the command from the MariaDB console:
bench --site <site_name> mariadb
Add a Composite Index
bench --site <site_name> add-database-index --doctype "<doctype_name>" --column <column_1> --column <column_2>
Example:
bench --site <site_name> add-database-index --doctype "Sales Order" --column order_type --column status
When an index is created using this command, Frappe also creates a Property Setter so the index persists across future migrations and restores.
Important
Adding too many indexes can slow down record inserts and updates. Only create indexes for queries that genuinely need optimization. If an index causes issues, remove the corresponding Property Setter and run bench migrate to remove it.
Avoid Using COALESCE on Indexed Columns
Functions such as COALESCE() can prevent MariaDB from using indexes efficiently, resulting in slower queries.
- If you’re using the Frappe ORM, set
ignore_ifnull=Truein yourget_list()query to avoid generating unnecessaryCOALESCE()statements. - If you’re optimizing reports, consider creating a custom SQL Query Report that removes unnecessary
COALESCE()functions.
Best Practice
Start by optimizing the slowest and most frequently executed queries before adding indexes. Measure the impact of each change to ensure you’re improving performance without introducing unnecessary overhead.