I need to do select data from a table based on some kind of priority like so:
select product, price from table1 where project = 1
-- pseudo: if no price found, do this:
select product, price from table1 where customer = 2
-- pseudo: if still no price found, do this:
select product, price from table1 where company = 3
That is, if I found 3 products with prices based on project = X
, I don't want to select on customer = Y
. I just want to return the resulting 3 rows and be done.
How are you supposed to do stuff like this in SQL? Use some kind of CASE-statement for the pseudo-if's? Do a union or some other smart thing?
Edit: I'm using MS SQL.
Thanks!
With SQL server you can just use a CTE instead of IF/THEN logic to make it easy to map from your existing queries and change the number of involved queries;
An SQLfiddle to test with.
Alternately, you can combine it all into one
SELECT
to simplify it for the optimizer;Another SQLfiddle.
Instead of using
EXISTS
andCOUNT
just use@@ROWCOUNT
:--Similar answer as above for the most part. Code included to test
Please check whether this helps:
You can make the following sql query
The CASE statement is the closest to an IF statement in SQL, and is supported on all versions of SQL Server: