sql server interview questions 2

14
SQL Server Interview Questions What is DESCRIBE command in SQL Server 2005? What is its purpose? How to use it? DESCRIBE is used to see table structure. In SQL server 2005 we can use sp_columns, sp_tables or sp_help. sp_columns will show list of columns and its details in table. sp_tables will show list of tables in the database How do you optimize stored procedures in SQL Server 2005? 1. Use as much as possible WHERE clause filters. Where Clause is the most important part for optimization 2. Select only those fields which really require. 3. Joins are expensive in terms of time. Make sure that use all the keys that relate the two tables together and don't join to unused tables, always try to join on indexed fields. The join type is important as well (INNER, OUTER). What are the properties of the Relational tables? Relational tables have six properties 1. Values are atomic. 2. Column values are of the same kind. 3. Each row is unique. 4. The sequence of columns is insignificant. 5. The sequence of rows is insignificant. 6. Each column must have a unique name. Values Are Atomic Columns in a relational table are not repeating group or arrays. Such tables are referred to as being in the "first normal form" (1NF). The atomic value property of relational

Upload: hemant026

Post on 12-Nov-2014

1.261 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SQL Server Interview Questions 2

SQL Server Interview Questions

What is DESCRIBE command in SQL Server 2005? What is its purpose? How to use it? DESCRIBE is used to see table structure. In SQL server 2005 we can use sp_columns, sp_tables or sp_help.

sp_columns will show list of columns and its details in table. sp_tables will show list of tables in the database

How do you optimize stored procedures in SQL Server 2005? 1. Use as much as possible WHERE clause filters. Where Clause is the most important part for optimization 2. Select only those fields which really require. 3. Joins are expensive in terms of time. Make sure that use all the keys that relate the two tables together and don't join to unused tables, always try to join on indexed fields. The join type is important as well (INNER, OUTER).

What are the properties of the Relational tables? Relational tables have six properties 1. Values are atomic. 2. Column values are of the same kind. 3. Each row is unique. 4. The sequence of columns is insignificant. 5. The sequence of rows is insignificant. 6. Each column must have a unique name.

Values Are Atomic Columns in a relational table are not repeating group or arrays. Such tables are referred to as being in the "first normal form" (1NF). The atomic value property of relational tables is important because it is one of the cornerstones of the relational model. The key benefit of the one value property is that it simplifies data manipulation logic.

Column Values Are of the Same Kind All values in a column come from the same set of values or domain. For example, a Product_Price column contains only specific to product price. It never contains other information such as comments, status flags, or even weekly salary. It simplifies data access because developers and users can be certain of the type of data contained in a given column. It also simplifies data validation. Because all values are from the same domain, the domain can be defined and enforced with the Data Definition

Page 2: SQL Server Interview Questions 2

Language (DDL) of the database software.

Each Row is Unique Each unique row ensures that no two rows in a relational table are identical; there is at least one column, or set of columns, the values of which uniquely identify each row in the table. Such columns are called primary keys. This property guarantees that every row in a relational table is meaningful and that a specific row can be identified by specifying the primary key value.

The Sequence of Columns is Insignificant Ordering of the columns in the relational table has no meaning. Columns can be retrieved in any order and in various sequences. The benefit of this property is that it enables many users to share the same table without concern of how the table is organized. It also permits the physical structure of the database to change without affecting the relational tables.

The Sequence of Rows is Insignificant This property is analogous the one above but applies to rows instead of columns. The main benefit is that the rows of a relational table can be retrieved in different order and sequences. Adding information to a relational table is simplified and does not affect existing queries.

Each Column Has a Unique Name Because the sequence of columns is insignificant, columns must be referenced by name and not by position. In general, a column name need not be unique within an entire database but only within the table to which it belongs.

An automatic commit ocurrs under the following circumstances? NOTE: This is objective type question, Please click question title for correct answer.

Some more differences related to Truncate and Delete? 1) Delete keep the lock over each row where Truncate keps the lock on table not on all the row 2) Counter of the Identity column is reset in Truncate where it is not reset in Delete. 3) Trigger is not fired in Truncate where as trigger is fired in Delete.

What is the difference between DELETE and TRUNCATE? In TRUNCATE we can not rollback.. In DELETE we can rollback

Page 3: SQL Server Interview Questions 2

