Sql Server Interview Questions and Answers (1758) - Page 85

Why are cursors generally slower in performance? What is the alternative approach for that to improve performance?

In the case of CURSORS the rows are rows are processed one after another.This consumes more memory and create page/row locks.To elaborate more on the point, the moment a cursor opens it loads a chunk of rows into memory and locks them.This creates a potential block.Then as we loop through the cursor we are making changes to other tables, performing some operations like insert/update/delete and still keeping all of the memory and locks of the cursor open.This cause the performance issues.Where as if we can re-write the same query by using in a SET Based manner, we can submit a complete batch of job(s) to the query engine which on the other hand will be processed much faster way.
Write a program to generate Sequence number using RECURSIVE CTE LOOP

--*********** THE QUERY BEGINS ************************
DECLARE @maxLimit INT = 1000000

;WITH NumCTE AS(
SELECT Rn = 1
UNION ALL
SELECT Rn+1
FROM NumCTE WHERE Rn < @maxLimit)
SELECT *
FROM NumCTE
OPTION(MAXRECURSION 0)

--*********** THE QUERY ENDS ************************

In the above query, we are starting with number 1 and then in the recursive part the CTE moves on going till it reaches the @maxLimit. And at every step, the merging of the values is happening through the UNION ALL.

Finally the result is displayed outside the CTE.
Write a program in SQL Server to measure the time consumed to execute the query.

The below program will do so

DECLARE @t1 DATETIME;

DECLARE @t2 DATETIME;
SET @t1 = GETDATE();

--*********** THE QUERY BEGINS ************************

DECLARE @maxLimit INT = 1000000

;WITH
a AS (SELECT 1 AS i UNION ALL SELECT 1),
b AS (SELECT 1 AS i FROM a AS x, a AS y),
c AS (SELECT 1 AS i FROM b AS x, b AS y),
d AS (SELECT 1 AS i FROM c AS x, c AS y),
e AS (SELECT 1 AS i FROM d AS x, d AS y),
f AS (SELECT 1 AS i FROM e AS x, e AS y),
NumCTE AS (SELECT TOP(@maxLimit) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS Number
FROM f)
SELECT *
FROM NumCTE

--*********** THE QUERY ENDS ************************

SET @t2 = GETDATE();
SELECT
DATEDIFF(millisecond,@t1,@t2) AS ElapsedTimeInMilliSeconds,
(DATEDIFF(millisecond,@t1,@t2) - (((DATEDIFF(millisecond,@t1,@t2))/60000)*60000)) /1000 AS ElapsedTimeInSeconds;

/* Result */
ElapsedTimeInMilliSeconds ElapsedTimeInSeconds
5246 5.246


We declared two variables viz @t1 and @t2 as DATETIME. @t1 is set to current date and time. Then we wrote the SQL Query. Then we set the Date and Time component for @t2. And finally we performed a difference between the two dates and their times for obtaining the Difference in time both the seconds and milliseconds.
How to measure the total time taken for a cursor to execute?

The below example will help to do so

DECLARE @t1 DATETIME


SELECT * INTO #temp
FROM master..spt_values

--*********** THE CURSOR BEGINS ************************
BEGIN TRAN
DECLARE @name VARCHAR
SELECT @t1 = GETDATE()

--Declare a cursor and loads the rows/data into the cursor memory
DECLARE tempCursor CURSOR
FOR SELECT name FROM #temp

-- Open the cursor
OPEN tempCursor

--Loop thru each row for processing
FETCH NEXT
FROM tempCursor
INTO @name

--Do something interesting
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE #temp
SET number = 0
WHERE NAME = @name

--Repeat the process for accessing the next row available in cursor memory
FETCH NEXT FROM tempCursor
INTO @name
END

-- All operations completed.Now close the cursor
CLOSE tempCursor

-- Clean up
DEALLOCATE tempCursor

--*********** THE CURSOR ENDS ************************

--Measure the cursor processing time
SELECT
DATEDIFF(millisecond, @t1, GETDATE()) AS ElapsedTimeFromCursorInMillis;

--Clean up the table
DROP TABLE #temp

What it is not recommended to name the user defined store procedures with sp_?

They are system defined and mostly resides under the master db. So if we write a user defined stored procedure by the name sp_ the query engine will first search the Stored Procedure inside the master db and if not found then it will search in the current session db. This brings unnecessary round trip. Better to use some other naming convention as usp_.E.g. instead of writing sp_GetEmployeesDetail, let's write usp_GetEmployeesDetail
Why should we avoid using * in SELECT statement?

Avoid
SELECT * FROM TableName

Here * indicates all columns. When we write SELECT *, we are asking the query engine to send back all the columns which we may not need in our application. The way of unnecessary columns makes for more data inflow from the database server to the client which on the other hand slows access and increases the load on the client machines thereby causes more more time to travel across the network. Not only that, using SELECT * refrains the query from applying the covering index. Consider, that we have 5 columns in a table and we have applied the covering index for 3 columns.Now we added 2 more columns to the underlying table.This would cause the query optimizer to ignore the optimized covering index and will go for a Full Table scan.

Another reason could be that we have two tables where both of them having ID column as their primary key and we have performed a join operation between the tables like

Select *

From table1
Join table2 ON table1.ID = table2.ID


In such as case, it will be difficult for the data consumer to understand which ID column pertains to whom.
Why EXISTS a better choice in general than IN?

EXISTS informs if a query returned any results as soon as a match is found.E.g.

       SELECT ColumnName(s)

FROM TABLENAME t1
WHERE
-- the statemet turn out true as soon as a match is found
EXISTS ( SELECT COLUMNNAME(S)
FROM TABLENAME t2
WHERE t1.ID = t2.ID
)


In comparison, IN compares one value to several values e.g.

        SELECT ColumnName(s)

FROM TABLENAME t1
WHERE t1.ID IN(SELECT ID FROM FROM TABLENAME t2)


Also EXISTS clause uses INDEX at the time of fetching records and is there by faster than IN which on the other hand does not.
Why it is advisable to maintain as small clustered index?

It is advisable to maintain as small clustered index as much as possible since the fields used in clustered index may also used in nonclustered index.Data in the database is also stored in the order of clustered index.So, maintaining a huge clustered index on a table with a large number of rows increases the size drastically.
How to get last year last month last Date using date function in SQL server?

NOTE: This is objective type question, Please click question title for correct answer.
List out the true statements about the below

NOTE: This is objective type question, Please click question title for correct answer.
List out the true statements

NOTE: This is objective type question, Please click question title for correct answer.
List out the true statements

NOTE: This is objective type question, Please click question title for correct answer.
List out the true statements

NOTE: This is objective type question, Please click question title for correct answer.
Which of the following is true?

NOTE: This is objective type question, Please click question title for correct answer.
List out the true statements

NOTE: This is objective type question, Please click question title for correct answer.
What is the true statements?

NOTE: This is objective type question, Please click question title for correct answer.
Which of the following are true?

NOTE: This is objective type question, Please click question title for correct answer.
Why sequence provides better performance as opposed to Identity Columns?

Sequence gives better performance as compared to Identity Column since it reads from memory rather than from the disk and caches that.
Identify the true statements

NOTE: This is objective type question, Please click question title for correct answer.
What are the datatypes for which Sequence can be defined?

DataTypes for which Sequence can be defined

Int

Smallint
Tinyint
Bigint
Decimal
Numeric

Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Interview Questions and Answers Categories