Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT Sort by specific row

Tags:

sql

Suppose I have a table food, which I query SELECT name FROM food ORDER BY name:

| name
|--------
| Apple
| Banana
| Carrot
| Donut
...

I wish to specify that specific items of my choice be pinned to the top (e.g. "Lemon" and then "Carrot"), if they are in the table. Like so:

| name
| -------
| Lemon
| Carrot
| Apple
| Banana
| Donut
...

What kind of SQL query can I use to get this specific sort?

like image 355
cameraguy258 Avatar asked May 31 '26 17:05

cameraguy258


2 Answers

You can use a case statement in your order by clause to prioritize items with a certain name.

The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.

SELECT *
FROM food
ORDER BY
  CASE name
    WHEN 'Lemon' THEN 1
    WHEN 'Carrot' THEN 2
    ELSE 3
  END,
  name
like image 73
Daniel Gimenez Avatar answered Jun 04 '26 11:06

Daniel Gimenez


Make a look up table like this:

WITH odering(F, Ord) AS
(
   VALUES ('Lemmon', 2),
          ('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
like image 35
Hogan Avatar answered Jun 04 '26 11:06

Hogan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!