interview questions.docx

22
RE: sql server interview questions and answers for experienced What is the purpose of using SET ANSI NULLS ON? The purpose of using SET ANSI_NULLS ON to follow the ISO Standard. Acording to this = and <> should not be used for null comparison. Instead we use null and is not null how ever if you will use = null it will return zero rows. If we want to use = or <> for null comparison use SET ANSI_NULLS OFF it means do not follow ISO Standard. SET ANSI_NULLS should be set to ON for executing distributed queries for maintaining compatibility of queries across Servers. Difference between cluster and non cluster index in sql? A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Can we create non primary key as cluster index? Yes we can do this on non-primary key column but that column must be unique and the primary key column of that table must have non-clustered index because there is one cluster index in table. By default primary key column contains clustered index so its recommended to create such non-primary key clustered index column first and then should create primary key column so in such case the primary key on that column will be with non-clustered. But its highly recommended to create primary key column as a clustered indexed column. Can we call a Trigger in store procedure? A Trigger is also a special kind of Stored Procedure which will fire automatically on the happening of an event like before or after insert, update or delete. We cannot call a trigger explicitly from a Stored Procedure. Difference Between GETDATE and SYSDATETIME? When we use GETDATE the precision is till miliseconds and in case of SYSDATETIME the precision is till nanoseconds. Get top two records without Top keyword. [SQL]

Upload: jayrathod03

Post on 29-Nov-2015

32 views

Category:

Documents


2 download

DESCRIPTION

MS sql server 2008

TRANSCRIPT

Page 1: Interview Questions.docx

RE: sql server interview questions and answers for experienced

What is the purpose of using SET ANSI NULLS ON?

The purpose of using SET ANSI_NULLS ON to follow the ISO Standard. Acording to this =

and <> should not be used for null comparison. Instead we use null and is not null how

ever if you will use = null it will return zero rows. If we want to use = or <> for null

comparison use SET ANSI_NULLS OFF it means do not follow ISO Standard. SET

ANSI_NULLS should be set to ON for executing distributed queries for maintaining

compatibility of queries across Servers.

Difference between cluster and non cluster index in sql?

A clustered index is a special type of index that reorders the way records in the table are

physically stored. Therefore table can have only one clustered index. The leaf nodes of a

clustered index contain the data pages. 

A non clustered index is a special type of index in which the logical order of the index

does not match the physical stored order of the rows on disk. The leaf node of a non

clustered index does not consist of the data pages. Instead, the leaf nodes contain index

rows. 

Can we create non primary key as cluster index?

Yes we can do this on non-primary key column but that column must be unique and the

primary key column of that table must have non-clustered index because there is one

cluster index in table. By default primary key column contains clustered index so its

recommended to create such non-primary key clustered index column first and then

should create primary key column so in such case the primary key on that column will be

with non-clustered. But its highly recommended to create primary key column as a

clustered indexed column.

Can we call a Trigger in store procedure?

A Trigger is also a special kind of Stored Procedure which will fire automatically on the

happening of an event like before or after insert, update or delete. We cannot call a

trigger explicitly from a Stored Procedure.

Difference Between GETDATE and SYSDATETIME?

When we use GETDATE the precision is till miliseconds and in case of SYSDATETIME the

precision is till nanoseconds.

Get top two records without Top keyword.

[SQL]set rowcount 2

select Column1, Column2 from TableName

Difference between Set and Select.

Page 2: Interview Questions.docx

-Set is a ANSI standard for variable assignment. It assigns value to only one variable at a

time.

-Select is a Non-ANSI standard when assigning variables. It assigns multiple variable at a

time.

-When assigning from a query that returns more than one value, SET will fail with an

error.

-When assigning from a query that returns more than one value, SELECT will assign the

last value returned by the query and hide the fact that the query returned more than one

row.

How to get number of Maximum connection can be establish to SQL?

select @@MAX_Connections

Why we use SET ROWCOUNT in Sql?

This syntax is used in SQL Server to stop processing the query after the specified number

of rows are returned.

What are the Global Temporary Tables?

We can create global temporary tables but these are not using much in sql an the name

of these table start with two pound signs. For example, ##globaltbl is a global temporary

