SlideShare a Scribd company logo
1 of 37
Database
1.What is DBMS?
A.DBMS stands for database management system. It is collection of program that
enables user to create and maintain a database.
2.What is Database?
A. It is collection of information that is organized.So that it can be easily
accessed,managed and updated.
2.What is RDBMS?
A.RDBMS are the database management system which use to maintain data records
and indices in the table.
3.What are the ACID properties?
A.ACID properties takes grantee for all the database transactions to accomplish all
tasks.(applies when modifying a database)
Atomicity:-Either all or none,eg:our app is inserting 30 records and in between problem
occurs at the point of 12 records.In this state transaction will rollback so this will be
either all or none.
Consistency:-Ensures that only valid data following all rules and constraints is written in
the database.[ATM PIN:Incorrect]. Whatever data is going to insert they all should be
validated by defining rules and ensure that there are no invalid data is going to insert in
database so this way it will manage consistency of the database. In any case running
transaction violate rule at that same time entire transaction will be a rollback.
Isolation:-make sure two transaction is unaware of each other
In one shop seller is selling items very fast and due to this number of items is also
decreasing in stocks and at other side one person is also adding new items in stocks.
Here, this both transactions is different and totally unaware of another. These
properties ensure that one transaction is not interrupted by another transaction. (no
two documents get mixed up while printing)
Durability:-committed data stored forever.
Application inserted 30 records in one transaction and this transaction is completed and
committed successfully in the database that means this record persist forever in
database until and unless it’s not deleted by any application users or database users.
4.What is Normalization?
A.The process of organizing data to minimize redundancy.Usually dividing a db into two
or more table and defining relationship betwn the tables.Add, delete, update can be
done in one table and then propogate through the rest of the DB.
5.What is D-normalization and when do we need it?
D-normalization is used to speed up the read performance (data retrieval) of a
database by adding a redundant data.We need when the application is read intensive
i.e under heavy read load.
6.What are the different Normal Forms?
1NF:Eliminate repeating groups
2NF:-Eliminate Redundant Data
3NF:-Eliminate columns not dependent on Key.
7.Why we use normalization and denormalization. which is the better techniques?
A.Pros and Cons of normalization:
1.It is used basically under the condition where the app is write intensive and the write-
load is more than the read-load.
2.Updates,Inserts are faster bcz data is located into single place and there are no
duplicates.
3.Select will simple if there are fetched from single table or else it would be slow down
because of joins.
Pros and Cons of De-normalization:
1.It is used basically under the condition where the app is only read intensive.
2.The data is same table so there is no need for any joins. hence the select is very fast.
3.But bcz the data is duplicate , the update and inserts become complex and costly.
Hence we need to use both the techniques together? Yes they can be, because real
word applications have a mix of read and write loads.
Although, denormalized schema can greatly improve performance under extreme read-
loads but the updates and inserts become complex as the data is duplicate and hence
has to be updated/inserted in more than one places.
When mixing normalization and denormalization, focus on denormalizing tables that are
read intensive, while tables that are write intensive keep them normalized.
Table Design
1.What is Table?
In a relational database , a table which contains a set of data element(values) using a
vertical columns(identifies by a name) and horizontal rows. A table has a specified
number of columns , but can have any number of rows.
Syntax:-
CREATE TABLE table_name
(
Column_name1 data_type(size),
Column_name2 data_type(size),
Column_name3 data_type(size),
..
);
2.What is Data type?
A.Sql Data type is use to specify type of data of any object. Each column, variable ,
expression has related data type in sql
Eg:-bit,int,tinyint,smallint,decimal,float,real,numeric,date,time,char,varchar.
3.What are the different types of data types in SQL Server?
A. bit,int,tinyint,smallint,decimal,float,real,numeric,date,time,char,varchar,
varchar(mar)[only in 2005].
4.What is the difference between Float, BIG Int and Integer?
A.Integer type can contain only whole number(like 23 or 342). Numeric type can
contain decimal numbers (like 45.5).Float(n<24) and storage size is 4 bytes.decimal
(precision,scale) and storage size is 5 to 17 bytes. Big int and int is a whole number(big
int storage size is 8 bytes and int is 4 bytes).
5.Explain the Decimal Data types and its uses?
A. Decimal/Numeric is Fixed-Precision data type, which means that all the values in the
data type can be represented exactly with precision and scale. DECIMAL(2,2) and
DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are
different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222
are same data types.
6.What is the use of different types of Integer data types?
A.int,bigint,tinyint,smallint are the different integer datatypes.
7.What is the difference between bit, Char and Varchar?
A.char and nchar are fixed length and which will reserve storage space. Varchar and
nvarchar are variable length and which will use only the spaces for the character which
we store. It will not reserve storage like char or nchar. Bit is nothing but 0 or 1.
8.What is Unicode? **
A.Unicode character takes more bytes to store the data in the database.As many global
industries want to increase their business worldwide they provide services to the
customer to support diff language like Chinese ,Japanese, Korean, Arabic. For storage
no difference in database for Unicode and non Unicode, only the difference is Unicode
takes two times the space.
Non-Unicode Unicode
(char, varchar, text) (nchar, nvarchar, ntext)
Stores data in fixed or variable length Same as non-Unicode
char: data is padded with blanks to fill the
field size. For example, if a char(10) field
contains 5 characters the system will pad it
with 5 blanks
nchar: same as char
varchar: stores actual value and does not
pad with blanks
nvarchar: same as varchar
requires 1 byte of storage requires 2 bytes of storage
char and varchar: can store up
to 8000 characters
nchar and nvarchar: can store up to
characters
Best suited for US English: "One problem
with data types that use 1 byte to encode
each character is that the data type can
only represent 256 different characters.
This forces multiple encoding specifications
(or code pages) for different alphabets
such as European alphabets, which are
relatively small. It is also impossible to
Best suited for systems that need to support
at least one foreign language: "The Unicode
specification defines a single encoding
scheme for most characters widely used in
businesses around the world. All computers
consistently translate the bit patterns in
Unicode data into characters using the
single Unicode specification. This ensures
handle systems such as the Japanese Kanji
or Korean Hangul alphabets that have
thousands of characters."1
that the same bit pattern is always
converted to the same character on all
computers. Data can be freely transferred
from one database or computer to another
without concern that the receiving system
will translate the bit patterns into characters
incorrectly.
9.What is the difference between Varchar and Nvarchar? **
A.Varchar holds non Unicode and Nvarchar is Unicode data (where it can store non
Asian langaue like Chinese but it spaces more bytes).
Declare @sampleVar varchar(10)
Declare @sampleNVar nvarchar(10)
set @sampleVar = 'VarSamp Ж'
set @sampleNVar = 'NVarSamp Ж'
Select @sampleNVar, @sampleVar
set @sampleNVar = N'NVarSamp Ж'
set @sampleVar = N'VarSamp Ж'
Select @sampleNVar, @sampleVar
10.What are different date time data types? *
A.There are two types of datatime datatypes
-Datatime:store dates from January 1,1753 through dec 31, 9999. Millisec will be
round to three hundredth.
-SmallDatatime: store dates from January 1,1900 through june 6, 2079.The date,hours
and minutes are copied. The seconds are set to 0.
DECLARE @smalldatetime smalldatetime = '12:10:05.122';[only 3 digit should be there in
millisec]
DECLARE @datetime datetime = '12:10:05.122';
SELECT @datetime AS '@datetime', @smalldatetime AS '@smalldatetime';
--Result
--@datetime @smalldatetime
------------------------- -----------------------
--1900-01-01 12:10:05.123 1900-01-01 12:10:00
Date datatype:
DECLARE @date date = '12-21-05';
DECLARE @datetime datetime = @date;
SELECT @datetime AS '@datetime', @date AS '@date';
--Result
--@datetime @date
------------------------- ----------
--2005-12-21 00:00:00.000 2005-12-21
Time datatype:
DECLARE @time time(4) = '12:10:05.1237';
DECLARE @datetime datetime = @time;
SELECT @datetime AS '@datetime', @time AS '@time';
--Result
--@datetime @time
------------------------- -------------
--1900-01-01 12:10:05.123 12:10:05.1237
Datetimeoffset(n)
DECLARE @datetimeoffset datetimeoffset(4) = '1968-10-23 12:45:37.1234 +10:0';
DECLARE @datetime datetime = @datetimeoffset;
SELECT @datetime AS '@datetime', @datetimeoffset AS '@datetimeoffset';
--Result
--@datetime @datetimeoffset
------------------------- ------------------------------
--1968-10-23 12:45:37.123 1968-10-23 12:45:37.1237 +01:0
DateTime2(n):n is nothing but the millisecond it can take from the given datevalue
(N=7 max).
DECLARE @datetime2 datetime2(7)/ datetime2 = '1968-10-23 12:45:37.123790455';
DECLARE @datetime datetime = @datetime2;
SELECT @datetime AS '@datetime', @datetime2 AS '@datetime2';
--Result
--@datetime @datetime2
------------------------- ------------------------
--1968-10-23 12:45:37.123 1968-10-23 12:45:37.1237905[max number it can fetch]
11.What are unique identifiers in SQL Server Table? **
A.Unique identifier are new in sql 7.0 and behave little different then our identity
column. Unique identifier is also referred as a GUID(globally unique identifier).
It can be generated by NEWID() or NEWSEQUENTIALID().GUID is a unique binary
number; no other computer in the world will generate a duplicate of that GUID value.
The major advantage of using GUIDs is that they are unique across all space and time.
This comes in handy if you're consolidating records from multiple SQL Servers into one
table, as in a data warehousing situation. GUIDs are also used heavily by SQL Server
replication to keep track of rows when they're spread out among multiple SQL Servers.
The main disadvantage to using GUIDs as key values is that they are BIG. At 16 bytes
a pop, they are one of the largest datatypes in SQL Server. Indexes built on GUIDs are
going to be larger and slower than indexes built on IDENTITY columns, which are
usually ints (4 bytes).Not only that, identity they are just plain hard to read. Mostly for
security reason it is used , we cannot track the ID of uniqueIdentifier.
create table #temp
(
Item int,
GUID1 uniqueidentifier
);
INSERT into #temp VALUES (1,NEWID())
select * from #temp
output
Item GUID1
1 F3323B56-9961-4096-9595-83A53E7B0CCE
12.What is check constraint in SQL Server? **
A.We can use check constraint to enforce specific patterns for data or to limit the range
of possible values in a column.There are two diff leve
Column level:-This is applied only to the column and cannot reference data in another
column.
Table level:-This is applied only to all the column within the table and not applied
outside the column.
Mostly will use data column for check salary <= 50000.
Table level check constraints for the Email ID.
13.What is default constraint? *
A.Default constraint is used to insert a default value into a column.The default value will
be added to all the new records, if no other value is specified.
Example: city with default value Mumbai
CREATE TABLE Persons
(
P_ID int not null,
City varchar(255) DEFAULT ‘Mumbai’,
JoiningDate DEFAULT GETDATE()
);
14.What is Null ability?
A value of NULL indicates that the value is unknown. A value of NULL is different from
an empty or zero value. No two null values are equal. Comparisons between two null
values, or between a NULL and any other value, return unknown because the value of
each NULL is unknown.
Null values generally indicate data that is unknown, not applicable, or that the data will
be added later. For example, a customer's middle initial may not be known at the time
the customer places an order.
To test for null values in a query, use IS NULL or IS NOT NULL in the WHERE clause.
15.Explain table relationship?
A. When creating a database, common sense dictates that we use separate tables for
different types of entities. Some examples are: customers, orders, items, messages
etc... But we also need to have relationships between these tables. For instance,
customers make orders, and orders contain items. These relationships need to be
represented in the database. Also, when fetching data with SQL, we need to use certain
types of JOIN queries to get what we need.
There are several types of database relationships. Today we are going to cover the
following:
One to One Relationships
One to Many and Many to One Relationships
Many to Many Relationships
Self Referencing Relationships
When selecting data from multiple tables with relationships, we will be using the JOIN
query. There are several types of JOIN's, and we are going to learn about the the
following:
Cross Joins
Natural Joins
Inner Joins
Left (Outer) Joins
Right (Outer) Joins
We will also learn about the ON clause and the USING clause.
16.What is Primary Key? *
The PRIMARY KEY is a field in a table which uniquely identifies each record in a
database table.
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE primary
key.
Syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
17.What is Foreign Key?
A foreign key is a column (or columns) that references a column (most often the
primary key) of another table. The purpose of the foreign key is to ensure referential
integrity of the data.
18.What is composite key? *
A key composed of two to more attributes. A primary key consists of one or more
columns (from that table) are called composite key. A composite key is made up of
elements that should need foreign keys.
CREATE TABLE voting (
QuestionID NUMERIC,
MemberID NUMERIC,
PRIMARY KEY (QuestionID, MemberID)
);
Exp : Let say EmpID, EmailID, SSN are columns in Employee table and projectID in
project table .
if EmpID and project id are put in projectionHours table then combination of empid and
project ID called as composite key because combination of these two act as primary
key in projectionHours table.
19.What is surrogate Key?
A key with no business meaning, example :zipCode.
20.What is component/candidate key?
A Candidate Key is a set of one or more fields/columns that can identify a record
uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate
Key can work as Primary Key.A composite key is made up of elements that may or may
not be foreign keys. Example empID, Rollnumber,EnrollNo etc.
21.What are Primary Key and Foreign Key Constraint? *
22.How to get the list of primary key and foreign key of the table? ****
A.By querying information_schema or sys.object or system database we can get the
list.
21.Can we insert null value in primary column? *
A.No we cant insert null value in a single column primary key while in composite
primary key only one column can be null
22.What is difference between Primary Key and Unique Key? **
A.Primary key and unique both are used to perform same that is unique identify the
rows in the table. Unique keys can have nulls but primary key cannot have nulls.
We can create multiple unique keys on a table but we can have only one primary key.
Unique key contains non- clustered index by default and primary key creates a
clustered index by default.Both the key can be referenced by the foreign key.
We can insert one null value in unique key but not in primary key.
23.What is Identity Column in Table? *
A.Identity is the property of column which inserts incremental value in the column at
the insert of new row in parent table of that column.
For example in Employee table when we set ID as identity then for every inserted
employee record there will be an auto incremental value get inserted in the ID column
automatically.
For Identity you can set the increment value i.e. the value by which next inserted value
increment. So if you set increment by 10 then inserted value will be like 10, 20, 30,
40……..
25.Syntax to check current Identity of the table? *
A.DBCC CHECKIDENT
(
table_name
[, { NORESEED | { RESEED [, new_reseed_value ] } } ]
)
[ WITH NO_INFOMSGS ]
Example
DBCC CHECKIDENT (table)
DBCC CHECKIDENT (table, NORESEED)
DBCC CHECKIDENT (table, RESEED, 10)
26.What is the difference between Scope of Identity on @@identity? ***
A.
SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are function used for same
value type but different results.
IDENT_CURRENT returns the current identity value irrespective of session and scope.
SCOPE_IDENTITY returns last identity value generated the current scope Irrespective of
tables. I.e. it could be value from last table which is updated in current scope.
@@IDENTITY returns the last identity values that are generated in any table in the
current session. It’s not limited to any specific scope. I.e. while updating in current
scope the trigger on this table insert data in some other table
For example, there are two tables, Table1 and Table2, and an INSERT trigger is defined
on Table1.
When a row is inserted to Table1, the trigger inserts a row in Table2. This scenario
illustrates two scopes: the insert on Table1 and the insert on Table2 by the trigger.
Table1 and Table2 have identity columns, @@IDENTITY and SCOPE_IDENTITY will
return different values at the end of an INSERT statement on Table1.
@@IDENTITY will return the last identity column value inserted across any scope in the
current session. This is the value inserted in Table2.
SCOPE_IDENTITY () will return the IDENTITY value inserted in Table1.
27.Can we change identity key values for a table or reset the identity key value.
A.Yes
28.What is function Ident_INCR? ***
29.What is times stamp data type is SQL Server? **
A. Timestamp is a data type that exposes automatically generated binary numbers, which are
guaranteed to be unique within a database. timestamp is used typically as a mechanism for
version-stamping table rows. The storage size is 8 bytes.
create table #temp
(
Name varchar(50),
TS timestamp,
RS RowVersion
)
Error: A table can only have one timestamp column. Because table '#temp' already has one, the
column 'RS' cannot be added.
TimeStamp:
create table #temp
(
Name varchar(50),
TS timestamp
)
insert into #temp (name)
Select 'pukal' union all
select 'rani' union all
select 'nadar'
go
select * from #temp
update #temp set name ='pukal a' where name='pukal'
select * from #temp
BTW, now a day, you should use RowVersion datatype (above sql server 2008) rather than
TimeStamp as I told you above too that TimeStamp will be deprecated and RowVersion is synonyms
for TimeStamp.
30.What is the alternative of timestamp? **
A.BTW, now a day, you should use RowVersion datatype (above sql server 2008) rather than
TimeStamp as I told you above too that TimeStamp will be deprecated and RowVersion is synonyms
for TimeStamp.
JOINS AND SELECT
1.What is select statement in TSQL? *
A. The SELECT statement is used to query the database and retrieve selected data that
match the criteria that we have specify.
2.What is the Join in SQL Server? *
A.SQL Server (Transact-SQL) JOINS are used to retrieve data from multiple tables. A
SQL Server JOIN is performed whenever two or more tables are joined in a SQL
statement.
3.What are the different types of join? *
A.There are 4 different types of SQL Server joins:
SQL Server INNER JOIN (or sometimes called simple join)
SQL Server LEFT OUTER JOIN (or sometimes called LEFT JOIN)
SQL Server RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
SQL Server FULL OUTER JOIN (or sometimes called FULL JOIN)
4.Difference between Left join and Outer Join? *
A.There is actually no difference between a left join and a left outer join – they both
refer to the exact same operation in SQL. Only in the syntax will write the outer join.
5.What is full outer join? *
A.matching row from both the table and unmatching row frm left and right table.
Eg.
6.What is inner join? *
A.Inner join gets only the matching rows from the table.
7.What is cross join? *
A.A cross join that does not have a WHERE clause produces the Cartesian product of
the tables involved in the join. The size of a Cartesian product result set is the number
of rows in the first table multiplied by the number of rows in the second table
8.Write one example for self-join? **
A. A self join is a join in which a table is joined with itself (which is also called Unary
relationships), specially when the table has a FOREIGN KEY which references its own
PRIMARY KEY.
Manager is an employee, so we need to do self join in Employee table
Example:
SELECT DISTINCT e.emp_id AS 'mng_id', e.emp_name AS 'mng_name'
FROM employees e, employees m WHERE e.emp_id = m.mng_id
9.What is where clause? *
A. The WHERE clause is used to filter records. The WHERE clause is used to extract only
those records that fulfill a specified criterion.
Syntax:
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
10.What are the sub queries? *
A. A subquery is a query within a query.In SQL Server (Transact-SQL), asubquery is also
called an INNER QUERY or INNER SELECT. In SQL Server (Transact-SQL), the
main query that contains the subquery is also called the OUTER QUERY or
OUTER SELECT.
Subquery in Where,From and Select Clause
1.Where Clause: The subquery will be found in the WHERE clause. These subqueries
are also called nested subqueries.
SELECT p.product_id, p.product_name
FROM products p
WHERE p.product_id IN
(SELECT inv.product_id
FROM inventory inv
WHERE inv.quantity > 10);
2. FROM CLAUSE: A subquery can also be found in the FROM clause. These are
called inline views.
SELECT suppliers.supplier_name, subquery1.total_amt
FROM suppliers,
(SELECT supplier_id, SUM(orders.amount) AS total_amt
FROM orders
GROUP BY supplier_id) subquery1
WHERE subquery1.supplier_id = suppliers.supplier_id;
3. SELECT CLAUSE: A subquery can also be found in the SELECT clause. These are
generally used when you wish to retrieve a calculation using an aggregate function such
as the SUM, COUNT, MIN, or MAX function, but you do not want the aggregate function
to apply to the main query.
SELECT e1.last_name, e1.first_name,
(SELECT MAX(salary)
FROM employees e2
WHERE e1.employee_id = e2.employee_id) subquery2
FROM employees e1;
The subquery has been aliased with the name subquery2. This will be the name used to
reference this subquery or any of its fields.
The trick to placing a subquery in the select clause is that the subquery must return a
single value. This is why an aggregate function such as the SUM, COUNT, MIN,
or MAX function is commonly used in the subquery.
11.What are the nested queries in SQL Server? **
A.If a subquery contains another sub query inside it the its called nested sub query.
there could be multiple no of nesting possible in a sub query.
if two sub queries or queries are dependent on each other then its called correlated
subqueries.
Example
select EmpName , (select Empname from emp where empid=a.managerid) as manager
from Emp A
in this example a column is used in upper sub query then its correlated subquery.
Nested Sub Query [Single or Multi-Level]:
Select * from tableA where columnA=(Select * from TableB where
ColumnB=’SomeValue’)
If the value is more then one then use <,>,>=,!=(IN/NOT IN, ANY – [>ANY or <ANY],
ALL – [>ALL or <ALL], EXISTS(The EXISTS keyword produces a Boolean value [TRUE/FALSE].
This EXISTS checks the existence of the rows returned by the sub query) )
12.What is inline query? **
A. Nested and correlated query
13.What are the aggregate functions in SQL Server? *
A. Count, Min, Max and Average are the few aggregate functions in SQL Server.
Count function: Select count (*) from Table1. It will deliver count of the table i.e. no
of records. If you will put the filters in the query then it will give the count of filtered
records.Example 1.The null values in a column doesn’t counts by the count function in
SQL Server.2.The space will be consider as a value by count function in SQL Server.
Min function: Min function retrieves the minimum values in a column it works on
group by function and also without any group by function.
Max Function: Max function is used to get the max value of a column.
Average Function: Average is used to get the average of the column. Average can be
on the groups also. This functions returns value as mathematics average function
returns.
14.What is Group By? *
A. Aggregate functions often need an added GROUP BY statement. The GROUP BY
statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
“SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;”
15.What is Having clause? **
A. The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.
“SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;”
16.What is difference between where and having clause? **
A.1.Where can be used in select , update and delete statement.Having can be used only
with select statement.
2.Where is used before group by function and having is used after group by function
3.where cannot use aggregate unless it is a subquery contained but having clause can
use it.
select name from #temp
where count(Name)>0
“Error:An aggregate may not appear in the WHERE clause unless it is in a subquery contained in
a HAVING clause or a select list, and the column being aggregated is an outer reference.”
select name from #temp
group by name
having count(Name)>0
success output
4.Where is applies to each and every row whereas a having clause applies to a
summarized or group by clause.
5.In where clause the data is fetched from memory depending on the condition but
having will fetch the entire data and then condition is applied.
17.What is the table variable? **
A. Same structure as a normal table but only difference is the shortest life time among
all the varieties.@table_variables are created implicitly when a batch containing
a DECLARE @.. TABLE statement is executed (before any user code in that batch runs)
and are dropped implicitly at the end. No drop statement used for table variable but for
temptable drop command needed. Transaction is not supported for table variable below
example. This table is created and stored in memory and its lifetime is decided by the
stored procedure who have created it. Once stored procedure/DML statement exits, this
table gets auto cleaned and memory gets free. Apart from that, log activity is truncated
immediately. An important note, If we have a requirement to use a table structure in
user defined function then we have only one option as Table variable and no other
variety can be used. Syntax:Declare @Student Table (Id int, Name varchar(50))
CREATE table #T (s varchar(128))
DECLARE @T table (s varchar(128))
INSERT into #T select 'old value #'
INSERT into @T select 'old value @'
;with CTE as (
SELECT * from #T union all
SELECT * from @T)
select * from CTE
BEGIN transaction
UPDATE #T set s='new value #'
UPDATE @T set s='new value @'
ROLLBACK transaction
;with CTE as (
SELECT * from #T union all
SELECT * from @T)
select * from CTE
We need to execute the whole query in one go. Or else error will through.
declare @temp table
(name varchar(50))
insert into @temp (name)
Select 'pukal' union all
select 'rani' union all
select 'nadar'
select * from @temp
go
error: Must declare the table variable "@temp".
18.What is the temporary table? **
A.Temp table is use create a temporary record in tempDb.Temp table cannot used in user
defined function but table variable can be used. Temp table are of two types local or global.
1.Local Temp table:- Local declared by (#). It will be within the same new query block.it will
be used only for current user. Unlike the majority of the other data types in SQL Server, you
cannot use a table variable as an input or an output parameter. In fact, a table variable is
scoped to the stored procedure, batch, or user-defined function just like any local variable
you create with a DECLARE statement. The variable will no longer exist after the procedure
exits - there will be no table to clean up with a DROP statement. However, because you
can’t pass a table variable to another stored procedure as input .Using a temporary table
inside of a stored procedure may result in additional re-compilations of the stored
procedure. Table variables can often avoid this recompilation hit. You cannot create a non-
clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or
UNIQUE constraint on the table.Also, SQL Server does not maintain statistics on a table
variable, and statistics are used heavily by the query optimizer to determine the best
method to execute a query. The table definition of a table variable cannot change after the
DECLARE statement. Any ALTER TABLE query attempting to alter a table variable will fail
with a syntax error. you cannot use a table variable with SELECT INTO or INSERT EXEC
queries.
Local Temporary Tables
These tables are created within a procedure and stored in the temp_db provided by
SQL server. They can be identified with a session specific identifier. It can be used when
data is coming from another stored procedure. It also reduces the amount of locking
required and also involves less logging. Still, there are few limitations such as character limit
is 116 and transactions can create unnecessary locks in temp_db.
Syntax:
Create table #Student (Id int, Name varchar(50))
19.What is the global temporary table? **
A.Global Temp table:-global declared by (##).It will be next block. Session doesn’t get
expired.It is visible to everyone.
Global Temporary Tables:
These tables are same as local temporary table but the difference lies in the lifetime as it is
available for all the sessions. This can be useful when the same set of data is required by
one or more users. But the issue will come when the user, who should not be given access
to this data, will have access to it as it is a global table and available for all users.
Syntax:
Create table ##Student (Id int, Name varchar(50))
See the difference of two #.
20.Difference between temporary table and table variable? **
A.
TABLE Variable Temporary TABLE
Current batch Current session nested stored
procedures. Global: all sessions.
UDFs, Stored Procedures, Triggers,
Batches.
Stored Procedures, Triggers, Batches.
DECLARE statement only. CREATE TABLE statement.
SELECT INTO statement.
Can only have indexes that are
automatically created with PRIMARY KEY
& UNIQUE constraints as part of the
DECLARE statement.
Indexes can be added after the table has
been created.
PRIMARY KEY, UNIQUE, NULL, CHECK,
but they must be incorporated with the
creation of the table in the DECLARE
statement. FOREIGN KEY not allowed.
PRIMARY KEY, UNIQUE, NULL, CHECK.
Can be part of the CREATE TABLE
statement, or can be added after the
table has been created. FOREIGN KEY
not allowed.
The SET IDENTITY_INSERT statement is
not supported.
The SET IDENTITY_INSERT statement is
supported.
Truncation Not allowed.drop not
required
Truncate Allowed.drop is required
Not affected (Data not rolled back). Affected (Data is rolled back).
If we use nested stored procedures which use the resultset, certain scenarios using dy-
namic SQL, and cases where you need not transaction rollback support.
Secondly, the size of the resultset will determine which solution to choose. If the table
stores a resultset so large you require indexes to improve query performance, you’ll need to
stick to a temporary table. If the resultset is small, the table variable is always the optimum
choice. “Table variables can offer performance benefits and flexibility when compared to
temporary tables”.
21.What is the union all clause? **
A.The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT
statements. It does not remove duplicate rows between the various SELECT statements (all
rows are returned).
Each SELECT statement within the UNION ALL must have the same number of fields in the
result sets with similar data types.
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions
UNION ALL
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions;
22.What is union Clause? **
A.The UNION operator is used to combine the result-set of two or more SELECT
statements.
Notice that each SELECT statement within the UNION must have the same number of
columns. The columns must also have similar data types. Also, the columns in each
SELECT statement must be in the same order.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
The column names in the result-set of a UNION are usually equal to the column names in
the first SELECT statement in the UNION.
23.Difference between union all and union clause? **
A.
UNION removes duplicate rows.
UNION ALL does not remove duplicate rows.
example:
select * from #temp1
select * from #temp
select id from #temp1 union
select id from #temp
select id from #temp1 union all
select id from #temp
24.What is the Ranking function in SQL Server? ****
A.Row_Number():Returns the sequential number of a row within a partition of a result set,
starting at 1 for the first row in each partition.
It assigns continous and unique number.
Rank():Returns the rank of each row within the partition of a result set.
It is not continguous nor unique.
Dense_Rank():Returns the rank of rows within the partition of a result set, without any gaps
in the ranking.It is continguous but not unique.
25.Difference between rank and dense rank? ****
A.Rank():Returns the rank of each row within the partition of a result set.
It is not continguous nor unique.
Dense_Rank():Returns the rank of rows within the partition of a result set, without any gaps
in the ranking.It is continguous but not unique.
Ntile():Distributes the rows in an ordered partition into a specified number of groups.
select * from #TempRank
with rownumer as
(select *,Row_Number() over(order by salary) as sal from #TempRank)
select * from rownumer
order by rownumer.sal asc
with ranking as
(select *,rank() over(order by salary) as sal from #TempRank)
select * from ranking
order by ranking.sal asc
with denserank as
(select *,dense_rank() over(order by salary) as sal from #TempRank)
select * from denserank
with ntile1 as
(select *,ntile(3) over(order by salary) as sal from #TempRank)
select * from ntile1
26.What is top operator in SQL Server? **
A.Fetch the rows returned in a query result set to a specified number of rows.
When TOP is used in conjunction with the ORDER BY clause, the result set is limited to the
first N number of ordered rows; otherwise, it returns the first N number of rows in an
undefined order. Use this clause to specify the number of rows returned from a SELECT
statement or affected by an INSERT, UPDATE, MERGE, or DELETE statement.
Syntax:
[
TOP (expression) [PERCENT]
[ WITH TIES ]
]
27.What is table sample in SQL Server? ***
A.TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM
clause. The rows retrieved are random and they are are not in any order. This sampling can
be based on a percentage of number of rows. You can use TABLESAMPLE when only a
sampling of rows is necessary for the application instead of a full result set.
Example 1:
SELECT FirstName,LastName
FROM Person.Contact
TABLESAMPLE SYSTEM (10 PERCENT)
Example 2:
SELECT FirstName,LastName
FROM Person.Contact
TABLESAMPLE SYSTEM (1000 ROWS)
28.What is the delete command? *
A. The T SQL DELETE statement is a used to delete a one or more records from a table.
Syntax:DELETE FROM table WHERE conditions;
29.What is truncate command? **
A. The TRUNCATE TABLE statement is used to remove all records from a table in SQL
Server. It performs the same function as a DELETE statement without a WHERE clause. If
you truncate a table, the TRUNCATE TABLE statement can not be rolled back.
30.Difference between delete and truncate? **
A.Both command empty the table
Delete will use to delete each or full tbale but truncate can delete whole table bcz it doesn’t
have where condition in it.
Delete can be rollback or commit or trigger but truncate cannot
Delete is DML and Truncate is DDL
Why we use truncate is bcz it is faster then delete.
31.What are dynamic queries? ***
A. A dynamic SQL in a stored procedure is a single Transact-SQL statement or a set of statements
stored in a variable and executed using a SQL command. A Dynamic SQL is needed when we need
to retrieve a set of records based on different search parameters.
create table #tblEmployees
(
EmpID varchar(50)
)
insert into #tblEmployees (EmpID)
( select 1 union all
select 2)
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
/* set the parameter value */
SET @EmpID = 1
/* Build Transact-SQL String with parameter value */
SET @SQLQuery = 'SELECT * FROM #tblEmployees WHERE EmpID = ' +
CAST(@EmpID AS NVARCHAR(10))
/* Execute Transact-SQL String */
EXECUTE(@SQLQuery)
Output:EmpId
1
32.What is distinct clause? How it works? **
A. The SQL DISTINCT clause is used to remove duplicates result set.The syntax for the SQL DISTINCT
clause is:
SELECT DISTINCT expressions
FROM tables
WHERE conditions;
Eg: 1.SELECT DISTINCT city
FROM Customers;
This SQL DISTINCT example would return all unique city values from the Customers table.
2. SELECT DISTINCT city, state
FROM Customers;
This SQL DISTINCT clause example would return each unique city and state combination. In this case,
the DISTINCT applies to each field listed after the DISTINCT keyword. If there are multiple column
distinct will apply that many time with multiple of rows.
33.How to use Order by in Sub Queries? **
A. The SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.
Syntax
The syntax for the SQL ORDER BY clause is:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ ASC | DESC ];
Thing to Remember
If the ASC or DESC option is not provided in the ORDER BY clause, the results will be sorted by
expression in ascending order (which is equivalent to "ORDER BY expression ASC").
Order by clause can’t be used in a view definition.
Order by cant be used in a sub query having aggregate functions in select statement
35.What is the @@error? **
The @@ERROR system function is used to implement error handling code. It contains the error ID
produced by the last SQL statement executed during a client’s connection. When a statement
executes successfully, @@ERROR contains 0. To determine if a statement executes successfully, an IF
statement is used to check the value of the function immediately after the target statement executes.
It is imperative that @@ERROR be checked immediately after the target statement, because its value
is reset when the next statement executes successfully.
USE tempdb
go
CREATE PROCEDURE ErrorHandling
AS
Select * from EMP
Print 'Fatal Error'
GO
EXEC ErrorHandling
Use tempdb
go
Create Table EMP
(
ID int identity,
EmpName varchar(50) not null
)
Use TempDB
GO
Create PROCEDURE ErrorHandling_Insert
@EmpName varchar(50)=null
As
insert EMP values (@EmpName)
Print 'Error Inserting Null Name'
GO
Use TempDB
GO
Alter PROCEDURE ErrorHandling_Insert
@EmpName varchar(50)=null
As
insert EMP values (@EmpName)
if @@ERROR <> 0
Begin
PRINT 'Error Occured'
END
Exec ErrorHandling_Insert
Exec ErrorHandling_Insert 'Pukal'
36.What is the @@raise error? **
37.What is the @@row count? **
38.What is Date Diff function? **
A. Date diff tells the difference between the two dates.
Syntax:
DATEDIFF (datepart , startdate , enddate )
Datepart could e mm or dd or yy or mi depends upon the requirement.
Below are the few points related to date diff.
DATEDIFF does not guarantee that the full number of the specified time units passed between
2 datetime Values.
-- Get difference in hours between 8:55 and 11:00
SELECT DATEDIFF(hh, '08:55', '11:00');
-- Returns 3 although only 2 hours and 5 minutes passed between times
-- Get difference in months between Sep 30, 2011 and Nov 02, 2011
SELECT DATEDIFF(mm, '2011-09-30', '2011-11-02')
-- Returns 2 although only 1 month and 2 days passed between date
To get the number of full time units passed between date times, you can calculate the difference
in lower Units and then divide by the appropriate number:
SELECT DATEDIFF(mi, '08:55', '11:00')/60;
-- Returns 2 hours now
39.What is Date Add Function? **
40.What is date part function? ***
41.What is coalesce function in SQL Server? ***
42.What is difference between stuff and Replace function? ***
A.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.
Example:
select stuff('Pukal',1,1,'r')
Ouput
rukal
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
Example:
select replace('Pukal','k','g')
output
Pugal
43.What are the sparse column and when we use it? ****
44.How to Convert Integer to String in SQL Server?
A. DECLARE @i int
SET @i=98235
-- Firs Ways - Use CAST function
SELECT CAST(@i as varchar(10))
-- Second Way --> Use CONVERT function
SELECT CONVERT(varchar(10),@i)
--Third Way : Use STR function
SELECT LTRIM(STR(@i,10))
45.What is CrossTab?
pivot which converts rows into columns.
example:
-------------------Pivot and unPivot(Crossab)-----------------------------
Create table #tempPivot
(
customername varchar(50),
Productname varchar(50),
Amount int
)
insert into #tempPivot(customername,Productname,Amount)
(
select 'pukalrani','Skirts',200 union all
select 'rani','Shoes',200 union all
select 'nadar','skirts',200 union all
select 'pukalrani','Skirts',400
)
select * from #tempPivot
--------------define the column names------------
select customername,shoes,skirts
----------------actual data---------------------
from
(
select customername,productname,amount from #tempPivot
) as pivotdata
---------------pivot function---------------------
pivot
(
sum(amount) for productname in(skirts,shoes)
) as pivoting
The Cross-tabulation, or Crosstab, query pivots the second GROUP BY column (or
dimension) values counterclockwise 90 degrees and turns it into the crosstab columns.
The following are the methods to transform the row data into different column attributes-
Pivot Method
Case Expression Method
Dynamic Crosstab Queries
PIVOT Method:
Microsoft have the introduced this keyword with the release of SQL Server 2005, which is
being used for coding crosstab queries.
The pivot method deviates from the normal logical query flow by performing the aggregate
GROUP BY function and generating the crosstab results as a data source within the FROM
clause.
If you think of PIVOT as a table-valued function that’s used as a data source, then it accepts
two parameters. The first parameter is the aggregate function for the crosstab’s values. The
second measure parameter lists the pivoted columns.
Using Coalesce() in sqlserver
When we have multi-value attribute with single or more null values in a Table,
the Coalesce() function is very useful.
d Name Ph_ no Alt_ no Office no
101 Albert 999999 456453 321333
102 khan null null 123455
103 victor 112121 null null
104 lovely null null 1897321
The above Employee table may have single value or three values. If it has single value,
then it fills null values with remaining attributes.
When we retrieve the number from employee table, that number Should Not be Null value.
To get not nullvalue from employee table, we use Coalesce() function. It returns the first
encountered Not Null Value from employee table.
Hide Copy Code
select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from employee
It returns:
id Name Contactnumber
101 Albert 999999
102 khan 123455
103 victor 112121
104 lovely 1897321
VIEWS
What is the view in SQL Server? **
A.It is nothing but a virtual table, hide complexity.
1.hide some data from user
2.make query easier /more natural
3.modularity of database access
similarly there in materialized views but only difference is performance is faster then views.
It creates a physical table , if there is any in the base table we need to recompute mviews.
What are the updated views? ***
A.Views can update only if it is in the same base table. if we are having joins and updating
only one table then it will work.
What are the materialized views or Indexed Views in SQL Server? ****
A.views:data are up to date,slow performance everytime it execute.
Mviews:not up to date, faster performance,outside the database we cn create a mviews, we
can hv index in ths, similar to normal table.
What is view with check option? ****
The with check option causes the where clause of the view to check the data being inserted
or updated through the view in addition to the data being retrieved. In a sense, it makes the
where clause a two-way restriction.
This option is useful when the view should limit inserts and updates with the same
restrictions applied to the where clause.
Write the Create syntax for Views. **
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
What is common table expression (CTE)? ***
A CTE is a temporary/logical View, it is not store physically. It is a named query, the result
for which is only available to the very next query after the CTE is defined. CTE is defined
using WITH clause.Short life span.
Recursive CTE[sql server2005] which calls itself example emp and manager data.
What is difference between CTE and View? ****
A CTE is a temporary/logical View, it is not store physically. It is a named query, the result
for which is only available to the very next query after the CTE is defined. CTE is defined
using WITH clause.
A View is a physical object that is present in the database. View is as good as a
Table but it doesn't store data physically as compared to a table, only the data schema is
stored in View. View,when referred, pulls data by executing the query that is associated with
it.
The biggest difference between a CTE and View, is that, View or derived table cannot call
itself, whereas CTE can call itself and hence support recursion.
In many databases, views have options, for instance to index them.
Stored procedure
1.What is stored procedure in SQL Server? **
A.It is a Named group of sql statements that have been previously created and stored in the
server DB.Sp accept input parameter so that a single SP can be used over the network by
several clients using diff input data.Sp reduce network traffic and improve performance.
2.How to pass record set in stored procedure? ***
A. One solution would be to store the rows returned for your initial query into a cursor then
you can loop thru the cursor and either call a function passing one row at a time... or just do
the process in the same block.
3.Is nesting possible in stored procedure? If yes How many number of times? ***
A.Yes,33.
4.Write the create syntax for the procedure. **
A. CREATE PROCEDURE proc_name
Parameter
As begin
…
End
go
Correct Syntax:
CREATE PROCEDURE usp_SelectRecord
AS
BEGIN
SELECT *
FROM TABLE
END
GO
5.How to return output parameter from stored procedure? ***
CREATE PROC sales_for_type @type VARCHAR(55), @total_sales INT OUTPUT
AS
SELECT SUM(qty) FROM sales a, titles b
WHERE
a.title_id = b.title_id
and
b.type = @type
This procedure can be executed as follows:
DECLARE @total_sales_business int
EXEC sales_for_type business, @total_sales=@total_sales_business OUTPUT
Results: 90
6.How to perform error handling in Stored procedure? ****
DECLARE @errNum int
DECLARE @rowCount int
BEGIN TRY
INSERT INTO [TABLE] (COL1) VALUES ('1")
END TRY
BEGIN CATCH
SET @errNum = @@ERROR
SET @rowCount = @@ROWCOUNT
RAISEERROR(@errNum)
END CATCH
Function
What are different types of function?
A.SystemDefined function and userdefined function
SystemDefined function:- Scalar and aggregate function
Scalar function:-operates with single value returns single value.eg:-
abs(-10.67):This returns absolute number of the given number means 10.67.
rand(10):This will generate random number of 10 characters.
round(17.56719,3):This will round off the given number to 3 places of decimal means
17.567
upper('dotnet'):This will returns upper case of given string means 'DOTNET'
lower('DOTNET'):This will returns lower case of given string means 'dotnet'
ltrim(' dotnet'):This will remove the spaces from left hand side of 'dotnet' string.
convert(int, 15.56):This will convert the given float value to integer means 15.
Aggregated Function:- Aggregate functions operates on a collection of values and
returns a single value.eg:-min(),max(),avg(),count().
User Defined Function:- These functions are created by user in system database or in
user defined database. We three types of user defined functions.
1.scalar function also returns single value as a result of actions perform by function. We return
any datatype value from function.
1. --Create a table
2. CREATE TABLE Employee
3. (
4. EmpID int PRIMARY KEY,
5. FirstName varchar(50) NULL,
6. LastName varchar(50) NULL,
7. Salary int NULL,
8. Address varchar(100) NULL,
9. )
10. --Insert Data
11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address)
Values(1,'Mohan','Chauahn',22000,'Delhi');
12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address)
Values(2,'Asif','Khan',15000,'Delhi');
13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address)
Values(3,'Bhuvnesh','Shakya',19000,'Noida');
14. Insert into Employee(EmpID,FirstName,LastName,Salary,Address)
Values(4,'Deepak','Kumar',19000,'Noida');
15. --See created table
16. Select * from Employee
17. --Create function to get emp full name
18. Create function fnGetEmpFullName
19. (
20. @FirstName varchar(50),
21. @LastName varchar(50)
22. )
23. returns varchar(101)
24. As
25. Begin return (Select @FirstName + ' '+ @LastName);
26. end
27. --Calling the above created function
28. Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary
from Employee
2.Inline Table-Valued Function
User defined inline table-valued function returns a table variable as a result of actions perform by
function. The value of table variable should be derived from a single SELECT statement.
29. --Create function to get employees
30. Create function fnGetEmployee()
31. returns Table
32. As
33. return (Select * from Employee)
34. --Now call the above created function
35. Select * from fnGetEmployee()
3.Multi-Statement Table-Valued Function
User defined multi-statement table-valued function returns a table variable as a result of actions
perform by function. In this a table variable must be explicitly declared and defined whose value can
be derived from a multiple sql statements.
36. --Create function for EmpID,FirstName and Salary of Employee
37. Create function fnGetMulEmployee()
38. returns @Emp Table
39. (
40. EmpID int,
41. FirstName varchar(50),
42. Salary int
43. )
44. As
45. begin
46. Insert into @Emp Select e.EmpID,e.FirstName,e.Salary from Employee
e;
47. --Now update salary of first employee
48. update @Emp set Salary=25000 where EmpID=1;
49. --It will update only in @Emp table not in Original Employee table
50. return
51. end
52. --Now call the above created function
53. Select * from fnGetMulEmployee()
54. --Now see the original table. This is not affected by above
function update command
55. Select * from Employee
Note
 Unlike StoredProcedure,Functionreturnsonlysingle value.
 Unlike StoredProcedure,Functionacceptsonlyinputparameters.
 Unlike StoredProcedure,FunctionisnotusedtoInsert,Update,Delete dataindatabase table(s).
 Like Stored Procedure,Functioncanbe nestedupto32 level.
 User DefinedFunctioncanhave upto1023 inputparameterswhile aStoredProcedure canhave
upto2100 inputparameters.
 User DefinedFunctioncan'treturnsXML Data Type.
 User DefinedFunctiondoesn'tsupportExceptionhandling.
 User DefinedFunctioncancall onlyExtendedStoredProcedure.
 User DefinedFunctiondoesn'tsupportsetoptionslike setROWCOUNTetc.
What are difference between UDF and stored procedure? ***
A.Stored Procedures are pre-compile objects which are compiled for first time and its
compiled format is saved which executes (compiled code) whenever it is called. But
Function is compiled and executed every time when it is called.
Basic Difference
 Functionmustreturna value butin StoredProcedure itisoptional( Procedure canreturnzeroor n
values).
 Functionscanbe calledfromProcedure whereasProcedurescannotbe calledfrom Function.
Advance Difference
 Procedure allowsSELECTas well asDML(INSERT/UPDATE/DELETE) statementinitwhereasFunction
allowsonlySELECTstatementinit.
 Procedurescannot be utilizedinaSELECT statementwhereasFunctioncanbe embeddedina
SELECT statement.
 StoredProcedurescannotbe usedinthe SQL statementsanywhereinthe WHERE/HAVING/SELECT
sectionwhereasFunctioncanbe.
 The most importantfeature of storedproceduresoverfunctionistoretentionandreuse the
executionplanwhile incase of functionitwill be compiledeverytime.
 Functionsthatreturntablescan be treatedas anotherrowset.Thiscan be usedinJOINswithother
tables.
 Inline Functioncanbe thoughof as viewsthattake parametersandcan be usedinJOINsandother
Rowsetoperations.
 Exceptioncanbe handledbytry-catchblockin a Procedure whereastry-catchblockcannotbe used
ina Function.
 We can go for TransactionManagementinProcedure whereaswe can'tgo inFunction.
Can we create a table in function? ****
Yes we create table variable infunctionnottemptable.

More Related Content

What's hot

MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsDataminingTools Inc
 
Sas basis imp intrw ques
Sas basis imp intrw quesSas basis imp intrw ques
Sas basis imp intrw quesVinod Kumar
 
Oracle sql in 7 days by suesh.n v 1.0
Oracle sql in 7 days by suesh.n v 1.0Oracle sql in 7 days by suesh.n v 1.0
Oracle sql in 7 days by suesh.n v 1.0nsureshreddy51
 
Database Administrator interview questions and answers
Database Administrator interview questions and answersDatabase Administrator interview questions and answers
Database Administrator interview questions and answersMLR Institute of Technology
 
Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)Zhang Bo
 
Relational Database Fundamentals
Relational Database FundamentalsRelational Database Fundamentals
Relational Database FundamentalsKHALID C
 
SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4jeetendra mandal
 
Relational database- Fundamentals
Relational database- FundamentalsRelational database- Fundamentals
Relational database- FundamentalsMohammed El Hedhly
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmHARINATH REDDY
 
DBMS - Relational Model
DBMS - Relational ModelDBMS - Relational Model
DBMS - Relational ModelOvais Imtiaz
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql databasegourav kottawar
 

What's hot (20)

MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
 
Rdbms concepts
Rdbms conceptsRdbms concepts
Rdbms concepts
 
Sas basis imp intrw ques
Sas basis imp intrw quesSas basis imp intrw ques
Sas basis imp intrw ques
 
Ordbms
OrdbmsOrdbms
Ordbms
 
Oracle sql in 7 days by suesh.n v 1.0
Oracle sql in 7 days by suesh.n v 1.0Oracle sql in 7 days by suesh.n v 1.0
Oracle sql in 7 days by suesh.n v 1.0
 
Data structures
Data structuresData structures
Data structures
 
Oracle
OracleOracle
Oracle
 
Database Administrator interview questions and answers
Database Administrator interview questions and answersDatabase Administrator interview questions and answers
Database Administrator interview questions and answers
 
The Smartpath Information Systems | BASIC RDBMS CONCEPTS
The Smartpath Information Systems | BASIC RDBMS CONCEPTSThe Smartpath Information Systems | BASIC RDBMS CONCEPTS
The Smartpath Information Systems | BASIC RDBMS CONCEPTS
 
Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)
 
Viva voce
Viva voceViva voce
Viva voce
 
Relational Database Fundamentals
Relational Database FundamentalsRelational Database Fundamentals
Relational Database Fundamentals
 
SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4
 
Relational database- Fundamentals
Relational database- FundamentalsRelational database- Fundamentals
Relational database- Fundamentals
 
PPL, OQL & oodbms
PPL, OQL & oodbmsPPL, OQL & oodbms
PPL, OQL & oodbms
 
Sv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvmSv data types and sv interface usage in uvm
Sv data types and sv interface usage in uvm
 
Unit 02 dbms
Unit 02 dbmsUnit 02 dbms
Unit 02 dbms
 
DBMS - Relational Model
DBMS - Relational ModelDBMS - Relational Model
DBMS - Relational Model
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
Unit01 dbms 2
Unit01 dbms 2Unit01 dbms 2
Unit01 dbms 2
 

Viewers also liked

SQL Server 2012 Certifications
SQL Server 2012 CertificationsSQL Server 2012 Certifications
SQL Server 2012 CertificationsMarcos Freccia
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dbaNaviSoft
 
Sql server 2008 interview questions answers
Sql server 2008 interview questions answersSql server 2008 interview questions answers
Sql server 2008 interview questions answersJitendra Gangwar
 
Top 5 TSQL Improvements in SQL Server 2014
Top 5 TSQL Improvements in SQL Server 2014Top 5 TSQL Improvements in SQL Server 2014
Top 5 TSQL Improvements in SQL Server 2014Boris Hristov
 
Sql server 2012 dba online training
Sql server 2012 dba online trainingSql server 2012 dba online training
Sql server 2012 dba online trainingsqlmasters
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 Richie Rump
 
Data Quality Services in SQL Server 2012
Data Quality Services in SQL Server 2012Data Quality Services in SQL Server 2012
Data Quality Services in SQL Server 2012Stéphane Fréchette
 
70-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 201270-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 2012siphocha
 
Introduction to Master Data Services in SQL Server 2012
Introduction to Master Data Services in SQL Server 2012Introduction to Master Data Services in SQL Server 2012
Introduction to Master Data Services in SQL Server 2012Stéphane Fréchette
 
Best MCSA - SQL SERVER 2012 Training Institute in Delhi
Best MCSA - SQL SERVER 2012 Training Institute in DelhiBest MCSA - SQL SERVER 2012 Training Institute in Delhi
Best MCSA - SQL SERVER 2012 Training Institute in DelhiInformation Technology
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql serverDivya Sharma
 
Always on in SQL Server 2012
Always on in SQL Server 2012Always on in SQL Server 2012
Always on in SQL Server 2012Fadi Abdulwahab
 

Viewers also liked (14)

SQL Server 2012 Certifications
SQL Server 2012 CertificationsSQL Server 2012 Certifications
SQL Server 2012 Certifications
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dba
 
Sql server 2008 interview questions answers
Sql server 2008 interview questions answersSql server 2008 interview questions answers
Sql server 2008 interview questions answers
 
Top 5 TSQL Improvements in SQL Server 2014
Top 5 TSQL Improvements in SQL Server 2014Top 5 TSQL Improvements in SQL Server 2014
Top 5 TSQL Improvements in SQL Server 2014
 
Sql server 2012 dba online training
Sql server 2012 dba online trainingSql server 2012 dba online training
Sql server 2012 dba online training
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
Data Quality Services in SQL Server 2012
Data Quality Services in SQL Server 2012Data Quality Services in SQL Server 2012
Data Quality Services in SQL Server 2012
 
70-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 201270-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 2012
 
Good sql server interview_questions
Good sql server interview_questionsGood sql server interview_questions
Good sql server interview_questions
 
Introduction to Master Data Services in SQL Server 2012
Introduction to Master Data Services in SQL Server 2012Introduction to Master Data Services in SQL Server 2012
Introduction to Master Data Services in SQL Server 2012
 
Best MCSA - SQL SERVER 2012 Training Institute in Delhi
Best MCSA - SQL SERVER 2012 Training Institute in DelhiBest MCSA - SQL SERVER 2012 Training Institute in Delhi
Best MCSA - SQL SERVER 2012 Training Institute in Delhi
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
 
Always on in SQL Server 2012
Always on in SQL Server 2012Always on in SQL Server 2012
Always on in SQL Server 2012
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 

Similar to Sql Server Interview Question

Structured Query Language (SQL) _ Edu4Sure Training.pptx
Structured Query Language (SQL) _ Edu4Sure Training.pptxStructured Query Language (SQL) _ Edu4Sure Training.pptx
Structured Query Language (SQL) _ Edu4Sure Training.pptxEdu4Sure
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMSonia Pahuja
 
Implementing the Databese Server session 02
Implementing the Databese Server session 02Implementing the Databese Server session 02
Implementing the Databese Server session 02Guillermo Julca
 
SQL, Oracle, Joins
SQL, Oracle, JoinsSQL, Oracle, Joins
SQL, Oracle, JoinsGaurish Goel
 
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLA STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLijscai
 
A Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLA Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLIJSCAI Journal
 
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLA STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLijscai
 
A Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLA Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLIJSCAI Journal
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018Dave Stokes
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San FranciscoMySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San FranciscoDave Stokes
 
17-NoSQL.pptx
17-NoSQL.pptx17-NoSQL.pptx
17-NoSQL.pptxlevichan1
 
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortals
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortalsChapter 4 terminolgy of keyvalue databses from nosql for mere mortals
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortalsnehabsairam
 
Ch-11 Relational Databases.pptx
Ch-11 Relational Databases.pptxCh-11 Relational Databases.pptx
Ch-11 Relational Databases.pptxShadowDawg
 
Data massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesData massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesUlf Wendel
 

Similar to Sql Server Interview Question (20)

Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Structured Query Language (SQL) _ Edu4Sure Training.pptx
Structured Query Language (SQL) _ Edu4Sure Training.pptxStructured Query Language (SQL) _ Edu4Sure Training.pptx
Structured Query Language (SQL) _ Edu4Sure Training.pptx
 
Cassandra data modelling best practices
Cassandra data modelling best practicesCassandra data modelling best practices
Cassandra data modelling best practices
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Implementing the Databese Server session 02
Implementing the Databese Server session 02Implementing the Databese Server session 02
Implementing the Databese Server session 02
 
Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
SQL, Oracle, Joins
SQL, Oracle, JoinsSQL, Oracle, Joins
SQL, Oracle, Joins
 
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLA STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
 
A Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLA Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQL
 
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQLA STUDY ON GRAPH STORAGE DATABASE OF NOSQL
A STUDY ON GRAPH STORAGE DATABASE OF NOSQL
 
A Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQLA Study on Graph Storage Database of NOSQL
A Study on Graph Storage Database of NOSQL
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
 
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San FranciscoMySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
MySQL 8 Tips and Tricks from Symfony USA 2018, San Francisco
 
17-NoSQL.pptx
17-NoSQL.pptx17-NoSQL.pptx
17-NoSQL.pptx
 
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortals
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortalsChapter 4 terminolgy of keyvalue databses from nosql for mere mortals
Chapter 4 terminolgy of keyvalue databses from nosql for mere mortals
 
Sql fundamentals
Sql fundamentalsSql fundamentals
Sql fundamentals
 
Ch-11 Relational Databases.pptx
Ch-11 Relational Databases.pptxCh-11 Relational Databases.pptx
Ch-11 Relational Databases.pptx
 
Bigtable_Paper
Bigtable_PaperBigtable_Paper
Bigtable_Paper
 
Data massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesData massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodes
 
Sql material
Sql materialSql material
Sql material
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 

Sql Server Interview Question

  • 1. Database 1.What is DBMS? A.DBMS stands for database management system. It is collection of program that enables user to create and maintain a database. 2.What is Database? A. It is collection of information that is organized.So that it can be easily accessed,managed and updated. 2.What is RDBMS? A.RDBMS are the database management system which use to maintain data records and indices in the table. 3.What are the ACID properties? A.ACID properties takes grantee for all the database transactions to accomplish all tasks.(applies when modifying a database) Atomicity:-Either all or none,eg:our app is inserting 30 records and in between problem occurs at the point of 12 records.In this state transaction will rollback so this will be either all or none. Consistency:-Ensures that only valid data following all rules and constraints is written in the database.[ATM PIN:Incorrect]. Whatever data is going to insert they all should be validated by defining rules and ensure that there are no invalid data is going to insert in database so this way it will manage consistency of the database. In any case running transaction violate rule at that same time entire transaction will be a rollback. Isolation:-make sure two transaction is unaware of each other In one shop seller is selling items very fast and due to this number of items is also decreasing in stocks and at other side one person is also adding new items in stocks. Here, this both transactions is different and totally unaware of another. These properties ensure that one transaction is not interrupted by another transaction. (no two documents get mixed up while printing) Durability:-committed data stored forever. Application inserted 30 records in one transaction and this transaction is completed and committed successfully in the database that means this record persist forever in database until and unless it’s not deleted by any application users or database users. 4.What is Normalization? A.The process of organizing data to minimize redundancy.Usually dividing a db into two or more table and defining relationship betwn the tables.Add, delete, update can be done in one table and then propogate through the rest of the DB. 5.What is D-normalization and when do we need it? D-normalization is used to speed up the read performance (data retrieval) of a database by adding a redundant data.We need when the application is read intensive i.e under heavy read load. 6.What are the different Normal Forms? 1NF:Eliminate repeating groups 2NF:-Eliminate Redundant Data 3NF:-Eliminate columns not dependent on Key.
  • 2. 7.Why we use normalization and denormalization. which is the better techniques? A.Pros and Cons of normalization: 1.It is used basically under the condition where the app is write intensive and the write- load is more than the read-load. 2.Updates,Inserts are faster bcz data is located into single place and there are no duplicates. 3.Select will simple if there are fetched from single table or else it would be slow down because of joins. Pros and Cons of De-normalization: 1.It is used basically under the condition where the app is only read intensive. 2.The data is same table so there is no need for any joins. hence the select is very fast. 3.But bcz the data is duplicate , the update and inserts become complex and costly. Hence we need to use both the techniques together? Yes they can be, because real word applications have a mix of read and write loads. Although, denormalized schema can greatly improve performance under extreme read- loads but the updates and inserts become complex as the data is duplicate and hence has to be updated/inserted in more than one places. When mixing normalization and denormalization, focus on denormalizing tables that are read intensive, while tables that are write intensive keep them normalized. Table Design 1.What is Table? In a relational database , a table which contains a set of data element(values) using a vertical columns(identifies by a name) and horizontal rows. A table has a specified number of columns , but can have any number of rows. Syntax:- CREATE TABLE table_name ( Column_name1 data_type(size), Column_name2 data_type(size), Column_name3 data_type(size), .. ); 2.What is Data type? A.Sql Data type is use to specify type of data of any object. Each column, variable , expression has related data type in sql Eg:-bit,int,tinyint,smallint,decimal,float,real,numeric,date,time,char,varchar. 3.What are the different types of data types in SQL Server? A. bit,int,tinyint,smallint,decimal,float,real,numeric,date,time,char,varchar, varchar(mar)[only in 2005].
  • 3. 4.What is the difference between Float, BIG Int and Integer? A.Integer type can contain only whole number(like 23 or 342). Numeric type can contain decimal numbers (like 45.5).Float(n<24) and storage size is 4 bytes.decimal (precision,scale) and storage size is 5 to 17 bytes. Big int and int is a whole number(big int storage size is 8 bytes and int is 4 bytes). 5.Explain the Decimal Data types and its uses? A. Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type can be represented exactly with precision and scale. DECIMAL(2,2) and DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types. 6.What is the use of different types of Integer data types? A.int,bigint,tinyint,smallint are the different integer datatypes. 7.What is the difference between bit, Char and Varchar? A.char and nchar are fixed length and which will reserve storage space. Varchar and nvarchar are variable length and which will use only the spaces for the character which we store. It will not reserve storage like char or nchar. Bit is nothing but 0 or 1. 8.What is Unicode? ** A.Unicode character takes more bytes to store the data in the database.As many global industries want to increase their business worldwide they provide services to the customer to support diff language like Chinese ,Japanese, Korean, Arabic. For storage no difference in database for Unicode and non Unicode, only the difference is Unicode takes two times the space. Non-Unicode Unicode (char, varchar, text) (nchar, nvarchar, ntext) Stores data in fixed or variable length Same as non-Unicode char: data is padded with blanks to fill the field size. For example, if a char(10) field contains 5 characters the system will pad it with 5 blanks nchar: same as char varchar: stores actual value and does not pad with blanks nvarchar: same as varchar requires 1 byte of storage requires 2 bytes of storage char and varchar: can store up to 8000 characters nchar and nvarchar: can store up to characters Best suited for US English: "One problem with data types that use 1 byte to encode each character is that the data type can only represent 256 different characters. This forces multiple encoding specifications (or code pages) for different alphabets such as European alphabets, which are relatively small. It is also impossible to Best suited for systems that need to support at least one foreign language: "The Unicode specification defines a single encoding scheme for most characters widely used in businesses around the world. All computers consistently translate the bit patterns in Unicode data into characters using the single Unicode specification. This ensures
  • 4. handle systems such as the Japanese Kanji or Korean Hangul alphabets that have thousands of characters."1 that the same bit pattern is always converted to the same character on all computers. Data can be freely transferred from one database or computer to another without concern that the receiving system will translate the bit patterns into characters incorrectly. 9.What is the difference between Varchar and Nvarchar? ** A.Varchar holds non Unicode and Nvarchar is Unicode data (where it can store non Asian langaue like Chinese but it spaces more bytes). Declare @sampleVar varchar(10) Declare @sampleNVar nvarchar(10) set @sampleVar = 'VarSamp Ж' set @sampleNVar = 'NVarSamp Ж' Select @sampleNVar, @sampleVar set @sampleNVar = N'NVarSamp Ж' set @sampleVar = N'VarSamp Ж' Select @sampleNVar, @sampleVar 10.What are different date time data types? * A.There are two types of datatime datatypes -Datatime:store dates from January 1,1753 through dec 31, 9999. Millisec will be round to three hundredth. -SmallDatatime: store dates from January 1,1900 through june 6, 2079.The date,hours and minutes are copied. The seconds are set to 0. DECLARE @smalldatetime smalldatetime = '12:10:05.122';[only 3 digit should be there in millisec] DECLARE @datetime datetime = '12:10:05.122'; SELECT @datetime AS '@datetime', @smalldatetime AS '@smalldatetime'; --Result --@datetime @smalldatetime ------------------------- ----------------------- --1900-01-01 12:10:05.123 1900-01-01 12:10:00 Date datatype:
  • 5. DECLARE @date date = '12-21-05'; DECLARE @datetime datetime = @date; SELECT @datetime AS '@datetime', @date AS '@date'; --Result --@datetime @date ------------------------- ---------- --2005-12-21 00:00:00.000 2005-12-21 Time datatype: DECLARE @time time(4) = '12:10:05.1237'; DECLARE @datetime datetime = @time; SELECT @datetime AS '@datetime', @time AS '@time'; --Result --@datetime @time ------------------------- ------------- --1900-01-01 12:10:05.123 12:10:05.1237 Datetimeoffset(n) DECLARE @datetimeoffset datetimeoffset(4) = '1968-10-23 12:45:37.1234 +10:0'; DECLARE @datetime datetime = @datetimeoffset; SELECT @datetime AS '@datetime', @datetimeoffset AS '@datetimeoffset'; --Result --@datetime @datetimeoffset ------------------------- ------------------------------ --1968-10-23 12:45:37.123 1968-10-23 12:45:37.1237 +01:0 DateTime2(n):n is nothing but the millisecond it can take from the given datevalue (N=7 max). DECLARE @datetime2 datetime2(7)/ datetime2 = '1968-10-23 12:45:37.123790455'; DECLARE @datetime datetime = @datetime2; SELECT @datetime AS '@datetime', @datetime2 AS '@datetime2'; --Result --@datetime @datetime2 ------------------------- ------------------------ --1968-10-23 12:45:37.123 1968-10-23 12:45:37.1237905[max number it can fetch]
  • 6. 11.What are unique identifiers in SQL Server Table? ** A.Unique identifier are new in sql 7.0 and behave little different then our identity column. Unique identifier is also referred as a GUID(globally unique identifier). It can be generated by NEWID() or NEWSEQUENTIALID().GUID is a unique binary number; no other computer in the world will generate a duplicate of that GUID value. The major advantage of using GUIDs is that they are unique across all space and time. This comes in handy if you're consolidating records from multiple SQL Servers into one table, as in a data warehousing situation. GUIDs are also used heavily by SQL Server replication to keep track of rows when they're spread out among multiple SQL Servers. The main disadvantage to using GUIDs as key values is that they are BIG. At 16 bytes a pop, they are one of the largest datatypes in SQL Server. Indexes built on GUIDs are going to be larger and slower than indexes built on IDENTITY columns, which are usually ints (4 bytes).Not only that, identity they are just plain hard to read. Mostly for security reason it is used , we cannot track the ID of uniqueIdentifier. create table #temp ( Item int, GUID1 uniqueidentifier ); INSERT into #temp VALUES (1,NEWID()) select * from #temp output Item GUID1 1 F3323B56-9961-4096-9595-83A53E7B0CCE 12.What is check constraint in SQL Server? ** A.We can use check constraint to enforce specific patterns for data or to limit the range of possible values in a column.There are two diff leve Column level:-This is applied only to the column and cannot reference data in another column. Table level:-This is applied only to all the column within the table and not applied outside the column. Mostly will use data column for check salary <= 50000. Table level check constraints for the Email ID. 13.What is default constraint? * A.Default constraint is used to insert a default value into a column.The default value will be added to all the new records, if no other value is specified. Example: city with default value Mumbai CREATE TABLE Persons ( P_ID int not null, City varchar(255) DEFAULT ‘Mumbai’, JoiningDate DEFAULT GETDATE() ); 14.What is Null ability?
  • 7. A value of NULL indicates that the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown because the value of each NULL is unknown. Null values generally indicate data that is unknown, not applicable, or that the data will be added later. For example, a customer's middle initial may not be known at the time the customer places an order. To test for null values in a query, use IS NULL or IS NOT NULL in the WHERE clause. 15.Explain table relationship? A. When creating a database, common sense dictates that we use separate tables for different types of entities. Some examples are: customers, orders, items, messages etc... But we also need to have relationships between these tables. For instance, customers make orders, and orders contain items. These relationships need to be represented in the database. Also, when fetching data with SQL, we need to use certain types of JOIN queries to get what we need. There are several types of database relationships. Today we are going to cover the following: One to One Relationships One to Many and Many to One Relationships Many to Many Relationships Self Referencing Relationships When selecting data from multiple tables with relationships, we will be using the JOIN query. There are several types of JOIN's, and we are going to learn about the the following: Cross Joins Natural Joins Inner Joins Left (Outer) Joins Right (Outer) Joins We will also learn about the ON clause and the USING clause. 16.What is Primary Key? * The PRIMARY KEY is a field in a table which uniquely identifies each record in a database table. Primary keys must contain UNIQUE values. A primary key column cannot contain NULL values. Most tables should have a primary key, and each table can have only ONE primary key. Syntax: CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) 17.What is Foreign Key?
  • 8. A foreign key is a column (or columns) that references a column (most often the primary key) of another table. The purpose of the foreign key is to ensure referential integrity of the data. 18.What is composite key? * A key composed of two to more attributes. A primary key consists of one or more columns (from that table) are called composite key. A composite key is made up of elements that should need foreign keys. CREATE TABLE voting ( QuestionID NUMERIC, MemberID NUMERIC, PRIMARY KEY (QuestionID, MemberID) ); Exp : Let say EmpID, EmailID, SSN are columns in Employee table and projectID in project table . if EmpID and project id are put in projectionHours table then combination of empid and project ID called as composite key because combination of these two act as primary key in projectionHours table. 19.What is surrogate Key? A key with no business meaning, example :zipCode. 20.What is component/candidate key? A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.A composite key is made up of elements that may or may not be foreign keys. Example empID, Rollnumber,EnrollNo etc. 21.What are Primary Key and Foreign Key Constraint? * 22.How to get the list of primary key and foreign key of the table? **** A.By querying information_schema or sys.object or system database we can get the list. 21.Can we insert null value in primary column? * A.No we cant insert null value in a single column primary key while in composite primary key only one column can be null 22.What is difference between Primary Key and Unique Key? ** A.Primary key and unique both are used to perform same that is unique identify the rows in the table. Unique keys can have nulls but primary key cannot have nulls. We can create multiple unique keys on a table but we can have only one primary key. Unique key contains non- clustered index by default and primary key creates a clustered index by default.Both the key can be referenced by the foreign key. We can insert one null value in unique key but not in primary key.
  • 9. 23.What is Identity Column in Table? * A.Identity is the property of column which inserts incremental value in the column at the insert of new row in parent table of that column. For example in Employee table when we set ID as identity then for every inserted employee record there will be an auto incremental value get inserted in the ID column automatically. For Identity you can set the increment value i.e. the value by which next inserted value increment. So if you set increment by 10 then inserted value will be like 10, 20, 30, 40…….. 25.Syntax to check current Identity of the table? * A.DBCC CHECKIDENT ( table_name [, { NORESEED | { RESEED [, new_reseed_value ] } } ] ) [ WITH NO_INFOMSGS ] Example DBCC CHECKIDENT (table) DBCC CHECKIDENT (table, NORESEED) DBCC CHECKIDENT (table, RESEED, 10) 26.What is the difference between Scope of Identity on @@identity? *** A. SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are function used for same value type but different results. IDENT_CURRENT returns the current identity value irrespective of session and scope. SCOPE_IDENTITY returns last identity value generated the current scope Irrespective of tables. I.e. it could be value from last table which is updated in current scope. @@IDENTITY returns the last identity values that are generated in any table in the current session. It’s not limited to any specific scope. I.e. while updating in current scope the trigger on this table insert data in some other table For example, there are two tables, Table1 and Table2, and an INSERT trigger is defined on Table1. When a row is inserted to Table1, the trigger inserts a row in Table2. This scenario illustrates two scopes: the insert on Table1 and the insert on Table2 by the trigger. Table1 and Table2 have identity columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on Table1. @@IDENTITY will return the last identity column value inserted across any scope in the current session. This is the value inserted in Table2. SCOPE_IDENTITY () will return the IDENTITY value inserted in Table1. 27.Can we change identity key values for a table or reset the identity key value. A.Yes 28.What is function Ident_INCR? ***
  • 10. 29.What is times stamp data type is SQL Server? ** A. Timestamp is a data type that exposes automatically generated binary numbers, which are guaranteed to be unique within a database. timestamp is used typically as a mechanism for version-stamping table rows. The storage size is 8 bytes. create table #temp ( Name varchar(50), TS timestamp, RS RowVersion ) Error: A table can only have one timestamp column. Because table '#temp' already has one, the column 'RS' cannot be added. TimeStamp: create table #temp ( Name varchar(50), TS timestamp ) insert into #temp (name) Select 'pukal' union all select 'rani' union all select 'nadar' go select * from #temp update #temp set name ='pukal a' where name='pukal' select * from #temp BTW, now a day, you should use RowVersion datatype (above sql server 2008) rather than TimeStamp as I told you above too that TimeStamp will be deprecated and RowVersion is synonyms for TimeStamp.
  • 11. 30.What is the alternative of timestamp? ** A.BTW, now a day, you should use RowVersion datatype (above sql server 2008) rather than TimeStamp as I told you above too that TimeStamp will be deprecated and RowVersion is synonyms for TimeStamp. JOINS AND SELECT 1.What is select statement in TSQL? * A. The SELECT statement is used to query the database and retrieve selected data that match the criteria that we have specify. 2.What is the Join in SQL Server? * A.SQL Server (Transact-SQL) JOINS are used to retrieve data from multiple tables. A SQL Server JOIN is performed whenever two or more tables are joined in a SQL statement. 3.What are the different types of join? * A.There are 4 different types of SQL Server joins: SQL Server INNER JOIN (or sometimes called simple join) SQL Server LEFT OUTER JOIN (or sometimes called LEFT JOIN) SQL Server RIGHT OUTER JOIN (or sometimes called RIGHT JOIN) SQL Server FULL OUTER JOIN (or sometimes called FULL JOIN) 4.Difference between Left join and Outer Join? * A.There is actually no difference between a left join and a left outer join – they both refer to the exact same operation in SQL. Only in the syntax will write the outer join. 5.What is full outer join? * A.matching row from both the table and unmatching row frm left and right table. Eg.
  • 12. 6.What is inner join? * A.Inner join gets only the matching rows from the table. 7.What is cross join? * A.A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table 8.Write one example for self-join? ** A. A self join is a join in which a table is joined with itself (which is also called Unary relationships), specially when the table has a FOREIGN KEY which references its own PRIMARY KEY. Manager is an employee, so we need to do self join in Employee table Example: SELECT DISTINCT e.emp_id AS 'mng_id', e.emp_name AS 'mng_name' FROM employees e, employees m WHERE e.emp_id = m.mng_id
  • 13. 9.What is where clause? * A. The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified criterion. Syntax: SELECT column_name,column_name FROM table_name WHERE column_name operator value; 10.What are the sub queries? * A. A subquery is a query within a query.In SQL Server (Transact-SQL), asubquery is also called an INNER QUERY or INNER SELECT. In SQL Server (Transact-SQL), the main query that contains the subquery is also called the OUTER QUERY or OUTER SELECT. Subquery in Where,From and Select Clause 1.Where Clause: The subquery will be found in the WHERE clause. These subqueries are also called nested subqueries. SELECT p.product_id, p.product_name FROM products p WHERE p.product_id IN (SELECT inv.product_id FROM inventory inv WHERE inv.quantity > 10); 2. FROM CLAUSE: A subquery can also be found in the FROM clause. These are called inline views. SELECT suppliers.supplier_name, subquery1.total_amt FROM suppliers, (SELECT supplier_id, SUM(orders.amount) AS total_amt FROM orders GROUP BY supplier_id) subquery1 WHERE subquery1.supplier_id = suppliers.supplier_id; 3. SELECT CLAUSE: A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM, COUNT, MIN, or MAX function, but you do not want the aggregate function to apply to the main query. SELECT e1.last_name, e1.first_name, (SELECT MAX(salary)
  • 14. FROM employees e2 WHERE e1.employee_id = e2.employee_id) subquery2 FROM employees e1; The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields. The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such as the SUM, COUNT, MIN, or MAX function is commonly used in the subquery. 11.What are the nested queries in SQL Server? ** A.If a subquery contains another sub query inside it the its called nested sub query. there could be multiple no of nesting possible in a sub query. if two sub queries or queries are dependent on each other then its called correlated subqueries. Example select EmpName , (select Empname from emp where empid=a.managerid) as manager from Emp A in this example a column is used in upper sub query then its correlated subquery. Nested Sub Query [Single or Multi-Level]: Select * from tableA where columnA=(Select * from TableB where ColumnB=’SomeValue’) If the value is more then one then use <,>,>=,!=(IN/NOT IN, ANY – [>ANY or <ANY], ALL – [>ALL or <ALL], EXISTS(The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query) ) 12.What is inline query? ** A. Nested and correlated query 13.What are the aggregate functions in SQL Server? * A. Count, Min, Max and Average are the few aggregate functions in SQL Server. Count function: Select count (*) from Table1. It will deliver count of the table i.e. no of records. If you will put the filters in the query then it will give the count of filtered
  • 15. records.Example 1.The null values in a column doesn’t counts by the count function in SQL Server.2.The space will be consider as a value by count function in SQL Server. Min function: Min function retrieves the minimum values in a column it works on group by function and also without any group by function. Max Function: Max function is used to get the max value of a column. Average Function: Average is used to get the average of the column. Average can be on the groups also. This functions returns value as mathematics average function returns. 14.What is Group By? * A. Aggregate functions often need an added GROUP BY statement. The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. “SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;” 15.What is Having clause? ** A. The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. “SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value;” 16.What is difference between where and having clause? ** A.1.Where can be used in select , update and delete statement.Having can be used only with select statement. 2.Where is used before group by function and having is used after group by function 3.where cannot use aggregate unless it is a subquery contained but having clause can use it. select name from #temp where count(Name)>0 “Error:An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.”
  • 16. select name from #temp group by name having count(Name)>0 success output 4.Where is applies to each and every row whereas a having clause applies to a summarized or group by clause. 5.In where clause the data is fetched from memory depending on the condition but having will fetch the entire data and then condition is applied. 17.What is the table variable? ** A. Same structure as a normal table but only difference is the shortest life time among all the varieties.@table_variables are created implicitly when a batch containing a DECLARE @.. TABLE statement is executed (before any user code in that batch runs) and are dropped implicitly at the end. No drop statement used for table variable but for temptable drop command needed. Transaction is not supported for table variable below example. This table is created and stored in memory and its lifetime is decided by the stored procedure who have created it. Once stored procedure/DML statement exits, this table gets auto cleaned and memory gets free. Apart from that, log activity is truncated immediately. An important note, If we have a requirement to use a table structure in user defined function then we have only one option as Table variable and no other variety can be used. Syntax:Declare @Student Table (Id int, Name varchar(50)) CREATE table #T (s varchar(128)) DECLARE @T table (s varchar(128)) INSERT into #T select 'old value #' INSERT into @T select 'old value @' ;with CTE as ( SELECT * from #T union all SELECT * from @T) select * from CTE BEGIN transaction UPDATE #T set s='new value #' UPDATE @T set s='new value @' ROLLBACK transaction ;with CTE as ( SELECT * from #T union all SELECT * from @T) select * from CTE
  • 17. We need to execute the whole query in one go. Or else error will through. declare @temp table (name varchar(50)) insert into @temp (name) Select 'pukal' union all select 'rani' union all select 'nadar' select * from @temp go error: Must declare the table variable "@temp". 18.What is the temporary table? ** A.Temp table is use create a temporary record in tempDb.Temp table cannot used in user defined function but table variable can be used. Temp table are of two types local or global. 1.Local Temp table:- Local declared by (#). It will be within the same new query block.it will be used only for current user. Unlike the majority of the other data types in SQL Server, you cannot use a table variable as an input or an output parameter. In fact, a table variable is scoped to the stored procedure, batch, or user-defined function just like any local variable you create with a DECLARE statement. The variable will no longer exist after the procedure exits - there will be no table to clean up with a DROP statement. However, because you can’t pass a table variable to another stored procedure as input .Using a temporary table inside of a stored procedure may result in additional re-compilations of the stored procedure. Table variables can often avoid this recompilation hit. You cannot create a non- clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or UNIQUE constraint on the table.Also, SQL Server does not maintain statistics on a table variable, and statistics are used heavily by the query optimizer to determine the best method to execute a query. The table definition of a table variable cannot change after the DECLARE statement. Any ALTER TABLE query attempting to alter a table variable will fail with a syntax error. you cannot use a table variable with SELECT INTO or INSERT EXEC queries. Local Temporary Tables These tables are created within a procedure and stored in the temp_db provided by SQL server. They can be identified with a session specific identifier. It can be used when data is coming from another stored procedure. It also reduces the amount of locking required and also involves less logging. Still, there are few limitations such as character limit is 116 and transactions can create unnecessary locks in temp_db. Syntax:
  • 18. Create table #Student (Id int, Name varchar(50)) 19.What is the global temporary table? ** A.Global Temp table:-global declared by (##).It will be next block. Session doesn’t get expired.It is visible to everyone. Global Temporary Tables: These tables are same as local temporary table but the difference lies in the lifetime as it is available for all the sessions. This can be useful when the same set of data is required by one or more users. But the issue will come when the user, who should not be given access to this data, will have access to it as it is a global table and available for all users. Syntax: Create table ##Student (Id int, Name varchar(50)) See the difference of two #. 20.Difference between temporary table and table variable? ** A. TABLE Variable Temporary TABLE Current batch Current session nested stored procedures. Global: all sessions. UDFs, Stored Procedures, Triggers, Batches. Stored Procedures, Triggers, Batches. DECLARE statement only. CREATE TABLE statement. SELECT INTO statement. Can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement. Indexes can be added after the table has been created. PRIMARY KEY, UNIQUE, NULL, CHECK, but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY not allowed. PRIMARY KEY, UNIQUE, NULL, CHECK. Can be part of the CREATE TABLE statement, or can be added after the table has been created. FOREIGN KEY not allowed. The SET IDENTITY_INSERT statement is not supported. The SET IDENTITY_INSERT statement is supported. Truncation Not allowed.drop not required Truncate Allowed.drop is required Not affected (Data not rolled back). Affected (Data is rolled back). If we use nested stored procedures which use the resultset, certain scenarios using dy- namic SQL, and cases where you need not transaction rollback support. Secondly, the size of the resultset will determine which solution to choose. If the table stores a resultset so large you require indexes to improve query performance, you’ll need to stick to a temporary table. If the resultset is small, the table variable is always the optimum choice. “Table variables can offer performance benefits and flexibility when compared to temporary tables”.
  • 19. 21.What is the union all clause? ** A.The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It does not remove duplicate rows between the various SELECT statements (all rows are returned). Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types. SELECT expression1, expression2, ... expression_n FROM tables WHERE conditions UNION ALL SELECT expression1, expression2, ... expression_n FROM tables WHERE conditions; 22.What is union Clause? ** A.The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; The column names in the result-set of a UNION are usually equal to the column names in the first SELECT statement in the UNION. 23.Difference between union all and union clause? ** A. UNION removes duplicate rows. UNION ALL does not remove duplicate rows. example: select * from #temp1 select * from #temp
  • 20. select id from #temp1 union select id from #temp select id from #temp1 union all select id from #temp 24.What is the Ranking function in SQL Server? **** A.Row_Number():Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition. It assigns continous and unique number. Rank():Returns the rank of each row within the partition of a result set. It is not continguous nor unique. Dense_Rank():Returns the rank of rows within the partition of a result set, without any gaps in the ranking.It is continguous but not unique. 25.Difference between rank and dense rank? **** A.Rank():Returns the rank of each row within the partition of a result set. It is not continguous nor unique. Dense_Rank():Returns the rank of rows within the partition of a result set, without any gaps in the ranking.It is continguous but not unique. Ntile():Distributes the rows in an ordered partition into a specified number of groups. select * from #TempRank
  • 21. with rownumer as (select *,Row_Number() over(order by salary) as sal from #TempRank) select * from rownumer order by rownumer.sal asc with ranking as (select *,rank() over(order by salary) as sal from #TempRank) select * from ranking order by ranking.sal asc with denserank as (select *,dense_rank() over(order by salary) as sal from #TempRank) select * from denserank with ntile1 as (select *,ntile(3) over(order by salary) as sal from #TempRank)
  • 22. select * from ntile1 26.What is top operator in SQL Server? ** A.Fetch the rows returned in a query result set to a specified number of rows. When TOP is used in conjunction with the ORDER BY clause, the result set is limited to the first N number of ordered rows; otherwise, it returns the first N number of rows in an undefined order. Use this clause to specify the number of rows returned from a SELECT statement or affected by an INSERT, UPDATE, MERGE, or DELETE statement. Syntax: [ TOP (expression) [PERCENT] [ WITH TIES ] ] 27.What is table sample in SQL Server? *** A.TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM clause. The rows retrieved are random and they are are not in any order. This sampling can be based on a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set. Example 1: SELECT FirstName,LastName FROM Person.Contact TABLESAMPLE SYSTEM (10 PERCENT) Example 2: SELECT FirstName,LastName FROM Person.Contact TABLESAMPLE SYSTEM (1000 ROWS) 28.What is the delete command? * A. The T SQL DELETE statement is a used to delete a one or more records from a table. Syntax:DELETE FROM table WHERE conditions; 29.What is truncate command? **
  • 23. A. The TRUNCATE TABLE statement is used to remove all records from a table in SQL Server. It performs the same function as a DELETE statement without a WHERE clause. If you truncate a table, the TRUNCATE TABLE statement can not be rolled back. 30.Difference between delete and truncate? ** A.Both command empty the table Delete will use to delete each or full tbale but truncate can delete whole table bcz it doesn’t have where condition in it. Delete can be rollback or commit or trigger but truncate cannot Delete is DML and Truncate is DDL Why we use truncate is bcz it is faster then delete. 31.What are dynamic queries? *** A. A dynamic SQL in a stored procedure is a single Transact-SQL statement or a set of statements stored in a variable and executed using a SQL command. A Dynamic SQL is needed when we need to retrieve a set of records based on different search parameters. create table #tblEmployees ( EmpID varchar(50) ) insert into #tblEmployees (EmpID) ( select 1 union all select 2) DECLARE @EmpID AS SMALLINT DECLARE @SQLQuery AS NVARCHAR(500) /* set the parameter value */ SET @EmpID = 1 /* Build Transact-SQL String with parameter value */ SET @SQLQuery = 'SELECT * FROM #tblEmployees WHERE EmpID = ' + CAST(@EmpID AS NVARCHAR(10)) /* Execute Transact-SQL String */ EXECUTE(@SQLQuery) Output:EmpId 1 32.What is distinct clause? How it works? ** A. The SQL DISTINCT clause is used to remove duplicates result set.The syntax for the SQL DISTINCT clause is: SELECT DISTINCT expressions FROM tables WHERE conditions; Eg: 1.SELECT DISTINCT city FROM Customers; This SQL DISTINCT example would return all unique city values from the Customers table. 2. SELECT DISTINCT city, state FROM Customers;
  • 24. This SQL DISTINCT clause example would return each unique city and state combination. In this case, the DISTINCT applies to each field listed after the DISTINCT keyword. If there are multiple column distinct will apply that many time with multiple of rows. 33.How to use Order by in Sub Queries? ** A. The SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement. Syntax The syntax for the SQL ORDER BY clause is: SELECT expressions FROM tables WHERE conditions ORDER BY expression [ ASC | DESC ]; Thing to Remember If the ASC or DESC option is not provided in the ORDER BY clause, the results will be sorted by expression in ascending order (which is equivalent to "ORDER BY expression ASC"). Order by clause can’t be used in a view definition. Order by cant be used in a sub query having aggregate functions in select statement 35.What is the @@error? ** The @@ERROR system function is used to implement error handling code. It contains the error ID produced by the last SQL statement executed during a client’s connection. When a statement executes successfully, @@ERROR contains 0. To determine if a statement executes successfully, an IF statement is used to check the value of the function immediately after the target statement executes. It is imperative that @@ERROR be checked immediately after the target statement, because its value is reset when the next statement executes successfully. USE tempdb go CREATE PROCEDURE ErrorHandling AS Select * from EMP Print 'Fatal Error' GO EXEC ErrorHandling Use tempdb go Create Table EMP ( ID int identity, EmpName varchar(50) not null ) Use TempDB GO Create PROCEDURE ErrorHandling_Insert @EmpName varchar(50)=null
  • 25. As insert EMP values (@EmpName) Print 'Error Inserting Null Name' GO Use TempDB GO Alter PROCEDURE ErrorHandling_Insert @EmpName varchar(50)=null As insert EMP values (@EmpName) if @@ERROR <> 0 Begin PRINT 'Error Occured' END Exec ErrorHandling_Insert Exec ErrorHandling_Insert 'Pukal' 36.What is the @@raise error? ** 37.What is the @@row count? ** 38.What is Date Diff function? ** A. Date diff tells the difference between the two dates. Syntax: DATEDIFF (datepart , startdate , enddate ) Datepart could e mm or dd or yy or mi depends upon the requirement. Below are the few points related to date diff. DATEDIFF does not guarantee that the full number of the specified time units passed between 2 datetime Values. -- Get difference in hours between 8:55 and 11:00 SELECT DATEDIFF(hh, '08:55', '11:00'); -- Returns 3 although only 2 hours and 5 minutes passed between times -- Get difference in months between Sep 30, 2011 and Nov 02, 2011 SELECT DATEDIFF(mm, '2011-09-30', '2011-11-02') -- Returns 2 although only 1 month and 2 days passed between date
  • 26. To get the number of full time units passed between date times, you can calculate the difference in lower Units and then divide by the appropriate number: SELECT DATEDIFF(mi, '08:55', '11:00')/60; -- Returns 2 hours now 39.What is Date Add Function? ** 40.What is date part function? *** 41.What is coalesce function in SQL Server? *** 42.What is difference between stuff and Replace function? *** A.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. Example: select stuff('Pukal',1,1,'r') Ouput rukal 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 Example: select replace('Pukal','k','g') output Pugal 43.What are the sparse column and when we use it? **** 44.How to Convert Integer to String in SQL Server?
  • 27. A. DECLARE @i int SET @i=98235 -- Firs Ways - Use CAST function SELECT CAST(@i as varchar(10)) -- Second Way --> Use CONVERT function SELECT CONVERT(varchar(10),@i) --Third Way : Use STR function SELECT LTRIM(STR(@i,10)) 45.What is CrossTab? pivot which converts rows into columns. example: -------------------Pivot and unPivot(Crossab)----------------------------- Create table #tempPivot ( customername varchar(50), Productname varchar(50), Amount int ) insert into #tempPivot(customername,Productname,Amount) ( select 'pukalrani','Skirts',200 union all select 'rani','Shoes',200 union all select 'nadar','skirts',200 union all select 'pukalrani','Skirts',400 ) select * from #tempPivot --------------define the column names------------ select customername,shoes,skirts ----------------actual data--------------------- from ( select customername,productname,amount from #tempPivot ) as pivotdata ---------------pivot function--------------------- pivot ( sum(amount) for productname in(skirts,shoes) ) as pivoting
  • 28. The Cross-tabulation, or Crosstab, query pivots the second GROUP BY column (or dimension) values counterclockwise 90 degrees and turns it into the crosstab columns. The following are the methods to transform the row data into different column attributes- Pivot Method Case Expression Method Dynamic Crosstab Queries PIVOT Method: Microsoft have the introduced this keyword with the release of SQL Server 2005, which is being used for coding crosstab queries. The pivot method deviates from the normal logical query flow by performing the aggregate GROUP BY function and generating the crosstab results as a data source within the FROM clause. If you think of PIVOT as a table-valued function that’s used as a data source, then it accepts two parameters. The first parameter is the aggregate function for the crosstab’s values. The second measure parameter lists the pivoted columns. Using Coalesce() in sqlserver When we have multi-value attribute with single or more null values in a Table, the Coalesce() function is very useful. d Name Ph_ no Alt_ no Office no 101 Albert 999999 456453 321333 102 khan null null 123455 103 victor 112121 null null 104 lovely null null 1897321
  • 29. The above Employee table may have single value or three values. If it has single value, then it fills null values with remaining attributes. When we retrieve the number from employee table, that number Should Not be Null value. To get not nullvalue from employee table, we use Coalesce() function. It returns the first encountered Not Null Value from employee table. Hide Copy Code select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from employee It returns: id Name Contactnumber 101 Albert 999999 102 khan 123455 103 victor 112121 104 lovely 1897321 VIEWS What is the view in SQL Server? ** A.It is nothing but a virtual table, hide complexity. 1.hide some data from user 2.make query easier /more natural 3.modularity of database access similarly there in materialized views but only difference is performance is faster then views. It creates a physical table , if there is any in the base table we need to recompute mviews.
  • 30. What are the updated views? *** A.Views can update only if it is in the same base table. if we are having joins and updating only one table then it will work. What are the materialized views or Indexed Views in SQL Server? **** A.views:data are up to date,slow performance everytime it execute. Mviews:not up to date, faster performance,outside the database we cn create a mviews, we can hv index in ths, similar to normal table. What is view with check option? **** The with check option causes the where clause of the view to check the data being inserted or updated through the view in addition to the data being retrieved. In a sense, it makes the where clause a two-way restriction. This option is useful when the view should limit inserts and updates with the same restrictions applied to the where clause. Write the Create syntax for Views. ** CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition What is common table expression (CTE)? *** A CTE is a temporary/logical View, it is not store physically. It is a named query, the result for which is only available to the very next query after the CTE is defined. CTE is defined using WITH clause.Short life span.
  • 31. Recursive CTE[sql server2005] which calls itself example emp and manager data. What is difference between CTE and View? **** A CTE is a temporary/logical View, it is not store physically. It is a named query, the result for which is only available to the very next query after the CTE is defined. CTE is defined using WITH clause. A View is a physical object that is present in the database. View is as good as a Table but it doesn't store data physically as compared to a table, only the data schema is stored in View. View,when referred, pulls data by executing the query that is associated with it. The biggest difference between a CTE and View, is that, View or derived table cannot call itself, whereas CTE can call itself and hence support recursion. In many databases, views have options, for instance to index them. Stored procedure 1.What is stored procedure in SQL Server? ** A.It is a Named group of sql statements that have been previously created and stored in the server DB.Sp accept input parameter so that a single SP can be used over the network by several clients using diff input data.Sp reduce network traffic and improve performance. 2.How to pass record set in stored procedure? *** A. One solution would be to store the rows returned for your initial query into a cursor then you can loop thru the cursor and either call a function passing one row at a time... or just do the process in the same block. 3.Is nesting possible in stored procedure? If yes How many number of times? *** A.Yes,33. 4.Write the create syntax for the procedure. ** A. CREATE PROCEDURE proc_name Parameter As begin … End go Correct Syntax: CREATE PROCEDURE usp_SelectRecord AS BEGIN SELECT * FROM TABLE
  • 32. END GO 5.How to return output parameter from stored procedure? *** CREATE PROC sales_for_type @type VARCHAR(55), @total_sales INT OUTPUT AS SELECT SUM(qty) FROM sales a, titles b WHERE a.title_id = b.title_id and b.type = @type This procedure can be executed as follows: DECLARE @total_sales_business int EXEC sales_for_type business, @total_sales=@total_sales_business OUTPUT Results: 90 6.How to perform error handling in Stored procedure? **** DECLARE @errNum int DECLARE @rowCount int BEGIN TRY INSERT INTO [TABLE] (COL1) VALUES ('1") END TRY BEGIN CATCH SET @errNum = @@ERROR SET @rowCount = @@ROWCOUNT RAISEERROR(@errNum) END CATCH Function What are different types of function? A.SystemDefined function and userdefined function SystemDefined function:- Scalar and aggregate function Scalar function:-operates with single value returns single value.eg:- abs(-10.67):This returns absolute number of the given number means 10.67. rand(10):This will generate random number of 10 characters. round(17.56719,3):This will round off the given number to 3 places of decimal means 17.567 upper('dotnet'):This will returns upper case of given string means 'DOTNET' lower('DOTNET'):This will returns lower case of given string means 'dotnet' ltrim(' dotnet'):This will remove the spaces from left hand side of 'dotnet' string. convert(int, 15.56):This will convert the given float value to integer means 15. Aggregated Function:- Aggregate functions operates on a collection of values and returns a single value.eg:-min(),max(),avg(),count().
  • 33. User Defined Function:- These functions are created by user in system database or in user defined database. We three types of user defined functions. 1.scalar function also returns single value as a result of actions perform by function. We return any datatype value from function. 1. --Create a table 2. CREATE TABLE Employee 3. ( 4. EmpID int PRIMARY KEY, 5. FirstName varchar(50) NULL, 6. LastName varchar(50) NULL, 7. Salary int NULL, 8. Address varchar(100) NULL, 9. ) 10. --Insert Data 11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(1,'Mohan','Chauahn',22000,'Delhi'); 12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(2,'Asif','Khan',15000,'Delhi'); 13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(3,'Bhuvnesh','Shakya',19000,'Noida'); 14. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(4,'Deepak','Kumar',19000,'Noida'); 15. --See created table 16. Select * from Employee 17. --Create function to get emp full name 18. Create function fnGetEmpFullName 19. ( 20. @FirstName varchar(50),
  • 34. 21. @LastName varchar(50) 22. ) 23. returns varchar(101) 24. As 25. Begin return (Select @FirstName + ' '+ @LastName); 26. end 27. --Calling the above created function 28. Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee 2.Inline Table-Valued Function User defined inline table-valued function returns a table variable as a result of actions perform by function. The value of table variable should be derived from a single SELECT statement. 29. --Create function to get employees 30. Create function fnGetEmployee() 31. returns Table 32. As 33. return (Select * from Employee) 34. --Now call the above created function 35. Select * from fnGetEmployee()
  • 35. 3.Multi-Statement Table-Valued Function User defined multi-statement table-valued function returns a table variable as a result of actions perform by function. In this a table variable must be explicitly declared and defined whose value can be derived from a multiple sql statements. 36. --Create function for EmpID,FirstName and Salary of Employee 37. Create function fnGetMulEmployee() 38. returns @Emp Table 39. ( 40. EmpID int, 41. FirstName varchar(50), 42. Salary int 43. ) 44. As 45. begin 46. Insert into @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e; 47. --Now update salary of first employee 48. update @Emp set Salary=25000 where EmpID=1; 49. --It will update only in @Emp table not in Original Employee table 50. return 51. end 52. --Now call the above created function 53. Select * from fnGetMulEmployee()
  • 36. 54. --Now see the original table. This is not affected by above function update command 55. Select * from Employee Note  Unlike StoredProcedure,Functionreturnsonlysingle value.  Unlike StoredProcedure,Functionacceptsonlyinputparameters.  Unlike StoredProcedure,FunctionisnotusedtoInsert,Update,Delete dataindatabase table(s).  Like Stored Procedure,Functioncanbe nestedupto32 level.  User DefinedFunctioncanhave upto1023 inputparameterswhile aStoredProcedure canhave upto2100 inputparameters.  User DefinedFunctioncan'treturnsXML Data Type.  User DefinedFunctiondoesn'tsupportExceptionhandling.  User DefinedFunctioncancall onlyExtendedStoredProcedure.  User DefinedFunctiondoesn'tsupportsetoptionslike setROWCOUNTetc. What are difference between UDF and stored procedure? *** A.Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. But Function is compiled and executed every time when it is called. Basic Difference  Functionmustreturna value butin StoredProcedure itisoptional( Procedure canreturnzeroor n values).  Functionscanbe calledfromProcedure whereasProcedurescannotbe calledfrom Function. Advance Difference  Procedure allowsSELECTas well asDML(INSERT/UPDATE/DELETE) statementinitwhereasFunction allowsonlySELECTstatementinit.
  • 37.  Procedurescannot be utilizedinaSELECT statementwhereasFunctioncanbe embeddedina SELECT statement.  StoredProcedurescannotbe usedinthe SQL statementsanywhereinthe WHERE/HAVING/SELECT sectionwhereasFunctioncanbe.  The most importantfeature of storedproceduresoverfunctionistoretentionandreuse the executionplanwhile incase of functionitwill be compiledeverytime.  Functionsthatreturntablescan be treatedas anotherrowset.Thiscan be usedinJOINswithother tables.  Inline Functioncanbe thoughof as viewsthattake parametersandcan be usedinJOINsandother Rowsetoperations.  Exceptioncanbe handledbytry-catchblockin a Procedure whereastry-catchblockcannotbe used ina Function.  We can go for TransactionManagementinProcedure whereaswe can'tgo inFunction. Can we create a table in function? **** Yes we create table variable infunctionnottemptable.