Convert columns to rows in SQL Server 2008 without unpivot

Today I will show how to write a query in order to convert the columns to rows in SQL Server 2008 without using the unpivot function:

Step 1: Let's analyse the input first which is as shown below:

Convert columns to rows in SQL Server 2008 without unpivot


Step 2: Now lets write a query that would help us inorder to get the columns into rows as shown below:

DECLARE @rowId INT=1,@noOfRows INT=0,@id varchar(20),@age varchar(20),@gender varchar(20)
--First get the no of rows in the table
SET @noOfRows=(SELECT count(*) FROM students)

--create a table variable to store the output data required
DECLARE @tbl TABLE
(
      col1 VARCHAR(20)
)

--Put a while loop to iterate through all the rows in the table one by one:
WHILE(@rowId<=@noOfRows)
BEGIN
      SELECT @id=CAST(id AS VARCHAR),@age=CAST(age AS VARCHAR),@gender=gender FROM students WHERE id=@rowId

      Insert into @tbl (col1) values (@id)
      Insert into @tbl (col1) values (@age)
      Insert into @tbl (col1) values (@gender)

      --increment the @rowId counter by 1 to get the next row in the next iteration
      SET @rowId=@rowId+1;
END

SELECT * FROM @tbl

Step 3: The output will be as shown below:

Convert columns to rows in SQL Server 2008 without unpivot

Insert INTO table from select query in SQL Server 2005

The INSERT INTO statement is used to insert new records in a table. But in SQL Server 2005 we cannot write an insert into statement & insert the whole tables or output values into a table. We have some other approaches out of which I'll showcase 3 of them in my post as mentioned below:

1st Approach:

INSERT INTO [MyDB].[dbo].[MyTable]
      ([FieldID]
      ,[Description])
VALUES
      (1000,N'test')

2nd Approach:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
VALUES
       (1001,N'test2')
One other option is to use UNION ALL:
INSERT INTO [MyDB].[dbo].[MyTable]
      ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

3rd Approach:

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

How to convert binary to decimal in SQL Server?

Today I will show you how we can write a query in order to convert Binary to Decimal in SQL Server and vice-versa:

1. Query to convert Binary to Decimal value:
DECLARE @input varchar(max) = '1010'

;WITH N(V) AS
(
    SELECT
        ROW_NUMBER()over(ORDER BY (SELECT 1))
    FROM
        (VALUES(1),(1),(1),(1))M(a),
        (VALUES(1),(1),(1),(1))L(a),
        (VALUES(1),(1),(1),(1))K(a)
)
SELECT SUM(SUBSTRING(REVERSE(@input),V,1)*POWER(CAST(2 as BIGINT), V-1))
FROM N
WHERE V <= LEN(@input)

2. Query to convert Decimal to Binary value:
DECLARE @input BIGINT = 10

;WITH N(N)AS
(
    SELECT top 63
        POWER(cast(2 as bigint),
        ROW_NUMBER()over(ORDER BY (SELECT 1))-1)
    FROM
         (VALUES(1),(1),(1),(1))M(a),
        (VALUES(1),(1),(1),(1))L(a),
        (VALUES(1),(1),(1),(1))K(a)
)
SELECT
    COALESCE
    (
         REVERSE
         (
             (
                SELECT CAST(@input/N%2 as CHAR(1))
                FROM N
                WHERE N <= @input
                for xml path(''), type
             ).value('.', 'varchar(max)')
            )
         , '0'
)



Formatting stored procedure in SQL Server 2014?

Code Formatting in Stored Procedure on any version of SQL Server:

With the Editor you can format your code with indenting, hidden text, URLs, and so forth. You can also auto-format your code as you type by using Smart Indenting.

Indenting

You can choose three different styles of text indenting. You can also specify how many spaces compose a single indentation or tab, and whether the Editor uses tabs or space characters when indenting.

Formatting stored procedure in SQL Server 2014?

To choose an indenting style:

1.     On the Tools menu, click Options.

2.     Click Text Editor.

3.     Click the folder, and select All Languages to set indenting for all languages.

4.     Click Tabs.

5.     Click one of the following options:

