SQL Server Interview Question

Interview Question and answers of SQL Server

1. What is normalization?

Relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization.
There are two goals of the normalization process:
eliminating redundant data (for example, storing the same data in more than one table
ensuring data dependencies Make sense (only storing related data in a table).
Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database:
· Eliminate duplicate columns from the same table.
· Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
Second Normal Form (2NF)
Second normal form (2NF) further addresses the concept of removing duplicative data:
· Meet all the requirements of the first normal form.
· Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
· Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:
· Meet all the requirements of the second normal form.
· Remove columns that are not dependent upon the primary key.
Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:
· Meet all the requirements of the third normal form.
· A relation is in 4NF if it has no multi-valued dependencies. (one column depend on other column and that column depend on other column)
Fifth Normal Form
An entity is in Fifth Normal Form (5NF) if, and only if, it is in 4NF and every join dependency for the entity is a consequence of its candidate keys.

2. What is a Stored Procedure?

It’s a set of T-SQL statements combined to perform a single task of several tasks. It’s basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.

Benefits of Stored Procedures
· Precompiled execution. SQL Server compiles each stored procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when stored procedures are called repeatedly.
· Reduced client/server traffic. If network bandwidth is a concern in your environment, you’ll be happy to learn that stored procedures can reduce long SQL queries to a single line that is transmitted over the wire.
· Efficient reuse of code and programming abstraction. Stored procedures can be used by multiple users and client programs. If you utilize them in a planned manner, you’ll find the development cycle takes less time.
· Enhanced security controls. You can grant users permission to execute a stored procedure independently of underlying table permissions.

3. Can you give an example of Stored Procedure?

sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way.
sp_helpdb [ @dbname=  ‘name’ ]
Give the detail of the database with dbid.
The sp_who2 stored procedure returns information about current SQL Server 2000 users and processes similar to sp_who, but it provides more detailed information. sp_who2 returns CPUTime, DiskIO, LastBatch and
Change name of the database
sp_renamedb ‘OLD NAME’ ‘new_name’

4. What is a trigger?

Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.
A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server.
DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.
DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations. Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established.
Eg: Create trigger Tn on table name for insert as print getdate()

5. What is a view?

If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specific users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.
A view is a virtual table that consists of columns from one or more tables. Though it is similar to a table, it is stored in the database. It is a query stored as an object. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as base or underlying tables. A view can be created by using the CREATE VIEW statement.

CREATE VIEW view_name
AS select statement [WITH CHECK OPTION]
Where: view_name specifies the name of the view and must follow the rules for identifiers. column_name specifies the name of the column to be used in view. If the column_name option is not specified, then the view is created with the same columns as specified in the select_statement. WITH ENCRYPTION encrypts the text for the view in the syscomments table. AS specifies the actions that will be performed by the view.select_statement specifies the SELECT Statement that defines a view. The view may use the data contained in other views and tables. WITH CHECK OPTION forces the data modification statements to fulfill the criteria given in the SELECT statement defining the view. It also ensures that the data is visible after the modifications are made permanent.

6. What is an Index?

When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrieval are much faster when we have an index.
Indexes allow you to speed query performance on commonly used columns and improve the overall processing speed of your database.
Microsoft SQL Server supports two types of indexes:
·Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index. If a PRIMARY KEY constraint is created for a database table and no clustered index currently exists for that table, SQL Server automatically creates a clustered index on the primary key.
·Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself. SQL Server 2000 supports a maximum of 249 non-clustered indexes per table. However, it’s important to keep in mind that non-clustered indexes slow down the data modification and insertion process, so indexes should be kept to a minimum
To see a list of all indexes:  #    sp_helpindex ‘table_name’
For creation: #   Create index   on column
Advantage of Indexes :   Searching For Records, Sorting Records, Grouping Records, Maintaining a Unique Column
Index Drawbacks :  Used Disk Space  e.g. Exec sp_spaceused

7.  What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.

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

The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
Eg. CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name ON ( column [ ASC | DESC ] [ ,…n ] ) [ INCLUDE ( Column Name[ , . . .n])]

9. What are cursors?

Well cursors help us to do an operation on a set of data that we retrieve by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retrieval one by one and remove rows which have duplicate values.
In order to work with a cursor we need to perform some steps in the following order
1.    Declare cursor: Declare MyCur Cursor For Select * From Users
2.    Open cursor
3.    Fetch row from the cursor
4.    Process fetched row
5.    Close cursor
6.    deallocate cursor

10.  When do we use the UPDATE_STATISTICS command?

This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. Updates query optimization statistics on a table or indexed view. By default, the query optimizer already updates statistics as necessary to improve the query plan; in some cases you can improve query performance by using UPDATE STATISTICS or the stored procedure sp_updatestats to update statistics more frequently than the default updates. Update statistics ensures that queries compile with up-to-date statistics. However, updating statistics causes queries to recompile. We recommend not updating statistics too frequently because there is a performance trade-off between improving query plans and the time it takes to recompile queries

11. Which TCP/IP port does SQL Server run on?

SQL Server runs on port 1433 but we can also change it for better security.

12. From where can you change the default port?

From the Network Utility TCP/IP properties –> Port number. Both on client and the server.

13. Can you tell me the difference between DELETE & TRUNCATE & DROP 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.
TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server. TRUCATE is faster
DELETE is a DML command and can be rolled back.
DROP command removes a table from the database. All the tables’ rows, indexes and privileges will also be removed. The operation cannot be rolled back.

14. Can we use truncate command on a table which is referenced by FOREIGN KEY?

No. We cannot use truncate command on a table with Foreign Key because of referential integrity.

15. What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. Refer to DBCC commands document

16. Can you give me some DBCC command options?

(Database consistency check) – DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked. And DBCC CHECKALLOC – To check that all pages in a db are correctly allocated. DBCC SQLPERF – It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP – Checks all tables file group for any damage.

17. What command do we use to rename a db?

sp_renamedb ‘oldname’, ‘newname’

18. Well sometimes sp_renamedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases?

In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.
Eg: # sp_dboption
Exec sp_dboption ‘Utrack’, ‘single user’,’true’
A. Set a database to read-only
EXEC sp_dboption ‘dbname’,’read only’, ‘TRUE’
B. Turn off an option
EXEC sp_dboption ‘dbname’,’read only’,’FALSE’
C. Take a database offline
This example takes the sales database offline if there are no users accessing the database.
EXEC sp_dboption ‘dbname’,’offline’,’TRUE’

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

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
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.
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. (Reference :BOL)
Example of HAVING and WHERE in one query:
SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
ON titles.pub_id = publishers.pub_id
WHERE publishers.state = ‘CA’
GROUP BY titles.pub_id
HAVING AVG(titles.price) > 10

20. What do you mean by COLLATION?

Collation refers to a set of rules that determine how data is sorted and compared.
Character data is sorted using rules that define the correct character sequence,
with options for specifying
1) case-sensitivity,
2) accent marks,
3) kana character types
4)character width.
Case sensitivity
If A and a, B and b, etc. are treated in the same way then it is case-insensitive. A computer treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65, while a is 97. The ASCII value of B is 66 and b is 98.