table. As the name suggest these table is Global temporary tables and visible to all SQL

Server connections. When we create any one of these all users can see it.

What is a View in SQL?

View is just a virtual table nothing else which is based or we can say develop with SQL

SELECT query.So we can say that its a real database table (it has columns and rows just

like a regular table),but one difference is that real tables store data, but views can''t.

View data is generated dynamically when the view is referenced. And view can also

references one or more existing database tables or other views. We can say that it is

filter of database.

Why Group BY and Order By clause are so expensive?

Both Group By and Order By clause requires Temporary table to process the result of

query so these are expensive.

What is the use of SET NOCOUNT ON?

When we use SELECT and DML statement in SQL. SQL server return a message which

specify the number of rows effected by these statements. This information helps coder

when they are debugging the code other wise this is not useful we can disable this by

typing SET NOCOUNT ON. It is very helpful when we are doing on store procedure

contains lots of statements, loops its also increase in performance and boost network

traffic.

What are the differences between SQL and PL/SQL?

We can get modify, Retrieve by single command or statement in SQL but PL/SQL process

all SQL statements one at a time. With PL/SQL, an entire block of statement process in a

Page 3: Interview Questions.docx

single command line. SQL is structured query language, various queries are used to

handle the database in a simplified manner. While PL/SQL is procedural language

contains various types of variables, functions and procedures and other major diffrence is

Sql as the name suggest it is just structured query language wheareas PLSQL is a

combination of Programming language & SQL. 

What is a join? List different types of joins

Joins are used in queries to explain how different tables are related. Joins also let you

select data from a table depending upon data from another table. 

Types of joins:

-INNER JOIN

-OUTER JOIN (OUTER JOIN is further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS

and FULL OUTER JOINS)

-CROSS JOINs

What is a Cursor?

Cursor is a database object used by applications to manipulate data in a set on a row-by-

row basis, instead of the typical SQL commands that operate on all the rows in the set at

one time. For example, you can use cursor to include a list of all user databases and

make multiple operations against each database by passing each database name as a

variable.

Difference between stored procedure and user defined function

1>Procedure can return zero or n values whereas function can return one value which is

mandatory.

2>Procedures can have input, output parameters for it whereas functions can have only

input parameters.

3>Procedure allow select as well as DML statement in it whereas function allow only

select statement in it.

4>Functions can be called from procedure whereas procedures cannot be called from

function.

5>Exception can be handled by try-catch block in a procedure whereas try-catch block

cannot be used in a function.

6>We can go for transaction management in procedure whereas we can''t go in function.

7>Procedures can not be utilized in a select statement whereas function can be

embedded in a select statement.

Page 4: Interview Questions.docx

RE: sql server interview questions and answers for experienced

Below are few interview questions:

What is Extent and Page?

Extent is a basic unit of storage to provide space for tables. Every extent has number of

data pages. As new records are inserted new data pages are allocated. There are eight

data pages in an extent. So as soon as the eight pages are consumed it allocates new

extent with data pages. 

While extent is basic unit storage from database point of view, page is a unit of allocation

within extent.

What are the types of JOIN used in SQL Server?

-Inner join

- Outer Join (Left outer join and right outer join)

- Self Join

- Cross Join

What’s the difference between “UNION” and “UNION ALL” ?

UNION SQL syntax is used to select information from two tables. But it selects only

distinct records from both the table, while UNION ALL selects all records from both the

tables.

What is a cursor?

It is used to handle a set of data. Using cursors, you can loop through all the rows and

update data accordingly.

What are the steps involved in creating a cursor?

1. Declare Cursor

2. Open Cursor

3. Fetch the data''s

4. Operation

5. Close and Deallocate

How is the SUBSTR keyword used in SQL?

SUBSTR is used for string manipulation with column name, first position and string length

used as arguments. 

What is a trigger? Write its syntax.

A Trigger is also a special kind of Stored Procedure which will fire automatically on the

happening of an event like before or after insert, update or delete. We cannot call a

trigger explicitly from a Stored Procedure.

[SQL]

Page 5: Interview Questions.docx

CREATE TRIGGER TriggerName

