• Home
  • SQL Server
    • Articles
    • T-SQL Puzzles
    • Output Puzzles
    • Interview Questions
    • Performance Tuning
    • SQL SERVER On Linux
    • Resources
  • SSRS
    • SSRS Articles
    • Interview Questions
  • SSAS
    • SSAS Articles
    • DAX
  • SQL Puzzles
  • Interview Questions
    • SQL Interview Questions
    • Data Interview Questions
  • Python Interview Puzzles
  • New Features(SQL SERVER)
    • SQL SERVER 2017
    • SQL SERVER 2016
    • SQL SERVER On Linux
  • Social
    • Expert Exchange
      • Top Expert in SQL
      • Yearly Award
      • Certifications
      • Achievement List
      • Top Expert of the Week
    • HackerRank (SQL)
    • StackOverflow
    • About Me
      • Contact Me
      • Blog Rules

Improving my SQL BI Skills

Improving my SQL BI Skills

Monthly Archives: May 2015

SQL SERVER Interview Questions & Answers – SET 2 (40 Questions & Answers) [Page 3]

28 Thursday May 2015

Posted by Pawan Kumar Khowal in Download SQL Interview Q's, SQL Server Interview Questions

≈ 2 Comments

Tags

ACID, ACID Properties, Advanced SQL tutorial pdf, Can you tell us different types of Isolation levels? Default Isolation level., Does foreign Key slows down the insertion process in SQL Server ?, Download SQL Questions, Download SQL Server Interview Question in PDF, Download SQL SERVER Interview questions, Download SQL Server Interview questions and answers, download sql server interview questions and answers pdf, download sql server interview questions by Pawan Khowal, download sql server interview questions by Pawan Kumar, download sql server interview questions by Pawan Kumar Khowal, Download T-SQL Interview Questions, Free Download SQL SERVER Interview questions, How can you move the master database?, How to calculate the likely size of an OLAP cube from the Relational database size ?, SQL, SQL Common Interview Questions, SQL Common Interview Questions and answers, SQL FAQ, SQL FAQs, SQL Interview Q & A, SQL Interview Questions, SQL Queries asked in interviews, SQL Questions, SQL Server - General Interview Questions and Answers, SQL Server developer Interview questions and answers, SQL Server developer Interview questions with answers, SQL SERVER Interview questions, SQL SERVER Interview questions & Answers, SQL Server Interview questions and answers, SQL Server Interview Questions and Answers - Free PDF, sql server interview questions and answers for net developers, SQL SERVER Tips, SQL Tips & Tricks, SQL Tips and Tricks, SQL Tricks, T-SQL Server Interview Questions, What are the properties of a transaction?, Where does SQL Server Agent save jobs?, Why do some system functions require parenthesis and some do not require ?, Why does Right Joins exists ?


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

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

PREV

NEXT

Question21. Can you tell us different types of Isolation levels? Default Isolation level.

Answer –

There are five type of Isolation level in MS SQL Server
1. Read Committed (The Default Isolation Level of MS SQL Server)
2. Read Uncommitted
3. Repeatable Read
4. Serializable
5. Snapshot

Question22. How can you move the master database?

Answer – To move master database, you also have to move the Resource database. Microsoft states that the Resource database must reside in the same location as the Master database.

Follow the steps given @

https://msdn.microsoft.com/en-us/library/ms345408.aspx

Question23. When the lazywriter happens and what it’ll do?

Answer – The lazy writer is a process that periodically checks the available free space in the buffer cache between two checkpoints and ensures that there is always enough free memory. When the lazy writer determines free pages are needed in the buffer for better performance, it removes the old pages before the regular checkpoint occurs.

Ideally, Lazy Writes should be close to zero. That means that the buffer cache doesn’t have to free up dirty pages immediately, it can wait for the automatic check point.

For detailed explaination please click on the below URL-
http://www.sqlshack.com/sql-server-memory-performance-metrics-part-5-understanding-lazy-writes-free-list-stallssec-memory-grants-pending/

Question24. What are the properties of a transaction?

Answer – Atomicity Consistency Isolation Durability (ACID) is a concept referring to a database system’s four transaction properties: atomicity, consistency, isolation and durability.

Atomicity

Here either all the statements (whether an update, delete or insert) of the transaction will happen or not happen. To guarantee atomicity, SQL Server uses a Write Ahead Transaction Log. The log always gets written to first before the associated data changes. That way, if and when things go wrong, SQL Server will know how to rollback to a state where every transaction happened or didn’t happen.

Consistency

A transaction reaching its normal end, thereby committing its results, preserves the consistency of the database. If something bad happens then everything in the transaction will be rolled back. After each transaction DB should be in a consistent state.

Isolation

Events happening within a transaction must be hidden from other transactions running concurrently.

Durability

Once a transaction has been completed and has committed its results to the database, the system must guarantee that these results survive any subsequent malfunctions.