Accent sensitivity
If a and á, o and ó are treated in the same way, then it is accent-insensitive. A computer treats a and á differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and áis 225. The ASCII value of o is 111 and ó is 243.

Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.

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

21. What is a Join in SQL Server?

Join actually puts data from two or more tables into a single result set.
In previous versions of SQL Server, join logic could also have been included in the WHERE clause with = (INNER JOIN), *= (LEFT OUTER JOIN), =* (RIGHT OUTER JOIN), etc. syntax

22. Can you explain the types of Joins that we can have with Sql Server?

There are three types of joins: Inner Join, Outer Join, Cross Join

Match rows between the two tables specified in the INNER JOIN statement based on one or more columns having matching data.
E.g. Select * FROM Sales.Sales SOD INNER JOIN Production.Product P ON SOD.ProductID = P.ProductID

Based on the two tables specified in the join clause, all data is returned from the left table.  On the right table, the         matching data is returned in addition to NULL values where a record exists in the left table, but not in the right table.
E.g.  Select * from FROM Person. Contact C INNER JOIN Sales. Salesperson SP ON C.ContactID =                                        SP.SalesPersonID LEFT OUTER JOIN Sales.SalesTerritory ST ON ST.TerritoryID = SP.TerritoryID

Based on the two tables specified in the join clause, all data is returned from the right table.  On the left table, the         matching data is returned in addition to NULL values where a record exists in the right table but not in the left table.
E.g.  Select * FROM Sales.SalesTerritory ST RIGHT OUTER JOIN Sales.SalesPerson SP
ON ST.TerritoryID = SP.TerritoryID