ON TableName

AFTER INSERT | UPDATE | DELETE 

AS

Query to be executed...

GO

Posted By: Anonymous

Posted Dt: 18-Mar-2012

93     2

Total Points: 9059

RE: sql server interview questions and answers for experienced

Hi All,

I have given the interview for RBS, Chennai a week ago. They asked me a question in sql

server. How to fetch the second highest salary from a table without using top, rowcount

and rank keywords...

Could anyone know how to write the query fro fetching the second highest salary without

using top, rowcount and rank keywords?

Thanks,

Posted By: Anonymous

Posted Dt: 18-Mar-2012

169     28

Total Points: 20889

RE: sql server interview questions and answers for experienced

Hi Karthik,

Below are few sql server interview questions and answers.

What are CODD rules?

Page 6: Interview Questions.docx

There are 12 rules that every DBMS should adhere in order to be true RDBMS. These

rules were laid by E.F.CODD in 1969.

1. Information Rule

2. Guaranteed access rule

3. Systematic treatment of null values

4. Dynamic on-line catalog based on the relational model

5. Comprehensive data sub-language Rule

6. View updating Rule

7. High-level insert, update and delete

8. Physical data independence

9. Logical data independence

10.Integrity independence

11.Distribution independence

12.Non-subversion Rule

How many types of relationship exists in Database designing?

1. One to One

2. One to Many

3. Many to Many

What is a DDL, DML and DCL concept?

DDL (Data definition language) defines your database structure. CREATE and ALTER are

DDL statements as they affect the way your database structure is organized.

DML (Data Manipulation Language) lets you do basic functionalities like INSERT, UPDATE,

DELETE and MODIFY data in database.

DCL (Data Control Language) controls you DML and DDL statements so that your data is

protected and has consistency. COMITT and ROLLBACK are DCL control statements. DCL

guarantees ACID fundamentals of a transaction.

Difference between DELETE and TRUNCATE.

- DELETE table can be rolled back while TRUNCATE can not be.

- DELETE TABLE syntax logs the deletes thus making the delete operations low.

TRUNCATE table does not log any information but it logs information about deallocation

of data page of the table. So TRUNCATE table is faster as compared to delete table.

- DELETE table can have criteria while TRUNCATE can not.

- TRUNCATE table can not have triggers.

What is a Cursor?

Cursor is a database object used by applications to manipulate data in a set on a row-by-

row basis, instead of the typical SQL commands that operate on all the rows in the set at

one time. 

Thanks,

Priya

Page 7: Interview Questions.docx

Posted By: Anonymous

Posted Dt: 24-Mar-2012

50     11

Total Points: 5781

RE: sql server interview questions and answers for experienced

Hi Vaishnavi,

I have written a query to fetch the second highest salary from the table. Please find the

query below and let me know if it is not working

[SQL]select points from tablename as tbl where (select count(*) from tablename

where salary>=tbl.salary)=2

Thanks,

Hariharan T G

Posted By: Anonymous

Posted Dt: 27-Mar-2012

45     9

Total Points: 9059

RE: sql server interview questions and answers for experienced

Hi Hari,

Thanks for posting the query. It works fine. :-)

Thanks

Page 8: Interview Questions.docx

Posted By: Anonymous

Posted Dt: 28-Mar-2012

12     3

Total Points: 20889

RE: sql server interview questions and answers for experienced

Hi All,

Below are the few sql server interview questions.

Difference between truncate and delete in sql server.

• DELETE TABLE syntax logs the deletes thus make the delete operation slow. TRUNCATE

table does not log any information but it logs information about deallocation of data page

of the table so TRUNCATE table is faster as compared to delete table.

• DELETE table can have criteria while TRUNCATE cannot.

• TRUNCATE table does not invoke trigger.

• TRUNCATE will reset any identity columns to the default seed value.

• You cannot TRUNCATE a table that has any foreign key constraints. You will have to

remove the constraints, TRUNCATE the table, and re-apply the constraints.

Difference between where and having clause

• SQL WHERE clause condition is tested against each and every row of data, while the

SQL HAVING clause condition is tested against the groups and/or aggregates specified in

