UNION ALL in SQL Server
How to retrieve particular records in top position.
One of my friends Mr. Hari asked my help to fulfill his requirement.
Hari 's requirement
In a table there are number of records. He want to retrieve all records, but he want to show some records first based on a condition, and then remaining records.
I worked on this requirement by taking an example.
Table
I have five records in my table. I want to show the records in top, which state names starts with K (Kerala, Karnataka).
I tried to solve this by using ORDER BY and GROUP BY CLAUSES, but I didn't get result what I expected.
For this I found this method, and this works fine.
Query
DECLARE @Key VARCHAR(50)
SET @Key='K%'
SELECT * FROM tbl_Population
WHERE StateName LIKE @Key
UNION ALL
SELECT * FROM tbl_Population
WHERE StateName NOT LIKE @Key
Output
|