Question25. Why do some system functions require parenthesis and some do not require ?

Answer –

In SQL Server most of the system functions require parenthesis at the end. The examples can be GETDATE(), NEWID(), RAND(), ERROR_MESSAGE(), etc

Some functions do not need the parenthesis. The examples can be CURRENT_TIMESTAMP, CURRENT_USER, etc.

ANSI SQL standard functions do not need parenthesis.

SQL Server functions requires parenthesis

 

Question26. Why does Right Joins exists ?

Answer –

Personally I have never used right join.

As per Jeremiah Peschka – Convenience and optimization. Just because we can write our query as a LEFT OUTER JOIN, doesn’t mean that you should.

SQL Server provides a RIGHT OUTER JOIN showplan operator (http://msdn.microsoft.com/en-us/library/ms190390.aspx).

There are times when it’s going to be most efficient to use a right outer join. Leaving that option in the language 1) gives you the same functionality in the language that you have in the optimizer and 2) supports the ANSI SQL specification. There’s always a chance, in a sufficiently complex plan on a sufficiently overloaded SQL Server, that SQL Server may time out query compilation.

In theory, if you specify RIGHT OUTER JOIN instead of a LEFT OUTER JOIN, your SQL could provide SQL Server with the hints it needs to create a better plan. If you ever see this situation, though, you should probably blog about it 🙂

No programming task requires a join, but you can also write all of your queries using syntax like SELECT * FROM a, b, c, d WHERE (a.id = b.a_id OR b.a_id IS NULL) and still have perfectly valid, well-formed, and ANSI compliant SQL.

 

Question27. Does foreign Key slows down the insertion process in SQL Server ?

Answer – Hardly or negligible.

Please read excellent post below for details.

http://www.brentozar.com/archive/2015/05/do-foreign-keys-matter-for-insert-speed/

 

Question28. Where does SQL Server Agent save jobs?

In MSDB, jobs are stored in dbo.sysjobs.

dbo.sysjobsteps – Stores details of the individual steps

dbo.sysjobschedules – Stored schedules of the job

dbo.sysjobhistory – Job history is maintained here.

MSDB also contains other instance level objects such as alerts, operators and SSIS packages.

 

Question29. How to calculate the likely size of an OLAP cube from the Relational database size ?

Answer –

You can use a general rule of Analysis Services data being about 1/4 – 1/3 size of the same data stored in relational database.

Reference – https://social.msdn.microsoft.com/Forums/sqlserver/en-US/6b16d2b2-2913-4714-a21d-07ff91688d11/cube-size-estimation-formula

Question30. SQL Query | Consider the below table below and write some queries to replace 0 by 1 and 1 by 0.


--

CREATE TABLE ZeroOne
(
	Id INT
)
GO

INSERT INTO ZeroOne VALUES (0),(1),(0),(1),(0),(0)

--

Answer – Check out some queries below-


************************  5 Methods are given below to achieve the required output ***********

SELECT * , CASE ID WHEN 0 THEN 1 ELSE 0 END Ids FROM ZeroOne

SELECT * , (Id - 1) * -1 Ids FROM ZeroOne

SELECT * , 1 - Id Ids FROM ZeroOne

SELECT * , IIF(ID=0,1,0) Ids FROM ZeroOne

SELECT Id, (Id+1/2 -1) * -1 Ids FROM ZeroOne

DECLARE @t AS INT = 1
SELECT Id, CHOOSE(@t,1,0) Ids FROM ZeroOne

--

PREV

NEXT

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email

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

26 Tuesday May 2015

Posted by Pawan Kumar Khowal in Download SQL Interview Q's, SQL Server Interview Questions

≈ 2 Comments

Tags

Advanced SQL tutorial pdf, Can you give some examples for One to One, Download SQL Questions, Download SQL Server Interview Question in PDF, Download SQL SERVER Interview questions, Download SQL Server Interview questions and answers, download sql server interview questions and answers pdf, download sql server interview questions by Pawan Khowal, download sql server interview questions by Pawan Kumar, download sql server interview questions by Pawan Kumar Khowal, Download T-SQL Interview Questions, Free Download SQL SERVER Interview questions, How to filter nested stored procedure code from profiler?, How to find all dependent objects of a table?, How VLF’s created for tempDB, One to Many and Many to Many relationships?, pessimistic locking and optimistic locking, SQL, SQL Common Interview Questions, SQL Common Interview Questions and answers, SQL FAQ, SQL FAQs, SQL Interview Q & A, SQL Interview Questions, SQL Queries asked in interviews, SQL Questions, SQL Server - General Interview Questions and Answers, SQL Server developer Interview questions and answers, SQL Server developer Interview questions with answers, SQL SERVER Interview questions, SQL SERVER Interview questions & Answers, SQL Server Interview questions and answers, SQL Server Interview Questions and Answers - Free PDF, sql server interview questions and answers for net developers, SQL SERVER Tips, SQL Tips & Tricks, SQL Tips and Tricks, SQL Tricks, T-SQL Server Interview Questions, What are the limitations on “SET ROWCOUNT”?, What is a deadlock and what is a live lock? How will you go, What is the SQL Query Order of Operations, While creating a “Include” columns on which basis we should consider main column and include columns


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

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

