Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all
SQL
pk_id    name 
1        bhagi
2        sumit
3        raju
4        ramesh
5        mac
6        hellen
7        allen
8        krishna
9        rashmi
10       radhamadhaba

This is my table.
I want to show all the data in this sequence

first 3 row pk_id = 1,2,10 than rest order by name.
means
SQL
pk_id    name
1        bhagi
2        sumit
10       radhamadhaba
rest order by name like
7        allen
6        hellen
etc...

In one query

Thanks in advance
Posted

Add a column for your exceptions (1,2,10) rows and set a sort order number in that column, then query as follows:
SQL
select * from [table] where [exception] > 0 order by [exceptions]
union 
select * from [table] where [exception] = 0 order by [name]


EDIT :
SQL
select * from [table] where pk_id in (1,2,10)
union
select * from [table] where pk_id not in (1,2,10) order by [name]
 
Share this answer
 
v2
Comments
bhagirathimfs 30-Apr-12 3:52am    
Thanks for response but i can't add a column into that table.

I tried like this also

select * from [table] where pk_id in (1,2,10)
union
select * from [table] where pk_id not in (1,2,10) order by name

the above query is not doing order by for both the case
means this result is coming with out any sorting.
Mehdi Gholam 30-Apr-12 3:59am    
Run the query in the management studio to check.
bhagirathimfs 30-Apr-12 5:15am    
select * from [table] where pk_id in (1,2,10) order by pk_id
union
select * from [table] where pk_id not in (1,2,10) order by name
SQL
(select * from [table] where pk_id in (1,2,10)order by pk_id limit 1000)
union 
(select * from [table] order by name limit 1000)
 
Share this answer
 
SQL
(select * from [table] where pk_id in (1,2,10))
union 
(select * from (SELECT * FROM [table] where pk_id not in (1,2,10) order by [name]) as somename )


Just try this code it should work.

Even pk_id not in (1,2,10) is not required because UNION will remove all duplicate entries.
 
Share this answer
 
v2
Well, you already got your answer but i would add an small suggestion, you might have those time when you would have to change the name list. what would you do then? you better add another column and give those three user least same value, and put some other value to rest of the user. you can call it user type, in that case your query complexity will be reduced too
 
Share this answer
 
Comments
bhagirathimfs 1-May-12 2:44am    
Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900