What are the types of triggers and how the sequence of firing in text item? Triggers can be classified as Key Triggers, Mouse Triggers ,Navigational Triggers. Key Triggers :: Key Triggers are fired as a result of Key action.e.g :: Key-next-field, Key-up,Key-Down Mouse Triggers :: Mouse Triggers are fired as a result of the mouse navigation.e.g. When-mouse-button-presed,when-mouse-doubleclicked,etc Navigational Triggers :: These Triggers are fired as a result of Navigation. E.g : Post-Text-item,Pre-text-item. We also have event triggers like when ?Vnew-form-instance and when-new-block-instance. We cannot call restricted procedures like go_to(??my_block.first_item??) in the Navigational triggers But can use them in the Key-next-item. The Difference between Key-next and Post-Text is an very important question. The key-next is fired as a result of the key action while the post text is fired as a result of the mouse movement. Key next will not fire unless there is a key event. The sequence of firing in a text item are as follows :: a) pre - text b) when new item c) key-next d) when validate e) post text

which Caluse returns only one copy of each set of duplicate rows selected? NOTE: This is objective type question, Please click question title for correct answer.

What are joins in SQL Server? Using joins, we can get the data from two or more tables based on logical condition between the tables. Use following article to know about all types of joins http://www.techbubbles.com/sql-server/joins-in-sql-server/

What is the use of COALESCE in SQL Server? Coalesce returns the first non-null expression among its arguments. Lets say we have to return a non-null from more than one column, then we can use COALESCE function.

SELECT COALESCE(hourly_wage, salary, commission) AS 'Total Salary' FROM wages

Page 4: SQL Server Interview Questions 2

In this case, If hourly_wage is not null and other two columns are null then hourly_wage will be returned. If hourly_wage, commission are null and salary is not null then salary will be returned. If commission is non-null and other two columns are null then commission will be returned.

What is OPENXML in SQL Server? OPENXML can parse the xml data in SQL server very efficiently in SQL Server. OpenXML primarily gives the ability to insert XML data to the relational database, however we can query the data too using OpenXML. We need to specify the path of the xml element using xpath.

Syntax:

DECLARE @index int

DECLARE @xmlString varchar(8000)

SET @xmlString ='<Persons>

<Person id="1">

<Name>Mohan</Name>

<PhoneNo>34343</PhoneNo>

</Person>

<Person id="2">

<Name>Sita</Name>

<PhoneNo>23432</PhoneNo>

</Person>

</Persons>'

EXEC sp_xml_preparedocument @index OUTPUT, @xmlString

SELECT *

FROM OPENXML (@index, 'Persons/Person')

WITH (id Varchar(10), Name varchar(100) 'Name' , PhoneNo Varchar(50) 'PhoneNo')

Page 5: SQL Server Interview Questions 2

EXEC sp_xml_removedocument @index

The above code snippet will give following result. --------------------------------- 1 Mohan 34343 2 Sita 23432 ---------------------------------

How to return XML in SQL Server? We can use FOR XML statement at the end of the query to return xml data from the SQL Server. select * from mytable for xml auto

There are three mode of returning XML and they are auto, raw and explicit

For more details see http://www.sqljunkies.ddj.com/Article/296D1B56-8BDD-4236-808F-E62CC1908C4E.scuk

What is #temp table and @table variable in SQL Server? #temp Table (Temporary Table)

temp table is a temporary table that is generally created to store session specific data. Its kind of normal table but it is created and populated on disk, in the system database tempdb — with a session-specific identifier packed onto the name, to differentiate between similarly-named #temp tables created from other sessions.

The data in this #temp table (in fact, the table itself) is visible only to the current scope. Generally, the table gets cleared up automatically when the current procedure goes out of scope, however, we should manually clean up the data when we are done with it.

Syntax:

-- create temporary table

CREATE TABLE #myTempTable (

AutoID int,

MyName char(50) )

Page 6: SQL Server Interview Questions 2

-- populate temporary table

INSERT INTO #myTempTable (AutoID, MyName )

SELECT AutoID, MyName

FROM myOriginalTable

WHERE AutoID <= 50000

-- Drop temporary table

drop table #myTempTable

@table variable table variable is similar to temporary table except with more flexibility. It is not physically stored in the hard disk, it is stored in the memory. We should choose this when we need to store less 100 records.

