Mysql – How to get the top 20 percent records with a single query

mariadbMySQLoffset-fetch

SELECT start_coins
FROM   coins
ORDER BY  start_coins DESC LIMIT 10; /* till here the query works*/
CAST((COUNT(start_coins) * 0.2) AS INT);

I want the number returning from the count to be used as the LIMIT instead of 10. My database version is 10.1.32-MariaDB.

Best Answer

The LIMIT clause parameters are always literals. So You cannot use the value calculated by some statement in it.

The solution can be in prepared statement use.

Variant 1:

SET @sql := CONCAT( 'SELECT start_coins FROM coins ORDER BY start_coins DESC LIMIT '
                  , (SELECT ROUND(COUNT(*) * 0.2) FROM coins));
PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP PREPARE stmt;

Variant 2:

SELECT COUNT(*) * 0.2 INTO @cnt FROM coins;
PREPARE stmt FROM 'SELECT start_coins FROM coins ORDER BY start_coins DESC LIMIT ?;';
EXECUTE stmt USING @cnt;
DROP PREPARE stmt;

In both variants You MUST to execute all 4 statements in the same connection to database. The best vairant is the connector You use allows multi-statements (sending all statements as 1 command).