Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return 50% of random result

I want to get 50% randomly form the result set. What I’ve tried which is close:

SELECT * FROM Customers
WHERE RAND() < 0.5;

But this gives me less or more than 50% of the result set. In other words, this is not stable.

The second try is as below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * FROM Customers
ORDER BY RAND()
LIMIT (SELECT COUNT(*) / 2 FROM Customers);

But I have an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘(SELECT COUNT(*) / 2 FROM Customers)’ at line 3.

As you can test here: https://www.w3schools.com/MySQL/trymysql.asp?filename=trysql_select_all

The expected result should be making the order to be random, and then select 50% of the result set.

>Solution :

On MySQL 8+, we can use ROW_NUMBER() here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn,
              COUNT(*) OVER () cnt
    FROM Customers
)

SELECT *
FROM cte
WHERE rn <= cnt / 2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading