axt.rein
axt.rein

Reputation: 3

SQL Sort entries based on how often they occur in the table

i have a table like this:

user_id | date
-----------------------------
1       |  2022-03-30 09:29:11
3       |  2022-03-30 09:29:11
4       |  2022-03-30 09:29:11
1       |  2022-03-30 09:29:11
2       |  2022-03-30 09:29:11

i want to sort the user_ids in ascending order according to the number of entries of this user_id. So it should always be the user_id that occurs the least total in the table at the top and the user_id that has the most entries at the bottom.

I am new to working with databases and was wondering if there is a way to do this directly with an ORDER BY in the database.

Upvotes: 0

Views: 29

Answers (1)

Bjarni Ragnarsson
Bjarni Ragnarsson

Reputation: 1781

Like this:

select user_id, count(*) from the_table group by user_id order by count(*);

Best regards, Bjarni

Upvotes: 1

Related Questions