Home > Database > Mysql Tutorial > body text

How Can I Speed Up Row Counting Queries in Large MySQL Tables?

DDD
Release: 2024-11-19 16:46:03
Original
351 people have browsed it

How Can I Speed Up Row Counting Queries in Large MySQL Tables?

Speeding Up Row Counting in MySQL

Problem:

MySQL queries to count the number of rows in a large table or group them by a particular column can become slow as the table grows. Even indexing the column used for grouping doesn't consistently improve performance.

Exploration:

To optimize these queries, alternative approaches without using caching include:

  • Using a Column-Based Storage Engine: This approach may improve count(*) queries, but could compromise performance for other operations.
  • Maintaining a Summary Table: Triggers can update a separate summary table each time a row is inserted, deleted, or updated. This approach provides instant row counts during SELECT operations.

Implementation:

For maintaining a summary table, the following boilerplate triggers can be used:

DELIMITER //

CREATE TRIGGER ai_books AFTER INSERT ON books
FOR EACH ROW UPDATE books_cnt SET total = total + 1 WHERE status = NEW.status
//
CREATE TRIGGER ad_books AFTER DELETE ON books
FOR EACH ROW UPDATE books_cnt SET total = total - 1 WHERE status = OLD.status;
//
CREATE TRIGGER au_books AFTER UPDATE ON books
FOR EACH ROW
BEGIN
    IF (OLD.status <> NEW.status)
    THEN
        UPDATE books_cnt SET total = total + IF(status = NEW.status, 1, -1) WHERE status IN (OLD.status, NEW.status);
    END IF;
END
//
Copy after login

By maintaining a summary table, row counting queries can be executed much faster, regardless of the table size.

The above is the detailed content of How Can I Speed Up Row Counting Queries in Large MySQL Tables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template