Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL Difference

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 61

http://onlydifferencefaqs.blogspot.

in
1. What are the Differences between TRUNCATE and Delete?
S.No Truncate Delete

1 Truncate is faster Delete is comparatively slower

2 Removes all rows from a table Can remove specific rows with
Where clause

3 Is DDL Command Is DML Command

4 Resets identity of the table Does not reset identity of the table

5 Removes the data by Removes one row at a time and


deallocating the data pages and records an entry in the transaction
logs the deallocation. log for each deleted row.

6 Cannot be rolled back Can be rolled back

2. What are the differences between Primary key and Unique key?
S.No Primary Key Unique Key

1 Creates Clustered index Creates Non-Clustered index

2 Null values are not allowed. Allows only one null value.

3 We can have only one Primary We can have more than one unique
key in a table.  key in a table. 

4 Primary key can be made foreign Unique key cannot be made foreign
key into another table.  key into another table. 

3. What are the Differences between Clustered Indexes and Non-Clustered


Indexes?

S.No Clustered Indexes Non-Clustered Indexes

1 It reorders the physical storage of It sorts and maintain a separate


records in the table storage

2 There can be only one Clustered We can have 249 non-clustered


index per table indexes in a table

3 The leaf nodes contain data The leaf node contains pointer to data
4 To create clustered index Sql To create non-clustered index Sql
server required more memory server requires less memory because
because the leaf pages in the the leaf pages will contain pointers to
tree structure will maintain actual actual data
data .

5 By using clustered index By using non-clustered index


retrieving data is more retrieving data is slower than
faster,when we compare with clustered index.
non-clustered index.

4. What are the differences between Stored Procedures and User Defined
Functions?
S.No Stored Procedures User Defined Functions

1 Stored Procedure cannot be used User Defined Function can be used in


in a Select statement a Select statement

2 Stored procedure supports User Defined Function does not


Deferred Name Resolution support Deferred Name Resolution

3 Stored Procedures are generally User Defined Functions are generally


used for performing Business used for Computations
Logic

4 Stored Procedure need not return User Defined Functions should return
a value a value

5 Stored Procedures can return any User Defined Functions cannot return
datatype Image

6 Stored Procedures can accept User Defined Functions accept lesser


more number of input parameters number of input parameters than
than User Defined Functions. Stored Procedures. UDF can have
Stored Procedures can have upto upto 1023 input parameters
21000 input parameters

7 Stored Procedures can use Temporary Tables cannot be used in


Temporary Tables a User Defined Function

8 Stored Procedures can execute User Defined Functions cannot


Dynamic SQL execute Dynamic SQL

9 Stored Procedure supports error User Defined Function does not


handling support error handling.
RAISEERROR or @@ERROR are
not allowed in UDFs

10 Non-deterministic functions can Non-deterministic functions cannot be


be used in Stored Procedures. used in User Defined Functions
(UDFs). For example, GETDATE()
cannot be used in User Defined
Functions(UDFs)

5. What are the differences between Where and Having clauses?


S.No Where clause Having clause

1 It applies to individual rows It applies to a group as a whole

2 It selects rows before grouping It selects rows after grouping

3 It cannot contain aggregate It can contain aggregate functions


functions

4 It can be used in select, delete It is used only in select clause


,insert etc.

6. What are the differences between Union and UnionAll?


S.No Union UnionAll

1 This is used to eliminate duplicate It will not eliminate duplicate rows


rows

2 This selects only distinct rows It selects all the values

3 It can be used to combine any It can be used to combine maximum


number of queries of 2 queries

4 It cannot contain aggregate It can contain aggregate functions


functions

5 Union is slower than UnionAll UnionAll is faster than Union

6 Output is in sorted order Output is not in sorted order

Example : Example :
SELECT Col SELECT Col
FROM @Table1 FROM @Table1
UNION UNION ALL
SELECT Col SELECT Col
FROM @Table2 FROM @Table2
Result: Result:
1 1
2 2
3 3
5 2
5

7. What is the difference between normal Select statement and a Cursor?


S.No Select statement Cursor

1 Select statements are used for Cursors are used for row-level
table-level processing processing

8) Difference between Primary Key and Foreign Key


S.No Primary Key Foreign Key

1 Primary key uniquely identify a Foreign key is a field in the table that
record in the table.  is primary key in another table. 

2 Primary Key cannot accept null Foreign key can accept multiple null
values.  values. 

3 By default, Primary key is While Foreign key is non-clustered


clustered index and data in the index. 
database table is physically
organized in the sequence of
clustered index. 

4 We can have only one Primary We can have more than one foreign
key in a table.  key in a table. 

1. What are the differences between Instead of Triggers and After Triggers?

S.No Instead of Triggers After Triggers

1 Each table or view can have one A table can have several AFTER
INSTEAD OF trigger for each triggers for each triggering action.
triggering action (UPDATE,
DELETE, and INSERT)
2 INSTEAD OF triggers fire in place AFTER triggers fire after the
of the triggering action and before triggering action (INSERT, UPDATE,
constraints are processed. or DELETE) and after any constraints
are processed.
2. What are the differences between Views and User-Defined Functions?

S.No Views User-Defined Functions

1 Views cannot accept parameters. User-Defined Functions can accept


parameters.

2 Output of the Views cannot be Output of the User-Defined Functions


directly used in the SELECT can be directly used in the SELECT
clause. clause.
3. What are the differences between Triggers and Stored Procedures?

S.No Triggers Stored Procedures

1 Triggers cannot return a value Stored Procedures may return a


value

2 We cannot pass parameters in We can pass parameter in Stored


Triggers Procedures

3 We can write a Stored procedure We cannot write a Trigger within a


within a Trigger Stored Procedure

4 Triggers are implicitly fired Stored Procedures need to be


whenever insert, update or delete explicitly called by the programmer
operations take place on table

5 Triggers can only be Stored procedures can be written for


implemented on Tables or Views the Database

6 We cannot schedule a trigger. Stored procedures can be scheduled


through a job to execute on a
predefined time

7 We cannot use the print We can use the Print commands


command inside a trigger. inside the stored procedure for
debugging purpose

8 We cannot call a trigger from We can call a stored procedure from


these files. front end (.asp files, .aspx files, .ascx
files etc.)
Difference between Identity and Sequence in SQL Server 2012
S.No Identity Sequence

1 Dependant on table. Independent from table.

2 Identity is a property in a Sequence is an object.


table.
Example :
Example :
CREATE SEQUENCE [dbo].
CREATE TABLE Table [Sequence_ID]
test_Identity
AS [int]
(
START WITH 1
[ID] int Identity (1,1),
INCREMENT BY 1
[Product Name]
varchar(50) MINVALUE 1

) MAXVALUE 1000

NO CYCLE

NO CACHE

3 If we need a new ID In the sequence, we do not


from an identity column need to insert new ID, we
we need to can view the new ID directly.
insert and then get new
ID. Example :

Example : SELECT NEXT VALUE


FOR dbo.[Sequence_ID]
Insert into [test_Identity]
Values (‘SQL Server’)

GO

SELECT @@IDENTITY
AS ‘Identity’

–OR
Select
SCOPE_IDENTITY() AS
‘Identity’

4 We cannot perform a In the sequence, we can


cycle in identity column. simply add one property to
Meaning, we cannot make it a cycle.
restart the counter after
a Example :
particular interval.
ALTER SEQUENCE [dbo].
[Sequence_ID]

CYCLE;

5 We cannot cache Sequence can be easily


Identity column cached by just setting cache
property. property of
sequence. It also improves
the performance.

Example :

ALTER SEQUENCE [dbo].


[Sequence_ID]

CACHE 3;

6 We cannot remove the The sequence is not table


identity column from the dependent so we can easily
table directly. remove it

Example :

Create table dbo.


[test_Sequence]

[ID] int,

[Product Name] varchar(50)

GO
–First Insert With Sequence
object

INSERT INTO
dbo.test_Sequence ([ID],
[Product Name]) VALUES
(NEXT VALUE FOR
[Ticket] , ‘MICROSOFT SQL
SERVER 2008′)

GO

–Second Insert without


Sequence

INSERT INTO
dbo.test_Sequence ([ID],
[Product Name]) VALUES (2
, ‘MICROSOFT SQL
SERVER 2012′)

7 We cannot define the Here we can set up its


maximum value in maximum value.
identity column it is
based on the data type Example :
limit.
ALTER SEQUENCE [dbo].
[Sequence_ID]

MAXVALUE 2000;

8 We can reseed it but We can reseed as well as


