Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do an IF in Microsoft SQL SELECT query?

I am an absolute beginner in SQL. Example: I want to do a query to select people whose names begin with X if the result is 0, I want to select people whose names begin with Y.

How do I do this? Thanks.

like image 696
user776676 Avatar asked Jun 13 '26 08:06

user776676


1 Answers

I interpret the question as: show names starting with Y if no names starting with X are found. This solution will be fast as it will short-cut the exists from the moment 1 record is found

if exists(select * from table where name like 'X%')
  begin
    select * from table where name like 'X%'
  end
else
  begin
    select * from table where name like 'Y%'
  end

Ideally the name column is indexed for this to work well.

like image 110
Filip De Vos Avatar answered Jun 15 '26 20:06

Filip De Vos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!