You add this condition to a case expression in the order by
clause and thus make sure you get these records first:
SELECT TOP 500 *
FROM mytable
WHERE /* conditions */
ORDER BY CASE WHEN /* optional condition */ THEN 0 ELSE 1 END
You can try the following query using union clause
create table #temp (id int, Age int, Course varchar(20))
insert into #temp values (1, 25, 'BE'),(2, 30, 'BE'),(3, 40, 'BE'),(4, 22, 'BE'),(5, 25, 'B. Tech'),(6, 27, 'BE')
select Top 4 * from #temp
where age >= 25
union
select * from #temp
where (Course is null or Course = 'B. Tech')
union
select * from #temp
where age >= 25 OR (Course is null or Course = 'B. Tech')
The output is as shown below
id Age Course
1 25 BE
2 30 BE
3 40 BE
5 25 B. Tech
6 27 BE
You can find the live domo here- Demo Data Matches
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.