cannot change the step change the step size.
size.
Example :
Example :
ALTER SEQUENCE [dbo].
DBCC CHECKIDENT [Sequence_ID]
(test_Identity, RESEED,
4) RESTART WITH 7

INCREMENT BY 2;
9 We cannot generate We can generate a range of
range from identity. sequence
values from a sequence
object with the help of
sp_sequence_get_range.

2.Difference between Temp table and Table variable


S.No Temp table Table variable

1 A Temp table is easy to But the table variable


create and back up data. involves the effort when we
usually create the normal
tables.

2 Temp table result can be But the table variable can


used by multiple users. be used by the current user
only. 

3 Temp table will be stored But a table variable will


in the tempdb. It will store in the physical
make network traffic. memory for some of the
When we have large data, then later when the
data in the temp table size increases it will be
then it has to work moved to the tempdb.
across the database. A
Performance issue will
exist.

4 Temp table can do all the Whereas table variable


DDL operations. It allows won't allow doing the DDL
creating the indexes, operations. But the table
dropping, altering, etc.., variable allows us to create
the clustered index only.

5 Temp table can be used But the table variable can


for the current session or be used up to that program.
global. So that a multiple (Stored procedure)
user session can utilize
the results in the table.

6 Temp variable cannot But we cannot do it for table


use the transactions. variable.
When we do the DML
operations with the temp
table then it can be
rollback or commit the
transactions.

7 Functions cannot use the But the function allows us to


temp variable. More over use the table variable. But
we cannot do the DML using the table variable we
operation in the functions can do that.
.

8 The stored procedure will Whereas the table variable


do the recompilation won't do like that.
(can't use same
execution plan) when we
use the temp variable for
every sub sequent calls.

Another Good Reference:

http://sqljunkieshare.com/2011/11/05/difference-between-temporary-tables-and-table-
variables/

3.Difference between RAISERROR and THROW statements

S.No RAISERROR Statement THROW Statement

1 If amsg_id is passed to The error_number


RAISERROR, the ID parameter does not have to
must be defined in be defined in
sys.messages. sys.messages.

2 The msg_str parameter The message parameter


can contain printf does not accept printf style
formatting styles. formatting.

3 The severity parameter There is no severity


specifies the severity of parameter. The exception
the exception. severity is always set to 16.

http://sqlhints.com/2013/06/30/differences-between-raiserror-and-throw-in-sql-server/

.Difference between Database Mail and SQL Mail

S.No Database Mail SQL Mail


1 Based on SMTP (Simple Based on MAPI (Messaging
Mail Transfer Protocol). Application Programming
Interface).

2 Introduced in Sql Server Used prior versions of Sql


2005. Server 2005.

3 No need to install Require Outlook to be


Outlook. installed.

4 More secure than Sql Less secure than Database


mail. mail.

2.Difference between Azure Table storage and SQL Azure

S.No Azure Table storage SQL Azure

1 It is built on top of the It is an SQL Server that has


Azure Storage platform. been configured to be
hosted on top 
of the Windows Azure in a
high availability mode.

2 It comprises flexible or It comprises standard SQL


schema-less entities. No Tables with indexes and
referential integrity referential integrity.
between the tables, and
no custom indexes.

3 It can scale massive It may not scale as far as


amounts of data due to Azure Table storage.
the partition key.

4 Can be thought as single Look familiar to any .Net


spreadsheet. developer who has used
Sql server 2008 prior.

3.Difference between DBMS and RDBMS

S.No DBMS RDBMS

1 Stands for DataBase Stands for Relational


Management System DataBase Management
System
2 In dbms no relationship It is used to establish the
concept relationship concept
between two database
objects, i.e, tables

3 It supports Single User It supports multiple users


only

4 It treats Data as Files It treats data as Tables


internally internally

5 It supports 3 rules of It supports minimum 6 rules


E.F.CODD out off 12 of E.F.CODD
rules

6 It requires low Software It requires High software


and Hardware and hardware
Requirements. requirements.

7 DBMS is used for RDBMS is used for more


simpler business complex applications.
applications

8 DBMS does not impose RDBMS defines the


any constraints or integrity constraint for the
security with regard to purpose of holding ACID
data manipulation PROPERTY

9 In DBMS Normalization In RDBMS, normalization


process will not be process will be present to
present check the database table
consistency

10 There is no enforcement Although the foreign key


to use foreign key concept is supported by
concept compulsorily in both DBMS and RDBMS
DBMS but its only RDBMS that
enforces the rules

11 FoxPro, IMS are SQL Server, Oracle are


Examples examples

4.Difference between SQL Server 2000 and SQL Server 2005

S.No SQL Server 2000 SQL Server 2005


1 Query Analyser and Both are combined as
Enterprise manager are SSMS(Sql Server
separate. management Studio).

2 No XML datatype is .XML datatype is introduced.


used.

3 We can create We can create 2(pow(20))-1


maximum of 65,535 databases.
databases.

4 Exception Handling Exception Handling


mechanism is not mechanism is available
available

5 There is no Varchar(Max) data type is


Varchar(Max) data type introduced.
is not available

6 DDL Triggers is not DDL Triggers is introduced


available

7 DataBase Mirroring DataBase Mirroring facility is


facility is not available introduced

8 RowNumber function for RowNumber function for


paging is not available paging is introduced

9 Table fragmentation Table fragmentation facility


facility is not available is introduced

10 Full Text Search facility Full Text Search facility is


is not available introduced

11 Bulk Copy Update Bulk Copy Update facility is


facility is not available introduced

12 Data Encryption concept .Cannot encrypt the entire


is not introduced database

13 Cannot compress the Can Compress tables and


tables and indexes. indexes.(Introduced in 2005
SP2)
14 No varchar(max) or Varchar(max) and
varbinary(max) is varbinary(max) is used.
available.

15 Data Transformation SQL Server Integration


Services(DTS) is used Services(SSIS) is started
as ETL tool using from this SQL Server
version and which is used as
ETL tool
1.Difference between SQL Server and PostgreSQL

S.No SQL Server PostgreSQL

1 INSERT t VALUES (…) This syntax is not allowed.


Allows: 
INSERT
INTO t VALUES (…)

2 BULK uses COPY instead 
INSERT and BCP (which has the functionality
of both BCP and BULK
INSERT)

3 Management Studio pgAdmin

4 Bit type Boolean type (accepts


values true andfalse)

5 IDENITTY Has sequencers (like Oracle)

6 default schema is dbo default schema


is PostgreSQL

7 Default Listening on Default listening on 5432


1433

8 datatype: varchar(max) datatype: text

9 Key is clustered by key is not clustered by


default default (and it is enforced by
a constraint and not an an
index!)

10 User Defined Data Domains


Types
11 user: sa user: postgres

12 No such thing NATURAL and USING joins

13 SELECT TOP 10 SELECT * FROM t LIMIT 10


* FROM t

14 Query plans read from Query plan read from left to


right to left right

15 Estimate Query Plan: Estimate Query Plan: F7


CTRL+L

2.Difference between Cross Join and Full Outer Join

S.No Cross Join Full Outer Join

1 No join conditions are A combination of both left


specified. and right outer joins.

2 Results in pairs of rows. Results in every row from


both of the tables , at least
once.

3 Results in Cartesian Assigns NULL for


product of two tables. unmatched fields.

3.Difference between SQL Server and Oracle

S.No SQL Server Oracle

1 SQL History: Oracle History:


IBM introduced Oracle Corp is the leading
structured Query supplier for S/w products,
Language (SQL) as the headquartered in Redwood
language to interface shores, California, USA. It
with its prototype was founded by Larry
relational database Ellison, Bob Miner and Ed
management system; Oates in 1977. Now they
System R. Oracle have 43,000 Employees in
Corporation introduced 150 countries. Oracle first
the first commercially commercial RDBMS was
available SQL relational built in 1979, and it is the
database management first to support the SQL.
system in 1979. Today, Oracle is the first S/w
SQL has become an company to develop and
industry standard, and deploy 100 % Internet-
Oracle Corporation enabled enterprise
clearly leads the world in Software.
RDBMS technology.
SQL is used for all types
of DB activities by all
type of users. The basic
SQL commands can be
learned in a few hours
and even the most
advanced commands
can be mastered in a
few days.

