Friday, 7 June 2013

SqlServer Query Optimization Tips


    Tip 1: Always use WHERE Clause in SELECT Queries while we don’t need all the rows to be returned. This will help to narrow the return rows else it will perform a whole table scan and waste the Sql server resources with increasing the network traffic. While scanning the whole it will lock the Table which may prevent other users to access the table.

Tip 2: It is seen many times developers use codes like 

SELECT * FROM OrderTable WHERE LOWER(UserName)='telsa'

Instead of writing it like the below

SELECT * FROM OrderTable WHERE UserName='telsa'

Infact both the queries does the same work but the 2nd one is better and retrieves rows more speedly than the first query. Because Sql Server is not case sensitive

Tip 3: While running a query, the operators used with the WHERE clause directly affect the performance. The operators shown below are in their decreasing order of their performance.

    =
    >,>=,<, <=
    LIKE
    <>

Tip 4 : When we are writing queries containing NOT IN, then this is going to offer poor performance as the optimizer need to use nested table scan to perform this activity. This can be avoided by using EXISTS or NOT EXISTS.

When there is a choice to use IN or EXIST, we should go with EXIST clause for better performance.

Tip 5: It is always best practice to use the Index seek while the columns are covered by an index, this will force the Query Optimizer to use the index while using IN or OR clauses as a part of our WHERE clause.

SELECT * FROM OrderTable WHERE Status = 1 AND OrderID IN (406,530,956)

Takes more time than

SELECT * FROM OrderTable (INDEX=IX_OrderID) WHERE Status = 1 AND OrderID IN (406,530,956)

Tip 6: While we use IN, in the sql query it better to use one or more leading characters in the clause instead of using the wildcard character at the starting.

SELECT * FROM CustomerTable WHERE CustomerName LIKE 'm%'

SELECT * FROM CustomerTable WHERE CustomerName LIKE '%m'

In the first query the Query optimizer is having the ability to use an index to perform the query and there by reducing the load on sql server. But in the second query, no suitable index can be created while running the query.

Tip 7: While there is case to use IN or BETWEEN clause in the query, it is always advisable to use BETWEEN for better result.

SELECT * FROM CustomerTable WHERE CustomerID BETWEEN (5000 AND 5005)

Performs better than

SELECT * FROM CustomerTable WHERE CustomerID IN (5000,5001,5002,5003,5004,5005)

Tip 8: Always avoid the use of SUBSTRING function in the query.

SELECT * FROM CustomerTable WHERE CustomerName LIKE 'n%'

Is much better than writing

SELECT * FROM CustomerTable WHERE SUBSTRING(CustomerName,1,1)='n'

Tip 9 : The queries having WHERE clause connected by AND operators are evaluated from left to right in the order they are written. So certain things should be taken care of like

    Provide the least likely true expressions first in the AND. By doing this if the AND expression is false at the initial stage the clause will end immediately. So it will save execution time
    If all the parts of the AND expression are equally like being false then better to put the Complex expression first. So if the complex works are false then less works to be done.

Tip 10: Its sometimes better to combine queries using UNION ALL instead of using many OR clauses.

SELECT CustomerID, FirstName, LastName FROM CustomerTable

WHERE City = 'Wichita' or ZIP = '67201' or State= 'Kansas'

The above query to use and index, it is required to have indexes on all the 3 columns.

The same query can be written as

SELECT CustomerID, FirstName, LastName FROM CustomerTable WHERE City = 'Wichita'

UNION ALL

SELECT CustomerID, FirstName, LastName FROM CustomerTable WHERE ZIP = '67201'

UNION ALL

SELECT CustomerID, FirstName, LastName FROM CustomerTable WHERE State= 'Kansas'

Both the queries will provide same results but if there is only an index on City and no indexes on the zip or state, then the first query will not use the index and a table scan is performed. But the 2nd one will use the index as the part of the query.

Tip 11:  While the select statement contains a HAVING clause, its better to make the WHERE clause to do most of the works (removing the undesired rows) for the Query instead of letting the HAVING clause to do the works.

 e.g. in a SELECT statement with GROUP BY and HAVING clause, things happens like first WHERE clause will select appropriate rows then GROUP BY divide them to group of rows and finally the HAVING clause have less works to perform, which will boost the performance.

Tip 12: Let’s take 2 situations

    A query that takes 30 seconds to run, and then displays all of the required results.
    A query that takes 60 seconds to run, but displays the first screen full of records in less than 1 second.

By looking at the above 2 situations a developer may choose to follow the 1st option, as it uses less resources and faster in performance. But actually the 2nd one is more acceptable by a DBA. An application may provide immediate feedback to the user, but actually this may not be happening at the background.



We can use a hint like

SELECT * FROM CustomerTable WHERE City = 'Wichita' OPTION(FAST n)

where n = number of rows that we want to display as fast as possible. This hint helps to return the specified number of rows as fast as possible without bothering about the time taken by the overall query.

Thursday, 25 April 2013

Visual Studio.NET ShortCut Keys