PREV

NEXT

Question11. While creating a “Include” columns on which basis we should consider main column and include columns?

Answer – A nonclustered index can be extended by including nonkey columns in addition to the index key columns. The nonkey columns are stored at the leaf level of the index b-tree

The Syntax of a Non Clustered Index with Included column is given below

--

CREATE INDEX <Index_Name> ON <table> (KeyColumns) INCLUDE (NonKeyColumns)

--
  • KeyColumns – These columns are used for row restriction and processing E.g they were used in WHERE, JOIN, ORDER BY, GROUP BY etc.
  • NonKeyColumns – These columns are used in SELECT and Aggregation. For e.g. AVG(col) after selection/restriction.

So always choose KeyColumns and NonKeyColumns based on the query requirements only.

 

Question12. What is the difference between pessimistic locking and optimistic locking?

Answer –

Source – http://dba.stackexchange.com/questions/35812/why-is-optimistic-locking-faster-than-pessimistic-locking

Lets start with the analogy with banks..

Pessimistic locking is like having a guard at the bank door who checks your account number when you try to enter; if someone else accessing your account, then you cannot enter until that other person finishes his/her transaction and leaves.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.

Optimistic locking, on the other hand, allows you to walk into the bank at any time and try to do your business, but at the risk that as you are walking out the door the bank guard will tell you that your transaction conflicted with someone else’s and you will have to go back and do the transaction again.

Optimistic Locking is a strategy where you read a record, take note of a version number and check that the version hasn’t changed before you write the record back. When you write the record back you filter the update on the version to make sure it’s atomic. (i.e. hasn’t been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours), Optimistic locking possibly causes a transaction to fail, but it does so without any “lock” ever having been taken. And if a transaction fails because of optimistic locking, the user is required to start all over again. The word “optimistic” derives from exactly the expectation that the condition that causes transactions to fail for this very reason, will occur only very exceptionally. “Optimistic” locking is the approach that says “I will not be taking actual locks because I hope they won’t be needed anyway. If it turns out I was wrong about that, I will accept the inevitable failure.”.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Question13. How VLF’s created for tempDB?

Answer – VLFs are Virtual Log Files.

A transaction log stores every transaction made to a SQL Server database, except some which are minimally logged like BULK IMPORT or SELECT INTO.

Internally transaction log is split into the smaller parts called Virtual Log Files (VLFs). When one VLF becomes full, logging continue to write into the next available in the transaction log. The transaction log file can be represented as a circular file. When the logging reaches the end of the file it starts again from the beginning, but only if all the requirements has been met and the inactive parts has been truncated.

The truncation process is necessary to mark all inactive parts so they can be used again and overwritten.

Vlfs

Every time space is allocated for the transaction log file (It may be an Initial creation or log growth) new VLFs are created behind the scenes. The number of new VLFs is determined by the amount of space allocated.

  • If space added is between 0 to 64MB then 4 new VLFs
  • If space Added is between 64MB to 1GB then 8 new VLFs
  • If space Added is greater than 1GB then 16 new VLFs

Use below query to find out the growth and transaction log details


--

SELECT
    name FileName,
    CAST(size*8/1024 AS VARCHAR(10))+'MB' Size,
    CASE is_percent_growth
      WHEN 1 THEN CAST(growth AS VARCHAR(10))+'%'
      ELSE CAST(growth*8/1024 AS VARCHAR(10))+'MB'
     END AutoGrowth
FROM sys.database_files WHERE type_desc = 'LOG'

DBCC LOGINFO;
GO

--

 

Question14. Can you give some examples for One to One, One to Many and Many to Many relationships?

Answer – There are following types of database relationships.

  • One to One Relationships
  • One to Many and Many to One Relationships
  • Many to Many Relationships

One to One Relationships

Lets say we have two table Customers and Address. We have a relationship between the Customers table and the Addresses table. If each address can belong to only one customer, this relationship is “One to One”. Check out the example below.

OnetoOne

One to Many and Many to One Relationships

Lets say we have two table Customers and Orders. We have a relationship between the Customers table and the Addresses table. Customers can make multiple orders but we cannot have multiple customer in one order. This kind of relationship called “One to many relationship”. Check out the example below.

OnetoMany

Many and Many Relationships

Lets say we have two table Students and Teachers. We have a relationship between the Students table and the Teachers table. One teacher can teach multiple students and one student can be taught be multiple teacher. This kind of relationship called “One to many relationship”.

Note – Please note that for this kind of relationship we require 3rd table to handle relationship.