o   None. The cursor goes to the beginning of the next line.

o   Block. The cursor aligns the next line with the previous line.

o   Smart (Default). The language service determines the appropriate indenting style to use.

To change indent tab settings:

1.     On the Tools menu, click Options.

2.     Click Text Editor.

3.     Select the folder for All Languages to set indenting for all languages.

4.     Click Tabs.

5.     To specify tab characters for tab and indent operations, click Keep tabs. To specify space characters, select Insert spaces.

If you select Insert Spaces, enter the number of space characters each tab or indent represents under Tab Size or Indent Size, respectively.

To indent code:

1.     Select the text you want to indent.

2.     Press TAB, or click the Indent button on the Standard toolbar.

To unindent code:

1.     Select the text you want to unindent.

2.     Press SHIFT+TAB, or click the Unindent button on the Standard toolbar.

To automatically indent all of your code

1.     On the Tools menu, click Options.

2.     Click Text Editor.

3.     Click All Languages.

4.     Click Tabs.

5.     Click Smart.

To convert white space to tabs:

1.     Select the text whose white space you want to convert to tabs.

2.     On the Edit menu, point to Advanced, and click Tabify Selection.

To convert tabs to spaces:

1.     Select the text whose tabs you want to convert to spaces.

2.     On the Edit menu, point to Advanced, and click Untabify Selection.

The behavior of these commands depends on the tab settings in the Options dialog box. For example, if the tab setting is 4, Tabify Selection creates a tab for every 4 contiguous spaces, and Untabify Selection creates 4 spaces for every tab.

Converting Text to Upper and Lower Case

You can use commands to convert text to all uppercase or lower case.

To switch text to upper or lower case:

1.     Select the text you want to convert.

2.     To convert text to uppercase, press CTRL+SHIFT+U, or click Make Uppercase on the Advanced submenu of the Edit menu.

3.     To convert text to lowercase, press CTRL+SHIFT+L, or click Make Lowercase on the Advanced submenu of the Edit menu.

Displaying and Linking to URLs

You can create and display clickable URLs in your code. By default, the URLs:

·       Are underlined.

·       Change the mouse pointer to a hand when you move over them.

·       Open the URL when clicked, if the URL is valid.

To display a clickable URL:

1.     On the Tools menu, click Options.

2.     Click Text Editor.

3.     To change the option for only one language, click that language folder and then click General. To change the option for all languages, click All Languages and then click General.

4.     Select Enable single-click URL navigation.


How to convert multiple rows into single row in SQL Server 2008?

Today we will go through the steps in order to write the simplest query to combine multiple rows into single row in SQL Server 2008: 

Step 1: Create a table

CREATE TABLE [dbo].[Students]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[age] [int] NULL DEFAULT (NULL),
[gender] [char](1) NULL
)
GO

Step 2: Insert values into the table created in Step 1

INSERT INTO Students (age,gender) VALUES (24,'M')
INSERT INTO Students (age,gender) VALUES (26,'F')
INSERT INTO Students (age,gender) VALUES (25,'F')

Step 3: Below is the query to get multiple rows data in a single row and in a single column

DECLARE @singleRowData NVARCHAR(MAX)=''
SELECT @singleRowData=@singleRowData+CAST(Id AS VARCHAR)+':'+CAST(age AS VARCHAR)+':'+gender+';' FROM [dbo].[Students]

SELECT @singleRowData AS 'singleRowOutput'

Step 4: The output of the query would be as below:


Conclusion:

Today we saw how we can write a query in order to group multiple rows data into a single row & in a single column.

Replace last occurrence of a string in SQL Server?

Step 1: Create a procedure in order to replace the last occurrence of a string with a specified string as shown below:

CREATE PROC sp_ReplaceStringWithLastOccurence
(
      @Texto varchar(MAX),
      @findString VARCHAR(100),
      @replaceString VARCHAR(100)
)
AS
BEGIN
    DECLARE @Pos INT=0,@startPos INT=0,@endPos INT=0,@totalStringLength INT=LEN(@Texto),@Splitter CHAR(1)=' ',@initialString