Self -Join
In this circumstance, the same table is specified twice with two different aliases in order to match the data within the     same table.
E.g. Select * FROM HumanResources.Employee E INNER JOIN HumanResources.Employee M
ON E.ManagerID = M.ManagerID

Based on the two tables specified in the join clause, a Cartesian product is created if a WHERE clause does filter the     rows.  The size of the Cartesian product is based on multiplying the number of rows from the left table by the number   of rows in the right table.
E.g. Select * FROM Sales.SalesOrderDetail SOD CROSS JOIN Production.Product P

Based on the two tables specified in the join clause, all data is returned from both tables regardless of matching data.
E.g.  Select * FROM Person.Contact C INNER JOIN Sales.SalesPerson SP ON C.ContactID = SP.SalesPersonID                   FULL OUTER JOIN Sales.SalesTerritory ST ON ST.TerritoryID = SP.TerritoryID

23. When do you use SQL Profiler?

SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as         which SQL Scripts are running, failed jobs etc.
SQL Profiler is a tool that captures SQL Server events from the server and saves those events in what’s known as a     trace file. You can then analyze or use the trace file to troubleshoot logic or performance problems. You can use this     utility to monitor several areas of server activity, such as:
Analyzing and debugging SQL statements and stored procedures.
Monitoring slow performance.
Stress analysis.
General debugging and troubleshooting.
Fine-tuning indexes.
Auditing and reviewing security activity.

24. What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.
A linked server configuration enables SQL Server to execute commands against OLE DB data sources on remote servers. Linked servers offer the following advantages:
Remote server access.
The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise.
The ability to address diverse data sources similarly.
You can use stored procedures and catalog views to manage linked server definitions:
Create a linked server definition by running sp_addlinkedserver.
View information about the linked servers defined in a specific instance of SQL Server by running a query against the sys.servers system catalog views.
Delete a linked server definition by running sp_dropserver. You can also use this stored procedure to remove a remote server.
You can also define linked servers by using SQL Server Management Studio. In the Object Explorer, right-click Server Objects, select New, and select Linked Server. You can delete a linked server definition by right-clicking the linked server name and selecting Delete.

25. Can you link only other SQL Servers or any database servers such as Oracle?

We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that Microsoft provides to add it as a linked server to the SQL Server group.

26. Which stored procedure will you be running to add a linked server?

sp_addlinkedserver,   sp_addlinkedsrvlogin

27. What are the OS services that the SQL Server installation adds?

MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
SQL Server Database Services – The service for the SQL Server relational Database Engine.
SQL Server Agent – Executes jobs, monitors SQL Server, fires alerts, and enables automation of some administrative tasks.
Analysis Services – Provides online analytical processing (OLAP) and data mining functionality for business intelligence applications.
Reporting Services – Manages, executes, creates, schedules, and delivers reports.
Integration Services – Provides management support for Integration Services package storage and execution.
SQL Server Browser – The name resolution service that provides SQL Server connection information for client computers.
Full-text search – Quickly creates full-text indexes on content and properties of structured and semistructured data to provide document filtering and word-breaking for SQL Server.
SQL Server Active Directory Helper – Publishes and manages SQL Server services in Active Directory.
SQL Writer – Allows backup and restore applications to operate in the Volume Shadow Copy Service (VSS) framework

28. How do you troubleshoot SQL Server if its running very slow?

First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexex.
To troubleshoot performance issues, you must complete a series of steps to isolate and determine the cause of the problem. Possible causes include:
System resource contention
Application design problems
Queries or stored procedures that have long execution times

29. What are the authentication modes in SQL Server? – Windows mode and mixed mode (SQL & Windows).

SQL Server security model
To be able to access data from a database, a user must pass through two stages of authentication, one at the SQL Server level and the other at the database level. These two stages are implemented using Logins names and User accounts respectively. A valid login is required to connect to SQL Server and a valid user account is required to access a database.

Login: A valid login name is required to connect to an SQL Server instance. A login could be:
A Windows NT/2000 login that has been granted access to SQL ServerAn SQL Server login, that is maintained within SQL Server

30. Where do you think the users names and passwords will be stored in sql server?

SQL Server User names and Passwords are stored in Master DB in the syslogins table.

31. What is log shipping?

Log shipping is a term used to describe the process of taking a transaction log backup from a primary database, and restoring the transaction log backup on a secondary database.
to have a read-only copy of the primary database available on another server, in order to lighten the load on the primary server
to have multiple copies of the database available in different locations
to have a standby database ready in case of a service disruption to the primary database

32. Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot?

First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ——Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues.

33. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow?

First of all stop the sql services running and then we have to bring the server in single user mode and by applying the command sqlserver -m  whose exe is located in the directory C:\Program Files\Microsoft SQL Server\MSSQL\Binn  can rebuild the master database  rebuildm (rebuild.exe)command located at C:\Program Files\Microsoft SQL Server\80\Tools\Binn directory at cmd prompt.

34. Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take?

Step 1. Put SQL Server into Single User Mode
The first thing you will want to do is stop the SQL Sever Sevicer (sqlservr.exe) and the associated services (Agent, Full Text, Etc). There are a few ways to do this, but the easiest way would be to use the SQL Configuration Manager (Start->All Programs->Microsoft Sql Server 2005->Configuration Tools->Sql Server Configuration Manager). From this console you can manage the various SQL server services running on the machine. Right Click on each service listed and stop the service. The services are stopped, you can proceed to Step 2.
Step 2. Start the SQL server in Single User Mode
Open a command window and navigate to the folder where Sqlservr.exe resides (generally :\Program Files\Microsoft Sql Server\MSSQL.1\MSSQL\Binn). Run “sqlserver.exe -m”  to start the sql server from single user mode.
Step 3. Rebuild the system databases
In SQL 2005, the rebuildm.exe program is nto supported. To rebuild the master database you need to use the setup.exe found on the SQL 2005 installation media. To rebuild, use the following command “start /wait setup.exe /qn INSTANCENAME= REINSTALL=SQL_Engine REBUILDDATABASE=1 SAPWD=”. Please refere to Books on Line for compelete details on how to use Setup.exe.
Step 4. Restart the SQL Server Services in regular mode
End the command shell you started earlier. Ctrl-C to stop SQL server in single user mode, then close the command window. Go back to the Sql Server Configuration Manager and restart the SQL services.

35. What is BCP? When do we use it?

The bcp utility bulk copies data between an instance of Microsoft SQL Server and a data file in a user-specified format. The bcp utility can be used to import large numbers of new rows into SQL Server tables or to export data out of tables into data files.

E.g. BCP  [Database Name. Schema Name. Table Name]   { in | Out | Queryout}  “Datafile”  -t –c –S server Name –U user id –P password

36. What should we do to copy the tables, schema and views from one SQL Server to another?

We have to write some DTS packages for it and use Export Import Utility of database.

37. What is Catalog Views?

Catalog views return information that is used by the SQL Server Database Engine. Catalog Views are the most general interface to the catalog metadata and provide the most efficient way to obtain, transform, and present customized forms of this information. All user-available catalog metadata is exposed through catalog views.

38. What is PIVOT and UNPIVOT?

A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.
UNPIVOT table is reverse of PIVOT Table.

39. What is Filestream?

Filestream allows you to store large objects in the file system and have these files integrated within the database. It enables SQL Server based applications to store unstructured data such as documents, images, audios, videos etc. in the file system. FILESTREAM basically integrates the SQL Server Database Engine with New Technology File System (NTFS); it basically stores the data in varbinary (max) data type. Using this data type, the unstructured data is stored in the NTFS file system and the SQL Server Database Engine manages the link between the Filestream column and the actual file located in the NTFS. Using Transact SQL statements users can insert, update, delete and select the data stored in FILESTREAM enabled tables.

40. What is Dirty Read ?

A dirty read occurs when two operations say, read and write occurs together giving the incorrect or unedited data. Suppose, A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong so that is Dirty Read.

41. What are the four main query statements?

select,insert,update ,delete

42. What is a sub-query? When would you use one?

A sub query is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set.

43. What is a NOLOCK?

Do not issue shared locks and do not honor exclusive locks.When this option is in effect, it is possible to read an uncommitted transaction or a set of pages that are rolled back in the middle of a read. Dirty reads are possible. Only applies to the SELECT statement.
Advantage: applying nolock in select statement will increase concurrency and performance in fetching.
Disadvantage:it doesn’t consider the transaction scenario, even if the transaction is under process not yet committed or rollback

Begin tran
Insert into tablename Values (‘1′,’asdf’)
Select * from tablename with (nolock)

— it will display the table with inserted record. but the transaction is not completed, it can be rollback
So it became dirty read.

44. What are three SQL keywords used to change or set someone’s permissions?


45. What command do we use to rename a db?

sp_renamedb  ‘oldname’ , ‘newname’
If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode.

46. What is sp_configure commands and set commands?

Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.

47. What are the different types of replication? Explain.

The SQL Server having replication types are as follows:

48. Explain the replication types

Snapshot replication distributes data exactly as it appears at a specific moment in time and does not monitor for updates to the data. Snapshot replication is best used as a method for replicating data that changes infrequently or where the most up-to-date values (low latency) are not a requirement. When synchronization occurs, the entire snapshot is generated and sent to Subscribers.

Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data modifications are made at the Publisher, the individual transactions are captured and propagated to Subscribers.

Merge replication is the process of distributing data from Publisher to Subscribers, allowing the Publisher and Subscribers to make updates while connected or disconnected, and then merging the updates between sites when they are connected.

49. 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.

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

STUFF function 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 occurrence. Using this 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.

51. Using query analyzer, name 3 ways to get an accurate count of the number of records in a table?

SELECT * FROM table1


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

52. What is the basic functions for master, msdb, model, tempdb databases?

The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.

53. What are primary keys and foreign keys?

Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys and constraints. A table can have only one Primary key.

Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables.

54. What is data integrity? Explain constraints?

Data integrity is an important feature in SQL Server. When used properly, it ensures that data is accurate, correct, and valid. It also acts as a trap for otherwise undetectable bugs within applications.

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.

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.

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.

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.

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.

55. What are the properties of the Relational tables?

Relational tables have six properties:
Values are atomic.
Column values are of the same kind.
Each row is unique.
The sequence of columns is insignificant.
The sequence of rows is insignificant.
Each column must have a unique name.

56. 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

57. What is Identity?

Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers, the value of this cannot be controled. Identity/GUID columns do not need to be indexed.

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

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.