the SQL GROUP BY clause and/or the SQL SELECT column list.

• HAVING specifies a search condition for a group or an aggregate function used in

SELECT statement.

• A HAVING clause is like a WHERE clause, but applies only to groups as a whole,

whereas the WHERE clause applies to individual rows. A query can contain both a WHERE

clause and a HAVING clause. The WHERE clause is applied first to the individual rows in

the tables . Only the rows that meet the conditions in the WHERE clause are grouped.

The HAVING clause is then applied to the rows in the result set. Only the groups that

meet the HAVING conditions appear in the query output. You can apply a HAVING clause

only to columns that also appear in the GROUP BY clause or in an aggregate function. 

Difference between DBMS and RDBMS

A DBMS has to be persistent, that is it should be accessible when the program created

the data ceases to exist or even the application that created the data restarted. A DBMS

also has to provide some uniform methods independent of a specific application for

accessing the information that is stored. RDBMS is a Relational Data Base Management

System Relational DBMS. This adds the additional condition that the system supports a

Page 9: Interview Questions.docx

tabular structure for the data, with enforced relationships between the tables. This

excludes the databases that don''t support a tabular structure or don''t enforce

relationships between tables. Many DBA''s think that RDBMS is a Client Server Database

system but thats not the case with RDBMS. 

Thanks,

Balaji T G

Posted By: tgbalajiPosted Dt: 28-Mar-2012

42     2

Total Points: 9489

RE: sql server interview questions and answers for experienced

What is a index in sql server?

An index is a physical structure containing pointers to the data. Indexes are created in an

existing table to locate rows more quickly and efficiently. 

It is possible to create an index on one or more columns of a table, and each index is

given a name.

They are just used to speed up queries.

Drawbacks of Index:

- Any DML operation performed in the table will be slow since it has to update the index

pointers.

Difference between subquery and corelated subquery?

In a subquery first the the inner query will be executed then the outer query will be

executed.

In corelated subquery the inner query refers to the outer query.

What are Clustered & non Clustered Indexes

In clustered index table are physically stored. Only one clustered index. The leaf nodes of

a clustered index contain the data pages.

A non clustered index logical order of the index does not match the physical stored order

of the rows on disk. The leaf node of a non clustered index does not consist of the data

pages. Instead, the leaf nodes contain index rows

What are the types of joins in SQL Server?

INNER JOIN

Page 10: Interview Questions.docx

LEFT OUTER JOIN

RIGHT OUTER JOIN

FULL OUTER JOIN

CROSS JOIN

Difference between delete and truncate in sql server.

The deletion of each row gets logged in the transaction log, which makes it slow deletes

all the rows in a table, but it won’t log the deletion of each row, instead it logs the

deallocation of the data pages of the table, which makes it faster.

Thanks,

Posted By: Anonymous

Posted Dt: 30-Mar-2012

40     7

Total Points: 9059

RE: sql server interview questions and answers for experienced

Good collection of SQL Interview questions and answers.

Please post more questions.. 

Thanks

Posted By: Rocket Raja

Posted Dt: 12-May-2012

6     9

Total Points: 522

RE: sql server interview questions and answers for experienced

What are the error functions used in SQL Try catch block?

TRY…CATCH uses the following error functions to capture error information:

- ERROR_NUMBER() returns the error number.

- ERROR_MESSAGE() returns the complete text of the error message. The text includes

the values supplied for any substitutable parameters such as lengths, object names, or

Page 11: Interview Questions.docx

times.

- ERROR_SEVERITY() returns the error severity.

- ERROR_STATE() returns the error state number.

- ERROR_LINE() returns the line number inside the routine that caused the error.

- ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the

error occurred.

What new indexes are introduced in SQL Server 2005 in comparison to 2000?

- Spatial

- XML

What are Cursors and their types? What type do you use most and which one is fast?

Cursor is a database object used by applications to manipulate data in a set on a row-by-

row basis, instead of the typical SQL commands that operate on all the rows in the set at

one time. 

Types: FORWARD-ONLY, FAST-FORWARD or READ-ONLY cursors.

Fastest to slowest: Dynamic, Static, and Keyset.