VARCHAR(MAX)=@Texto
  DECLARE @Lista TABLE (
      rowData VARCHAR(8000),
      startPos INT,
      endPos INT
  )
  WHILE LEN(@Texto)>0
  BEGIN
      SET @startPos=@startPos+@Pos
      SET @Pos = PATINDEX('%'+@Splitter+'%',@Texto)
      SET @endPos=@Pos-1

      IF @Pos > 0
      BEGIN
        INSERT INTO @Lista(rowData,startPos,endPos)
        SELECT left(@Texto, @Pos-1),@startPos+1,@endPos

        SET @Texto = right(@Texto, LEN(@Texto)-@Pos)
      END
      ELSE
      BEGIN
        DECLARE @end INT=0
        set @end=@totalStringLength+1-@startPos

        INSERT INTO @Lista(rowData,startPos,endPos)
        SELECT @Texto,@startPos+1,@end

        SET @Texto = ''
      END
    END

--Break the input string into by space using the split function
DECLARE @startPos1 INT=0,@endPos1 INT=0
SELECT TOP 1
@startPos1=startPos,
@endPos1=startPos+endPos
FROM
@Lista
WHERE
rowData=@findString
ORDER BY
startPos DESC

--Replace the replace string with last occurence of find string
SELECT SUBSTRING(@initialString,0,@startPos1) +@replaceString+ SUBSTRING(@initialString,@endPos1,@totalStringLength) as 'Result'

END
GO

Step 2: Call the SP created above and pass the string in which we need to search the last occurrence of a string & replace with a specified string as shown below:

exec sp_SplitToGetLastOccurence 'is hello is is world this world is so beautiful is','is','YES'

Step 3: The Output will be as shown below:




How to convert date of birth in words in SQL Server?

Step 1: Below is the query that we can use in order to convert the date into words:

declare @date datetime = '01-10-1985'--Input DateOfBirth

declare @yr smallint = datepart(year, @date);
declare @month smallint= datepart(month, @date);
declare @day smallint = datepart(day, @date);
declare @word varchar(2000)

declare @NumTable table(NumId int, Name varchar(50))

insert into @NumTable
values(1,'First'),
(2,'Second'),(3,'Third'),(4, 'Fourth'),(5,'Five'), (6,'Six'),
(7,'Seventh'),(8,'Eighth'),(9,'Nineth'),(10,'Ten'),(11,'Eleven'),
(12,'Twelve'),(13,'Thirteen'),(14,'Fourteen'),(15,'Fifteen'),(16,'Sixteen'),
(17,'Seventeen'),(18,'Eighteen'),(19,'Nineteen'), (20,'Twenty'),(21,'TwentyFirst'),
(22,'Twenty Second'),(23,'Twenty Third'),(24,'Twenty Fourth'),(25,'Twenty Five'),
(26,'Twenty Six'), (27,'Twenty Seven'),(28,'Twnety Eight'),(29, 'Twenty Nine'),
(30,'Thirty'),(31, 'Thirty First'),(32,'Thrity Two'),(33,'Thrity three'),(34,'Thirty Four'),
(35,'Thrity Five'),(36,'Thiry Six'),(37,'Thirty Seven'),(38,'thrity eight'),(39,'Thirty Nine'),(40,'Forty'),
(41,'Forty one'), (42,'Forty two'),(43,'Forty three'),(44,'Forty four'),(45,'Forty Five'),(46,'Forty Six'),(47,'Forty Seven'),
(48,'Forty eight'),(49,'Forty nine'),(50,'fifty'),(51,'Fifty one'),(51,'Fifty one'),(52,'Fifty two'),(53,'Fifty three'),
(54,'Fifty four'),(55,'Fifty five'),(56,'Fifty six'),(57,'fifty seven'),(58,'fifty eight'),(59,'fifty nine'),
(60,'Sixty'),(61,'sixty one'),(62,'sixty two'),(63,'sixty three'),(64,'sixty four'),(65,'sixty five'),(66,'sixty six'),(67,'sixty seven'),
(68,'sixty eight'),(69,'sixty nine'),(70,'seventy'),(71,'seventy one'),(72, 'seventy two'),(73,'seventy three'),
(74,'seventy four'),(75,'seventy five'),(76,'seventy six'),(77,'seventy seven'),(78,'seventy eight'),(79,'seventy nine'),
(80,'eighty'),(81,'eighty one'),(82,'eighty two'),(83,'eighty three'),(84,'eighty four'),(85,'eight five'),(86,'eight six'),
(87,'eight seven'),(88,'eighty eight'),(89,'eighty nine'),(90,'ninety'),(91,'ninety one'),(91,'ninety one'),
(92,'ninety two'),(93,'ninety three'),(94,'ninety four'),(95,'ninety four'),(95,'ninety five'),(96,'ninety six'),
(97,'ninety seven'),(98,'ninety eight'),(99,'ninety nine')

