Search This Blog

Tuesday, October 11, 2011

Best Sql Server Interview Questions 2000/2005/2008 : Part 2


Part 1
Part 3

1.       What’s difference between “Optimistic” and “Pessimistic”   locking?

In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other user’s can only view the data when there is pessimistic locking.

In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking practically. Now a days in browser based application it is very common and having pessimistic locking is not a practical solution.

2.      When is the use of update_statistics command?

This command is basically used when a large amount of data is processed. If a large amount of deletions, modifications 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.

3.       What is the difference between a HAVING CLAUSE and a WHERE
      CLAUSE?
You can use Having Clause with the GROUP BY function in a query and WHERE Clause is applied to each row before, they are part of the GROUP BY function in a query.

4.      What is Connection Pooling and why it is Used?

To minimize the cost of opening and closing connections, ADO.NET uses an optimization technique called connection pooling.
The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

5.      Types of Sub-query

·         Single-row sub-query, where the sub-query returns only one row.
·         Multiple-row sub-query, where the sub-query returns multiple rows, and
·         Multiple column sub-query, where the sub-query returns multiple columns
Note: A sub-query can’t contain an ORDER BY clause; however sub-query can use                           ORDER BY when used with TOP clause.

6.      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 very slowly.

7.      What is an SQL Server Agent?

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

8.      Can a Stored Procedure call itself or a Recursive Stored Procedure? How many levels of SP nesting are possible?
Yes. You can nest stored procedures and managed code references up to 32 levels.
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. The nesting level increases by one when the called stored procedure or managed code reference begins execution and decreases by one when the called stored procedure or managed code reference completes execution. Attempting to exceed the maximum of 32 levels of nesting causes the whole calling chain to fail. The current nesting level for the stored procedures in execution is stored in the @@NESTLEVEL function.

9.      What is the Difference between a Local and a Global Temporary Table?
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 accessible across the connections. Once the connection where original global table is declared dropped this becomes unavailable.

10.  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), where 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 is used to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), every incidence of search_string found in the string_expression will be replaced with replacement_string.

11.  What is the difference between UNION and UNION ALL?
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between UNION and UNION ALL is that UNION ALL will not eliminate duplicate rows; instead it just pulls all rows from all the tables fitting your query specifics and combines them into a table.

12.  What is B-Tree?
The database server uses a B-tree structure to organize index information. B-Tree generally has following types of index pages or nodes:
·         Root node: A root node contains node pointers to only one branch node.
·         Branch nodes: A branch node contains pointers to leaf nodes or other branch nodes, which can be two or more.
·         Leaf nodes: A leaf node contains index items and horizontal pointers to other leaf nodes, which can be many. 

13.  What are the Advantages of Using Stored Procedures?
·         Stored procedure can reduced network traffic and latency, boosting application performance.
·         Stored procedure execution plans can be reused; they 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. 

14.  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 the indexes from table and then do bulk of Inserts and restore those indexes after that.

15.  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 that Microsoft provides to add it as a linked server to the SQL Server group.

16.  What is BCP? When is it used?
BCP or BulkCopy is a tool used to copy huge amounts of data from tables and views. BCP does not copy the complete structures from source to destination. BULK INSERT command helps to import a data file into a database table or view in a user-specified format.

17.  What Command do we Use to Rename a db, a Table and a Column?
To Rename db
sp_renamedb ‘oldname’ , ‘newname
If someone is using db it will not accept sp_renamedb. In that case, first bring db to single user mode using sp_dboptions. Use sp_renamedb to rename the database. Use sp_dboptions to bring the database to multi-user mode.
e.g.
USE MASTER;
GO
EXEC sp_dboption YourDbName, 'Single User', True
GO
EXEC sp_renamedb 'YourDbName',' YourDbName_New'
GO
EXEC sp_dboption YourDbName, 'Single User', False
GO
To Rename Table
We can change the table name using sp_rename as follows:
sp_rename 'oldTableName' 'newTableName'
GO
To rename Column
The script for renaming any column is as follows:
sp_rename 'TableName.[OldcolumnName]', 'NewColumnName', 'Column'
GO

18.  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 it 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.
Within the Query Analyzer, there is an option called “Show Execution Plan” (in the Query drop-down menu). If this option is turned on, it will display query execution plan in a separate window when the query is ran again.

19.  What is the difference between CHAR and VARCHAR Datatypes?
VARCHARS are variable length strings with a specified maximum length. If a string is less than the maximum length, then it is stored verbatim without any extra characters, e.g. names and emails. CHARS are fixed-length strings with a specified set length. If a string is less than the set length, then it is padded with extra characters, e.g. phone number and zip codes. For instance, for a column which is declared as VARCHAR(30) and populated with the word ‘SQL Server,’ only 10 bytes will be stored in it. However, if we have declared the column as CHAR(30) and populated with the word ‘SQL Server,’ it will still occupy 30 bytes in database.

20.  What is the Difference between VARCHAR and VARCHAR (MAX) Data types?
VARCHAR stores variable-length character data whose range varies up to 8000 bytes; varchar(MAX) stores variable-length character data whose range may vary beyond 8000 bytes and till 2 GB. TEXT datatype is going to be deprecated in future versions, and the usage of VARCHAR (MAX) is strongly recommended instead of TEXT datatypes.
If you know the max length of characters to be entered go for varchar (length) otherwise go for VARCHAR (MAX).

21.  What is the Difference between VARCHAR and NVARCHAR data types?
In principle, they are the same and are handled in the same way by your application. The only difference is that NVARCHAR can handle Unicode characters, allowing you to use multiple languages in the database (Arabian, Chinese, etc.). NVARCHAR takes twice as much space when compared to VARCHAR.
Use NVARCHAR only if you are using foreign languages.

22.  Which are the Important Points to Note when Multilanguage Data is Stored in a Table?
There are two things to keep in mind while storing unicode data. First, the column must be of unicode data type (nchar, nvarchar, ntext). Second, the value must be prefixed with N while insertion.
For example: INSERT INTO table (Hindi_col) values (N’hindi data’)

23.  How to Optimize Stored Procedure Optimization?
·         Include SET NOCOUNT ON statement.
·         Use schema name with object name.
·         Do not use the prefix “sp_” in the stored procedure name.
·         Use IF EXISTS (SELECT 1) instead of (SELECT *).
·         Use the sp_executesql stored procedure instead of the EXECUTE statement.
·         Try to avoid using SQL Server cursors whenever possible.
·         Keep the Transaction as short as possible.
·         Use TRY-Catch for error handling. 
24.      How to Find Out the List Schema Name and Table Name for the Database?
We can use following script:
SELECT '['+ SCHEMA_NAME (schema_id) +'].['+name+']' AS SchemaTable
FROM sys.tables

25.      What is CHECKPOINT Process in the SQL Server?
CHECKPOINT process writes all dirty pages for the current database to disk. Dirty pages are data pages that have been entered into the buffer cache and modified, but not yet written to disk.

No comments:

Popular Posts