11

Hi i have 100 records in my SQL table i want to sort them ASC by name but i need one record on top of all record nr 43.

Is there way i can pull this record 43 first and then everything else ASC order by name?

Trick is to do it in one query.

BUddhaxx
  • 151
  • 1
  • 5

4 Answers4

30

No UNIONs or CASEs needed:

ORDER BY id = 43 DESC, name ASC
sqwk
  • 1,506
  • 2
  • 12
  • 13
6

Use this:

ORDER BY CASE WHEN (record is 43) THEN 0 ELSE 1 END, Name
Narnian
  • 3,858
  • 1
  • 26
  • 29
0

Use a union to create a query that selects the first record then appends the set of records that should appear beneath.

E.g:

select * from table where id = 43;
union
select * from table where id <> 43;
mdm
  • 12,480
  • 5
  • 34
  • 53
0

This query should add a column called priority, which has the value 1 on the record with id 43 and 0 on all others. Then you sort by priority first.

SELECT mytable.*, IF(id = 43, 1, 0) AS priority FROM mytable ORDER BY priority DESC, name ASC
sled
  • 14,525
  • 3
  • 42
  • 70