You are on page 1of 5

GUIDELINES TO WRITE T-SQL EFFECIENTLY

Always use T-SQL Clauses in CAPITAL LETTER for easy readability and understanding
Example SELECT EmpID,EmpName FROM Employees;

Always Put Fully Qualified Object Name (Four Part Name) like [servername].[dbname].[schema].[Table_View_Fun]
Example SELECT EmpID,EmpName FROM [SYNEDBSRV].[HR].[dbo].[Employees];

Start with new line for each T-SQL Clause


For E.g. SELECT EmpID,EmpName FROM [SYNEDBSRV].[HR].[dbo].[Employees] WHERE EmpID IN (1,2,3);

Put NOLOCK hint if you are writing T-SQL form generating report and you are ok with dirty read over the large period
For E.g. SELECT EmpID,EmpName FROM [SYNEDBSRV].[HR].[dbo].[Employees] (NOLOCK) WHERE EmpID IN (1,2,3);

Use SET NOCOUNT ON at the beginning of Stored Procedure (Before writing any T-SQL Statements)
Example CREATE PROC usp_Employee_Get @EmpID INT AS BEGIN SET NOCOUNT ON; SELECT EmpID,EmpName FROM [SYNEDBSRV].[HR].[dbo].[Employees] WHERE EmpID = @EmpID; END;

For Stored Procedures, Use Proper Naming Conventions like usp_ObjectName_OperationName


Example Usp_Employees_Get, Usp_Employees_InsertUpdate, Usp_Employees_Delete

Minimize the number of rows in results set by applying WHERE / HAVING Clause to select only those rows which are required. Try to NOT use Negative Operators like <>, NOT, !=
For Example TranDate <> 01/01/1900 can be replace by TranDate BETWEEN 1900-01-02 00:00:00 AND 2079-06-06 23:59:00 1|Page

Use variables and control-of-flow statements to build logic into batches, stored procedures, and triggers instead of pulling large result sets to the client and performing the logic there. Use the UPDATE statement with the FROM clause to update values in one table using values from other tables in one operation instead of selecting the source result set to the client and then updating the target table one row at a time.
For Example UPDATE dbo.Table2 SET dbo.Table2.ColB = dbo.Table2.ColB + dbo.Table1.ColB FROM dbo.Table2 INNER JOIN dbo.Table1 ON (dbo.Table2.ColA = dbo.Table1.ColA);

Use EXISTS properly instead of IS NOT NULL or IN Clause


Example IF EXISTS (SELECT OBJECT_ID(tablename)) DROP TABLE tablename;

Use SEMI-JOIN instead of using FULL JOIN if you need to check only atleast single existance of related record in Right table from Left Table in JOINS.
Example SELECT DISTINCT C.CustID,C.CName FROM Customers C INNER JOIN Sales S ON S.Cust_Id = C.Cust_Id Can be replaced by using semi join SELECT C.CustID,C.CName FROM Customers C WHERE EXISTS ( SELECT 1 FROM Sales S WHERE S.Cust_Id = C.Cust_Id )

Within a batch, keep all data definition language (DDL) statements for a temporary table together.
Example CREATE TABLE #temp1 (ColA INT NOT NULL) CREATE UNIQUE INDEX MyIndex ON #temp1(ColA) INSERT INTO #temp1 SELECT IntCol FROM SomeTable SELECT * FROM #temp1 GO

Before you are done with your stored procedure code, review it for any unused code, parameters or variables (NOT COMMENTS ) that you may have forgotten to remove while you were making changes and remove them. Unused code just adds unnecessary bloat to your stored procedures, although it will not necessarily negatively affect performance of the stored procedure.
2|Page

For best performance, all objects that are called within the same stored procedure should be owned by the same object owner or schema and should also be referred to in the format of object_owner.object_name or schema_owner.object_name.
Example dbo.#BasicLoanPopln

If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications If your application requires you to create temporary tables for use, consider the possibility of creating indexes for these temporary tables. While most temporary tables probably won't need an index, some larger complex temporary tables can benefit from them. A properly designed index on a temporary table can be as great a benefit as a properly designed index on a standard database table. If you have a WHERE clause that includes expressions connected by two or more AND operators, SQL Server will evaluate them from left to right in the order they are written. This assumes that no parentheses have been used to change the order of execution. Because of this, you may want to consider one of the following when using AND: Locate the least likely true AND expression first. If both parts of an AND expression are equally likely of being false, put the least complex AND expression first. You may want to consider using Query Analyzer or Management Studio to look at the execution plans of your queries to see which is best for your situation.
WHERE DRM_Task.AsOfMonthendDate = @AsofMonthEndDate AND TaskNum=1046 can be replace by WHERE TaskNum=1046 AND DRM_Task.AsOfMonthendDate = @AsofMonthEndDate

Don't use ORDER BY in your SELECT statements unless you really need to, as it adds a lot of extra overhead. If
you have to sort by a particular column often, consider making that column a clustered index. Example Insert into #DRMTaskNum1046 (AsofDate , Loannumber , InstNum , TaskNumber , CompDate ) Select AsOfMonthendDate ,Loannumber,InstNum , TaskNum , MAX(CompletionDate) from RCSMonthEnd.dbo.DRM_Task where DRM_Task.AsOfMonthendDate = @AsofMonthEndDate AND TaskNum=1046 group by LoanNumber , InstNum , TaskNum , AsOfMonthendDate --having MAX(CompletionDate) <> '1/1/1900' order by LoanNumber

To make complex queries easier to analyze, consider breaking them down into their smaller constituent parts. One way to do this is to simply create lists of the key components of the query, such as: List all of the columns that are to be returned
3|Page

List all of the columns that are used in the WHERE clause List all of the columns used in the JOINs (if applicable) List all the tables used in JOINs (if applicable) Once you have the above information organized into this easy-to-comprehend form, it is much easier to identify those columns that could potentially make use of indexes when executed.

Use TRY-Catch for error handling


BEGIN TRY --Your t-sql code goes here END TRY BEGIN CATCH --Your error handling code goes here END CATCH

Join tables in the proper order.Always perform the most restrictive search first to filter out the maximum number of rows in the early phases of a multiple table join. This way, the optimizer will have to work with fewer rows in the subsequent phases of join, improving performance Do not put Conditions with Join On clause in SQL Query.
Example SELECT a.EmpID,a.EmpNAme ,b.PANNo FROM employees a LEF TJOIN EMPX b ON a.EmpID=b.EMPID AND b.EmpID=1 Result EmpID EmpName mgrid EMPID AGE DOB 1 SACHIN KAMBLE+ 0 1 30 NULL 2 SAMIR GIRADKAR 1 NULL NULL NULL 3 ANKIT PAREEK 2 NULL NULL NULL 4 amruta 2 NULL NULL NULL 6 neeta 1 NULL NULL NULL 7 shakir 4 NULL NULL NULL 8 ritesh 7 NULL NULL NULL 9 a 0 NULL NULL NULL 10 b 0 NULL NULL NULL 13 aniket 1 NULL NULL NULL 14 NULL 5 NULL NULL NULL 16 NULL 1 NULL NULL NULL 18 ntiur 1 NULL NULL NULL Can be replaced by SELECT a.EmpID,a.EmpNAme ,b.PANNo FROM employees a LEF TJOIN EMPX b ON a.EmpID=b.EMPID WHERE b.EmpID=1 REsult

EmpID EmpName mgrid EMPID AGE 1 SACHIN KAMBLE+ 0 1


4|Page

DOB 30

NULL

5|Page

You might also like