Difference between DELETE & TRUNCATE statement? Which statement can be

Rollbacked?

- With DELETE we can provide conditional WHERE clause to remove/delete specific rows,

which is not possible with TRUNCATE.

- TRUNCATE is faster than DELETE as Delete keeps log of each row it deletes in

transaction logs, but truncate keeps log of only de-allocated pages in transaction logs.

- Both statements can be rolled backed if provided in a transaction (BEGIN TRANS). If not

then none of them can be rollbacked.

- DELETE is DML just like INSERT, UPDATE, but TRANCATE is DDL, just like CREATE,

ALTER, DROP

What are the tools that could be used for SQL Query performance tuning?

Query Analyzer, Profiler, Index Wizard, Performance Monitor

Thanks,

Posted By: quickfixkumar

Posted Dt: 06-Sep-2012

48     15

Total Points: 1780

Page 12: Interview Questions.docx

RE: sql server interview questions and answers for experienced

I have given the interview for RBS, Chennai a week ago. They asked me a question in sql

server. How to fetch the second highest salary from a table without using top, rowcount

and rank keywords...

Could anyone know how to write the query fro fetching the second highest salary without

using top, rowcount and rank keywords?

create table employee

(

id int identity (10,1) ,

name varchar(25),

salary int 

)

insert into employee values ('pankaj',10000)

insert into employee values ('pankaj1',15000)

insert into employee values ('pankaj',20000)

insert into employee values ('pankaj1',40000)

insert into employee values ('pankaj2',18000)

insert into employee values ('pankaj3',19000)

insert into employee values ('pankaj4',14400)

insert into employee values ('pankaj6',199990)

SELECT distinct top 1 e1.salary FROM

Table1 e1 ,Table1 e2

where e2.salary<e1.salary

order by e1.salary asc

Posted By: Pankaj Upadhyay

Posted Dt: 18-Oct-2013

4     0

Total Points: 14

RE: sql server interview questions and answers for experienced

Page 13: Interview Questions.docx

I have given the interview for RBS, Chennai a week ago. They asked me a question in sql

server. How to fetch the second highest salary from a table without using top, rowcount

and rank keywords...

Could anyone know how to write the query fro fetching the second highest salary without

using top, rowcount and rank keywords?

below given Solution 

create table #employee

(

id int identity (10,1) ,

name varchar(25),

salary int 

)

insert into #employee values ('pankaj',10000)

insert into #employee values ('pankaj1',15000)

insert into #employee values ('pankaj',20000)

insert into #employee values ('pankaj1',40000)

insert into #employee values ('pankaj2',18000)

insert into #employee values ('pankaj3',19000)

insert into #employee values ('pankaj4',14400)

insert into #employee values ('pankaj6',19999440)

insert into #employee values ('pankaj6',19999440)

SELECT distinct top 1 e1.salary FROM

#employee e1 ,#employee e2

where e2.salary>e1.salary

order by e1.salary DESC 

Posted By: Pankaj Upadhyay

Posted Dt: 18-Oct-2013

3     0

Total Points: 14

RE: sql server interview questions and answers for experienced

To find nth higest salary without using keyword top,rank,row count?

My Answer is

Page 14: Interview Questions.docx

select rownum,sal from (select rownum,sal from emp order by sal desc)

group by rownum,sal having rownum=&N;

(OR)

Using the keyword top

select top 1 sal from (select top 10 sal from emp order by sal desc) a

Order by sal desc

Posted By: Udaya Lakshmi

Posted Dt: 22-Oct-2013

5     0

Total Points: 6

1. Which TCP/IP port does SQL Server run on? How can it be changed?

SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.

2. What are the difference between clustered and a non-clustered index?

1. A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.

2. A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

3. What are the different index configurations a table can have?

A table can have one of the following index configurations:

1. No indexes2. A clustered index3. A clustered index and many nonclustered indexes4. A nonclustered index5. Many nonclustered indexes

4. What are different types of Collation Sensitivity?

1. Case sensitivity - A and a, B and b, etc.2. Accent sensitivity3. Kana Sensitivity - When Japanese kana characters Hiragana and Katakana are treated

differently, it is called Kana sensitive.

