Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT at least 1 row of a set when the WHERE conditions are not fulfilled?

I have a very simple query that returns a set of rows, from the following table:

Table1
N1  N2
1   A1
1   A2
2   B1
2   B2
2   B3

I only need one row (TOP(1)) from the table when N1 = @X. In all the cases I would rather get a specific N2 value, however in not all the cases a N2 value would exists for every N1

For example the following query will not return any row:

SELECT TOP(1) N1, N2 FROM Table WHERE N1 = 2 AND N2 = 'B4'

I am looking for a simple way to return at least 1 row even if the condition N2 = @N2 is not fulfilled. It does not matter which row is returned, any will be Ok if the @N2 value does not exists.

So far I have done the following but I would like if someone knows something simpler:

;with tmp AS (
SELECT TOP(1) *, 1 AS No FROM Table1 WHERE N1 = @N1 AND N2 = @N2
UNION
SELECT TOP(1) *, 2 AS No FROM Table1 WHERE N1 = @N1
)

SELECT TOP(1) * FROM tmp ORDER BY No

Any help will be appreciated

like image 943
Ayorus Avatar asked Dec 14 '25 17:12

Ayorus


1 Answers

I think you want order by:

SELECT TOP(1) N1, N2
FROM Table
WHERE N1 = 2 
ORDER BY (CASE WHEN N2 = 'B4' THEN 1 ELSE 2 END);
like image 85
Gordon Linoff Avatar answered Dec 16 '25 13:12

Gordon Linoff



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!