2 SQL (Structure Query Oracle (RDBMS):


Language):
Oracle is fastest and easiest
When a user wants to way to create applications in
get some information MS windows. It provides the
from any DB file, he can ability to store and access
issue a query. Structured data. Whether you are
query language (SQL), experienced or new to
pronounced “Sequel”, is windows in programming,
the set of commands Oracle provides you with the
that all programs and complete set of tools to
users must use to simplify rapid application
access data within the development. The Oracle
Oracle. SQL is a high refers to the method used to
performance fault create the graphical user
tolerant data base inter face. There is no need
management system. to write numerous lines of
The database is mostly code to describe the
maintained by SQL appearance and location of
language, which is inter face elements.
conceded as the heart of
the RDBMS.

3 SQL Technology: Oracle Technology:


SQL is divided into four Oracle DB structure is
parts: divided into two parts, one is
called Physical structure
DDL (Data Definition (these files define the
Language): Create, operating system that make
Alter, Drop, Rename, up the DB, each Oracle DB
Truncate. is made by three types of
files, data-files, redo logs
DML (Data Manipulate
file-controls file) and the
Language): Select,
other is called Logical
Update and Delete,
structure (these files define
Insert, Into.
the logical areas of storage
DCL (Data Control like schema, table spaces,
Language): Grant, segments and extents).
Revoke
TCL (Transaction
Control Language):
Commit, Rollback.

4 Advantages: Advantages:

 Provides easy  Data consistency


access to all data.  Integration of data
 Flexibility in data  Easy file generation
molding.
 Increased security
 Reduced data
 Easy updating of
storage and redundancy.
records
 Provides a high-
 No wastage of time
level manipulation
language.  Enforcement of
 SQL can save standards
data in common PC file  Controlled data
formats that can be redundancy
imported into other  Reduce the total
application (like Ms- expenditures
Excel).  Searching of
 SQL is not case particular data is easy
sensitive.  Dispose of heavy
 It can enter one or files and register work
more lines.  The work of three
 Tabs and indents persons is reduced to one
can be used to make  Instant intimation of
code more readable. modification of information
 Can be used by a
range of users.
 It is a
nonprocedural language
(English-like language).

5 Differences: Differences:

 SQL is a tool for  Oracle Corp is the


all DB like DBMS, world’s leading supplier of
RDBMS, T-SQL, and S/w products.
SQL Plus.  Oracle is the
 SQL maintains platform, where we develop
different RDBMS.  and implement different DB
 SQL is designs and software.
combination of different  Oracle is the
commands and functions combination of different S/w
that why, SQL is worked products, where they work
for Oracle DB as a together for designing DB.
command prompt  Oracle works with
shell (SQL is the different front and back end
command prompt shell, products/tools (like SQL).
where we can
communicate with any
DB).

4.Difference between View and Stored Procedure

S.No View Stored Procedure

1 Does not accepts Accept parameters


parameters

2 Can be used as a Cannot be used as a


building block in large building block in large
query. query.

3 Can contain only one Can contain several


single Select query. statement like if, else, loop
etc.

4 Cannot perform Can perform modification to


modification to any table. one or several tables.
5 Can be used Cannot be used as the
(sometimes) as the target for Insert, update,
target for Insert, update, delete queries.
delete queries.

5.Difference between IN and EXISTS

S.No IN EXISTS

1 Returns true if specified Return true if sub query


value matches any value contain any rows.
in the sub query or a list.

2 The sub query will run The Outer query will ran first
first and then only outer and then only sub query.
query.

3 IN is slower than Exists is faster than IN.The


EXISTS. The IN is used Outer query will run first and
in the widely For Static then only inner query.So it
variables for eg: select will reduce the over head.
name from table where The Exists is useful mostly
ID in (Select ID from in IF conditional statements.
table2).

4 Example: Example:

SELECT id, SELECT id,


[Name] [Name]
FROM dbo.tablea FROM dbo.tablea AS a
WHERE id IN (SELECT WHERE EXISTS (SELECT
id id2
FROM dbo.tableb) FROM dbo.tableb
WHERE id2 = a.id)

1.Difference between Checkpoint and Lazy Writer

S.No CheckPoint Lazy Writer

1 Flush dirty pages to Disk Flush dirty pages to disk

2 Flush only Data pages to Check for available memory


disk and removed Buffer pool
(execution plan/compile
plan/ Data pages /Memory
objects)

3 Default, Occurs Occurs depending upon


approximately every 1 memory pressure and
minute resource availability

4 Can be managed with It is lazy, Sql server


sp_confige -recovery manages by its own.
interval option

5 Does not check the Monitor the memory


memory pressure pressure and try maintain
the available free memory.

6 Crash recovery process No role in recovery


will be fast to read log as
data file is updated.

7 Occurs for any DDL Occurs per requirement


statement

8 Occurs before Occurs per requirement


Backup/Detach
command

9 Depends upon the Works on Least recent


configuration setting, we used pages and removed
can control. unused plans first, no user
control.

10 For simple recovery it No effect on recovery


flush the tlog file after model.
70% full.

11 Can manually /Forcefully No command for Lazy


run command Writer
“Checkpoint”

12 Very Less performance No performance impact


impact

2.Difference between Mirroring and Log Shipping


S.No Mirroring Log Shipping

1 Principle can have single Multiple stand by servers


mirror can be possible.

2 Generally good to have No limit


10 DB’s for one server

3 No data loss and can be May be some data loss as


used as high availability per schedule. And
like Clustering secondary server takes
some manual work and time
to be primary

4 Read log read and Transfer the log back up


transfer the committed and restored at standby
transaction through server.
endpoints.

5 Only committed Committed as well as


transaction uncommitted and whole log
backup restores.

6 PAGE repair is possible N/A


if principle database
page gets corrupt

7 Mirrored DB can only be Secondary server can be


accessed using reporting server (read-only)
snapshot DB

8 Principle and Mirror Primary and secondary


server should have server should be compatible
same edition server for restore.

9 Require FULL recovery Require  FULL or Bulk-


model Logged recovery model

10 Requires Sql Server Enterprise edition for Sql


2005 SP1 or higher – Server 2000 and even
Enterprise or Developer Standard edition for 2005
Editions can works

11 Immediate data moved Can control the flow of data


depending on SEND and by scheduling jobs
WAIT queue

12 As Immediate data As delay in data transfer can


moves, user error avoided user error.
reflects at mirrored DB

3.Difference between Change Track and Change Data Capture – CDC in SQL
Server 2008

S. Change Track Change Data Capture


N
o

1 It is about It is about the Data: Change data


fact: It captures capture provides historical change
only the fact as information for a user table by
the tracking capturing both the fact that DML
table has changes were made and the actual
changed. It does data that was changed.
NOT capture the
data. 
Therefore,
change tracking
is more limited
in the historical
questions it can
answer
compared to
change data
capture.
However, for
those
applications that
do not require
the historical
information,
there is far less
storage
overhead
because of the
changed data
not being
captured
2 Storage:  Storage: 
Internal tables When change data capture is enabled
are placed on for a database, a few things are added
the same to the database, including a new
filegroup as the schema (calledcdc), some metadata
parent entity. tables, and a trigger to capture Data
You could use Definition Language (DDL) events. 
thesys.internal
_tables catalog The two function names are,
view to show all respectively,fn_cdc_get_all_changes
the internal _ andfn_cdc_get_net_changes_, with
tables and the capture instance name appended.
parent entities. Note that (like the change tracking
For feature) this functionality requires the
example: select table to have aprimary key or
name, other unique index.
object_name(pa
rent_id) as
parent_object
from
sys.internal_tabl
es

3 Supported on Prevents Log truncation. 


“Simple” Forces full logging of some bulk
recovery model operations. 
also. 
It is One major point to note here is that
recommended once change data capture is enabled,
that you the transaction log behaves just as it
usesnapshot does withtransactional replication—
isolation when the log cannot be truncated until the log
change tracking reader has processed it. This means a
is enabled. checkpoint operation, even in SIMPLE
Snapshot recovery mode,will not truncate the log
isolation itself unless it has already been processed
can add by the log reader.
significant
workload
overhead and
requires much
more careful
management of
tempdb.

4 It Change Data Capture (CDC) uses


uses synchron theasynchronous process that reads
ous tracking the transaction log.
mechanism. 
once a database
is enabled for
change tracking,
a version
numberis
instituted, which
allows ordering
of operations

5 Change It has almost nil impact as it


Tracking has asynchronous mechanism reads from
minimal impact the transaction log.
on the system.

6 It It uses transaction log.


uses TempDB h
eavily

7 DDL No such DDL restriction


