January 8, 2008 at 9:05 am
Which one to compare 1'st string or integer in a where clause for better performance
I have a query which does validation before inserting/updating which is like
SELECT TOP(1) @result_category_id = category_id
FROM category_table
WHERE language_id =
AND
...Kumar
January 8, 2008 at 9:59 am
>>Which one to compare 1'st string or integer in a where clause for better performance
It doesn't make any difference. The optimizer makes a decision based on indexes, statistics etc.
Also, what you're doing can be expressed as a single, set-based operation. You don't need to declare variables and SELECT TOP 1 to determine if something exists prior to INSERT.
INSERT INTO YourTable
WHERE NOT EXISTS ()
January 8, 2008 at 10:09 am
Thank you. I will try to implement if not exists. Another one which one is faster IF EXISTS or IF NOT EXISTS...
...Kumar
January 8, 2008 at 10:18 am
>>Another one which one is faster IF EXISTS or IF NOT EXISTS...
There is no correct answer. As always ... "it depends".
Both of these contructs execute a query, and whichever is fastest depends on what exactly is being queried, indexes, statistics etc.
For a simple single table test, it is generally faster to check IF EXISTS, because the check can bail out on the first item found that proves existence=true.
January 8, 2008 at 10:25 am
Thanks a lot for the fast reply. I was checking in the Performance - Object Execution Statistics Report in SQL 2005, & as you said IF Exists was doing better .
...Kumar
January 8, 2008 at 10:27 am
Actually the fastest way would be to use UPSERT.
Update
set col2 = @par2
where Col1 = @par1
if @@rowcount = 0
insert into (Col1,Col2)
values
(@par1,@par2)
When you do a If Exist, it does an additional read to the table to find out if the record exist before you can update.
When you do Upsert, you reduce one table read IF THE RECORD EXIST.
If not, it will have the two reads as that off IF Exist
-Roy
January 8, 2008 at 10:37 am
Sounds Kool... Thanks i would definetely try using this
...Kumar
January 8, 2008 at 7:28 pm
It's great code! But only if you're inserting 1 row at a time from the GUI. 😉
--Jeff Moden
Change is inevitable... Change for the better is not.
January 9, 2008 at 7:40 am
Yes, when you are trying to update with the key it is useful.
-Roy
January 10, 2008 at 11:09 am
I normally use a set based solution with 2 passes for an UPSERT.
Something like:
UPDATE Tbl1
SET Tbl1.SomeData = Tbl2.SomeData
FROM Tbl1
INNER JOIN Tbl2 ON
Tbl1.PK = Tbl2.PK
INSERT INTO Tbl1
(PK, SomeData)
SELECT Tbl2.PK, Tbl2.SomeData
FROM Tbl2
LEFT JOIN Tbl1 ON
Tbl2.PK = Tbl1.PK
WHERE
Tbl1.PK IS NULL
Todd Fifield
Viewing 10 posts - 1 through 9 (of 9 total)
You must be logged in to reply to this topic. Login to reply