1.    Ctrl + N Opens the New Project Dialogue Box
2.    Ctrl + Shift + O Opens the Open File Dialog Box
3.    Ctrl + Shift + A Opens Add New Item window
4.    Ctrl + D Opens Add Existing Item window
5.    Ctrl + S Saves Current Form
6.    Ctrl + Shift + S Saves everything from Application
7.    Alt + Q Exits Visual Studio. NET
8.    Ctrl + Z Undo
9.    Ctrl + Shift + Z  Redo
10.    Ctrl + X Cuts your selection
11.    Ctrl + C Copies your selection
12.    Ctrl + V Pastes your selection
13.    Ctrl + A Selects All
14.    Del Deletes your selection
15.    Ctrl + F Opens Find window
16.    Ctrl + H Opens Find and Replace window
17.    Ctrl + Shift + H Opens Replace in Files window
18.    Ctrl + Alt + Shift + F12 Opens Find Symbol window
19.    F7 Opens Code Designer window
20.    Shift + F7 Gets you back to Design View
21.    Ctrl + R Opens the Solution Explorer window
22.    Ctrl + Alt + S Opens the Server Explorer window
23.    Ctrl + Shift + C Opens the Class View window
24.    F4 Opens the Properties window
25.    Ctrl + Shift + E Opens the Resource view window
26.    Ctrl + Alt + X Opens the Toolbar window
27.    Shift + Alt + Enter Takes you to Full Screen View
28.    Alt+F8 Opens Macro Explorer window
29.    F2  Opens Object Browser window
30.    Ctrl + Alt + T Opens Document Outline window
31.    Ctrl + Alt + K Opens Task List window
32.    Ctrl + Alt + A Opens Command window
33.    Ctrl + Alt + O Opens Output window
34.    Ctrl + Alt + Y Opens Find Symbol Results window
35.    Ctrl + Alt + F Lists Items under the Favorites Menu in your Internet Explorer
36.    Ctrl + Shift + B Builds your project
37.    F5 Runs your Application
38.    Ctrl + F5 Runs your Application without Debugging
39.    Ctrl + Alt + E Opens the Exceptions Dialog Box
40.    F8 Used while Debugging Applications
41.    Shift + F8 Used While Debugging Applications
42.    Ctrl + B Inserts a New Break point
43.    Ctrl + Shift + F9 Clears All Breakpoints
44.    Ctrl + Alt + P Opens the Processes Dialog box
45.    Ctrl + T Opens Customize Toolbox window
46.    Ctrl + Shift + P Runs Temporary Macro
47.    Ctrl + Shift + R Records Temporary Macro
48.    Alt + F11 Opens Macros IDE
49.    Ctrl + F1 Opens Dynamic Help window
50.    Ctrl +Alt + F1 Opens Help window sorted by Contents
51.    Ctrl + Alt + F2 Opens Help window sorted by Index
52.    Ctrl + Alt + F3 Opens Help Search window
53.    Shift + Alt + F2 Opens Index Results window
54.    Shift + Alt + F3 Opens Search Results window
55.    Ctrl + K +C Comment out the current selected section
56.    Ctrl + K +U Un comment the current selected section

Wednesday, 27 March 2013

Parsename to Extract Precision and Scale values‏ From Decimal Numbers


   
The numeric datatype stores numbers with precision and scale. Suppose you want to extract only a precision or a scale, you can do it via many ways. One of the ways is to make use of the PARSENAME function.

Consider the following example

declare @amount decimal(12,2)
set @amount=87234.50
select parsename(@amount,2) as precision, parsename(@amount,1) as scale

The result is

precision            scale
---------            --------
87234                  50

Parsename is used to extract specified part of a name. In general, it is used to extract names from four part object names separated by a dot. Argument number 1 extracts the last part of a string, and the 2nd argument extracts the next last part.

This way we can effectively make use of parsename function to extract precision and scale values from the decimal numbers.

TOP 5 costly Stored Procedures in a SQL Server Database

Execute this query on corresponding Database

SELECT TOP 5 obj.name, max_logical_reads,
 max_elapsed_time
FROM sys.dm_exec_query_stats a
CROSS APPLY sys.dm_exec_sql_text(sql_handle) hnd
INNER JOIN sys.sysobjects obj on hnd.objectid = obj.id
ORDER BY  max_logical_reads  DESC

Combine Multiple Rows into One Row using SQL Server


   
Imagine you have a column like this:

Numbers
---------
One
Two
Three
Four
Five

The output you desire is to combine all the rows and put it as one row similar to the following:

OneTwoThreeFourFive


Let us see how to do it:

-- Sample Script to create the table and insert rows
-- By SQLServerCurry.com

CREATE TABLE #Temp
(
[Numbers] varchar(40)
)
INSERT INTO #Temp VALUES('One');
INSERT INTO #Temp VALUES('Two');
INSERT INTO #Temp VALUES('Three');
INSERT INTO #Temp VALUES('Four');
INSERT INTO #Temp VALUES('Five');


-- Query to combine multiple rows into one

DECLARE @str VARCHAR(100)
SELECT @str = COALESCE(@str + '', '') + [Numbers]
FROM #Temp
Print @str

Monday, 25 March 2013

TO disable right click on any web page or image

In the body tag write property name oncontextmenu="return false"
this will stop right click on web page..

same thing write on img tag to disable right click ..

Total Pageviews