tags:

views:

99

answers:

3

Is there any way to write a select record starting with a particular record? Suppose I have an table with following data:

 SNO    ID  ISSUE
 ----------------------
   1    A1  unknown
   2    A2  some_issue
   3    A1  unknown2
   4    B1  some_issue2
   5    B3  ISSUE4
   6    B1  ISSUE4

Can I write a select to start showing records starting with B1 and then the remaining records? The output should be something like this:

4    B1  some_issue2
6    B1  ISSUE4
1    A1  unknown
2    A2  some_issue
3    A1  unknown2
5    B3  ISSUE4

It doesn't matter if B3 is last, just that B1 should be displayed first.

+7  A: 

Couple of different options depending on what you 'know' ahead of time (i.e. the id of the record you want to be first, the sno, etc.):

Union approach:

select   1 as sortOrder, SNO, ID, ISSUE
from     tableName
where    ID = 'B1'
union all
select   2 as sortOrder, SNO, ID, ISSUE
from     tableName
where    ID <> 'B1'
order by sortOrder;

Case statement in order by:

select   SNO, ID, ISSUE
from     tableName
order by case when ID = 'B1' then 1 else 2 end;

You could also consider using temp tables, cte's, etc., but those approaches would likely be less performant...try a couple different approaches in your environment to see which works best.

chadhoc
thank you very much. i was looking for the case approach.
JPro
A: 
select * from table1
where id = 'B1'
union all
select * from table1
where id <> 'B1'
BlackTigerX
why did this answer go -1?
JPro
Not sure (i.e. I didn't down vote), but I would assume it may be because to guarantee sort order you'd need to add an "order by" clause (i.e. there would be potential for this query to return data in any order). Not sure that's worth a downvote or not, particularly without a comment, but that's my guess.
chadhoc
people might just be "playing the game" (down vote others to get theirs positioned better)
BlackTigerX
A: 

Assuming you are using MySQL, you could either use IF() in an ORDER BY clause...

SELECT SNO, ID, ISSUE FROM table ORDER BY IF( ID = 'B1', 0, 1 );

... or you could define a function that imposes your sort order...

DELIMITER $$
CREATE FUNCTION my_sort_order( ID VARCHAR(2), EXPECTED VARCHAR(2) )
RETURNS INT
BEGIN
  RETURN IF( ID = EXPECTED, 0, 1 );
END$$
DELIMITER ;

SELECT SNO, ID, ISSUE FROM table ORDER BY my_sort_sort( ID, 'B1' );
nigeltc