Restriction: 
There are
restrictions on
the DDL that
can be
performed on a
table being
tracked. The
most notable
restriction is that
the primary key
cannot be
altered in any
way. The other
restriction worth
calling out here
is that an
ALTER TABLE
SWITCH will fail
if either table
involved has
change tracking
enabled.
8 SQL Agent not t requires SQL Agent to be running. 
needed SQL Agent Job & Transaction
Replication: 
Two SQL Agent jobs may be created:
thecapture job and the cleanup job. I
say "may be created" because the
capture job is the same as the one
used for harvesting transactions in
transactional replication. 
If transactional replication is already
configured, then only the cleanup job
will be created and the existing log
reader job will also be used as the
capture job

9 Permission Permission required to enable:


required to DBOwner
enable:
SYSADMIN

4.Difference between Index Rebuild and Index Reorganize in SQL Server 2005

S.N Index Rebuild Index Reorganize


o

1 Index Rebuild drops the Index Reorganize


existing Index and physically reorganizes the
Recreates the index from leaf nodes of the index.
scratch.

2 Rebuild the Index when an Reorganize the Index


index is over 30% when an index is between
fragmented. 10% and 30% fragmented.

3 Rebuilding takes more Always prefer to do


server resources and uses Reorganize the Index.
locks unless you use the
ONLINE option available
in 2005 Enterprise and
Development editions.

4 T-SQL for Rebuilding all T-SQL for Reorganize all


Indexes of a particular Indexes of a particular
table. table.
USE AdventureWorks;  USE AdventureWorks; 
GO  GO 
ALTER INDEX ALL ON ALTER INDEX ALL ON
HumanResources.Employ HumanResources.Employ
ee REBUILD  ee REORGANIZE 
GO GO

Note: If fragmentation is below 10%, no action required.

5.Difference between User -defined SP and System-defined SP

S.No User-defined SP System-defined SP

1 Once we create User System defined sp are


defined SP in one available in master
database i.e available to DB.Thesesp’s can be
only that database directly called from any DB
directly.i.e
we cannot call it from
some other DB’s directly

2 UDSP will be used to SDSP will be used for


fulfill the user managing sql server
requirements

1.Difference between Constraints and Triggers

S.No Constraints Triggers

1 Once we define some It will be stored as separate


constraint in a table object
they will be stored
along with table
definition

2 Constraints will do Triggers will do table to table


memory location to comparison.For this triggers
table comparison. will use magic
tables(inserted,deleted).
3 In the order of In the order of precedence
precedence first only after Constraints is
Constraints will be fired fired,then only Triggers will
be fired

4 Performance wise Performance wise triggers


Constraints will not give will give best performance
best performance because table to table
because memory comparison is faster than
location to table memory
comparison is slower location to table comparison.
than table to table
comparison.

5 Constraints cannot start Triggers are used to carry out


a chain reaction as like tasks which cant be done
triggers - for instance using constraints.
each delete, update For eg:-A change in the "sal"
action etc. can trigger column of a table should
off another function change the "tax" column in
another table.Thiscant be
done using constraints.It has
to be done using
triggers.Thats where the
importance of triggers lie.

6 Constraint is used for Trigger is used for table


column

7 Constraints are Trigger is a user defined


predefined business business rule for which user
rules in which all the is responsible for logic for
organizations follow this business rule
constraints without any
modification.

8 Constraints are used to Triggers are basically stored


maintain the integrity procedures which
and atomicity of automatically fired when any
database .In other insert,update or delete is
words it can be said issued on table
they are used to
prevent invalid data
entry . the main 5
constraints are
NOT NULL,PRIMARY
KEY,FOREIGN
KEY,UNIQUE KEY and
CHECK

2.Difference between Cast and Convert in SQL Server

S.No Cast Convert

1 Cast is ANSII Standard Convert is Specific to SQL


SERVER

2 Cast cannot be used for Convert can be used for


Formatting Purposes. Formatting Purposes.For
example Select convert
(varchar, datetime, 101)

3 Cast cannot convert a Convert can be used to


datetime to specific convert a datetime to
format specific format

4 Usage of CAST: Usage of CONVERT:

USE Sample USE Sample


GO GO
SELECT SELECT
SUBSTRING(Name, 1, SUBSTRING(Name, 1, 30)
30) AS ProductName, AS ProductName, ListPrice
ListPrice FROM Production.Product
FROM WHERE CAST(int,
Production.Product ListPrice) LIKE '3%';
WHERE GO
CAST(ListPriceAS int)
LIKE '3%';
GO

3.Difference between CUBE and ROLLUP

S.No CUBE ROLLUP

1 It is an additional switch It is an extension to GROUP


to GROUP BY clause. It BY clause. It’s used to
can be applied to all extract statistical and
aggregation functions to summarized information
return cross tabular from result sets. It creates
result sets. groupings and then applies
aggregation functions on
them.

2 Produces all possible Produces only some


combinations of possible subtotal
subtotals specified in combinations
GROUP BY clause and
a Grand Total.

Difference between SQL Server 2008 and SQL Server 2012


S.N SQL Server 2008 SQL Server 2012
o

1 Maximum number Maximum number


of  concurrent of  concurrent
connections:  connections:  
The Maximum number of SQL server 2012 has
concurrent connections to unlimited concurrent
SQL Server 2008 is 32767. connections.

2 Precision used for spatial Precision used for spatial


calculations: calculations: 
The SQL Server 2008 uses The SQL Server 2012 uses
27 bit bit precision for 48 bit precision for spatial
spatial calculations. calculations

3 TRY_CONVERT() and FO TRY_CONVERT() and FO
RMAT() functions:   RMAT() functions:   
TRY_CONVERT() and TRY_CONVERT() and
FORMAT() functions are FORMAT() functions are
not available in SQL Server newly included in SQL
2008 Server 2012

4 ORDER BY Clause with  ORDER BY Clause with


OFFSET / FETCH OFFSET / FETCH
options:  options: 
ORDER BY Clause does ORDER BY Clause now
not have OFFSET / have OFFSET / FETCH
FETCH options as in SQL options to use paging to
Server 2012 show required rows per
page in applications and
allow the user to scroll
through each page of
results rather than
download the entire set

In the sample query below,


SQL Server would return
10 records beginning with
record 11. The OFFSET
command provides a
starting point for the
SELECT statement in
terms of paging, and the
FETCH command provides
how many records to return
at a time.

SELECT BusinessEntityID,
FirstName, LastName
FROM Person.Person
ORDER BY
BusinessEntityID
OFFSET 10 ROWS
FETCH NEXT 10 ROWS
ONLY;

5 Code Name:  Code Name: 


SQL Server 2008 is code SQL Server 2012 is code
named as Katmai. named as Denali

In SQL Server 2008, audit In SQL Server


is an Enterprise-only 2012,support for server
feature. Only available in auditing is expanded to
Enterprise, Evaluation, and include all editions of SQL
Developer Edition. Server.

7 Sequence Object:  Sequence Object: 


Sequence is not available Sequence is included in
in SQL Server 2008 SQL Server
2012.Sequence is a user
defined object that
generates a sequence of a
number.
Here is an example using
Sequence.

/****** Create Sequence


Object ******/
CREATE SEQUENCE
MySequence
START WITH 1
INCREMENT BY 1;

/****** Create Temp Table


******/
DECLARE @Person
TABLE
(
ID int NOT NULL
PRIMARY KEY,
FullNamenvarchar(100)
NOT NULL
);