59. What is a table called, if it does not have 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 than do bulk of inserts and to restore those indexes after that.

60. 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.

61. How do you load large data to the SQL server database?

BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to Imports a data file into a database table or view in a user-specified format.

62. Can we rewrite subqueries into simple select statements or with joins?

Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to reproduce the result set without using a sub-query.

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

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

64. How to know which index a table is using?

SELECT table_name,index_name FROM user_constraints

65. How to copy the tables, schema and views from one SQL server to another?

Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets user extract, transform, and consolidate data from disparate sources into single or multiple destinations.

66. Which virtual table OR Magic table does a trigger use?

Inserted and Deleted.

67. List few advantages of Stored Procedure.

Stored procedure can reduced network traffic and latency, boosting application performance.
Stored procedure execution plans can be reused, staying cached in SQL Server’s memory, reducing server overhead.
Stored procedures help promote code reuse.
Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients.
Stored procedures provide better security to your data.

68. What is DataWarehousing?

Subject-oriented, meaning that the data in the database is organized so that all the data elements relating to the same real-world event or object are linked together;
Time-variant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time;
Non-volatile, meaning that data in the database is never over-written or deleted, once committed, the data is static, read-only, but retained for future reporting;
Integrated, meaning that the database contains data from most or all of an organization’s operational applications, and that this data is made consistent.

69. 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.

70. How do SQL server 2000 and XML linked? Can XML be used to access data?

You can execute SQL queries against existing relational databases to return results as XML rather than standard rowsets. These queries can be executed directly or from within stored procedures. To retrieve XML results, use the FOR XML clause of the SELECT statement and specify an XML mode of RAW, AUTO, or EXPLICIT.

OPENXML is a Transact-SQL keyword that provides a relational/rowset view over an in-memory XML document. OPENXML is a rowset provider similar to a table or a view. OPENXML provides a way to access XML data within the Transact-SQL context by transferring data from an XML document into the relational tables. Thus, OPENXML allows you to manage an XML document and its interaction with the relational environment.

71. 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 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.

72. What is user-defined function?

User-Defined function which is created by user for its uses in the coding. eg create function fn ;

73.  What kind of User-Defined Functions can be created?

There are three types of User-Defined functions in SQL Server:

Scalar User-Defined Function
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.

Inline Table-Value User-Defined Function
An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

74. 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 –> Port number.both on client and the server.

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

