0

I have some simple query:

SELECT * FROM table 

You all know the result:

|id|   foo   |    bar   |
-------------------------
|1 |   aaa   |    123   |
|2 |   bbb   |    234   |
|3 |   ccc   |    345   |
|4 |   ddd   |    456   |

but, what I want to do show from record number 3? I know I can do it with SELECT * FROM table where id=3, but I need to set the record I choose is in first rank, let say I choose id=3 so the result as follow:

|id|   foo   |    bar   |
-------------------------
|3 |   ccc   |    345   |
|4 |   ddd   |    456   |
|1 |   aaa   |    123   |
|2 |   bbb   |    234   |

or

|id|   foo   |    bar   |
-------------------------
|3 |   ccc   |    345   |
|1 |   aaa   |    123   |
|2 |   bbb   |    234   |
|4 |   ddd   |    456   |

is this possible?

  • Can you define 'rank'? is it a column? calculated? – dougajmcdonald Nov 24 '11 at 16:08
  • I'm sorry for my poor english, rank means i need to sort the query result starts from the id I choose. Please see my table result above. but Erwin Brandstetter has enlightened me :D Thanks to you all – syaiful bahri Nov 24 '11 at 17:37

1 Answers1

1

This way you get id = 3 first:

SELECT *
FROM tbl
ORDER BY (id = 3) DESC
-- ,id

Order by id additionally if you want the rest ordered, too.

Explanation:

The expression evaluates to boolean. FALSE (= 0 in mysql) sorts before TRUE (= 1 in mysql), so we order descending.

It also automatically covers the case of id being NULL. I quote the manual again here:

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228