Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


SQL SERVER Interview Questions & Answers – SET 2 (40 Questions & Answers)

Download – SQL SERVER Interview Questions with Answers – Set 2 [40 Questions&Answers]

NEXT

Question1. We have a query which is running fine in development but facing performance issues at production. You got the execution plan from production DBA. Now you need to compare with the development execution plan. What is your approach? / Poor query performance in Prod.

Answer – This is an open ended question; There could be possible reasons for this issue. Some of them are given below-

1. Fragmentation could be one of the issue.
2. Check statistics are updated or not.
3. Check What other processes are running on production server.
4. Check if query is returning multiple query plans; if yes then there could be two reasons – Parameter sniffing or invalid plans due to set options
5. Check which indexes are getting used.
6. Examine the execution plan to find out the Red Flags. You have to understand what is going on bad and then figure out the alternatives.

Question 2. What is lock Escalation

Answer – Lock escalation is the process of converting many fine-grain locks into fewer coarse-grain locks, reducing system overhead while increasing the probability of concurrency contention. Every lock takes some memory space – 128 bytes on 64 bit OS and 64 bytes on 32 bit OS. And memory is not the free resource.

So if we have a table with billions of rows and we doing lot of operations on that table, SQL Server starts to use the process that called “Lock Escalation” i.e. instead of keeping locks on every row SQL Server tries to escalate them to the higher (object) level. As soon as you have more than 5.000 locks on one level in your locking hierarchy, SQL Server escalates these many fine-granularity locks into a simple coarse-granularity lock.

By default SQL Server always escalates to the table level. You can control lock escalation using below code.

Note lock goes from top to bottom ( DB -> Table -> Page -> Row )


--Handle Lock Escalation

ALTER TABLE Area
SET
(
LOCK_ESCALATION = AUTO -- or TABLE or DISABLE
)
GO

--

Notes – You can disable Lock Escalation for time being, but you got to be very careful with this. Yo can use loop to perform DELETE/UPDATE statements, so that you can prevent Lock Escalations. With this approach huge transactions will be divided into multiple smaller ones, which will also help you with Auto Growth issues that you maybe have with your transaction log.

Question 3. What is a Race Condition

Answer – A race condition is when two or more programs (or independent parts of a single program) all try to acquire some resource at the same time, resulting in an incorrect answer or conflict.

Question 4. Difference between ISNULL and COAELSCE

Answer –

ISNULL COALESCE
IsNull can accept 2 parameters only. It can accept multiple parameters. Minimum parameters should be 2 in this case.
Data type here returned by the function is the data type of the first parameter. Data type returned is the expression with the highest data type precedence.  If all expressions are non-nullable, the result is typed as non-nullable.
It is a built in function Internally Coalesce will be converted to case.
If both the values are NULL it will return NULL ( of Data Type INT ) Here one of the values should be NON NULL. It will throw an error. At least one of the arguments to COALESCE must be an expression that is not the NULL constant. We can do some thing like below-DECLARE @d AS INT = NULL SELECT COALESCE(NULL, @d)
In the below case NULL will be returned.DECLARE @d AS INT = NULL SELECT ISNULL(NULL, @d) In the below case NULL will be returned.DECLARE @d AS INT = NULL SELECT COALESCE(NULL, @d)

Question 5. What is the difference between CROSS APPLY & OUTER APPLY IN T-SQL ?

Answer – The APPLY operator comes in two flavours, CROSS APPLY and OUTER APPLY. It is useful for joining two SQL tables or XML expressions. CROSS APPLY is equivalent to an INNER JOIN expression and OUTER APPLY is equivalent to a LEFT OUTER JOIN expression.


CREATE TABLE EmpApply
(
	 EmpId INT
	,EmpName VARCHAR(100)
	,DeptID INT
)
GO

INSERT INTO EmpApply VALUES
(1,'Rohit',1),
(2,'Rahul',2),
(3,'Isha',1),
(4,'Disha',NULL)

CREATE TABLE DeptApply
(
	 DeptID INT
	,Name VARCHAR(100)
)
GO

INSERT INTO DeptApply VALUES
(1,'IT'),
(2,'Finance')

SELECT * FROM EmpApply
CROSS APPLY ( SELECT * FROM DeptApply WHERE DeptApply.DeptID = EmpApply.DeptID )ax

--

Output of the above query is

EmpId EmpName DeptID DeptID Name
1 Rohit 1 1 IT
2 Rahul 2 2 Finance
3 Isha 1 1 IT
--

SELECT * FROM EmpApply
OUTER APPLY ( SELECT * FROM DeptApply WHERE DeptApply.DeptID = EmpApply.DeptID ) ax

--

Output of the above query is

EmpId EmpName DeptID DeptID Name
1 Rohit 1 1 IT
2 Rahul 2 2 Finance
3 Isha 1 1 IT
4 Disha NULL NULL NULL

