0 votes
1 view
in SQL by (6.1k points)

I want to take a database of say, 1000 users and select 20 random ones (ORDER BY rand(),LIMIT 20) then order the resulting set by the names. I tried the following query which is not working as I hoped.

SELECT * FROM users WHERE 1 ORDER BY rand(), name ASC LIMIT 20

1 Answer

0 votes
by (12.7k points)
edited ago by

Use a subquery:

SELECT * FROM
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query will select 20 users at random and the outer query will order the selected users by name.

Willing to Learn SQL? Join this SQL training course and certification program by Intellipaat.

You can also go through the below MySQL tutorial video that will help you out in a better way:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 3 in SQL by Appu (6.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...