How to bring a specific result of an SQL query above the others?

Asked

Viewed 1,290 times

1

I have the following SQL query:

SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users` ORDER BY `id` ASC;

That generates the output:

+----+--------+
| id | name   |
+----+--------+
|  1 | Calebe |
|  2 | João   |
|  3 | Lucas  |
|  4 | Pedro  |
+----+--------+

However, I need that determined user come in the results, before the others. Example: I want the user_id = 3 appears at the top. Then the result should come as follows:

+----+--------+
| id | name   |
+----+--------+
|  3 | Lucas  |
|  1 | Calebe |
|  2 | João   |
|  4 | Pedro  |
+----+--------+

How can I do it?

4 answers

4


For your specific query, something like this works:

SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users` 
ORDER BY `id` = 3 DESC, `id` ASC;

In this way, it is ensured that the first ordering term obeys the desired ID.

0

You can also use an order for the desired field and values using the following rule:


SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users` 
ORDER BY FIELD (id, 3, 1, 2, 4 ) ASC, id DESC;

0

SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name`, if(user_name = `Lucas`,0,1) as `ordem` FROM `users` ORDER BY `ordem` ASC, `id` ASC;

0

There’s a solution here: link

ORDER BY (user_id.id=3) ...
  • 1

    This will make ID 3 stay at the end of the results. You need to use a DESC to put you on top.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.