简体   繁体   中英

MariaDB LIMIT statement brings more than limit

I have 10,000 users on registrations table and want to limit this query to 3500 users from my application. But when I investigate the logs , sometimes it counts more than 3500. I can not understand why that query returns more than limit:

select  count(*)
    from  registrations
    where  (selectedtime IS NULL
       AND  expirationtime < NOW()
           )
    LIMIT  3500;

I tried manually on DB and saw sometimes more than 3500

Your query only returns 1 row, which is less than 3500.

If you want to limit the number of rows that are being counted, you need to put that in a subquery.

SELECT COUNT(*)
FROM (
    SELECT 1
    FROM registrations
    WHERE selectedtime IS NULL AND expirationtime < NOW()
    LIMIT 3500) AS x

A SELECT statement with COUNT returns the number of rows retrieved by the SELECT statement.

For performance reasons, the desired result is to limit that count. Including a LIMIT clause in the SELECT statement will not work since it only restricts the number of rows returned, which is always one.

The solution, what I call “Limited-Count”, is done by limiting a non-count SELECT statement and wrapping it in COUNT(*).

For example: If your count statement looks like

select count(*) from registrations where (selectedtime IS NULL AND expirationtime < NOW()) LIMIT 3500;

You can limit the results by replacing the query into:

SELECT COUNT(*) AS total
FROM (
    SELECT 1
    FROM registrations
    WHERE selectedtime IS NULL AND expirationtime < NOW()
    LIMIT 3500) AS x

If you need to know how many rows your non-count SELECT statement would have returned without the LIMIT, you could use the information function, FOUND_ROWS(). It will fetch the total rows number without running the statement again.

This does what you thought you were doing:

select  count(*)
    from  registrations
    where  (selectedtime IS NULL
       AND  expirationtime < NOW()
           )
    LIMIT ROWS EXAMINED 3500;

(Available since MariaDB 5.5.21 - see https://mariadb.com/kb/en/library/limit-rows-examined/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM