How to make an IF query in a SQL SQL SELECT query?

I am an absolute beginner in SQL. Example: I want to make 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 should I do it? Thank.

+3
source share
4 answers

Maybe this is the best solution:

select * from table where name like 'X%'

if @@ROWCOUNT = 0
   select * from table where name like 'Y%'
+1
source

I interpret the question as: show names starting with Y if names starting with X are not found. This solution will be quick, as it will reduce the existing one since the discovery of 1 record

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, name columns are indexed to make this work well.

+3
source

SQL, ( , ). .

0

:

SELECT * 
  FROM table 
 WHERE NAME LIKE 'X%'
UNION
SELECT * 
  FROM table 
 WHERE NAME LIKE 'Y%'
       AND NOT EXISTS (
                       SELECT * 
                         FROM table AS T1
                        WHERE T1.NAME LIKE 'X%'
                      );
0
source

All Articles