I would like to write a query that simply returns 1 or 0 depending if there will be results.
I am thinking to use this
IF EXISTS( select * from myTable where id=7 and rowInsertDate BETWEEN '01/01/2009' AND GETDATE() ) SELECT 1 ELSE SELECT 0
That's the general premise.
The final results will actually be a far more complex query, taking one to many parameters and the string built up and executed using sp_executesql
My question is lets say the 'count' would return 376986 and takes 4 seconds to calculate. Is using the IF EXISTS going to stop as soon as it find 1 row that satisfies the criteria.
I'm deciding wether to use IF EXISTS or just query the @@ROWCOUNT and see if it is greater than zero.
I did try some tests and both pretty much ran at the same speed but in 2 years time when there's alot more data is it likely using IF EXISTS is going to be a performance gain or not?
Thanks
The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Check - The check is a way for you to check if you have written a legal SQL query. Arrow - This is the execute command button. This will send the query to the server and the server will write back the result to you. Square - This is the stop execution command.
You can use @@ROWCOUNT. For e.g. You will get 0 if first statement will not return any rows. You can also use if statement to check that just after first statement.
This is the fastest i could get in my projects:
SELECT CASE WHEN EXISTS ( select top 1 1 from myTable where id=7 and rowInsertDate BETWEEN '01/01/2009' AND GETDATE() ) THEN 1 ELSE 0 END AS AnyData
Do you have an index on id and date?
maybe you just want:
select top 1 1 from myTable where id=7 and rowInsertDate > '01/01/2009'
note: this would return 1 if data exists, or nothing otherwise.
another edit. This won't return a row with the value null if there is no data, but rather will not return any rows. More like null in its more figurative sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With