Syntax:

DECLARE @myTable TABLE (

AutoID int,

myName char(50) )

INSERT INTO @myTable (AutoID, myName )

SELECT YakID, YakName

FROM myTable

WHERE AutoID <= 50

We don't need to drop the @temp variable as this is created inside the memory and automatically disposed when scope finishes.

Page 7: SQL Server Interview Questions 2

What is cursor in SQL Server? A cursor is a set of rows together with a pointer that identifies a current row.

In other word, Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, its like recordset in the ASP and visual basic.

Typical syntax of cursor is

DECLARE @fName varchar(50), @lName varchar(50)

DECLARE cursorName CURSOR -- Declare cursor

LOCAL SCROLL STATIC

FOR

Select firstName, lastName FROM myTable

OPEN cursorName -- open the cursor

FETCH NEXT FROM cursorName

INTO @fName, @lName

PRINT @fName + ' ' + @lName -- print the name

WHILE @@FETCH_STATUS = 0

BEGIN

FETCH NEXT FROM cursorName

INTO @fName, @lName

PRINT @fName + ' ' + @lName -- print the name

END

CLOSE cursorName -- close the cursor

DEALLOCATE cursorName -- Deallocate the cursor

To know more about cursor, see http://www.mssqlcity.com/Articles/General/UseCursor.htm

Page 8: SQL Server Interview Questions 2

Difference between Primary key Constraint and Unique key Constraint in SQL Server. Unique Key Constraint: The column values should retain uniqueness. It allows null values in the column. It will create non-clustered index by default. Any number of unique constraints can be added to a table.

Primary Key Constraint: Primary key will create column data uniqueness in the table. It Wont allow Null values. By default Primary key will create clustered index. Only one Primary key can be created for a table. Multiple columns can be consolidated to form a single primary key.

How to change Database name in SQL Server? Use following code

Supported in SQL Server 2000 and 2005 exec sp_renamedb "test", "test1"

Supported in SQL Server 2005 and later version ALTER Database "test1" Modify Name="test"

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

Difference Between Implict Transaction And Explict Transaction Implicit Transaction is the auto commit. There is no beginning or ending of the transaction.

Explicit Transaction has the beginning, ending and rollback of transactions with the command Begin Transaction Commit Transaction and Rollback Transation In the explicit transaction, if an error occurs in between we can rollback to the begining of the transaction which cannot be done in implicit transaction.

Page 9: SQL Server Interview Questions 2

What's the maximum size of a row? 8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

What is a transaction and what are ACID properties? A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also 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. Of course.

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.

How do you 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.

Page 10: SQL Server Interview Questions 2

How to join two tables in Sql Server? you can write following sql statement

select category.*, categoryparent.categoryparent from category, categoryparent where category.categoryparentid = categoryparent.autoid

I am assuming here that category.categoryparentid (foreign key) is the value of categoryparent.autoid (primary key).

What Primary key and Unique key? Primary key are used with Foreign key to enforce referential integrity. Unique constraints allows nulls to be inserted into the field. But there can't be null in Primary key.

What is the difference between Truncate and Delete? Delete statement removes rows of a table one by one & delete triggers on that table fires. But Truncate removes all rows by deallocating the data pages assigned to the table & only these deallocation are recorded in the transaction log.

What is constraints? SQL Server users constraints to enforce limitations on the data that can be entered into a particular column in table. There are following types of constraints.

Unique, Default, Check, Primary Key, Foreign Key, Not Null.

How many types of triggers are there? There are four types of triggers.

1. Insert 2. Delete 3. Update 4. Instead of

Page 11: SQL Server Interview Questions 2

What is Clustered & Non-Clustered Index? Clustered Index: Clustered index physically rearrange the data that users inserts in your tables. It is nothing but a dictionary type data where actual data remains.

Non-Clustered Index: It Non-Clustered Index contains pointers to the data that is stored in the data page. It is a kind of index backside of the book where you see only the reference of a kind of data.

What is trigger? Triggers allows us to execute a batch of SQL code when either an insert, update or delete command is executed against a specific table.

Triggers are special types of stored procedures that are defined to execute automatically in place of or after data modifications. They can be executed automatically on the insert, delete and update operation.