Page 15: Interview Questions.docx

4. Width sensitivity - A single-byte character (half-width) and the same character represented as a double-byte character (full-width) are treated differently than it is width sensitive.

5. What is OLTP (Online Transaction Processing)?

In OLTP - online transaction processing systems relational database design use the discipline of data modeling and generally follow the Codd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules.

6. What's the difference between a primary key and a unique key?

Both primary key and unique key enforces uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

7. What is difference between DELETE and TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

1. TRUNCATE:1. TRUNCATE is faster and uses fewer system and transaction log resources than

DELETE.2. TRUNCATE removes the data by deallocating the data pages used to store the

table's data, and only the page deallocations are recorded in the transaction log.3. TRUNCATE removes all rows from a table, but the table structure, its columns,

constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column.

4. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

5. TRUNCATE cannot be rolled back.6. TRUNCATE is DDL Command.7. TRUNCATE Resets identity of the table

2. DELETE:1. DELETE removes rows one at a time and records an entry in the transaction log for

each deleted row.2. If you want to retain the identity counter, use DELETE instead. If you want to

remove table definition and its data, use the DROP TABLE statement.3. DELETE Can be used with or without a WHERE clause4. DELETE Activates Triggers.5. DELETE can be rolled back.6. DELETE is DML Command.

Page 16: Interview Questions.docx

7. DELETE does not reset identity of the table.

Note: DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current session is not closed. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session is closed, it can not be rolled back but DELETE can be rolled back.

8. When is the use of UPDATE_STATISTICS command?

This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

9. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

10. What are the properties and different Types of Sub-Queries?

1. Properties of Sub-Query1. A sub-query must be enclosed in the parenthesis.2. A sub-query must be put in the right hand of the comparison operator, and3. A sub-query cannot contain an ORDER-BY clause.4. A query can contain more than one sub-query.

2. Types of Sub-Query1. Single-row sub-query, where the sub-query returns only one row.2. Multiple-row sub-query, where the sub-query returns multiple rows,. and3. Multiple column sub-query, where the sub-query returns multiple columns

11. What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performances by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process takes place over a long period of time.

12. What are the authentication modes in SQL Server? How can it be changed?

Windows mode and Mixed Mode - SQL and Windows. To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.

Page 17: Interview Questions.docx

13. Which command using Query Analyzer will give you the version of SQL server and operating system?

SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition').

14. What is SQL Server Agent?

SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full- function scheduling engine, which allows you to schedule your own jobs and scripts.

15. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels.

16. What is Log Shipping?

Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval.

17. Name 3 ways to get an accurate count of the number of records in a table?

SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

18. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF?

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers.

19. What is the difference between a Local and a Global temporary table?

1. A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.

2. A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary

Page 18: Interview Questions.docx

table disappears. However, the table definition remains with the database for access when database is opened next time.

20. What is the STUFF function and how does it differ from the REPLACE function?

STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string.

21. What is PRIMARY KEY?

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

22. What is UNIQUE KEY constraint?

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

23. What is FOREIGN KEY?

A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

24. What is CHECK Constraint?

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.

25. What is NOT NULL Constraint?

A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

26. How to get @@ERROR and @@ROWCOUNT at the same time?

If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the error-checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable.

SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

27. What is a Scheduled Jobs or What is a Scheduled Tasks?

Page 19: Interview Questions.docx

Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during times of slow business activity. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution.

28. What are the advantages of using Stored Procedures?

1. Stored procedure can reduced network traffic and latency, boosting application performance.

2. Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead.

3. Stored procedures help promote code reuse.4. Stored procedures can encapsulate logic. You can change stored procedure code without

affecting clients.5. Stored procedures provide better security to your data.

29. What is a table called, if it has neither Cluster nor Non-cluster Index? What is it used for?

Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A heap is a table that does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that.

30. Can SQL Servers linked to other servers like Oracle?

SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to allow a link. E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group.

31. What is BCP? When does it used?

BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures same as source to destination. BULK INSERT command helps to import a data file into a database table or view in a user-specified format.

32. How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

33. What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad- hoc query and is

Page 20: Interview Questions.docx

a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.