Check out the example below.

ManytoMany

 

Question15. How to find all dependent objects of a table?

Answer –

Multiple methods are there


--Note "testP" is the name of the proc

*********************** Method 1 *************************************

sp_depends 'testP'

*********************** Method 2 *************************************

SELECT * FROM information_schema.routines
WHERE CHARINDEX('testP', ROUTINE_DEFINITION) > 0
GO

*********************** Method 3 *************************************

SELECT referencing_schema_name, referencing_entity_name,
referencing_id, referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('testP', 'OBJECT');
GO

--

sp_depends will be deprecated, and instead, sys.dm_sql_referencing_entities and sys.dm_sql_referenced_entities are recommended.

For details please refer below URL

http://www.mssqltips.com/sqlservertip/2999/different-ways-to-find-sql-server-object-dependencies/

 

Question16. How to filter nested stored procedure code from profiler?

Answer –

Nested stored procedures are the stored procedures that call another stored procedure(s).

We can use SQL Server Profiler to peek into stored procedure execution details. Lets first create nested stored proc.

--

************** Child Proc *******************

CREATE PROC ChildProc
AS
	SELECT 'ChildProc'

********** Parent Proc ************************

CREATE PROC MainSP
AS
	EXEC ChildProc

--

After creating the above stored procedures, execute the parent stored proc using below command.


--

EXEC MainSP

--

For that please follow the steps given below.

Step 1. Open SQL Server profile by clicking on Start , type SQL SERVER Profiler and click on SQL Server profiler.

Click on “Show all events”, then select stored procedures as shown below.

SP1

Select SP:StmtCompleted event class as shown below

SP2

Now execute the Main sp and check the trace below

SPCompleted

We can see all the trace i.e. from Parent SP and child SP.

 

Question17.  What are the limitations on “SET ROWCOUNT”?

Answer –

Both TOP and SET ROWCOUNT are both acceptable methods of limiting the result sets from a query; However both are very different commands. The TOP clause of a command limits that single command, while the SET ROWCOUNT command limits all eligible queries within the connection until another SET ROWCOUNT 0 is called.

This could be dangerous sometime if you forget to reset the ROWCOUNT.

Microsoft recommends that we should not use this style as they are planning to stop its affect on DML statements. Microsoft recommends TOP Command.

If both TOP statement and SET ROWCOUNT are used, SET ROWCOUNT over rides TOP when ROWCOUNT value is smaller than TOP value

Example given below. The below statement will give us only 2 rows as output.


--

SET ROWCOUNT 2
SELECT TOP 4 * FROM Approver

--

SET ROWCOUNT limits all the queries including triggers.

As a part of a SELECT statement, the query optimizer can consider the value of expression in the TOP or FETCH clauses during query optimization. Because SET ROWCOUNT is used outside a statement that executes a query, its value cannot be considered in a query plan.

This setting comes into play during execution and not at parse time.

If you want to reset it, then use the statement below.


--

SET ROWCOUNT 0

--

Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in a future release of SQL Server. Avoid using SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. For a similar behavior, use the TOP syntax.

 

Question18. What is the SQL Query Order of Operations ? OR What is the Logical Query Processing Phases and their order in SQL Statement Execution.

Answer – SQL Server processes SQL statements in a Logical Order. We call it Logical Query Processing Phases. Phases and their order is given below-

1. FROM
2. ON
3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10.TOP
11.ORDER BY

If you want to remember the above sequence use below

Fred-Will-Give-Her-Some-O.

You can also learn this in detail from below URL – (Itzik Ben-Gan – SQL Expert)

Click to access Logical%20Query%20Processing%20Poster.pdf

 

Question19. What is .TUF file? What is the significance of the same? Any implications if the file is deleted?

Answer –

TUF file is the Transaction Undo File. This file is created when LogShipping is configured in SQL Server in stand by mode. This file is located @ the path where transaction log files were saved.

This File consists of list of uncommitted transactions while backup is going on the primary server in LogShipping. If .tuf file is got deleted there is no way to repair logshipping except reconfiguring it from scratch.