-- Day
select @word = name
from @NumTable where NumId = @day

set @word = @word + ' '
-- Month
select @word = @word + DATENAME(month,@date)

set @word = @word + ' '

-- Year
select @word = @word + name
from @NumTable where NumId = left(@yr,2)

set @word = @word + ' '

select @word = @word + name
from @NumTable where NumId = Right(@yr,2)

select @word as 'DOB_in_Words'

Step 2: The output is as shown below:

How to convert date of birth in words in SQL Server?

How to display a string vertically in SQL Server?

Below I have mentioned 2 queries using which you can display a string vertically:

Query 1: Using While loop:

DECLARE @string VARCHAR(256) = 'welcome'
DECLARE @cnt INT = 0;

WHILE(@cnt < len(@string))
BEGIN
    SET @cnt = @cnt + 1;
    PRINT SUBSTRING ( @string ,@cnt , 1 )
END;


Query 2: Using CTE(Common Table Expressions):

Declare @string varchar(10) ='welcome'
;with cte as
(
select 1 as i,substring(@string,1,1) as single_char
union all
select i+1 as i,convert(varchar(1),substring(@string,i+1,i+1)) as single_char from cte where
len(convert(varchar(1),substring(@string,i+1,i+1)))=1
)
select single_char From cte


Conclusion:

Above queries gives us a way how we can display a string vertically in Microsoft SQL Server.


How to insert different comma separated values into different columns in SQL Server?

Step 1: Create a table in which we will insert the CSV Data using the below query:

CREATE TABLE Test_Table(col1 NVARCHAR(200), col2 NVARCHAR(200), col3 NVARCHAR(200),col4 NVARCHAR(200),col5 NVARCHAR(200))

Step 2: Create an SP that will break the CSV string into columns and insert the data into the above created table as shown below:

ALTER PROC Test_SP
(
    @csvText NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @status NVARCHAR(20) = ''
DECLARE @error_desc NVARCHAR(MAX)
DECLARE @csv_data TABLE
  (
    id INT NOT NULL IDENTITY(1, 1),
    csv_text NVARCHAR(MAX)
  )

INSERT INTO @csv_data(csv_text)
SELECT SUBSTRING([VALUE],1,LEN([VALUE])-1) FROM STRING_SPLIT(@csvText, CHAR(10)) WHERE LEN(VALUE) > 0


;WITH cte_csv_data AS (
    SELECT DISTINCT id
    , S.a.value('(/H/r)[1]', 'NVARCHAR(200)') AS col1
    , S.a.value('(/H/r)[2]', 'NVARCHAR(200)') AS col2
    , S.a.value('(/H/r)[3]', 'NVARCHAR(200)') AS col3
    , S.a.value('(/H/r)[4]', 'NVARCHAR(200)') AS col4
    , S.a.value('(/H/r)[5]', 'NVARCHAR(200)') AS col5
FROM
  (
    SELECT *,CAST (N'' + REPLACE(csv_text, ',', '') + '' AS XML) AS [vals]
    FROM @csv_data WHERE id > 0) d
    CROSS APPLY d.[vals].nodes('/H/r') S(a)
  )
INSERT INTO Test_Table
(
    col1,
    col2,
    col3,
    col4,
    col5
)
Select
    col1,
    col2,
    col3,
    col4,
    col5
FROM
    cte_csv_data
END
GO

Step 3: Let's execute the above created SP with CSV String as the parameter:

exec Test_SP 'surya, construction, 23, 2, 234443 
sandeep, IT, 20, 1, 455443'

Step 4: The output is as shown below:

How to insert different comma separated values into different columns in SQL Server?


How to split comma delimited string in SQL Server 2008?

Step 1: 

Create a function that will accept the "text string" and "character" where we want to split the string:

ALTER FUNCTION [dbo].[funSplit]
(
@Texto varchar(max),
@Splitter varchar(3)
)
RETURNS
@Lista TABLE
(
rowData varchar(8000)
)
AS
BEGIN
DECLARE @Pos Smallint
While len(@Texto)>0 BEGIN
  SET @Pos = Patindex('%'+@Splitter+'%',@Texto)
  
  IF @Pos > 0 BEGIN
   INSERT INTO @Lista
   SELECT left(@Texto, @Pos-1)
  
   SET @Texto = right(@Texto, len(@Texto)-@Pos)
  END
  ELSE BEGIN
   INSERT INTO @Lista
   SELECT @Texto
  
   SET @Texto = ''
  END
End
RETURN
END GO


Step 2: 

Now call the function pass the "sample string" & "character" to split as shown below:

select * from dbo.funSplit('sql-server-query-world','-')


The output of the query would look like below, that is our desired output:

How to split comma delimited string in SQL Server 2008?


How to update XML data in SQL Server 2008 using stored procedure?

Step 1:

Create a stored procedure that would take the input as XML data  & then break down the data to columns depending upon the XML tags formed:

CREATE PROC spExtractDataFromXML
(
 @inputXML XML=''
)
AS
BEGIN
SET NOCOUNT ON;
  SELECT
    x.i.value('./EmpId[1]','int') AS 'EmpId',
    x.i.value('./EmpName[1]','varchar(100)') AS 'EmpName',
    x.i.value('./Address[1]','varchar(100)') AS 'Address'
  FROM
  @inputXML.nodes('/Info/Data') AS x(i)
END
GO


Step 2:

Now call the stored procedure we created & pass the XML string as input to the SP:

Exec spExtractDataFromXML
<Info>
 <Data>
    <EmpId>100</EmpId>
    <EmpName>ABC</EmpName>
    <Address>My Address</Address>
 </Data>
<Data>
    <EmpId>101</EmpId>
    <EmpName>ABC1</EmpName>
    <Address>My Address1</Address>
 </Data>
<Data>
    <EmpId>102</EmpId>
    <EmpName>ABC2</EmpName>
    <Address>My Address2</Address>
 </Data>
</Info>


The output of the query would look like below, that is our desired output:

saveXMLData


How to find duplicate characters in a string in SQL Server?

Below is the query that you can use in-order to get a character count from a string:

--Declared a table variable that will act as a temp table to hold the values

DECLARE @tbl_char TABLE (input VARCHAR(100),letter VARCHAR(1),remainder VARCHAR(100))

--SET the input & the character you want to search

DECLARE @Input VARCHAR(100)='suryapratapsingh', @characterToFind VARCHAR(1)='a', @remainder VARCHAR(100), @letter VARCHAR(100)=''
SET @remainder=@Input

--WHILE loop to iterate through all the remainder values of the string

WHILE(LEN(@remainder)>0)
BEGIN
  SELECT @Input=@Input, @letter=CONVERT(VARCHAR(1),LEFT(@remainder,1)), @remainder= RIGHT(@remainder, LEN(@remainder)-1)

  INSERT INTO @tbl_char(input,letter,remainder) VALUES (@Input,@letter,@remainder)
END

--Getting the count of the letter required by using a group by clause

SELECT Letter,count(1) AS 'Repeated_no_of_times' FROM @tbl_char
WHERE letter=@characterToFind
GROUP BY letter


Below is the output that we receive when we pass the inputstring=’suryapratapsingh’ and character_to_search=’a’:

findDuplicate characters in string Sql Server



How to shrink distribution database in SQL Server?

Fix the Retention days for Each Publication

Step 1:

Check for the publication properties subscription expiration setup. If it is set to "never expire" as you can see from the screen capture below.

shrinkDistribution db in sql server


Step 2:

Change the retention days to 120 hours and ran the above job, the distributor database space used was reduced from 30 GB to 300 MB.  After that I shrunk the database to 500 MB and then I re-indexed all tables in the distribution database and ran the clean up job again. Now, it takes less 3 sec to run the clean up job.  Also, replication as a whole is a lot faster.

You can in addition also do the below steps:

  • Setup an Alert to notify if any new publication is created where retention day is set to never expire
  • Implement additional replication monitoring
  • To shrink databases or database files look at DBCC SHRINKDATABASE and DBCC SHRINKFILE

How to insert dbnull in SQL Server?


Hello

First point that you need to keep in mind before you insert any null value in a SQL Server Table column is that you need to make the column to accept nulls by default which can be mentioned while creation of the Table by using the create table command as follows:

Example:

CREATE TABLE dbo.Students(Id INT IDENTITY(1,1) PRIMARY KEY, age INT default null, gender CHAR(1))
GO


Or if the table is created then Go-to the Database->TableName->Design->Column->Properties and set the default value as null-able.

Now if you send only those values that are to be inserted & has some value then those columns which has values will be inserted & the columns for which no values have been passed so by default NULL value will be inserted for those columns which are made null-able by default.

Hence, there is no need to pass null value from a front-end application to SQL Server it will automatically handle it at its end only pass the columns that have some value. 

DDL commands in SQL Server with examples

DDL (Data Definition Language): 

DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database.

Examples of DDL commands:


CREATE - is used to create the database or its objects (like table, index, function, views, store procedure and triggers).

Syntax of table creation:

CREATE TABLE [SCHEMA].TABLE_NAME(COLUMN_NAME COLUMN_DATATYPE)

Example of table creation:

CREATE TABLE dbo.Students(Id INT IDENTITY(1,1) PRIMARY KEY, age INT, gender CHAR(1))
GO


Syntax of view creation:

CREATE VIEW [SCHEMA].VIEW_NAME
AS
SELECT_STATEMENT


Example of view creation:

CREATE VIEW dbo.Students_VW
AS
SELECT
  Id,
  age,
  gender
FROM
  Students
GO


DROP - is used to delete objects from the database.

Syntax of dropping a table:

DROP TABLE [SCHEMA].TABLE_NAME

Example of dropping a table:

DROP TABLE dbo.Students


ALTER - is used to alter the structure of the database.

Syntax of altering size of a column in table:

ALTER TABLE [SCHEMA].TABLE_NAME
ALTER COLUMN COLUMN_NAME DATA_TYPE(DATA_LENGTH)

Example of altering a column size of a table:

ALTER TABLE dbo.Students
ALTER COLUMN gender VARCHAR(20)

Syntax of adding a new column in a table:

ALTER TABLE [SCHEMA].TABLE_NAME
ADD COLUMN_NAME DATA_TYPE(DATA_LENGTH)

Example of adding a new column in a table:

ALTER TABLE dbo.Students
ADD salary float


TRUNCATE - is used to remove all records from a table, including all spaces allocated for the records are removed.

Syntax of truncating a table:

TRUNCATE TABLE [SCHEMA].TABLE_NAME

Example of truncating a table:

TRUNCATE TABLE dbo.Students


Conclusion: 

So today we saw the SQL DDL Commands that we use very frequently while writing queries in SQL Server.




10 Ways to Improve SQL Query Performance

Overview

SQL query performance improvement is a very thought-provoking topic between developers and the user community. Users always wants a fast response on their data retrieval action and developers put forth their best efforts to provide the data in the shortest time, however, there is no straightforward way to define what is the best performance. Sometime it’s debatable what is good and what is bad performance of a query but overall if you follow best practices during development, you can provide the best query response to users and avoid such discussions.

You can choose multiple ways to improve SQL query performance, which falls under various categories like re-writing the SQL query, creation and use of Indexes, proper management of statistics, etc.

In this post we will see 10 different methods to improve SQL query performance.

10 Ways to Improve SQL Query Performance

1. Avoid Multiple Joins in a Single Query

Try to avoid writing a SQL query using multiple joins that includes outer joins, cross apply, outer apply and other complex sub queries. It reduces the choices for Optimizer to decide the join order and join type. Sometime, Optimizer is forced to use nested loop joins, irrespective of the performance consequences for queries with excessively complex cross apply or sub queries.


10 Ways to Improve SQL Query Performance

2. Eliminate Cursors from the Query

Try to remove cursors from the query and use set-based query; set-based query is more efficient than cursor-based. If there is a need to use cursor than avoid dynamic cursors as it tends to limit the choice of plans available to the query optimizer. For example, dynamic cursor limits the optimizer to using nested loop joins.

10 Ways to Improve SQL Query Performance

3. Avoid Use of Non-correlated Scalar Sub Query

You can re-write your query to remove non-correlated scalar sub query as a separate query instead of part of the main query and store the output in a variable, which can be referred to in the main query or later part of the batch. This will give better options to Optimizer, which may help to return accurate cardinality estimates along with a better plan.

10 Ways to Improve SQL Query Performance

4. Avoid Multi-statement Table Valued Functions (TVFs)

Multi-statement TVFs are more costly than inline TFVs. SQL Server expands inline TFVs into the main query like it expands views but evaluates multi-statement TVFs in a separate context from the main query and materializes the results of multi-statement into temporary work tables. The separate context and work table make multi-statement TVFs costly.

10 Ways to Improve SQL Query Performance

5. Creation and Use of Indexes

We are aware of the fact that Index can magically reduce the data retrieval time but have a reverse effect on DML operations, which may degrade query performance. With this fact, Indexing is a challenging task, but could help to improve SQL query performance and give you best query response time.

10 Ways to Improve SQL Query Performance

6. Understand the Data

Understand the data, its type and how queries are being performed to retrieve the data before making any decision to create an index. If you understand the behavior of data thoroughly, it will help you to decide which column should have either a clustered index or non-clustered index. If a clustered index is not on a unique column then SQL Server will maintain uniqueness by adding a unique identifier to every duplicate key, which leads to overhead. To avoid this type of overhead choose the column correctly or make the appropriate changes.


10 Ways to Improve SQL Query Performance

7. Create a Highly Selective Index

Selectivity define the percentage of qualifying rows in the table (qualifying number of rows/total number of rows). If the ratio of the qualifying number of rows to the total number of rows is low, the index is highly selective and is most useful. A non-clustered index is most useful if the ratio is around 5% or less, which means if the index can eliminate 95% of the rows from consideration. If index is returning more than 5% of the rows in a table, it probably will not be used; either a different index will be chosen or created or the table will be scanned.


10 Ways to Improve SQL Query Performance

8. Position a Column in an Index

Order or position of a column in an index also plays a vital role to improve SQL query performance. An index can help to improve the SQL query performance if the criteria of the query matches the columns that are left most in the index key. As a best practice, most selective columns should be placed leftmost in the key of a non-clustered index.

10 Ways to Improve SQL Query Performance

9. Drop Unused Indexes

Dropping unused indexes can help to speed up data modifications without affecting data retrieval. Also, you need to define a strategy for batch processes that run infrequently and use certain indexes. In such cases, creating indexes in advance of batch processes and then dropping them when the batch processes are done helps to reduce the overhead on the database.

10 Ways to Improve SQL Query Performance

10. Statistic Creation and Updates

You need to take care of statistic creation and regular updates for computed columns and multi-columns referred in the query; the query optimizer uses information about the distribution of values in one or more columns of a table statistics to estimate the cardinality, or number of rows, in the query result. These cardinality estimates enable the query optimizer to create a high-quality query plan.

Conclusion:

We discussed how SQL query performance can be improved by re-writing a SQL query, creation and use of Indexes, proper management of statistics and we revisited schema definitions. There are many more areas that can be looked at to improve the SQL query performance like using query hints, table hints and plan hints, etc.

Overall we explored 10 different ways to improve SQL query performance, which isn't much for this subject. You can come across many other ways with your experience and deeper knowledge of your SQL query execution plan to get better performance. You can also refer previous articles to understand SQL query execution plan and its operator.