Home > Software design >  how to select SQL , age 20 first , and then all the rest from table PERSONS?
how to select SQL , age 20 first , and then all the rest from table PERSONS?

Time:04-20

My table contains 113 people.

48 of them are 20 years old. Now I am just selecting all people like

select * from persons

this will get me all persons, but 20 yr old are not the first 48 people.

I need the 20 yr old to be first 48 in 113 results.

something like

20 year ols ( 48 of them ), after that ..... all the rest in the table

How can I query this using PostgreSQL.

EDIT : there are age less than 20 too. after getting the first 48 , 20 yr olds, I dont care rest of the order I am getting the 48 to 113 people.

CodePudding user response:

Just use order by :

select * 
from persons
order by age 

You can use asc or desc but because default is asc you do not need to put it in your example.

select * 
from persons
order by age desc

After the comment from OP here is the new code(I do not know why but my firs assumption was that the value 20 is the lowest possible value... bad assumption):

select * 
from persons
order by case when age = 20 then 1 else 2 end

OR

select * 
from persons
order by (age = 20) desc

Here is a demo

CodePudding user response:

If 20 is not your minimum age, you can use the CASE statement inside the ORDER BY clause, like this:

SELECT 
    * 
FROM 
    persons
ORDER BY 
    CASE WHEN age = 20 THEN 0 
         ELSE 1 
    END ASC
  • Related