The transaction undo file contains modifications that were not committed on the source database but were in progress when the transaction log was backed up AND when the log was restored to another database, you left the database in a state that allowed addition transaction log backups to be restored to it (at some point in the future. When another transaction log is restored, SQL Server uses data from the undo file and the transaction log to continue restoring the incomplete transactions (assuming that they are were completed in the next transaction log file). Following the restore, the undo file will be re-written with any transactions that, at that point, are incomplete.

 

Question 20. What is a deadlock and what is a live lock? How will you go
about resolving deadlocks?

Answer –

Deadlock is a situation when two processes, each having a
lock on one piece of data, attempt to acquire a lock on the
other’s piece. Each process would wait indefinitely for
the other to release the lock, unless one of the user
processes is terminated. SQL Server detects deadlocks and
terminates one user’s process.

A livelock is one, where a request for an exclusive lock
is repeatedly denied because a series of overlapping shared
locks keeps interfering. SQL Server detects the situation
after four denials and refuses further shared locks. A
livelock also occurs when read transactions monopolize a
table or page, forcing a write transaction to wait
indefinitely. A human example of live lock would be two people who meet
face-to-face in a corridor and each moves aside to let the
other pass, but they end up moving from side to side without
making any progress because they always move the same way at
the same time and never cross each other. This is good
example of live lock.

PREV

NEXT

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email

SQL SERVER Interview Questions & Answers – SET 2 (40 Questions & Answers) [Page – 1]

21 Thursday May 2015

Posted by Pawan Kumar Khowal in Download SQL Interview Q's, SQL Server Interview Questions

≈ 1 Comment

Tags

Advanced SQL tutorial pdf, Difference between ISNULL and COAELSCE, Download SQL Questions, Download SQL Server Interview Question in PDF, Download SQL SERVER Interview questions, Download SQL Server Interview questions and answers, download sql server interview questions and answers pdf, download sql server interview questions by Pawan Khowal, download sql server interview questions by Pawan Kumar, download sql server interview questions by Pawan Kumar Khowal, Download T-SQL Interview Questions, Free Download SQL SERVER Interview questions, Poor query performance in Prod, query which is running fine in development but facing performance issues at production, SQL, SQL Common Interview Questions, SQL Common Interview Questions and answers, SQL FAQ, SQL FAQs, SQL Interview Q & A, SQL Interview Questions, SQL Queries asked in interviews, SQL Questions, SQL Server - General Interview Questions and Answers, SQL Server developer Interview questions and answers, SQL Server developer Interview questions with answers, SQL SERVER Interview questions, SQL SERVER Interview questions & Answers, SQL Server Interview questions and answers, SQL Server Interview Questions and Answers - Free PDF, sql server interview questions and answers for net developers, SQL SERVER Tips, SQL Tips & Tricks, SQL Tips and Tricks, SQL Tricks, stuff and replace sql, T-SQL Server Interview Questions, What is a Race Condition, What is lock Escalation, what is memory grant in sql server, What is stuff function? Difference between stuff and replace?, What is the difference between CROSS APPLY & OUTER APPLY IN T-SQL ?, What things to consider while designing a Database.


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

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email

SSRS Interview Questions

18 Monday May 2015

Posted by Pawan Kumar Khowal in Reporting Services

≈ Leave a comment

Tags

Advanced SSRS tutorial pdf, deployment mechanism for ​​SSRS deployment, Download SSRS Questions, Download SSRS Server Interview Question in PDF, Download SSRS SERVER Interview questions, download SSRS server interview questions and answers, download SSRS server interview questions and answers pdf, download SSRS server interview questions by Pawan Khowal, download SSRS server interview questions by Pawan Kumar, download SSRS server interview questions by Pawan Kumar Khowal, Download T-SSRS Interview Questions, Free Download SSRS SERVER Interview questions, How to design a Drilldown report?, How to render a report to a user email?, SSRS, SSRS Common Interview Questions, SSRS Common Interview Questions and answers, SSRS FAQ, SSRS FAQs, SSRS Interview Q & A, SSRS Interview Questions, SSRS Queries asked in interviews, SSRS questions, SSRS Server - General Interview Questions and Answers, SSRS Server developer Interview questions and answers, SSRS Server developer Interview questions with answers, SSRS SERVER Interview questions, SSRS SERVER Interview questions & Answers, SSRS SERVER Interview questions and Answers, SSRS Server Interview Questions and Answers - Free PDF, SSRS server interview questions and answers for net developers, SSRS SERVER Tips, SSRS Tips & Tricks, SSRS Tips and Tricks, SSRS Tricks, T-SSRS Server Interview Questions, What is a sub report?, What is the difference between Table and Matrix?


SSRS Interview Questions – SET 1 ( 50 Questions )

CLICK HERE (SSRS Interview Questions) to download the questions in PDF format.

I have been collecting interview questions from the people who have given interviews at various organizations. Please go through these questions before attending any technical Interview. Below are the list of questions on SSRS (SQL SERVER Reporting Services). Please add a comment if you have any question in mind , will add that also. Answers to these questions are coming very soon.

Question1. How to render a report to a user email?
Question2. How to join two datasets and use in a single report?
Question3. How to do paging in SSRS?
Question4. How to deal with multi valued parameters?
Question5. I want one page should be displayed in landscape and other pages in different formats in a report. Can you design a SSRS report for this requirement?
Question6. How to tune the performance of SSRS report?
Question7. How to design a Drilldown report?
Question8. What is the difference between Table and Matrix?
Question9. What is drill across through report?
Question10. How to keep header in all pages – SSRS?
Question11. How to add custom code to change the colour of a node in report – SSRS
Question12. What is a sub report?
Question13. Difference between drill through and sub reports?
Question14. ​What is a shared dataset?
Question15. Can we use shared dataset with the sub report?
Question16. What is the deployment mechanism for ​​SSRS deployment?
Question17. What are the common performance issues in SSRS?
Question18. ​Can you tell me top 5 new features in SSIS and SSRS Both in 2008 and 2012?​
Question19. What kind of dashboards you have prepared using SSRS reports?
Question20. Design a SSRS report that can support dynamic columns.
Question21. How to remove PDF from the export options in SSRS report?
Question22. What are the user roles available in SSRS?
Question23. What are the data regions in SSRS?
Question24. Have you ever used custom assembles in SSRS?
Question25. How to enhance SSRS functionality?
Question26. How to design a report to show the alternative rows in a different colour?
Question27. Write a code to customize the SSRS report. Where the code has to be written?
Question28. In a SSRS report where to write custom code?
Question29. ​How to troubleshoot SSRS report using ExecutionLog2?
Question30. Have you ever seen .rdl file? What are the different sections in .rdl file?
Question31. How to upgrade SSRS reports?
Question32. How to give estimations to your report requirements?
Question33. How to design a SSRS report that shows alternative rows in different colour?
Question34. How to manually allocate memory to SSRS service?
Question35. How to view report server logs and call stacks in SSRS?
Question36. Can you explain how to disable parallel processing or how to serialize dataset execution?
Question37. How to pass multi-valued parameter to stored procedure in dataset?
Question38. How to control the pagination in SSRS?
Question39. What are the major differences between SSRS 2008 and SSRS 2012?
Question40. You have any idea about IIF, SWITCH and LOOKUP functions in SSRS?
Question41. We know in SSRS by default datasets are executed in parallel. But in our environment data Source is under high load and can’t handle parallel requests.
Question42. Do you create your reports using the wizard or manually?
Question43. What formats can SSRS export or render to?
Question44. What servers can be used with SSRS?
Question45. Can we create a chart report using Report Wizard?
Question46. Can you edit the .rdl code associated with a linked report?
Question47. What is reporting lifecycle?
Question48. What is ReportServer and ReportServerTempDB ?
Question49. What is toggling in SSRS?
Question50. I have a report server A with more than 600 reports; Now the report Server A is down and we would like to move all the reports, their subscriptions and alerts on server B in a minimum down time. What would be your approach?

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email

SQL SERVER Interview Questions & Answers – SET 1 (50 Questions & Answers) [Page – 5]

15 Friday May 2015

Posted by Pawan Kumar Khowal in Download SQL Interview Q's, SQL Server Interview Questions

≈ 2 Comments

Tags

Advanced SQL interview questions, Advanced SQL Queries, Advanced SQL tutorial, Advanced SQL tutorial pdf, Any alternative to triggers?, Difficult SQL Interview Questions, Download SQL Questions, Download SQL Server Interview Question in PDF, Download SQL SERVER Interview questions, Download SQL Server Interview questions and answers, download sql server interview questions and answers pdf, download sql server interview questions by Pawan Khowal, download sql server interview questions by Pawan Kumar, download sql server interview questions by Pawan Kumar Khowal, Download T-SQL Interview Questions, Free Download SQL SERVER Interview questions, How to create linked server., How to find the query running on a given SPID?, How to find the statistics are outdated?, I have written a recursive CTE, Interview Qs.SQL SERVER Questions, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Is “TRUNCATE” DDL or DML command?, it’s been running infinitely and failed with an error. The requirement is that the recursion required for 1000 times. How could you be able to handle the situation?, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Common Interview Questions, SQL Common Interview Questions and answers, SQL FAQ, SQL FAQs, SQL Interview Q & A, SQL Interview Questions, SQL Interview questions SQL questions SQL SERVER Interview questions SQL SERVER Interview questions Download SQL SERVER Interview questions Free Download SQL SERVER Interview questions SQL SERVER Tips, SQL Joins, SQL Queries, SQL Queries asked in interviews, SQL Questions, SQL Server, SQL Server - General Interview Questions and Answers, SQL Server developer Interview questions and answers, SQL Server developer Interview questions with answers, SQL SERVER Interview questions, SQL SERVER Interview questions & Answers, SQL Server Interview questions and answers, SQL Server Interview Questions and Answers - Free PDF, SQL SERVER Interview questions and answers for experienced, sql server interview questions and answers for net developers, SQL SERVER Interview questions for experienced, SQL SERVER Interview questions pdf, SQL SERVER Tips, SQL SERVER Tricky questions, SQL Skills, SQL Tips & Tricks, SQL Tips and Tricks, SQL Tricks, SQL Tricky question, SQL Tutorial, SQLSERVER, T-SQL, T-SQL Interview questions, T-SQL Programming, T-SQL Server Interview Questions, T-SQL Tutorial, TOP 100 SQL SERVER INTERVIEW QUESTIONS, Top 50 SQL Server Questions & Answers, Top performance tuning tools, Tough PL SQL Interview Questions, Tough SQL Interview Questions, Tough SQL Queries, Tough SQL Queries Interview Questions, Tough SQL Questions, Tricky SQL Interview Questions, Tricky SQL Interview Questions and answers, Tricky SQL Queries for Interview, Tricky SQL SERVER Interview Questions and answers, TSQL, TSQL Interview questions, TSQL Queries, What is the best value for MAXDOP value?, Which is better a CTE or a subquery? Why?, Which is better “Left Outer” Or “NOT EXIST”?, Why resourceDB introduced?


SQL SERVER Interview Questions & Answers – SET 1 (50 Questions & Answers)

Download – Pawan Kumar Khowal – SQL SERVER Interview Questions with Answers

PAGE – 5

PREV

Question 41. What is the best value for MAXDOP value?

Answer-

MAXDOP is Max degree of parallelism. This option controls the number of processors that are used for the execution of a query in a parallel plan.

One can use the max degree of parallelism option to limit the number of processors to use for parallel plan execution and to prevent run-away queries from impacting SQL Server performance by using all available CPUs.

The answer is: It depends. It depends on the hardware, the environment (OLTP vs. OLAP), and the load and so on.

The default value for MAXDOP is 0 (zero) and can be set or viewed using (sp_configure). A value of 0 means that SQL Server will use all processors if a query runs in parallel.

For details please visit –
http://www.mssqltips.com/sqlservertip/2650/what-maxdop-setting-should-be-used-for-sql-server/

Question 42. Which is better “Left Outer” Or “NOT EXIST”?

Answer-

In SQL Server, NOT EXISTS and NOT IN predicates are the best ways to search for missing values, as long as both columns in question are NOT NULL. They produce the safe efficient plans with some kind of an Anti-Join.

LEFT JOIN is less efficient, since it makes no attempt to skip the already matched values in the right table, returning all results and filtering them out instead.
http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/

Question 43. How to find the statistics are outdated?

Answer –

You can check statistics by using below command –


DBCC SHOW_STATISTICS('TestRIDInxs','Ix_Index')

Table Name – TestRIDInxs
Index Name - 'Ix_Index

Output of the above query is given below-

Statistics

Question 44. How to find the query running on a given SPID?

Answer-

You can use below query to find query running on an active SPID. Number (52) is the SPID showing in the below example.


DECLARE @sqltext VARBINARY(128)
SELECT @sqltext = sql_handle
FROM sys.dm_exec_requests
WHERE session_id = 52
SELECT TEXT
FROM sys.dm_exec_sql_text(@sqltext);

Question 45. Is “TRUNCATE” DDL or DML command?

Answer- DDL

Question 46. I have written a recursive CTE, it’s been running infinitely and failed with an error. The requirement is that the recursion required for 1000 times. How could you be able to handle the situation?

Answer-

Well if you write a proper recursive CTE then it will not run indefinitely.

MAXRECURSION can be used to break the recursive CTE. MAXRECURSION can be used to prevent a poorly formed recursive CTE from entering into an infinite loop.

The following example intentionally creates an infinite loop and uses the MAXRECURSION hint to limit the number of recursion levels to ten.


;WITH CTE AS
(
	SELECT ParentID FROM Hierarchies WHERE ParentID = 1
	UNION ALL
	SELECT C.ParentID FROM Hierarchies H INNER JOIN CTE C
	ON C.ParentID = H.ParentID
)
SELECT * FROM CTE
OPTION (MAXRECURSION 10);
GO

You will also get this kind of message-

Msg 530, Level 16, State 1, Line 1
The statement terminated. The maximum recursion 10 has been exhausted before statement completion.

Question 47. Which is better a CTE or a subquery? Why?

Answer-

Both CTEs and Sub Queries have pretty much the same performance and function.

CTE’s have an advantage over using a subquery in that you can use recursion in a CTE.

The biggest advantage of using CTE is readability. CTEs can be reference multiple times in the same statement where as sub query cannot.

Question 48. Any alternative to triggers?

Answer –

There are some options available depending exclusively on the requirement. They are
Change Data Capture
Change Tracking
Using output clause (Write the data out to a specific Audit table )
Computed column

Question 49. Why resourceDB introduced?

Answer –

It is a read-only database that contains system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.

Also Resource database makes upgrading to a new version of SQL Server an easier and faster procedure. In earlier versions of SQL Server, upgrading required dropping and creating system objects. Because the Resource database file contains all system objects, an upgrade is now accomplished simply by copying the single Resource database file to the local server.

For details please visit –

http://blogs.msdn.com/b/vsanil/archive/2012/11/02/resource-database-common-questions.aspx

Question 50. How to create linked server.

Answer –

Please use below T-SQL script or follow the screen shots


USE [master]
GO
EXEC MASTER.dbo.sp_addlinkedserver
    @server = N'SRVR002\ACCTG',
    @srvproduct=N'SQL Server' ;
GO

LinkedServer

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email
← Older posts

Blog Stats

  • 1,084,777 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 1,131 other subscribers

Pawan Khowal

502 SQL Puzzles with answers

Achievement - 500 PuzzlesJuly 18, 2018
The big day is here. Finally presented 500+ puzzles for SQL community.

200 SQL Server Puzzle with Answers

The Big DayAugust 19, 2016
The big day is here. Completed 200 SQL Puzzles today

Archives

May 2015
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031
« Apr   Jun »

Top Articles

  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…

Archives

  • October 2020 (29)
  • September 2018 (2)
  • August 2018 (6)
  • July 2018 (25)
  • June 2018 (22)
  • May 2018 (24)
  • April 2018 (33)
  • March 2018 (35)
  • February 2018 (53)
  • January 2018 (48)
  • December 2017 (32)
  • November 2017 (2)
  • October 2017 (20)
  • August 2017 (8)
  • June 2017 (2)
  • March 2017 (1)
  • February 2017 (18)
  • January 2017 (2)
  • December 2016 (5)
  • November 2016 (23)
  • October 2016 (2)
  • September 2016 (14)
  • August 2016 (6)
  • July 2016 (22)
  • June 2016 (27)
  • May 2016 (15)
  • April 2016 (7)
  • March 2016 (5)
  • February 2016 (7)
  • December 2015 (4)
  • October 2015 (23)
  • September 2015 (31)
  • August 2015 (14)
  • July 2015 (16)
  • June 2015 (29)
  • May 2015 (25)
  • April 2015 (44)
  • March 2015 (47)
  • November 2012 (1)
  • July 2012 (8)
  • September 2010 (26)
  • August 2010 (125)
  • July 2010 (2)

Article Categories

  • Analysis Services (6)
    • DAX (6)
  • Data (2)
    • Data warehousing (2)
  • Integration Services (2)
  • Magazines (3)
  • Python (29)
  • Reporting Services (4)
  • SQL SERVER (820)
    • Download SQL Interview Q's (212)
    • SQL Concepts (323)
    • SQL Performance Tuning (155)
    • SQL Puzzles (331)
    • SQL SERVER 2017 Linux (6)
    • SQL Server Interview Questions (308)
    • SQL SERVER Puzzles (332)
    • T SQL Puzzles (547)
    • Tricky SQL Queries (439)
  • UI (30)
    • ASP.NET (5)
    • C# (13)
    • CSS (9)
    • OOPS (3)
  • Uncategorized (5)

Recent Posts

  • Python | The Print and Divide Puzzle October 30, 2020
  • Python | Count consecutive 1’s from a list of 0’s and 1’s October 30, 2020
  • Python | How to convert a number into a list of its digits October 26, 2020
  • Python | Validate an IP Address-IPV6(Internet Protocol version 6) October 26, 2020
  • Python | Print the first non-recurring element in a list October 26, 2020
  • Python | Print the most recurring element in a list October 26, 2020
  • Python | Find the cumulative sum of elements in a list October 26, 2020
  • Python | Check a character is present in a string or not October 26, 2020
  • Python | Check whether a string is palindrome or not October 26, 2020
  • Python | Find the missing number in the array of Ints October 26, 2020
  • Python | How would you delete duplicates in a list October 26, 2020
  • Python | Check whether an array is Monotonic or not October 26, 2020
  • Python | Check whether a number is prime or not October 26, 2020
  • Python | Print list of prime numbers up to a number October 26, 2020
  • Python | Print elements from odd positions in a list October 26, 2020
  • Python | Print positions of a string present in another string October 26, 2020
  • Python | How to sort an array in ascending order October 26, 2020
  • Python | How to reverse an array October 26, 2020
  • Python | Find un-common words from two strings October 26, 2020
  • Python | How to convert a string to a list October 26, 2020
  • Python | Find unique words from a string October 26, 2020
  • Python | Calculate average word length from a string October 26, 2020
  • Python | Find common words from two strings October 26, 2020
  • Python | Find the number of times a substring present in a string October 26, 2020
  • Python | Find maximum value from a list October 26, 2020
  • Python | How to find GCF of two numbers October 26, 2020
  • Python | How to find LCM of two numbers October 26, 2020
  • Python | How to convert a list to a string October 26, 2020
  • Python | Replace NONE by its previous NON None value October 26, 2020
  • Microsoft SQL Server 2019 | Features added to SQL Server on Linux September 26, 2018

Create a website or blog at WordPress.com

  • Follow Following
    • Improving my SQL BI Skills
    • Join 231 other followers
    • Already have a WordPress.com account? Log in now.
    • Improving my SQL BI Skills
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...
 

You must be logged in to post a comment.