Some Sql Server Interview Questions
* Difference between Set and Select
Ans:
1) Set is a ANSI standard for variable assignment.
Select is a Non-ANSI standard when assigning variables.We can assign only one variable at a time
2) We can assign 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
* What is Network Packet Size in SQL
Ans:
NPS(Network Packet Size) is the size of the TDS (tabular data stream) packets used to communicate between your applications and your relational database engine and default packet size is 4 kilobytes and its manily depends on network packet size configuration option.
* How many different locks in SQL SERVER
Ans:
(1)Intent
(2)shared
(3)Update
(4)Exclusive
(5)Schema
(6)Bulk Update
* Diffrence between temp table and table variable
Ans:
(1)Temp Tables are created in the SQL Server TEMPDB database and therefore require more IO resources and locking. Table Variables and Derived Tables are created in memory.
(2)Temp Tables will generally perform better for large amounts of data that can be worked on using parallelism whereas Table Variables are best used for small amounts of data (I use a rule of thumb of 100 or less rows) where parallelism would not provide a significant performance improvement.
(3)You cannot use a stored procedure to insert data into a Table Variable or Derived Table. For example, the following will work: INSERT INTO #MyTempTable EXEC dbo.GetPolicies_sp whereas the following will generate an error: INSERT INTO @MyTableVariable EXEC dbo.GetPolicies_sp.
(4)Derived Tables can only be created from a SELECT statement but can be used within an Insert, Update, or Delete statement.
(5) In order of scope endurance, Temp Tables extend the furthest in scope, followed by Table Variables, and finally Derived Tables.
* What is Cursor
Ans:
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
* Write some disadvantage of Cursor
Ans:
Cursor plays there row quite nicely but although there are some disadvantage of Cursor . Because we know cursor doing roundtrip it will make network line busy and also make time consuming methods. First of all select query gernate output and after that cursor goes one by one so roundtrip happen.Another disadvange of cursor are ther are too costly because they require lot of resources and temporary storage so network is quite busy.
* Can you tell me the difference between DELETE and TRUNCATE commands
Ans:
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.
Differences between varchar and nvarchar in SQL Server
=>SQL Server 2000 and SQL Server 7, a row cannot exceed 8000 bytes in size. This means that a VARBINARY column can only store 8000 bytes (assuming it is the only column in a table), a VARCHAR column can store up to 8000 characters and an NVARCHAR column can store up to 4000 characters (2 bytes per unicode character). This limitation stems from the 8 KB internal page size SQL Server uses to save data to disk.
To store more data in a single column, you needed to use the TEXT, NTEXT, or IMAGE data types (BLOBs) which are stored in a collection of 8 KB data pages that are separate from the data pages that store the other data in the same table. These data pages are arranged in a B-tree structure. BLOBs are hard to work with and manipulate. They cannot be used as variables in a procedure or a function and they cannot be used inside string functions such as REPLACE, CHARINDEX or SUBSTRING. In most cases, you have to use READTEXT, WRITETEXT, and UPDATETEXT commands to manipulate BLOBs.
To solve this problem, Microsoft introduced the VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) data types in SQL Server 2005. These data types can hold the same amount of data BLOBs can hold (2 GB) and they are stored in the same type of data pages used for other data types. When data in a MAX data type exceeds 8 KB, an over-flow page is used. SQL Server 2005 automatically assigns an over-flow indicator to the page and knows how to manipulate data rows the same way it manipulates other data types. You can declare variables of MAX data types inside a stored procedure or function and even pass them as variables. You can also use them inside string functions.
The broad range of data types in SQL Server can sometimes throw people through a loop, especially when the data types seem to be highly interchangeable. Two in particular that constantly spark questions are VARCHAR and NVARCHAR: what’s the difference between the two, and how important is the difference?
VARCHAR is an abbreviation for variable-length character string. It’s a string of text characters that can be as large as the page size for the database table holding the column in question. The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters. This in turn limits the maximum size of a VARCHAR to 8,000 bytes.
The “N” in NVARCHAR means uNicode. Essentially, NVARCHAR is nothing more than a VARCHAR that supports two-byte characters. The most common use for this sort of thing is to store character data that is a mixture of English and non-English symbols — in my case, English and Japanese.
The key difference between the two data types is how they’re stored. VARCHAR is stored as regular 8-bit data. But NVARCHAR strings are stored in the database as UTF-16 — 16 bits or two bytes per character, all the time — and converted to whatever codepage is being used by the database connection on output (typically UTF-8). That said, NVARCHAR strings have the same length restrictions as their VARCHAR cousins — 8,000 bytes. However, since NVARCHARs use two bytes for each character, that means a given NVARCHAR can only hold 4,000 characters (not bytes) maximum. So, the amount of storage needed for NVARCHAR entities is going to be twice whatever you’d allocate for a plain old VARCHAR.
Because of this, some people may not want to use NVARCHAR universally, and may want to fall back on VARCHAR — which takes up less space per row — whenever possible.
Parameter Sniffing and OPTIMZE FOR
Parameter Sniffing refers to a process whereby SQL Server’s execution environment “sniffs” the parameter values during first invocation, and passes it along to the query optimizer so that they can be used to generate optimal query execution plans.
While parameter sniffing is certainly a powerful feature, it can cause problems when a procedure’s plan happens to have been kicked out of the procedure cache (or was never in it) just prior to the procedure being called with atypical parameter values. This can result in a plan that is skewed toward atypical use, one that is not optimal when called with typical values. Since, once cached, a query plan can be reused for parameter values that vary widely, the ideal situation is to have a plan in the cache that covers the typical usage of the procedure as much as possible. If a plan makes it into the cache that is oriented toward atypical parameter values, it can have a devastating effect on performance when executed with typical values.
Click here to read full article.
Update data in one table with data from another table
How to update more than one column in a table with values
from columns in another table and explains how to do it in the three RDBMS that we support.
Table Structures and values:
TableA has four columns: a, b, c, d (a is the primary key column)
TableB has five columns: a1, b1, c1, d1, e1 (a1 and b1 together constitute the primary key for this table)
The foreign key relationship between the two tables is based on A.a = B.a1
The data in these 2 tables is as follows:
I. TableA
a b c d
1 x y z
2 a b c
3 t x z
II. TableB
a1 b1 c1 d1 e1
1 x1 y1 z1 40
2 a1 b1 c1 50
The requirement is to write a SQL to update columns b, c and d in TableA from the columns b1, c1 and d1 from TableB where-ever the join condition satisfies and e1 > 40 in TABLEB.
SQL Server:
UPDATE TABLEA
SET b = TABLEB.b1,
c = TABLEB.c1,
d = TABLEB.d1
FROM TABLEA, TABLEB
WHERE TABLEA.a = TABLEB.a1
AND TABLEB.e1 > 40
GO
Note: This is an extension in SQL Server i.e. the FROM clause – it does make it simple to understand and is a nice feature.
Results after the update:
a b c d
————————————
1 x y z
2 a1 b1 c1
3 t x z
NOTE:
It is very important to make sure that your where clause for the update statement is correct since
that is what identifies the records that the update statement is going to qualify and do the update upon.
If it is incorrect, then you can get wrong results. The reason I am mentioning this is
because I have seen people write wrong where clauses and then wondering what went wrong
because they specified the correct condition in the SET clause.
In the above example,
if the Where condition was omitted, the other record’s columns would be updated to NULL value
and this will be the final result set:
a b c d
————————————
1 Null Null Null
2 a1 b1 c1
3 Null Null Null
–
happy programming
Ten Common SQL Programming Mistakes
Without further ado, here is the list:
- NULLs and the NOT IN predicate
- Functions on indexed columns in predicates
- Incorrect subquery column
- Data type mismatch in predicates
- Predicate evaluation order
- Outer joins and placement of predicates
- Subqueries that return more than one value
- Use of SELECT *
- Scalar user-defined functions
- Overuse of cursors
The examples are presented using SQL Server’s Transact-SQL dialect, but most of the concepts are valid in any SQL implementation.
Read full article here
–
Happy Programming
EXISTS or COUNT(*) Which Do You Use To Check How Many Rows There Are?
Do you use this
IF (SELECT COUNT(*) FROM SomeTable
WHERE SomeColumn = SomeValue ) > 0
Or do you use this
IF EXISTS (SELECT * FROM SomeTable WHERE SomeColumn = SomeValue )
If you answered COUNT(*) then maybe you should take a look these two articles
Andrew Kelly has a nice post on SQLBlog
http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx
Matija Lah has a good post on his snaps & snippets blog
http://milambda.blogspot.com/2006/10/exists-or-not-exists-that-is-question.html
How do I get the IDENTITY / AUTONUMBER value for the row I inserted?
To get the indentity value of table we can use any of these:
1) INDENT_CURRENT : – IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
SELECT IDENT_CURRENT(’tablename’):- It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns theidentity value generated for a specific table in any session and any scope.
2) @@IDENTITY :- @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SELECT @@IDENTITY :- It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get theidentity that was created last, even if it was the trigger that created it.
3) SCOPE_IDENTITY :- SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.
SELECT SCOPE_IDENTITY() :- It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a userdefined function.
Examaple of each:
Create Table #Table
(
Id int identity(1,1),
[name] varchar(10)
)
insert into #Table
select ‘P’
insert into #Table
select ‘S’
insert into #Table
select ‘G’
insert into #Table
select ‘PP’
select * From #Table
Select @@Identity As InsertId,IDENT_CURRENT(‘#Table’) As InsertId,SCOPE_IDENTITY() As InsertId
Drop table #Table
——————————————
Note : To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.
——————————————
Happy Programming…
What are the difference between DDL, DML and DCL commands
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
* CREATE – to create objects in the database
* ALTER – alters the structure of the database
* DROP – delete objects from the database
* TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed
* COMMENT – add comments to the data dictionary
* RENAME – rename an object
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
* SELECT – retrieve data from the a database
* INSERT – insert data into a table
* UPDATE – updates existing data within a table
* DELETE – deletes all records from a table, the space for the records remain
* MERGE – UPSERT operation (insert or update)
* CALL – call a PL/SQL or Java subprogram
* EXPLAIN PLAN – explain access path to data
* LOCK TABLE – control concurrency
DCL
Data Control Language (DCL) statements. Some examples:
* GRANT – gives user’s access privileges to database
* REVOKE – withdraw access privileges given with the GRANT command
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
* COMMIT – save work done
* SAVEPOINT – identify a point in a transaction to which you can later roll back
* ROLLBACK – restore database to original since the last COMMIT
* SET TRANSACTION – Change transaction options like isolation level and what rollback segment to use
-
Archives
- April 2011 (1)
- May 2010 (1)
- April 2010 (1)
- February 2010 (3)
- January 2010 (5)
- December 2009 (6)
- November 2009 (13)
- October 2009 (10)
- September 2009 (6)
- August 2009 (7)
- July 2009 (7)
- June 2009 (3)
-
Categories
-
RSS
Entries RSS
Comments RSS