Windows mode and mixed mode (SQL & 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.

76. Where are SQL server users names and passwords are stored in sql server?

They get stored in master db in the sysxlogins table.

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

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

78. 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.

79. Can a stored procedure call itself or recursive stored procedure? How many level SP nesting 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.

80. What is @@ERROR?

The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there was no error, @@ERROR returns zero. Because @@ERROR is reset after each Transact-SQL statement, it must be saved to a variable if it is needed to process it further after checking it.

81. What is Raiseerror?

Stored procedures report errors to client applications via the RAISERROR command. RAISERROR doesn’t change the flow of a procedure; it merely displays an error message, sets the @@ERROR automatic variable, and optionally writes the message to the SQL Server error log and the NT application event log.

82. 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 can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval.

83. What is the difference between a local and a global variable?

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.
A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

84. What is difference between DELETE & 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.

TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
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.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
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.
TRUNCATE can not be Rolled back using logs.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.

DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
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.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back using logs.
DELETE is DML Command.
DELETE does not reset identity of the table.

85. What are types of sub-queries?

Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.

86. What is cursors?

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.
In order to work with a cursor we need to perform some steps in the following order:

Declare cursor
Open cursor
Fetch row from the cursor
Process fetched row
Close cursor
Deallocate cursor

87. What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC – To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP – Checks all tables file group for any damage.

88. What’s the difference between a primary key and a unique key?

Both primary key and unique enforce 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.

89. 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.

90. What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

91. What is normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

92. What are different normalization forms?

1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF: Optimal Normal Form
a model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form
a model free from all modification anomalies.

93. What is the difference between HAVING clause and the WHERE clause?

WHERE applies to rows, HAVING applies to summarized rows (summarized with GROUP BY)
Having can used only with the select statement .it is typically used with group by clause. when it is used without group by it work like where clause

94. What is referential integrity? What are the advantages of it?

Referential integrity is usually enforced by the combination of a primary key or candidate key (alternate key) and a foreign key. For referential integrity to hold, any field in a table that is declared a foreign key can contain only values from a parent table’s primary key or a candidate key.

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

exec xp_msver
select @@version

96. check the performance of a query and how do you optimize it?
A query execution plan outlines how the SQL Server query optimizer actually ran (or will run) a specific query. This information if very valuable when it comes time to find out why a specific query is running slow.

There are several different ways to view a query’s execution plan. They include:
From within Query Analyzer is an option called “Show Execution Plan” (located on the Query drop-down menu). If you turn this option on, then whenever you run a query in Query Analyzer, you will get a query execution plan (in graphical format) displayed in a separate window.
If you want to see an execution plan, but you don’t want to run the query, you can choose the option “Display Estimated Execution Plan” (located on the Query drop-down menu). When you select this option, immediately an execution plan (in graphical format) will appear. The difference between these two (if any) is accountable to the fact that when a query is really run (not simulated, as in this option), current operations of the server are also considered. In most cases, plans created by either method will produce similar results.
When you create a SQL Server Profiler trace, one of the events you can collect is called: MISC: Execution Plan. This information (in text form) shows the execution plan used by the query optimizer to execute the query.
From within Query Analyzer, you can run the command SET SHOWPLAN_TEXT ON. Once you run this command, any query you execute in this Query Analyzer sessions will not be run, but a text-based version of the query plan will be displayed. If the query you are running uses temp tables, then you will have to run the command, SET STATISTICS PROFILE ON before running the query.

97. Difference between sql server 2000 and sql server 2005?
In SQL Server 2000 the Query Analyzer and Enterprise Manager are separate,whereas in SQL Server 2005 both were combined as Management Studio.
In Sql 2005,the new datatype XML is used,whereas in Sql 2000 there is no such datatype
In Sql server 2000 we can create 65,535 databases,whereas in Sql server 2005 2(pow(20))-1 databases can be created.
in stored procedure we can write try catch statement in 2005 not in 2000

98. SQL Server 2008 features:
1. Intellisense in the SQL Server Management Studio (SSMS).
This has been previously possible in SQL Server 2000 and 2005 with Intellisenseuse of 3rd party add-ins like SQL Prompt ($195). But these tools are a horrible hack at best
(e.g. they hook into the editor window and try to interpret what the application is doing).
Built-in intellisense is huge – it means new people can easily learn the database schema as they go.
2. Processing of delimited strings. This is awesome and I could have used this feature…well, always.
Currently, we pass in delimited strings in the following manner:
exec sp_MySproc ‘murphy,35;galen,31;samuels,27;colton,42’
3. Filtered Indexes.
4. C like math syntax. SET @i += 5. Enough said. They finally let a C# developer on the SQL team.
5. Auditing.

99. Can UNIQUE KEY in SQL Server 2005 have two or more NULL?
SQL server 2005 can not have more then one NULL, because in SQL server 2005 every null is having same value. UNIQUE KEY in ORACLE can have more then one NULL values as every NULL in ORACLE is having unique value.

100. Error handling in Programing of Sql server.
From SQL Server 2005 provides structured exception handing through TRY CATCH block as other programming language like JAVA, C# etc.

Begin try
end try
begin catch
end catch

Error Handling Function:
ERROR_NUMBER() returns the number of the error.
ERROR_SEVERITY() returns the severity.
ERROR_STATE() returns the error state number.
ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
ERROR_LINE() returns the line number inside the routine that caused the error.
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 times.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.