views:

66

answers:

3
+1  Q: 

Query optimization

Hi Team,

I am trying to learn SQL query optimization using SQL Server 2005. However, I did not find any practical example where I can improve performance by tweaking query alone. Can you please list some example queries - prior and after optimization?

It has to be query tuning – not adding index, not making covering index, not making any alteration to table. No change is supposed to be done on table and index. [ I understand that indexes are important. This is only for learning purpose]

It would be great if you can exaplain using temp table instead of refering any sample databases like adventureworks.

Expecting your support...

Thanks

Lijo

A: 

As a first step to your learning, use explain on your queries.

kiwicptn
Wrong RDBMS -- He's using SQL Server 2005, not MySQL.
roufamatic
Would the equivalent be **`SET SHOWPLAN_ALL ON`** ?
kiwicptn
A: 

1) Using as much JOIN where ever possible in SELECT, UPDATE and DELETE. Sometime people loop through records (or use cursors) to update, delet records from a table but you can almost always JOIN tables to achieve the same thing and that would tremendously improve performance. An example here.

2) You need not use temp tables unless you get some records into it and performing some intermediate operations on it and returning results. For that, you should use Table variables anyway.

3) If you dont want to use temp tables for the above reasons becuase you dont need intermediate updates etc but you still want to use the resultsets for further joins, try using CTE (Common table expressions). I know It may not be related to performance but very useful over derived tables.

4) As somebody suggested above, try using IF EXISTS instead of COUNT would be also good.

5) Try using column names instead of * in your SELECT queries whereever possible.

ydobonmai
A: 

I suggest you reading a good book, such as SQL Tuning

Denis Krjuchkov