Question 6. What is stuff function? Difference between stuff and replace?

Answer- REPLACE – Replaces all occurrences of a specified string value with another string value.


 -----------------Syntax -------------------
REPLACE ( string_expression , string_pattern , string_replacement )

-----------------Example------------------- 

DECLARE @Text1 AS VARCHAR(100) = 'Pawan - A SQL Dev'
SELECT REPLACE(@Text1,'SQL','MSBI')

Output of the above query is

(No column name)
Pawan – A MSBI Dev

STUFF function is used to overwrite existing characters.


 -----------------Syntax -------------------
STUFF ( character_expression , start , length , replaceWith_expression )

-----------------Example------------------- 

DECLARE @Text AS VARCHAR(100) = 'Pawan - A SQL Dev'
SELECT STUFF(@Text,2,5,'NEW')

Output of the above query is

(No column name)
PNEW- A SQL Dev

Question 7. How to change the port number for SQL Server? Default port no of SQL SERVER

Answer- Default PORT Number of SQL Server is 1433. You can view the port number under configuration Manager.

PortNumber

URL – https://msdn.microsoft.com/en-us/library/ms177440.aspx

To assign a TCP/IP port number to the SQL Server Database Engine

In SQL Server Configuration Manager, in the console pane, expand SQL Server Network Configuration, expand Protocols for , and then double-click TCP/IP.

  1. In the TCP/IP Properties dialog box, on the IP Addresses tab, several IP addresses appear in the format IP1, IP2, up to IPAll. One of these is for the IP address of the loopback adapter, 127.0.0.1. Additional IP addresses appear for each IP Address on the computer. Right-click each address, and then click Properties to identify the IP address that you want to configure.
  2. If the TCP Dynamic Ports dialog box contains 0, indicating the Database Engine is listening on dynamic ports, delete the 0.
  3. In the IPn Properties area box, in the TCP Port box, type the port number you want this IP address to listen on, and then click OK.
  4. In the console pane, click SQL Server Services.
  5. In the details pane, right-click SQL Server () and then click Restart, to stop and restart SQL Server.

After you have configured SQL Server to listen on a specific port, there are three ways to connect to a specific port with a client application:

  • Run the SQL Server Browser service on the server to connect to the Database Engine instance by name.
  • Create an alias on the client, specifying the port number.
  • Program the client to connect using a custom connection string.

Question 8. What is memory grant in sql server ?

Answer- Query memory grant OR Query Work Buffer is a part of server memory used to store temporary row data while sorting and joining rows. It is called “grant” because the server requires those queries to “reserve” before actually using memory. This reservation improves query reliability under server load, because a query with reserved memory is less likely to hit out-of-memory while running, and the server prevents one query from dominating entire server memory. For details please visit below

http://blogs.msdn.com/b/sqlqueryprocessing/archive/2010/02/16/understanding-sql-server-memory-grant.aspx

Question 9. When index scan happens? 

Asnwer – An index scan is when SQL Server has to scan all the index pages to find the appropriate records. Please check out the example below

--

CREATE TABLE testScan
(
	 ID INT IDENTITY(1,1) PRIMARY KEY
	,Name VARCHAR(10)
)
GO

INSERT INTO testScan(Name)
VALUES
('Isha'),
('Seema'),
('Ziva'),
('Sharlee')

SELECT * FROM testScan

--

Check out the execution plan of the above query

IndexScan

Question 10. How to prevent bad parameter sniffing? What exactly it means?

Answer –

Parameter sniffing is an expected behavior. SQL Server compiles the stored procedures using the parameters send to the first time the procedure is compiled and save it in plan cache for further reuse.

After that every time the procedure executed again, Now the SQL Server retrieves the execution plan from the cache and uses it.

The potential problem arises when the first time the stored procedure is executed, the set of parameters generate an acceptable plan for that set of parameters but very bad for other more common sets of parameters.

Workarounds to overcome this problem are given below

  • OPTION (RECOMPILE)
  • OPTION (OPTIMIZE FOR (@VARIABLE=VALUE))
  • OPTION (OPTIMIZE FOR (@VARIABLE UNKNOWN))
  • Use local variables

I have explained how we can overcome this using local variables


--

--**********OLD PROC******************

CREATE PROC Area
(
	@ToPoint VARCHAR(20)
)
AS
	SELECT ID , FromPoint , ToPoint , Distance FROM Area
	WHERE ToPoint = @ToPoint



--**********NEW PROC with Local Variables******************


CREATE PROC Area
(
	@ToPoint VARCHAR(20)
)
AS
	DECLARE @tP AS VARCHAR(20) = @ToPoint

	SELECT ID , FromPoint , ToPoint , Distance FROM Area
	WHERE ToPoint = @tP


--

 ParameterSniffing

NEXT

Advertisements