lisovaccaro
lisovaccaro

Reputation: 33986

MySQL order: put rows matching something on top of query?

I'm running a query that gets users with a certain age. E.G AGE <= 5

So the query gets these rows:

Country | Age
US        5
US        20
AR        3
ES        5
US        2

The problem is that to remain relevant I want to display the results matching the user's country first, using US as an example it should be like this:

Country | Age
US        2
US        5
US        20
US        2
AR        3
ES        5

I know how to do this with two queries, first getting US results and then the rest and order all by age but I wanted to know if it's possible to get results ordered with just one query.

Upvotes: 2

Views: 867

Answers (2)

Ariful Islam
Ariful Islam

Reputation: 7675

Assume that your table structure is :

CREATE TABLE tblName
(
   country VARCHAR(20) NOT NULL,
   age INT NOT NULL
)

Then you can do the following query to purpose your requirements.

SELECT * FROM tblName WHERE age <= 5 ORDER BY (country='US') DESC, age

Upvotes: 2

mu is too short
mu is too short

Reputation: 434785

You could use an ORDER BY like this:

order by case country when 'US' then 1 else 2 end, country, age

That would put US first and then the rest would come after and be sorted by country.

Upvotes: 5

Related Questions