/****** Insert Some Data


******/
INSERT @Person (ID,
FullName)
VALUES (NEXT VALUE
FOR MySequence, 'Umar
Ali'),
(NEXT VALUE FOR
MySequence, 'John
Peter'),
(NEXT VALUE FOR
MySequence, 'Mohamed
Iqbal');

/****** Show the Data


******/
SELECT * FROM
@Person;

The results would look like


this:

ID FullName
1 Umar Ali
2 John Peter
3 Mohamed Iqbal

8 Full Text Search Full Text


Capability:  Search Capability: 
The Full Text Search in The Full Text Search in
SQL Server 2008 does not SQL Server 2012 has been
allow us to search and enhanced by allowing us to
index data stored in search and index data
extended properties or stored in extended
metadata. properties or metadata.
Consider a PDF document
that has "properties" filled
in like Name, Type, Folder
path, Size, Date Created,
etc. In the newest release
of SQL Server, this data
could be indexes and
searched along with the
data in the document itself.
The data does have to be
exposed to work, but it's
possible now.

9 BISM Model:  BISM Model:  


Analysis Services in SQL Analysis Services will
Server does not have BI include a new BI Semantic
Semantic Model (BISM) Model (BISM). BISM is a 3-
concept. layer model that includes:

Data Model
Business Logic
Data Access

BISM will enhance


Microsoft's front end
analysis experiencing
including Excel, Reporting
Services and SharePoint
Insights. Microsoft has said
that BISM is not a
replacement for the current
BI Models but more of an
alternative model. In simple
terms, BISM is a relation
model that includes BI
artifact such as KPIs and
hierarchies.

Difference between SQL Server 2008 R2 and SQL Server 2012


(OR)
Difference between SQL Server 10.5 and SQL Server 11.0
S.No SQL Server 2008 R2 SQL Server 2012

1 SQL Server 2008 R2 is SQL Server 2012 is


codenamed codenamed as Denali
as Kilimanjaro

2 In SQL Server 2008 R2 , In SQL Server 2012, server


rebooting is requisite for down time is reduced by
OS patching , hence 50% , hence OS patching is
server down time is high not rebooting n times.

3 SQL Server 2008 R2 In SQL Server 2012, high


does not have this availability and disaster
feature of availability recovery factor has been
groups, hence fast introduced which duplicates
recovery is not possible. the data and rapidly
recovers the loss.

4 SQL Server 2008 R2 is In SQL Server 2012, the


slow compared to SQL performance is 10 times
Server 2012. faster than the predecessor.

5 However buffer rate is Buffer rate is high in SQL


less because there is no Server 2012 because of
data redundancy in SQL data compression.
Server 2008 R2

6 Data visualization is not Data visualization tool is


supported in SQL Server available in SQL Server
2008 R2 2012.This allows snapshots
of data.

7 Spatial features are not Support for persistent


supported more in SQL computed columns and
Server 2008 R2. Instead extra geographical
a traditional way for approach is possible with
geographical elements spatial features in SQL
have been set in SQL Server 2012.
Server 2008 R2.

Difference between SET and SELECT in SQL Server

S.No SET SELECT

1 Is it ANSI Standard ? Is it ANSI Standard ?


SET is ANSI Standard SELECT is Non-ANSI
for value assignment to Standard for value
variables. assignment to variables.

2 Variable Assignment: Variable Assignment:


SET can be used to SELECT can be used to
assign value to one assign values to multiple
variable at a time. variables in a single
SELECT statement.
DECLARE @i INT,
@j INT, The below query using
@k INT SELECT is valid:
SET @i = 10,@j = 1
20,@k = 30 2
3
It gives error: 4
5
Msg 102, Level 15, DECLARE @i INT,
State 1, Line 5 @j INT,
Incorrect syntax near ‘,’. @k INT
SELECT @i = 10,@j =
20,@k = 30

Output:
Command(s) completed
successfully.

The below query using SET


is not valid:
1
2
3
4
5

3 Behaviour of SET Behaviour of SELECT


when query returns when query returns more
more then one value: then one value:
When assigning from a When assigning from a
query that returns more query that returns more than
than one value, SET will one value, SELECT will
fail with an error. assign the last value
returned by the query and
The below query using hide the fact that the query
set will fail: returned
1 more than one row.
2
3 The below query using
DECLARE @i INT select will execute
SET @i = (SELECT n successfully:
FROM (VALUES (10), 1
(20),(30)) AS List(n)) 2
3
Error: 4
5
Msg 512, Level 16, DECLARE @i INT
State 1, Line 5 SELECT @i = n FROM
Subquery returned more (VALUES (10),(20),(30)) AS
than 1 value. This is not List(n)
permitted when the SELECT @i
subquery follows =, !=,
<, <= , >, >= or when the Output:
subquery is used as an
expression. 30

(1 row(s) affected)

4 Behaviour of SET Behaviour of SELECT


when query does not when query does not
return any rows: return any rows:
If the variable is initially If the variable is initially
assigned a value assigned a value following is
following is the behavior the behavior of variable
of variable assignment assignment for SELECT,
for SET,
Retains the initially assigned
Assigns null if the query value and does not assign
does not return any null if the query does not
rows. return any rows.
The output of the below The output of the below
statement will be NULL statement will be 1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
DECLARE @i INT DECLARE @i INT
SET @i = 1 SET @i = 1
SET @i = (SELECT n SELECT @i = n FROM
FROM (VALUES (10), (VALUES (10),(20),(30)) AS
(20),(30)) AS List(n) List(n) WHERE 1=2
WHERE 1=2) SELECT @i
SELECT @i
Output:
Output:
1
NULL
(1 row(s) affected)
(1 row(s) affected)

5 Performance: Performance:
Set does not provide Select has better
better performance over performance over set when
select when used for used for assigning values to
assigning values to multiple variables at the
multiple variables at the same time.
same time.
Assigning values to multiple
Assigning values to variables using Select:
multiple variables using 1
SET: 2
1 3
2 4
3 5
4 DECLARE @i INT,
5 @j INT,
6 @k INT
7 SELECT @i = 10,@j =
DECLARE @i INT, 20,@k = 30
@j INT,
@k INT
SET @i = 10
SET @j = 20
SET @k = 30

6 When to use ? When to use ?


Following are few Using SELECT is efficient
scenarios for using SET and flexible in the following
few cases.
1. If we are required to
assign a single value 1. Multiple variables are
directly to variable and being populated by
no query is involved to assigning values directly
fetch value. 2. Multiple variables are
2. NULL assignments being populated by single
are expected (NULL source (table , view)
returned in result set) 3. Less coding for assigning
3. Standards are meant multiple variables
to be follow for any 4. Use this if we need to get
planned migration @@ROWCOUNT and
4. Non scalar results are @ERROR for last statement
expected and are executed
required to be handled

1.Difference between VARCHAR and NVARCHAR in SQL Server


S. Varchar[(n)] NVarchar[(n)]
N
o

1 Basic Definition: Basic Definition:

Non-Unicode Variable UNicode Variable Length


Length character data type. character data type. It can
store both non-Unicode and
Example: Unicode (i.e. Japanese,
DECLARE @FirstName AS Korean etc) characters.
VARCHAR(50) = ‘UMAR’
SELECT @FirstName Example:
DECLARE @FirstName AS
NVARCHAR(50)= ‘UMAR’
SELECT @FirstName

2 No. of Bytes required for No. of Bytes required for


each character: each character:

It takes 2 bytes per


It takes 1 byte per character Unicode/Non-Unicode
character.
Example:
DECLARE @FirstName AS Example:
VARCHAR(50) = ‘UMAR’ DECLARE @FirstName AS
SELECT @FirstName AS NVARCHAR(50)= ‘UMAR’
FirstName,DATALENGTH( SELECT @FirstName AS
@FirstName) AS Length FirstName,DATALENGTH(
@FirstName) AS Length
Result:
FirstName Length Result:
UMAR 4 FirstName Length
UMAR 8

3 Optional Parameter n Optional Parameter n


range: range:

Optional Parameter n value Optional Parameter n value


can be from 1 to 8000.Can can be from 1 to 4000.Can
store maximum 8000 Non- store maximum 4000
Unicode characters. Unicode/Non-Unicode
characters

4 If Optional Parameter n is If Optional Parameter n is


not specified in the not specified in the
variable declaration or variable declaration or
column definition: column definition:

If Optional parameter value If Optional parameter value


is not specified in the n is not specified in the
variable declaration or variable declaration or
column definition then it is column definition then it is
considered as 1. considered as 2

Example: Example:
DECLARE @firstName DECLARE @firstName
VARCHAR =‘UMAR’ NVARCHAR =‘UMAR’
SELECT SELECT
@firstNameFirstName,DAT @firstNameFirstName,DAT
ALENGTH(@firstName) ALENGTH(@firstName)
Length Length

Result: Result:
FirstName Length FirstName Length
U1 U2
5 If Optional Parameter n is If Optional Parameter n is
not not
specified in while using specified in while using
CAST/CONVERT CAST/CONVERT
functions: functions:

When this optional When this optional


parameter n is not specified parameter n is not specified
while using the while using the CAST
CAST/CONVERT functions, CONVERT functions, then it
then it is considered as 30. is considered as 30.

Example: Example:
DECLARE @firstName DECLARE @firstName
VARCHAR(35) =‘UMAR NVARCHAR(35) =‘UMAR
ASIA INDIA TAMIL NADU ASIA INDIA TAMIL NADU
CUDDALORE’ CUDDALORE’
SELECT CAST(@firstName SELECT CAST(@firstName
AS VARCHAR) AS NVARCHAR)
FirstName,DATALENGTH( FirstName,DATALENGTH(
CAST(@firstName AS CAST(@firstName AS
VARCHAR)) Length NVARCHAR)) Length

Result: Result:
FirstName Length FirstName Length
UMAR ASIA INDIA TAMIL UMAR ASIA INDIA TAMIL
NADU CUD 30 NADU CUD 60

7 Which one to use? Which one to use?

If we know that data to be If we know that data to be


stored in the column or stored in the column or
variable doesn’t have any variable can have Unicode
Unicode characters. characters.

8 Storage Size: Storage Size:

Takes no. of bytes equal to Takes no. of bytes equal to


the no. of Characters twice the no. of Characters
entered plus two bytes entered plus two bytes extra
extra for defining offset. for defining offset.
2.Difference between SQL Server and MySQL
S.No SQL Server MySQL

1 Current Date and Current Date and Time:


Time:
SELECT NOW()
SELECT GETDATE()
Optionally: Use CURDATE()
for the date only.

2 Limiting Results: Limiting Results:

SELECT * FROM table


SELECT TOP 10 * WHERE id = 1 LIMIT 10
FROM table WHERE id
=1

3 Date Field Default Date Field Default Value:


Value:
DATETIME fields cannot
DATETIME DEFAULT have a default value, i.e.
GETDATE() "GETDATE()"

We must use your INSERT


statement to specify
CURDATE() for the field.

Optionally: Use datatype


TIMESTAMP DEFAULT
CURRENT_TIMESTAMP

4 Character Length: Character Length:

LEN() CHARACTER_LENGTH()
Aliases: CHAR_LENGTH(),
LENGTH()

5 Character Replace: Character Replace:

REPLACE() works REPLACE() works case


case insensitively sensitively

6 Trim Functions: Trim Functions:

LTRIM() and RTRIM() TRIM()

7 String Concatenation: String Concatenation:


CONCATENATION CONCAT(string, string),
USING + (Does not which accepts two or more
automatically cast arguments.
operands to compatible (Automatically casts values
types) into types which can be
concatenated)

8 Auto Increment Field Auto Increment Field


Definition: Definition:

tablename_id INT tablename_id INTEGER


IDENTITY PRIMARY AUTO_INCREMENT
KEY PRIMARY KEY

9 Get a List of Tables: Get a List of Tables:

SP_TABLES SHOW TABLES

10 Get Table Properties: Get Table Properties:

HELP tablename DESCRIBE tablename

11 Get Database Get Database Version:


Version:
SELECT VERSION()
SELECT
@@VERSION

12 Recordset Paging: Recordset Paging:

Recordset paging done Add to end of SQL: "LIMIT " &


by client side-ADO ((intCurrentPage-
(very involved) 1)*intRecsPerPage) & ", "
&intRecsPerPage
LIMIT: The first argument
specifies the offset of the first
row to return, and the second
specifies the maximum
number of rows to return. The
offset of the initial row is 0
(not 1).

13 Get ID of Newest Get ID of Newest Inserted


Inserted Record: Record:

SET NOCOUNT ON; Two step process:


INSERT INTO...; 1. Execute your statement:
SELECT objConn.Execute("INSERT
id=@@IDENTITY; SET INTO...")
NOCOUNT OFF; 2. Set objRS =
objConn.Execute("SELECT
LAST_INSERT_ID() AS ID")

14 Get a Random Get a Random Record:


Record:
SELECT * FROM Users
SELECT TOP 1 * ORDER BY RAND() LIMIT 1
FROM Users ORDER
BY NEWID()

15 Generate a Unique Generate a Unique GUID:


GUID:
SELECT UUID()
SELECT NEWID()

16 Licensing: Licensing:
SQL Server is not an MySQL is available for free
open source and since MySQL is an open
payment has to be source.
made to use SQL
Server.

17 View Support: View Support:


SQL Server offers MySQL offers only
indexed views which updateable views.
are much more
powerful, performance
wise.

18 XML Support: XML Support:


SQL Server supports MySQL does not support
XML. XML.

19 Security: Security:
SQL Server provides MySQL provides only table
column level security. level security.

20 Certiication for Certiication for Security:


Security: MySQL does not offer any
SQL Server has C2 certification for security.
compliant certification.
Database security is
verified by third party.

21 Support for Triggers: Support for Triggers:


SQL Server provides Earlier versionsof MySQL
triggers. does not support triggers.
Only MySQL 5.0 supports
triggers.

22 Support for UDF: Support for UDF:


User defined functions User defined functions are
are supported in SQL not supported in MySQL.
Server.

23 Support for Cursors: Support for Cursors:


Cursor feature is Cursor feature is not available
available in SQL in MySQL.
Server.

24 Support for SPs and Support for SPs and Joins:


Joins: Stored procedures and full
Stored procedures and join facility are offered in SQL
full join facility is not Server.
offered in MySQL.

25 Support for Support for Import/Export


Import/Export Functions:
Functions: Import and Export functions
Import and export are have very limited support in
extensively supported MySQL.
in MySQL.

26 Support for Support for Transaction:


Transaction: Transaction support is very
Transaction support is much limited in MySQL.
extensively and fully
offered in SQL Server.

27 Support for Support for Replication:


Replication: Replication support is very
Replication support is much limited in MySQL.
extensively and fully
offered in SQL Server.

28 Support for auto Support for auto tuning:


tuning: Auto tuning is not supported
Auto tuning is in MySQL.
supported in SQL
Server.

29 Support for job Support for job scheduling


scheduling and and profiling:
profiling: Job scheduling and profiling
Job scheduling and are not available in MySQL.
profiling are available
in SQL Server.

30 Support for online Support for online backup


backup and and clustering:
clustering: Online backup support and
Online backup support clustering support is limited in
and clustering support MySQL.
is extensive and
complete in SQL
Server.

31 Support for Log Support for Log shipping


shipping and SAN: and SAN:
Log Shipping and Log Shipping and Storage
Storage Area Network Area Network support is not
support is available in available in MySQL.
SQL Server.

32 Support for OLAP Support for OLAP Services,


Services, Data Data Reporting and Data
Reporting and Data Mining:
Mining: OLAP Services, Data
OLAP Services, Data Reporting and Data Mining
Reporting and Data are not supported in MySQL.
Mining are supported in
SQL Server.

3.Difference between SET QUOTED_IDENTIFIER ON and SET


QUOTED_IDENTIFIER OFF in SQL Server

S.No SET SET


QUOTED_IDENTIFIER QUOTED_IDENTIFIER
ON OFF

1 Characters Enclosed Characters Enclosed


within double quotes: within double quotes:
is treated as Identifier is treated as Literal

2 Try using Characters Try using Characters


Enclosed within double Enclosed within double
quotes as identifier: quotes as identifier:

Works Fails
Example: Below Example: Below statement
statement to create a to create a table with table
table with table name name “Table” Fails.
“Table” succeeds. SET
SET QUOTED_IDENTIFIER
QUOTED_IDENTIFIER OFF GO
ON GO CREATE TABLE
CREATE TABLE dbo.”Table”
dbo.”Table” (id int,”Function”
(id int,”Function” VARCHAR(20)) GO
VARCHAR(20)) GO Error Message:
Msg 102, Level 15, State 1,
Line 1 Incorrect syntax
near ‘Table’.

3 Try using Characters Try using Characters


Enclosed within double Enclosed within double
quotes as Literal: quotes as Literal:

Fails Works
Example: Below Example: Below Statement
statement fails. Works.
SET SET
QUOTED_IDENTIFIER QUOTED_IDENTIFIER
ON OFF
GO GO
SELECT “BIRADAR” SELECT “UMAR”
Error Message:
Msg 207, Level 16, State
1,
Line 1 Invalid column
name ‘UMAR’.

4 Characters Enclosed Characters Enclosed


within single quotes: within single quotes:

is treated as Literal is treated as Literal


Example: Example:
SET SET
QUOTED_IDENTIFIER QUOTED_IDENTIFIER ON
ON GO
GO SELECT ‘UMAR’
SELECT ‘UMAR’

5 How to find all the How to find all the


objects which are objects which are created
created with SET with SET
QUTOED_IDENTIFIER QUTOED_IDENTIFIER
ON/OFF: ON/OFF:

Below Statement can be Below Statement can be


used to find all the used to find all the objects
objects created with SET created with SET
QUTOED_IDENTIFIER QUTOED_IDENTIFIER
setting as ON: setting as OFF:

SELECT SELECT OBJECT_NAME


OBJECT_NAME (object_id) FROM
(object_id) FROM sys.sql_modules WHERE
sys.sql_modules WHERE uses_quoted_identifier = 0
uses_quoted_identifier =
1
4.Difference between DateTime and DateTime2 DataType

S.No DateTime DateTime2[(n)]

1 Min Value: 1753-01-01 Min Value: 0001-01-01


00:00:00 00:00:00

2 Max Value: Max Value:

9999-12-31 9999-12-31
23:59:59.997 23:59:59.9999999

3 Storage Size: Storage Size:

8 Bytes 6 to 8 bytes

Note: Parameter n is
optional and if it is not
specified then fractional
seconds precision is 7 digit
and it can be from 0 to 7
digit.
For fractional seconds
precision <3 6="6"
bytes="bytes" font="font"
takes="takes">
For fractional seconds
precision 3 or 4 it will take 7
bytes
For fractional seconds
precision >4 it will take 8
bytes

4 Usage: Usage:

Declare @now datetime Declare @now datetime2(7)

5 Current Date and Time Current Date and Time


function: function:

GetDate() – It returns SYSDATETIME()- It returns


DB Current Date and DB Current Date and Time
Time of DateTime Data of DateTime2 Data Type
Type
Example: SELECT
Example: SELECT SYSDATETIME()
GETDATE() Result: 2011-09-16
Result: 2011-09-16 13:23:18.7676720
13:23:18.767

6 +/- days: +/- days:

WORKS FAILS – Need to use only


Example: DECLARE DateAdd function
@nowDateTime Example: DECLARE
DATETIME = @nowDateTime2
GETDATE() DATETIME2=
SELECT SYSDATETIME()
@nowDateTime + 1 SELECT
Result: 2011-09-17 @nowDateTime2+1
13:44:31.247 Result: Msg 206, Level 16,
State 2, Line 2
Operand type clash:
datetime2 is incompatible
with int

7 Compliance: Compliance:

Is not an ANSI/ISO Is an ANSI/ISO compliant


compliant

1.Difference between Correlated subquery and Nested subquery

S.No Correlated subquery Nested subquery

1 Correlated subquery runs Nested subquery runs only


once for each row once for the entire nesting
selected by the outer (outer) query. It does not
query. It contains a contain any reference to the
reference to a value from outer query row.
the row selected by the
outer query.

2 Correlated subquery Nested subquery follows


follows down to top top-down approach i.e.,
approach i.e., main query child query is executed first
is executed first(even and then parent .
though parenthesis are
present) and then child We can also say:In a
query.  subquery
Outer query condition is
We can also say: in a used in the the inner query.
Correlated
subquery,Inner query
condition is used in the
outer query

4 Example: Example:

select e1.empname, select empname, basicsal,


e1.basicsal, e1.deptno deptno from emp
from emp e1

where e1.basicsal = where (deptno, basicsal) in


(select max(basicsal) (select deptno,
from emp e2 where max(basicsal) from emp
e2.deptno = e1.deptno) group by deptno)
2.Difference between Weak Entity Set and Strong Entity Set

S.N Weak Entity Set Strong Entity Set


o

1 An entity set which does An entity set which does have


not possess sufficient a primary key is called a
attributes to form a strong entity set.
primary key is known as
a weak entity set.

2 Member of a weak entity Member of a strong entity set


set is a subordinate is a dominant entity.
entity.

3 Example:  Example: 

Specific Set of all


Person,Company,Event, Persons,Companies,Trees,H
Plant olidays

3.Difference between char and varchar data types in Sql Server


S.No Char Varchar

1 Fixed length memory Variable length memory


storage storage(Changeable)

2 CHAR takes up 1 byte VARCHAR takes up 1 byte


per character per character, + 2 bytes to
hold length information

3 Use Char when the Use Varchar when the data


data entries in a entries in a column are
column are expected to expected to vary
be the same size like considerably in size like
phone number address

4 Ex:  Ex: 
Declare test Declare test VarChar(100); 
Char(100);  test="Test" - 
test="Test" -  Then "test" occupies only
Then "test" occupies 4+2=6 bytes. first four bytes
100 bytes first four for value and other two bytes
bytes with values and for variable length
rest with blank data information.
4.Difference between Sql Server 2005 and Sql Server 2008
S.No Sql Server 2005 Sql Server 2008

1 XML datatype is XML datatype is used.


introduced.

2 Cannot encrypt the Can encrypt the entire


entire database. database introduced in 2008.

3 Datetime is used for Date and time are seperately


both date and time. used for date and time

4 No table datatype is Table datatype introduced.


included.

5 SSIS is started using. SSIS avails in this version.

6 CMS is not available. Central Management


Server(CMS) is Introduced.

7 PBM is not available Policy based


management(PBM) server is
Introduced.

Difference between Count(*) and Count(column_name) in SQL Server


S.No Count(*) Count(column_name)

1 Will count all the rows Returns the number of rows


in the specified table which have a value (NULL
values will not be counted)
Difference between Check Constraint and Rule
S.No Check Constraint Rule

1 Check constraint is Rules are defined with in a


associated with columns database and can be
in a Table. So these applied to any number of
cannot be re-used. columns

Example for Constraint:


alter table Emp add constraint ck_op Check (Salary between 15000 and 45000)

Example for Rule (Creation & Binding):


Creating Rule:
CREATE RULE SAL_RANGE
as
@Sal > 15000 and @Sal > 45000
Binding Rule to a Column:
SP_BINDRULE 'SAL_RANGE','Emp.Salary'

Difference between a table scan and an index scan in SQL Server Database
S.No Table Scan Index Scan

1 Here, row by row Here in the first, index is


scanning is done to get created in the table. It then
the data. In case, there uses the index to get to the
are huge number of data data that we wanted. It
in a table, it becomes an increases the performance.
overhead.

Difference between SQL and T-SQL in SQL Server

S.No SQL T-SQL

1 SQL stands for Structured T-SQL stands for Transact


Query Language SQL

2 ANSI/ISO(American This is implementing in


National Standards SQL SERVER. T-SQL can
Institute) standard have one or more queries.
database query language

3 Set of queries submitted It is a batch program, and


individually to the server. submit to the server in a
single shot. We can run all
the programs at any time.

4 It is developed by IBM. T-Sql is implemetation of


SQL in Microsoft SQL
Server.

Difference between Database and Schema

S.No Database Schema


1 Database is a collection Database schema describes
of organized data the structure and
organization of data in a
database system

2 The database holds the Schema contains


records, fields and cells Databases and describes
of data how these database fields
and cells are structured and
organized and what types of
relationships are mapped
between these entities

1.Difference between OLTP and OLAP

S.N OLTP OLAP


o

1 Abbreviation: Abbreviation:

OLTP stands for Online OLAP stands for Online


transactional processing . analytical processing .

2 Meaning: Meaning:

OLTP is designed to OLAP is designed for


efficiently process high analysis and decision
volumes of transactions, support, allowing
instantly recording exploration of often hidden
business events (such as a relationships in large
sales invoice payment) and amounts of data by
reflecting changes as they providing unlimited views
occur. of multiple relationships at
any cross-section of
defined business
dimensions.

3 Used in: Used in:

ERP, TX system, Client Data warehouse


Server Architecture, application - MOLAP,
Desktop application ROLAP, HOLAP

4 Data Provision: Data Provision:


Current data Current and historical data

5 Type of Database Type of Database


Transactions: Transactions:

Short database Long database


transactions transactions

6 Type of Type of
update/insert/delete: update/insert/delete:

Online update/insert/delete Batch update/insert/delete

7 Normalization/Denomaliz Normalization/Denomaliz
ation: ation:

Normalization is Denormalization is
promoted (1st normal form, promoted (Dimension and
second normal form and Fact design).
third normal form).

8 Volume of Transactions: Volume of Transactions:

High volume of Low volume of transactions


transactions

9 Transaction Recovery Transaction Recovery


Needed: Needed:

Transaction recovery is Transaction recovery is not


necessary necessary

10 Amount of Index Amount of Index


Requirement: Requirement:

Less Index More Index

11 Amount of Join Amount of Join


Requirement: Requirement:
More Joins Less Joins

12 Model: Model:

Adopts an entity Adopts star, snowflake or


relationship(ER) model fact constellation model
and a subject-oriented
database design

13 Orientation: Orientation:

Customer-oriented, used Market-oriented, used for


for data analysis and data analysis by
querying by clerks, clients knowledge
and IT professionals workers( managers,
executives, analysis)

14 Source: Source:

Daily transactions. OLTP

15 Motive: Motive:

Faster insert, updates, Faster analysis and search


deletes and improve data by combining tables.
quality by reducing
redundancy.

16 SQL complexity: SQL complexity:

Simple and Medium. Highly complex due to


analysis and forecasting.
2.Difference between DTS and SSIS

S.No DTS SSIS

1 DTS stands for Data SSIS stands for Sql Server


Transformation Services Integration Services

2 DTS is a set of objects SSIS is an ETL tool


using an ETS tool to provided by Microsoft to
extract, transform, and extra data from different
load information to or sources.
from a database

3 DTS was originally part SSIS is a component of the


of the Microsoft SQL Microsoft SQL Server 2005
Server 2000

4 Uses Activex Script Uses Scripting Language

5 No Deployment wizard is Deployment wizard is


available available

6 Limited Set of Huge of Transformations


Transformation available available

7 Does not support BI Completely supports end to


Functionality end process of BI

8 Single Task at a time Multi Tasks run parallely

9 It is Unmanaged script It is managed by CLR

10 DTS can develop SSIS can develop through


through Enterprise Business Intelligence
manager Development Studio (BIDS,
nothing but new version of
VS IDE)

11 We can deploy only at It can be deployed using


local server multiple server using BIDS

12 Designer contains Single SSIS designer contains 4


Pane design panes:
a) Control Flow
b) Data Flow
c) Event Handlers &
d) Package Explorer.

13 No Event Hander Event Handler Available

14 No Solution Explorer Solution Explorer is


available, with packages,
connections and Data
Source Views (DSV)

15 Connection and other It can be controlled


values are static, not dynamically using
controlled at runtime. configuration

Difference between rdl and rdlc


S.No rdl rdlc

1 It stands for Report It stands for Report


Definition Language Definition Language, Client
Side
2 Created by Sql server Created by Visual studio
with reporting services

3 Runs on server side Runs on client side

4 Requires values for all Does not require to have


elements such as query values for all elements such
text as query text

5 Takes less time to Takes more time to produce


produce large data in large data in reports
reports

6 As runs in server license As runs in local license of


of the reporting services the reporting services not
not needed needed

Difference between Control Flow and Data Flow in SSIS

S.No Control Flow Data Flow

1 The smallest unit in The smallest unit in Data


Control Flow is called Flow is called component.
task.

2 In Control Flow , tasks In Data Flow , one


require completion component will not wait for
(success, failure or other component to finish,
completion) before all of them will work
moving to next task. together in processing and
managing data in streaming
way.

Difference Between Star Schema and Snowflake Schema

S. Star Schema Snowflake Schema


No

1 Data Structure: Data Structure:


De-Normalized Data Normalized Data Structure
Structure
2 Dimension: Dimension:
Category wise Single Dimension table split into
Dimension Table many pieces

3 Data dependency & Data dependency &


redundancy: redundancy:
More data dependency and Less data dependency and
redundancy No redundancy

4 Join: Join:
No need to use Complicated Join
complicated join

5 Query Result: Query Result:


Query Results Faster Some delay in Query
Processing

6 Parent Table: Parent Table:


No Parent Table It may contain Parent Table

7 DB Structure: DB Structure:
Simple DB Structure Complicated DB Structure

8 Sample: Sample:
http://blog- http://blog-
mstechnology.blogspot.in/2 mstechnology.blogspot.in/2
010/06/bi-dimensional- 010/06/bi-dimensional-
model-star-schema.html model-snowflake-
schema.html

Differences between Merge and Union All transformations in SSIS

S.No Merge Union All

1  Number of inputs  Number of inputs


allowed: allowed: 
Merge transformation Union all can take more
can accept only two than two inputs.
inputs.

2 Data to be sorted or Data to be sorted or not


not before Merge before Union All
transformation: transformation:
Data has to be sorted Union all does not have any
before Merge condition like Merge.
Transformation.
Difference between MOLAP, ROLAP and HOLAP in SSAS

MOLAP ROLAP HOLAP

MOLAP stands for ROLAP stands HOLAP stands for Hybrid


Multidimensional Online for Relational Online Online Analytical
Analytical Processing Analytical Processing Processing

The MOLAP storage mode The ROLAP storage mode The HOLAP storage mode
causes the aggregations of causes the aggregations of combines attributes of both
the partition and a copy of the partition to be stored in MOLAP and ROLAP. Like
its source data to be stored indexed views in the MOLAP, HOLAP causes
in a multidimensional relational database that the aggregations of the
structure in Analysis was specified in the partition to be stored in a
Services when the partition partition’s data source. multidimensional structure
is processed. in an SQL Server Analysis
Services instance.

This MOLAP structure is Unlike the MOLAP storage HOLAP does not cause a
highly optimized to mode, ROLAP does not copy of the source data to
maximize query cause a copy of the source be stored. For queries that
performance. The storage data to be stored in the access only summary data
location can be on the Analysis Services data in the aggregations of a
computer where the partition folders. Instead, when partition, HOLAP is the
is defined or on another results cannot be derived equivalent of MOLAP.
computer running Analysis from the query cache, the
Services. Because a copy of indexed views in the data
the source data resides in source are accessed to
the multidimensional answer queries.
structure, queries can be
resolved without accessing
the partition’s source data.

Query response times can Query response is Queries that access source
be decreased substantially generally slower with data—for example, if you
by using aggregations. The ROLAP storage than with want to drill down to an
data in the partition’s the MOLAP or HOLAP atomic cube cell for which
MOLAP structure is only as storage modes. Processing there is no aggregation
current as the most recent time is also typically slower data—must retrieve data
processing of the partition. with ROLAP. However, from the relational
ROLAP enables users to database and will not be as
view data in real time and fast as they would be if the
can save storage space source data were stored in
when you are working with the MOLAP structure. With
large datasets that are HOLAP storage mode,
infrequently queried, such users will typically
as purely historical data. experience substantial
differences in query times
depending upon whether
the query can be resolved
from cache or aggregations
versus from the source
data itself.

Pros Pros Pros


 Provides maximum  Ability to view the  HOLAP balances
query performance, data in near real-time. the disk space requirement,
because all the required  Since ROLAP does as it only stores the
data (a copy of the detail not make another copy of aggregate data on the
data and calculated data as in case of MOLAP, OLAP server and the detail
aggregate data) are stored it has less storage data remains in the
in the OLAP server itself requirements. This is very relational database. So no
and there is no need to refer advantageous for large duplicate copy of the detail
to the underlying relational datasets which are queried data is maintained.
database. infrequently such as  Since HOLAP does
 All the calculations historical data. not store detail data on the
are pre-generated when the  In ROLAP mode, the OLAP server, the cube and
cube is processed and detail data is stored on the partitions would be smaller
stored locally on the OLAP underlying relational in size than MOLAP cubes
server hence even the database, so there is no and partitions.
complex calculations, as a limitation on data size that  Performance is
part the query result, will be ROLAP can support or better than ROLAP as in
performed quickly. limited by the data size of HOLAP the summary data
 MOLAP uses relational database. In are stored on the OLAP
compression to store the nutshell, it can even handle server and queries can be
data on the OLAP server huge volumes of data. satisfied from this summary
and so has less storage data.
requirements than relational  HOLAP would be
databases for same amount optimal in the scenario
of data. where query response is
 MOLAP does not required and query results
need to have a permanent are based on aggregations
connection to the underlying on large volumes of data.
relational database (only at
the time of processing) as it
stores the detail and
aggregate data in the OLAP
server so the data can be
viewed even when there is
connection to the relational
database.

Cons Cons Cons


 With MOLAP mode,  Compared to  Query performance (response
time) degrades if it has to drill through the
you need frequent MOLAP or HOLAP the
detail data from relational data store, in
processing to pull refreshed query response is generally this case HOLAP performs very much
data after last processing slower because everything like ROLAP.
resulting in drain on system is stored on relational
resources. database and not locally on
 Latency; just after the the OLAP server.
processing if there is any  A permanent
changes in the relational connection to the
database it will not be underlying database must
reflected on the OLAP be maintained to view the
server unless re-processing cube data.
is performed.
 MOLAP stores a
copy of the relational data at
OLAP server and so
requires additional
investment for storage.
 If the data volume is
high, the cube processing
can take longer, though you
can use incremental
processing to overcome
this.

Difference between Full Load and Incremental Load

S.No Full Load Incremental Load

1 Truncates all rows and New records and updated


loads from scratch. ones are loaded.

2 Requires more time. Requires less time.

3 Can easily be Difficult. ETL must check for


guaranteed. new/updated rows.
4 Can be lost. Retained.

CTE,TableVariable,TempTable Difference:
1. Temp Tables are physically created in the Tempdb database. These tables act as the normal
table and also can have constraints, index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-queries
data. This exists for the scope of statement. This is created in memory rather than Tempdb database.
You cannot create any index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query execution. It gets
dropped once it comes out of batch. This is also created in the Tempdb database but not the
memory.

You might also like