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

Time:03-30

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.

CodePudding user response:

Like this:

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

Best regards, Bjarni

  • Related