SlideShare une entreprise Scribd logo
1  sur  59
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
deallocating the data pages and
logs the deallocation.
Removes one row at a time and
records an entry in the transaction
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
key in a table.
We can have more than one unique
key in a table.
4 Primary key can be made foreign
key into another table.
Unique key cannot be made foreign
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
records in the table
It sorts and maintain a separate
storage
2 There can be only one Clustered
index per table
We can have 249 non-clustered
indexes in a table
3 The leaf nodes contain data The leaf node contains pointer to
data
4 To create clustered index Sql
server required more memory
because the leaf pages in the
tree structure will maintain actual
data .
To create non-clustered index Sql
server requires less memory because
the leaf pages will contain pointers to
actual data
5 By using clustered index
retrieving data is more
faster,when we compare with
non-clustered index.
By using non-clustered index
retrieving data is slower than
clustered index.
1
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 in a Select statement
User Defined Function can be used in
a Select statement
2 Stored procedure supports
Deferred Name Resolution
User Defined Function does not
support Deferred Name Resolution
3 Stored Procedures are generally
used for performing Business
Logic
User Defined Functions are generally
used for Computations
4 Stored Procedure need not return
a value
User Defined Functions should return
a value
5 Stored Procedures can return
any datatype
User Defined Functions cannot return
Image
6 Stored Procedures can accept
more number of input parameters
than User Defined Functions.
Stored Procedures can have upto
21000 input parameters
User Defined Functions accept lesser
number of input parameters than
Stored Procedures. UDF can have
upto 1023 input parameters
7 Stored Procedures can use
Temporary Tables & table
variables.
Temporary Tables cannot be used in
a User Defined Function it uses table
variables.
8 Stored Procedures can execute
Dynamic SQL
User Defined Functions cannot
execute Dynamic SQL
9 Stored Procedure supports error
handling
User Defined Function does not
support error handling.
RAISEERROR or @@ERROR are
not allowed in UDFs
10 Non-deterministic functions can
be used in Stored Procedures.
Stored Procedures can call functions.
Non-deterministic functions cannot be
used in User Defined Functions
(UDFs). For example, GETDATE()
cannot be used in User Defined
Functions(UDFs)
function can't call a Stored Procedures.
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
functions
It can contain aggregate functions
4 It can be used in select, delete
,insert etc.
It is used only in select clause
6. What are the differences between Union and UnionAll?
S.No Union UnionAll
1 This is used to eliminate
duplicate rows
It will not eliminate duplicate rows
2 This selects only distinct rows It selects all the values
3 It can be used to combine any
number of queries
It can be used to combine maximum
of 2 queries
4 It cannot contain aggregate
functions
It can contain aggregate functions
5 Union is slower than UnionAll UnionAll is faster than Union
6 Output is in sorted order
Example :
Output is not in sorted order
Example :
SELECT Col
FROM @Table1
UNION
SELECT Col
FROM @Table2
Result:
1
2
3
5
SELECT Col
FROM @Table1
UNION ALL
SELECT Col
FROM @Table2
Result:
1
2
3
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
table-level processing
Cursors are used for row-level
processing
8) Difference between Primary Key and Foreign Key
S.No Primary Key Foreign Key
1 Primary key uniquely identify a
record in the table.
Foreign key is a field in the table that
is primary key in another table.
2 Primary Key cannot accept null
values.
Foreign key can accept multiple null
values.
3 By default, Primary key is
clustered index and data in the
database table is physically
organized in the sequence of
clustered index.
While Foreign key is non-clustered
index.
4 We can have only one Primary
key in a table.
We can have more than one foreign
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
INSTEAD OF trigger for each
triggering action (UPDATE,
DELETE, and INSERT)
A table can have several AFTER
triggers for each triggering action.
2 INSTEAD OF triggers fire in
place of the triggering action and
before constraints are processed.
AFTER triggers fire after the
triggering action (INSERT, UPDATE,
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
directly used in the SELECT
clause.
Output of the User-Defined Functions
can be directly used in the SELECT
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
Triggers
We can pass parameter in Stored
Procedures
3 We can write a Stored procedure
within a Trigger
We cannot write a Trigger within a
Stored Procedure
4 Triggers are implicitly fired
whenever insert, update or delete
operations take place on table
Stored Procedures need to be
explicitly called by the programmer
5 Triggers can only be
implemented on Tables or Views
Stored procedures can be written for
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
command inside a trigger.
We can use the Print commands
inside the stored procedure for
debugging purpose
8 We cannot call a trigger from
these files.
We can call a stored procedure from
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 table.
Example :
CREATE TABLE Table
test_Identity
(
[ID] int Identity (1,1),
[Product Name]
varchar(50)
)
Sequence is an object.
Example :
CREATE SEQUENCE
[dbo].[Sequence_ID]
AS [int]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 1000
NO CYCLE
NO CACHE
3 If we need a new ID
from an identity column
we need to
insert and then get new
ID.
Example :
Insert into [test_Identity]
Values (‘SQL Server’)
In the sequence, we do not
need to insert new ID, we
can view the new ID directly.
Example :
SELECT NEXT VALUE
FOR dbo.[Sequence_ID]
GO
SELECT @@IDENTITY
AS ‘Identity’
–OR
Select
SCOPE_IDENTITY()
AS ‘Identity’
4 We cannot perform a
cycle in identity column.
Meaning, we cannot
restart the counter after
a
particular interval.
In the sequence, we can
simply add one property to
make it a cycle.
Example :
ALTER SEQUENCE
[dbo].[Sequence_ID]
CYCLE;
5 We cannot cache
Identity column
property.
Sequence can be easily
cached by just setting cache
property of
sequence. It also improves
the performance.
Example :
ALTER SEQUENCE
[dbo].[Sequence_ID]
CACHE 3;
6 We cannot remove the
identity column from the
table directly.
The sequence is not table
dependent so we can easily
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
maximum value in
identity column it is
based on the data type
limit.
Here we can set up its
maximum value.
Example :
ALTER SEQUENCE
[dbo].[Sequence_ID]
MAXVALUE 2000;
8 We can reseed it but
cannot change the step
size.
We can reseed as well as
change the step size.
Example :
Example :
DBCC CHECKIDENT
(test_Identity, RESEED,
4)
ALTER SEQUENCE
[dbo].[Sequence_ID]
RESTART WITH 7
INCREMENT BY 2;
9 We cannot generate
range from identity.
We can generate a range of
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
create and back up data.
But the table variable
involves the effort when we
usually create the normal
tables.
2 Temp table result can be
used by multiple users.
But the table variable can
be used by the current user
only.
3 Temp table will be stored
in the tempdb. It will
make network traffic.
When we have large
data in the temp table
then it has to work
across the database. A
Performance issue will
exist.
But a table variable will
store in the physical
memory for some of the
data, then later when the
size increases it will be
moved to the tempdb.
4 Temp table can do all
the DDL operations. It
allows creating the
indexes, dropping,
altering, etc..,
Whereas table variable
won't allow doing the DDL
operations. But the table
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
global. So that a multiple
user session can utilize
the results in the table.
be used up to that program.
(Stored procedure)
6 Temp variable cannot
use the transactions.
When we do the DML
operations with the temp
table then it can be
rollback or commit the
transactions.
But we cannot do it for
table variable.
7 Functions cannot use the
temp table. More over
we cannot do the DML
operation in the functions
.
But the function allows us
to use the table variable.
But using the table variable
we can do that.
8 The stored procedure
will do the recompilation
(can't use same
execution plan) when we
use the temp variable for
every sub sequent calls.
Whereas the table variable
won't do like that.
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 a msg_id is passed to
RAISERROR, the ID
must be defined in
sys.messages.
The error_number
parameter does not have to
be defined in
sys.messages.
2 The msg_str parameter
can contain printf
formatting styles.
The message parameter
does not accept printf style
formatting.
3 The severity parameter There is no severity
specifies the severity of
the exception.
parameter. The exception
severity is always set to 16.
.Difference between Database Mail and SQL Mail
S.No Database Mail SQL Mail
1 Based on SMTP
(Simple Mail Transfer
Protocol).
Based on MAPI (Messaging
Application Programming
Interface).
2 Introduced in Sql Server
2005.
Used prior versions of Sql
Server 2005.
3 No need to install
Outlook.
Require Outlook to be
installed.
4 More secure than Sql
mail.
Less secure than Database
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
Azure Storage platform.
It is an SQL Server that has
been configured to be
hosted on top
of the Windows Azure in a
high availability mode.
2 It comprises flexible or
schema-less entities. No
referential integrity
between the tables, and
no custom indexes.
It comprises standard SQL
Tables with indexes and
referential integrity.
3 It can scale massive
amounts of data due to
the partition key.
It may not scale as far as
Azure Table storage.
4 Can be thought as single
spreadsheet.
Look familiar to any .Net
developer who has used
Sql server 2008 prior.
3.Difference between DBMS and RDBMS
S.No DBMS RDBMS
1 Stands for DataBase
Management System
Stands for Relational
DataBase Management
System
2 In dbms no relationship
concept
It is used to establish the
relationship concept
between two database
objects, i.e, tables
3 It supports Single User
only
It supports multiple users
4 It treats Data as Files
internally
It treats data as Tables
internally
5 It supports 3 rules of
E.F.CODD out off 12
rules
It supports minimum 6 rules
of E.F.CODD
6 It requires low Software
and Hardware
Requirements.
It requires High software
and hardware
requirements.
7 DBMS is used for
simpler business
applications
RDBMS is used for more
complex applications.
8 DBMS does not impose
any constraints or
security with regard to
data manipulation
RDBMS defines the
integrity constraint for the
purpose of holding ACID
PROPERTY
9 In DBMS Normalization
process will not be
present
In RDBMS, normalization
process will be present to
check the database table
consistency
10 There is no enforcement
to use foreign key
concept compulsorily in
DBMS
Although the foreign key
concept is supported by
both DBMS and RDBMS
but its only RDBMS that
enforces the rules
11 FoxPro, IMS are
Examples
SQL Server, Oracle are
examples
4.Difference between SQL Server 2000 and SQL Server 2005
S.No SQL Server 2000 SQL Server 2005
1 Query Analyser and
Enterprise manager are
separate.
Both are combined as
SSMS(Sql Server
management Studio).
2 No XML datatype is
used.
.XML datatype is introduced.
3 We can create
maximum of 65,535
databases.
We can create 2(pow(20))-1
databases.
4 Exception Handling
mechanism is not
available
Exception Handling
mechanism is available
5 There is no
Varchar(Max) data type
is not available
Varchar(Max) data type is
introduced.
6 DDL Triggers is not
available
DDL Triggers is introduced
7 DataBase Mirroring
facility is not available
DataBase Mirroring facility is
introduced
8 RowNumber function for
paging is not available
RowNumber function for
paging is introduced
9 Table fragmentation
facility is not available
Table fragmentation facility
is introduced
10 Full Text Search facility
is not available
Full Text Search facility is
introduced
11 Bulk Copy Update
facility is not available
Bulk Copy Update facility is
introduced
12 Data Encryption
concept is not
introduced
.Cannot encrypt the entire
database
13 Cannot compress the
tables and indexes.
Can Compress tables and
indexes.(Introduced in 2005
SP2)
14 No varchar(max) or
varbinary(max) is
available.
Varchar(max) and
varbinary(max) is used.
15 Data Transformation
Services(DTS) is used
as ETL tool
SQL Server Integration
Services(SSIS) is started
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
INSERT and BCP
uses COPY instead
(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
1433
Default listening on 5432
8 datatype: varchar(max) datatype: text
9 Key is clustered by
default
key is not clustered by
default (and it is enforced by
a constraint and not an an
index!)
10 User Defined Data
Types
Domains
11 user: sa user: postgres
12 No such thing NATURAL and USING joins
13 SELECT TOP 10
* FROM t
SELECT * FROM t LIMIT 10
14 Query plans read from
right to left
Query plan read from left to
right
15 Estimate Query Plan:
CTRL+L
Estimate Query Plan: F7
2.Difference between Cross Join and Full Outer Join
S.No Cross Join Full Outer Join
1 No join conditions are
specified.
A combination of both left
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
product of two tables.
Assigns NULL for
unmatched fields.
3.Difference between SQL Server and Oracle
S.No SQL Server Oracle
1 SQL History:
IBM introduced
Oracle History:
Oracle Corp is the leading
structured Query
Language (SQL) as the
language to interface
with its prototype
relational database
management system;
System R. Oracle
Corporation introduced
the first commercially
available SQL relational
database management
system in 1979. Today,
SQL has become an
industry standard, and
Oracle Corporation
clearly leads the world in
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.
supplier for S/w products,
headquartered in Redwood
shores, California, USA. It
was founded by Larry
Ellison, Bob Miner and Ed
Oates in 1977. Now they
have 43,000 Employees in
150 countries. Oracle first
commercial RDBMS was
built in 1979, and it is the
first to support the SQL.
Oracle is the first S/w
company to develop and
deploy 100 % Internet-
enabled enterprise
Software.
2 SQL (Structure Query
Language):
When a user wants to
get some information
from any DB file, he can
issue a query.
Structured query
language (SQL),
pronounced “Sequel”, is
the set of commands
that all programs and
users must use to
access data within the
Oracle. SQL is a high
performance fault
tolerant data base
management system.
The database is mostly
Oracle (RDBMS):
Oracle is fastest and
easiest way to create
applications in MS
windows. It provides the
ability to store and access
data. Whether you are
experienced or new to
windows in programming,
Oracle provides you with
the complete set of tools to
simplify rapid application
development. The Oracle
refers to the method used
to create the graphical user
inter face. There is no need
to write numerous lines of
code to describe the
maintained by SQL
language, which is
conceded as the heart of
the RDBMS.
appearance and location of
inter face elements.
3 SQL Technology:
SQL is divided into four
parts:
DDL (Data Definition
Language): Create,
Alter, Drop, Rename,
Truncate.
DML (Data Manipulate
Language): Select,
Update and Delete,
Insert, Into.
DCL (Data Control
Language): Grant,
Revoke
TCL (Transaction
Control Language):
Commit, Rollback.
Oracle Technology:
Oracle DB structure is
divided into two parts, one
is called Physical structure
(these files define the
operating system that make
up the DB, each Oracle DB
is made by three types of
files, data-files, redo logs
file-controls file) and the
other is called Logical
structure (these files define
the logical areas of storage
like schema, table spaces,
segments and extents).
4 Advantages:
 Provides easy
access to all data.
 Flexibility in data
molding.
 Reduced data
storage and
redundancy.
 Provides a high-
level manipulation
language.
 SQL can save
data in common PC file
formats that can be
imported into other
application (like Ms-
Excel).
Advantages:
 Data consistency
 Integration of data
 Easy file generation
 Increased security
 Easy updating of
records
 No wastage of time
 Enforcement of
standards
 Controlled data
redundancy
 Reduce the total
expenditures
 Searching of
particular data is easy
 SQL is not case
sensitive.
 It can enter one
or more lines.
 Tabs and indents
can be used to make
code more readable.
 Can be used by a
range of users.
 It is a
nonprocedural language
(English-like language).
 Dispose of heavy
files and register work
 The work of three
persons is reduced to one
 Instant intimation of
modification of information
5 Differences:
 SQL is a tool for
all DB like DBMS,
RDBMS, T-SQL, and
SQL Plus.
 SQL maintains
different RDBMS.
 SQL is
combination of different
commands and
functions that why, SQL
is worked for Oracle DB
as a command prompt
shell (SQL is the
command prompt shell,
where we can
communicate with any
DB).
Differences:
 Oracle Corp is the
world’s leading supplier of
S/w products.
 Oracle is the
platform, where we develop
and implement different DB
designs and software.
 Oracle is the
combination of different S/w
products, where they work
together for designing DB.
 Oracle works with
different front and back end
products/tools (like SQL).
4.Difference between View and Stored Procedure
S.No View Stored Procedure
1 Does not accepts
parameters
Accept parameters
2 Can be used as a
building block in large
Cannot be used as a
building block in large
query. query.
3 Can contain only one
single Select query.
Can contain several
statement like if, else, loop
etc.
4 Cannot perform
modification to any table.
Can perform modification to
one or several tables.
5 Can be used
(sometimes) as the
target for Insert, update,
delete queries.
Cannot be used as the
target for Insert, update,
delete queries.
5.Difference between IN and EXISTS
S.No IN EXISTS
1 Returns true if specified
value matches any value
in the sub query or a list.
Return true if sub query
contain any rows.
2 The sub query will run
first and then only outer
query.
The Outer query will ran
first and then only sub
query.
3 IN is slower than
EXISTS. The IN is used
in the widely For Static
variables for eg: select
name from table where
ID in (Select ID from
table2).
Exists is faster than IN.The
Outer query will run first
and then only inner
query.So it will reduce the
over head. The Exists is
useful mostly in IF
conditional statements.
4 Example:
SELECT id,
[Name]
FROM dbo.tablea
WHERE id IN (SELECT
id
FROM dbo.tableb)
Example:
SELECT id,
[Name]
FROM dbo.tablea AS a
WHERE EXISTS (SELECT
id2
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
disk
Check for available
memory and removed
Buffer pool (execution
plan/compile plan/ Data
pages /Memory objects)
3 Default, Occurs
approximately every 1
minute
Occurs depending upon
memory pressure and
resource availability
4 Can be managed with
sp_confige -recovery
interval option
It is lazy, Sql server
manages by its own.
5 Does not check the
memory pressure
Monitor the memory
pressure and try maintain
the available free memory.
6 Crash recovery process
will be fast to read log as
data file is updated.
No role in recovery
7 Occurs for any DDL
statement
Occurs per requirement
8 Occurs before
Backup/Detach
command
Occurs per requirement
9 Depends upon the
configuration setting, we
can control.
Works on Least recent
used pages and removed
unused plans first, no user
control.
10 For simple recovery it
flush the tlog file after
70% full.
No effect on recovery
model.
11 Can manually /Forcefully
run command
“Checkpoint”
No command for Lazy
Writer
12 Very Less performance
impact
No performance impact
2.Difference between Mirroring and Log Shipping
S.No Mirroring Log Shipping
1 Principle can have
single mirror
Multiple stand by servers
can be possible.
2 Generally good to have
10 DB’s for one server
No limit
3 No data loss and can be
used as high availability
like Clustering
May be some data loss as
per schedule. And
secondary server takes
some manual work and time
to be primary
4 Read log read and
transfer the committed
transaction through
endpoints.
Transfer the log back up
and restored at standby
server.
5 Only committed
transaction
Committed as well as
uncommitted and whole log
backup restores.
6 PAGE repair is possible
if principle database
page gets corrupt
N/A
7 Mirrored DB can only be
accessed using
snapshot DB
Secondary server can be
reporting server (read-only)
8 Principle and Mirror
server should have
same edition
Primary and secondary
server should be compatible
server for restore.
9 Require FULL recovery
model
Require FULL or Bulk-
Logged recovery model
10 Requires Sql Server Enterprise edition for Sql
2005 SP1 or higher –
Enterprise or Developer
Editions
Server 2000 and even
Standard edition for 2005
can works
11 Immediate data moved
depending on SEND
and WAIT queue
Can control the flow of data
by scheduling jobs
12 As Immediate data
moves, user error
reflects at mirrored DB
As delay in data transfer
can avoided user error.
3.Difference between Change Track and Change Data Capture – CDC in SQL
Server 2008
S.
No
Change Track Change Data Capture
1 It is about fact: It
captures only the fact
as the tracking table
has changed. It does
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
It is about the Data: Change data capture
provides historical change information for a user
table by capturing both the fact that DML changes
were made and the actual data that was changed.
2 Storage:
Internal tables are
placed on the same
Storage:
When change data capture is enabled for a
database, a few things are added to the database,
filegroup as the
parent entity. You
could use
thesys.internal_tabl
es catalog view to
show all the internal
tables and parent
entities. For
example: select
name,
object_name(parent_i
d) as parent_object
from
sys.internal_tables
including a new schema (calledcdc), some
metadata tables, and a trigger to capture Data
Definition Language (DDL) events.
The two function names are,
respectively,fn_cdc_get_all_changes_ andfn_cd
c_get_net_changes_, with the capture instance
name appended. Note that (like the change
tracking feature) this functionality requires the table
to have aprimary key or other unique index.
3 Supported on
“Simple” recovery
model also.
It is recommended
that you
usesnapshot
isolation when
change tracking is
enabled. Snapshot
isolation itself can
add significant
workload overhead
and requires much
more careful
management of
tempdb.
Prevents Log truncation.
Forces full logging of some bulk operations.
One major point to note here is that once change
data capture is enabled, the transaction log
behaves just as it does withtransactional
replication—the log cannot be truncated until the
log reader has processed it. This means a
checkpoint operation, even in SIMPLE recovery
mode,will not truncate the log unless it has already
been processed by the log reader.
4 It
uses synchronous tr
acking mechanism.
once a database is
enabled for change
tracking, a version
numberis instituted,
which allows ordering
of operations
Change Data Capture (CDC) uses
theasynchronous process that reads the
transaction log.
5 Change Tracking has
minimal impact on the
system.
It has almost nil impact as it asynchronous
mechanism reads from the transaction log.
6 It
uses TempDB heavil
y
It uses transaction log.
7 DDL 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.
No such DDL restriction
8 SQL Agent not
needed
t requires SQL Agent to be running.
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 required
to enable:
SYSADMIN
Permission required to enable: DBOwner
4.Difference between Index Rebuild and Index Reorganize in SQL Server 2005
S.No Index Rebuild Index Reorganize
1 Index Rebuild drops the
existing Index and
Recreates the index from
Index Reorganize physically
reorganizes the leaf nodes
of the index.
scratch.
2 Rebuild the Index when an
index is over 30%
fragmented.
Reorganize the Index when
an index is between 10%
and 30% fragmented.
3 Rebuilding takes more
server resources and uses
locks unless you use the
ONLINE option available in
2005 Enterprise and
Development editions.
Always prefer to do
Reorganize the Index.
4 T-SQL for Rebuilding all
Indexes of a particular
table.
USE AdventureWorks;
GO
ALTER INDEX ALL ON
HumanResources.Employee
REBUILD
GO
T-SQL for Reorganize all
Indexes of a particular
table.
USE AdventureWorks;
GO
ALTER INDEX ALL ON
HumanResources.Employee
REORGANIZE
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
defined SP in one
database i.e available to
only that database
directly.i.e
we cannot call it from
some other DB’s directly
System defined sp are
available in master
DB.These sp’s can be
directly called from any DB
2 UDSP will be used to
fulfill the user
requirements
SDSP will be used for
managing sql server
1.Difference between Constraints and Triggers
S.No Constraints Triggers
1 Once we define some
constraint in a table
they will be stored
along with table
definition
It will be stored as separate
object
2 Constraints will do
memory location to
table comparison.
Triggers will do table to table
comparison.For this triggers
will use magic
tables(inserted,deleted).
3 In the order of
precedence first
Constraints will be fired
In the order of precedence
only after Constraints is
fired,then only Triggers will
be fired
4 Performance wise
Constraints will not give
best performance
because memory
location to table
comparison is slower
than table to table
comparison.
Performance wise triggers
will give best performance
because table to table
comparison is faster than
memory
location to table comparison.
5 Constraints cannot
start a chain reaction
as like triggers - for
instance each delete,
update action etc. can
trigger off another
function
Triggers are used to carry
out tasks which cant be done
using constraints.
For eg:-A change in the "sal"
column of a table should
change the "tax" column in
another table.This cant be
done using constraints.It has
to be done using
triggers.Thats where the
importance of triggers lie.
6 Constraint is used for
column
Trigger is used for table
7 Constraints are
predefined business
Trigger is a user defined
business rule for which user
rules in which all the
organizations follow
this constraints without
any
modification.
is responsible for logic for
business rule
8 Constraints are used to
maintain the integrity
and atomicity of
database .In other
words it can be said
they are used to
prevent invalid data
entry . the main 5
constraints are
NOT NULL,PRIMARY
KEY,FOREIGN
KEY,UNIQUE KEY and
CHECK
Triggers are basically stored
procedures which
automatically fired when any
insert,update or delete is
issued on table
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
Formatting Purposes.
Convert can be used for
Formatting Purposes.For
example Select convert
(varchar, datetime, 101)
3 Cast cannot convert a
datetime to specific
format
Convert can be used to
convert a datetime to
specific format
4 Usage of CAST:
USE Sample
GO
SELECT
SUBSTRING(Name, 1,
30) AS ProductName,
Usage of CONVERT:
USE Sample
GO
SELECT
SUBSTRING(Name, 1, 30)
AS ProductName, ListPrice
ListPrice
FROM
Production.Product
WHERE CAST(ListPrice
AS int) LIKE '3%';
GO
FROM Production.Product
WHERE CAST(int,
ListPrice) LIKE '3%';
GO
3.Difference between CUBE and ROLLUP
S.No CUBE ROLLUP
1 It is an additional switch
to GROUP BY clause. It
can be applied to all
aggregation functions to
return cross tabular
result sets.
It is an extension to
GROUP BY clause. It’s
used to extract statistical
and summarized
information from result sets.
It creates groupings and
then applies aggregation
functions on them.
2 Produces all possible
combinations of
subtotals specified in
GROUP BY clause and
a Grand Total.
Produces only some
possible subtotal
combinations
Difference between SQL Server 2008 and SQL Server 2012
S.No SQL Server 2008 SQL Server 2012
1 Maximum number
of concurrent connections:
The Maximum number of
concurrent connections to SQL
Server 2008 is 32767.
Maximum number
of concurrent connections:
SQL server 2012 has unlimited
concurrent connections.
2 Precision used for spatial
calculations:
The SQL Server 2008 uses 27 bit
bit precision for spatial
calculations.
Precision used for spatial
calculations:
The SQL Server 2012 uses 48 bit
precision for spatial calculations
3 TRY_CONVERT() and FORMAT() TRY_CONVERT() and FORMAT()
functions:
TRY_CONVERT() and FORMAT()
functions are not available in SQL
Server 2008
functions:
TRY_CONVERT() and FORMAT()
functions are newly included in
SQL Server 2012
4 ORDER BY Clause with
OFFSET / FETCH options:
ORDER BY Clause does not have
OFFSET / FETCH options as in
SQL Server 2012
ORDER BY Clause with OFFSET
/ FETCH options:
ORDER BY Clause now have
OFFSET / FETCH options to use
paging to 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:
SQL Server 2008 is code named
as Katmai.
Code Name:
SQL Server 2012 is code named
as Denali
In SQL Server 2008, audit is an
Enterprise-only feature. Only
available in Enterprise, Evaluation,
and Developer Edition.
In SQL Server 2012,support for
server auditing is expanded to
include all editions of SQL Server.
7 Sequence Object:
Sequence is not available in SQL
Server 2008
Sequence Object:
Sequence is included in 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,
FullName nvarchar(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 Capability:
The Full Text Search in SQL
Server 2008 does not allow us to
search and index data stored in
extended properties or metadata.
Full Text Search Capability:
The Full Text Search in SQL
Server 2012 has been enhanced
by allowing us to search and index
data stored in extended 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:
Analysis Services in SQL Server
does not have BI Semantic Model
(BISM) concept.
BISM Model:
Analysis Services will include a
new BI Semantic Model (BISM).
BISM is a 3-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
codenamed
as Kilimanjaro
SQL Server 2012 is
codenamed as Denali
2 In SQL Server 2008 R2 , In SQL Server 2012, server
rebooting is requisite for
OS patching , hence
server down time is high
down time is reduced by
50% , hence OS patching is
not rebooting n times.
3 SQL Server 2008 R2
does not have this
feature of availability
groups, hence fast
recovery is not possible.
In SQL Server 2012, high
availability and disaster
recovery factor has been
introduced which duplicates
the data and rapidly
recovers the loss.
4 SQL Server 2008 R2 is
slow compared to SQL
Server 2012.
In SQL Server 2012, the
performance is 10 times
faster than the
predecessor.
5 However buffer rate is
less because there is no
data redundancy in SQL
Server 2008 R2
Buffer rate is high in SQL
Server 2012 because of
data compression.
6 Data visualization is not
supported in SQL Server
2008 R2
Data visualization tool is
available in SQL Server
2012.This allows snapshots
of data.
7 Spatial features are not
supported more in SQL
Server 2008 R2. Instead
a traditional way for
geographical elements
have been set in SQL
Server 2008 R2.
Support for persistent
computed columns and
extra geographical
approach is possible with
spatial features in SQL
Server 2012.
Difference between SET and SELECT in SQL Server
S.No SET SELECT
1 Is it ANSI Standard ?
SET is ANSI Standard
for value assignment to
variables.
Is it ANSI Standard ?
SELECT is Non-ANSI
Standard for value
assignment to variables.
2 Variable Assignment: Variable Assignment:
SET can be used to
assign value to one
variable at a time.
DECLARE @i INT,
@j INT,
@k INT
SET @i = 10,@j =
20,@k = 30
It gives error:
Msg 102, Level 15,
State 1, Line 5
Incorrect syntax near ‘,’.
SELECT can be used to
assign values to multiple
variables in a single
SELECT statement.
The below query using
SELECT is valid:
1
2
3
4
5
DECLARE @i INT,
@j INT,
@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
when query returns
more then one value:
When assigning from a
query that returns more
than one value, SET will
fail with an error.
The below query using
set will fail:
1
2
3
DECLARE @i INT
SET @i = (SELECT n
FROM (VALUES
Behaviour of SELECT
when query returns more
then one value:
When assigning from a
query that returns more than
one value, SELECT will
assign the last value
returned by the query and
hide the fact that the query
returned
more than one row.
The below query using
select will execute
successfully:
1
(10),(20),(30)) AS
List(n))
Error:
Msg 512, Level 16,
State 1, Line 5
Subquery returned more
than 1 value. This is not
permitted when the
subquery follows =, !=,
<, <= , >, >= or when
the subquery is used as
an expression.
2
3
4
5
DECLARE @i INT
SELECT @i = n FROM
(VALUES (10),(20),(30)) AS
List(n)
SELECT @i
Output:
30
(1 row(s) affected)
4 Behaviour of SET
when query does not
return any rows:
If the variable is initially
assigned a value
following is the behavior
of variable assignment
for SET,
Assigns null if the query
does not return any
rows.
The output of the below
statement will be NULL
1
2
3
4
5
6
7
DECLARE @i INT
SET @i = 1
SET @i = (SELECT n
FROM (VALUES
(10),(20),(30)) AS
List(n) WHERE 1=2)
SELECT @i
Behaviour of SELECT
when query does not
return any rows:
If the variable is initially
assigned a value following
is the behavior of variable
assignment for SELECT,
Retains the initially assigned
value and does not assign
null if the query does not
return any rows.
The output of the below
statement will be 1
1
2
3
4
5
6
7
DECLARE @i INT
SET @i = 1
SELECT @i = n FROM
(VALUES (10),(20),(30)) AS
List(n) WHERE 1=2
SELECT @i
Output:
Output:
NULL
(1 row(s) affected)
1
(1 row(s) affected)
5 Performance:
Set does not provide
better performance over
select when used for
assigning values to
multiple variables at the
same time.
Assigning values to
multiple variables using
SET:
1
2
3
4
5
6
7
DECLARE @i INT,
@j INT,
@k INT
SET @i = 10
SET @j = 20
SET @k = 30
Performance:
Select has better
performance over set when
used for assigning values to
multiple variables at the
same time.
Assigning values to multiple
variables using Select:
1
2
3
4
5
DECLARE @i INT,
@j INT,
@k INT
SELECT @i = 10,@j =
20,@k = 30
6 When to use ?
Following are few
scenarios for using SET
1. If we are required to
assign a single value
directly to variable and
no query is involved to
fetch value.
2. NULL assignments
are expected (NULL
returned in result set)
3. Standards are meant
to be follow for any
planned migration
When to use ?
Using SELECT is efficient
and flexible in the following
few cases.
1. Multiple variables are
being populated by
assigning values directly
2. Multiple variables are
being populated by single
source (table , view)
3. Less coding for assigning
multiple variables
4. Use this if we need to get
@@ROWCOUNT and
4. Non scalar results are
expected and are
required to be handled
@ERROR for last statement
executed
1.Difference between VARCHAR and NVARCHAR in SQL Server
S.N
o
Varchar[(n)] NVarchar[(n)]
1 Basic Definition:
Non-Unicode Variable Length
character data type.
Example:
DECLARE @FirstName AS
VARCHAR(50) = ‘UMAR’
SELECT @FirstName
Basic Definition:
UNicode Variable Length character
data type. It can store both non-
Unicode and Unicode (i.e.
Japanese, Korean etc) characters.
Example:
DECLARE @FirstName AS
NVARCHAR(50)= ‘UMAR’
SELECT @FirstName
2 No. of Bytes required for each
character:
It takes 1 byte per character
Example:
DECLARE @FirstName AS
VARCHAR(50) = ‘UMAR’
SELECT @FirstName AS
FirstName,DATALENGTH(@FirstN
ame) AS Length
Result:
FirstName Length
UMAR 4
No. of Bytes required for each
character:
It takes 2 bytes per Unicode/Non-
Unicode character.
Example:
DECLARE @FirstName AS
NVARCHAR(50)= ‘UMAR’
SELECT @FirstName AS
FirstName,DATALENGTH(@FirstN
ame) AS Length
Result:
FirstName Length
UMAR 8
3 Optional Parameter n range:
Optional Parameter n value can be
from 1 to 8000.Can store maximum
8000 Non-Unicode characters.
Optional Parameter n range:
Optional Parameter n value can be
from 1 to 4000.Can store maximum
4000 Unicode/Non-Unicode
characters
4 If Optional Parameter n is not
specified in the variable
declaration or column definition:
If Optional parameter value is not
specified in the variable declaration
or column definition then it is
considered as 1.
Example:
DECLARE @firstName VARCHAR
=‘UMAR’
SELECT @firstName
FirstName,DATALENGTH(@firstNa
me) Length
Result:
FirstName Length
U 1
If Optional Parameter n is not
specified in the variable
declaration or column definition:
If Optional parameter value n is not
specified in the variable declaration
or column definition then it is
considered as 2
Example:
DECLARE @firstName
NVARCHAR =‘UMAR’
SELECT @firstName
FirstName,DATALENGTH(@firstNa
me) Length
Result:
FirstName Length
U 2
5 If Optional Parameter n is not
specified in while using
CAST/CONVERT functions:
If Optional Parameter n is not
specified in while using
CAST/CONVERT functions:
When this optional parameter n is
not specified while using the
CAST/CONVERT functions, then it
is considered as 30.
Example:
DECLARE @firstName
VARCHAR(35) =‘UMAR ASIA
INDIA TAMIL NADU CUDDALORE’
SELECT CAST(@firstName AS
VARCHAR)
FirstName,DATALENGTH(CAST(@
firstName AS VARCHAR)) Length
Result:
FirstName Length
UMAR ASIA INDIA TAMIL NADU
CUD 30
When this optional parameter n is
not specified while using the CAST
CONVERT functions, then it is
considered as 30.
Example:
DECLARE @firstName
NVARCHAR(35) =‘UMAR ASIA
INDIA TAMIL NADU CUDDALORE’
SELECT CAST(@firstName AS
NVARCHAR)
FirstName,DATALENGTH(CAST(@
firstName AS NVARCHAR)) Length
Result:
FirstName Length
UMAR ASIA INDIA TAMIL NADU
CUD 60
7 Which one to use?
If we know that data to be stored in
the column or variable doesn’t have
any Unicode characters.
Which one to use?
If we know that data to be stored in
the column or variable can have
Unicode characters.
8 Storage Size:
Takes no. of bytes equal to the no.
of Characters entered plus two
bytes extra for defining offset.
Storage Size:
Takes no. of bytes equal to twice
the no. of Characters entered plus
two bytes extra for defining offset.
2.Difference between SQL Server and MySQL
S.No SQL Server MySQL
1 Current Date and
Time:
SELECT GETDATE()
Current Date and Time:
SELECT NOW()
Optionally: Use CURDATE()
for the date only.
2 Limiting Results:
SELECT TOP 10 *
FROM table WHERE
id = 1
Limiting Results:
SELECT * FROM table
WHERE id = 1 LIMIT 10
3 Date Field Default
Value:
DATETIME DEFAULT
GETDATE()
Date Field Default Value:
DATETIME fields cannot
have a default value, i.e.
"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:
REPLACE() works
case insensitively
Character Replace:
REPLACE() works case
sensitively
6 Trim Functions:
LTRIM() and RTRIM()
Trim Functions:
TRIM()
7 String
Concatenation:
CONCATENATION
USING + (Does not
automatically cast
operands to
compatible types)
String Concatenation:
CONCAT(string, string),
which accepts two or more
arguments.
(Automatically casts values
into types which can be
concatenated)
8 Auto Increment Field
Definition:
tablename_id INT
IDENTITY PRIMARY
KEY
Auto Increment Field
Definition:
tablename_id INTEGER
AUTO_INCREMENT
PRIMARY KEY
9 Get a List of Tables:
SP_TABLES
Get a List of Tables:
SHOW TABLES
10 Get Table Properties:
HELP tablename
Get Table Properties:
DESCRIBE tablename
11 Get Database
Version:
SELECT
@@VERSION
Get Database Version:
SELECT VERSION()
12 Recordset Paging:
Recordset paging
done by client side-
Recordset Paging:
Add to end of SQL: "LIMIT "
& ((intCurrentPage-
ADO (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
Inserted Record:
SET NOCOUNT ON;
INSERT INTO...;
SELECT
id=@@IDENTITY;
SET NOCOUNT OFF;
Get ID of Newest Inserted
Record:
Two step process:
1. Execute your statement:
objConn.Execute("INSERT
INTO...")
2. Set objRS =
objConn.Execute("SELECT
LAST_INSERT_ID() AS ID")
14 Get a Random
Record:
SELECT TOP 1 *
FROM Users ORDER
BY NEWID()
Get a Random Record:
SELECT * FROM Users
ORDER BY RAND() LIMIT 1
15 Generate a Unique
GUID:
SELECT NEWID()
Generate a Unique GUID:
SELECT UUID()
16 Licensing:
SQL Server is not an
open source and
payment has to be
made to use SQL
Server.
Licensing:
MySQL is available for free
since MySQL is an open
source.
17 View Support:
SQL Server offers
indexed views which
are much more
powerful, performance
wise.
View Support:
MySQL offers only
updateable views.
18 XML Support:
SQL Server supports
XML.
XML Support:
MySQL does not support
XML.
19 Security:
SQL Server provides
column level security.
Security:
MySQL provides only table
level security.
20 Certiication for
Security:
SQL Server has C2
compliant certification.
Database security is
verified by third party.
Certiication for Security:
MySQL does not offer any
certification for security.
21 Support for Triggers:
SQL Server provides
triggers.
Support for Triggers:
Earlier versionsof MySQL
does not support triggers.
Only MySQL 5.0 supports
triggers.
22 Support for UDF:
User defined functions
are supported in SQL
Server.
Support for UDF:
User defined functions are
not supported in MySQL.
23 Support for Cursors:
Cursor feature is
available in SQL
Server.
Support for Cursors:
Cursor feature is not
available in MySQL.
24 Support for SPs and
Joins:
Stored procedures and
full join facility is not
offered in MySQL.
Support for SPs and Joins:
Stored procedures and full
join facility are offered in SQL
Server.
25 Support for
Import/Export
Functions:
Import and export are
extensively supported
in MySQL.
Support for Import/Export
Functions:
Import and Export functions
have very limited support in
MySQL.
26 Support for
Transaction:
Transaction support is
Support for Transaction:
Transaction support is very
much limited in MySQL.
extensively and fully
offered in SQL Server.
27 Support for
Replication:
Replication support is
extensively and fully
offered in SQL Server.
Support for Replication:
Replication support is very
much limited in MySQL.
28 Support for auto
tuning:
Auto tuning is
supported in SQL
Server.
Support for auto tuning:
Auto tuning is not supported
in MySQL.
29 Support for job
scheduling and
profiling:
Job scheduling and
profiling are available
in SQL Server.
Support for job scheduling
and profiling:
Job scheduling and profiling
are not available in MySQL.
30 Support for online
backup and
clustering:
Online backup support
and clustering support
is extensive and
complete in SQL
Server.
Support for online backup
and clustering:
Online backup support and
clustering support is limited in
MySQL.
31 Support for Log
shipping and SAN:
Log Shipping and
Storage Area Network
support is available in
SQL Server.
Support for Log shipping
and SAN:
Log Shipping and Storage
Area Network support is not
available in MySQL.
32 Support for OLAP
Services, Data
Reporting and Data
Mining:
OLAP Services, Data
Reporting and Data
Mining are supported
in SQL Server.
Support for OLAP Services,
Data Reporting and Data
Mining:
OLAP Services, Data
Reporting and Data Mining
are not supported in MySQL.
3.Difference between SET QUOTED_IDENTIFIER ON and SET
QUOTED_IDENTIFIER OFF in SQL Server
S.No SET
QUOTED_IDENTIFIER
ON
SET
QUOTED_IDENTIFIER
OFF
1 Characters Enclosed
within double quotes:
is treated as Identifier
Characters Enclosed
within double quotes:
is treated as Literal
2 Try using Characters
Enclosed within double
quotes as identifier:
Works
Example: Below
statement to create a
table with table name
“Table” succeeds.
SET
QUOTED_IDENTIFIER
ON GO
CREATE TABLE
dbo.”Table”
(id int,”Function”
VARCHAR(20)) GO
Try using Characters
Enclosed within double
quotes as identifier:
Fails
Example: Below statement
to create a table with table
name “Table” Fails.
SET
QUOTED_IDENTIFIER
OFF GO
CREATE TABLE
dbo.”Table”
(id int,”Function”
VARCHAR(20)) GO
Error Message:
Msg 102, Level 15, State
1,
Line 1 Incorrect syntax
near ‘Table’.
3 Try using Characters
Enclosed within double
quotes as Literal:
Fails
Example: Below
statement fails.
SET
QUOTED_IDENTIFIER
ON
GO
Try using Characters
Enclosed within double
quotes as Literal:
Works
Example: Below Statement
Works.
SET
QUOTED_IDENTIFIER
OFF
GO
SELECT “BIRADAR”
Error Message:
Msg 207, Level 16, State
1,
Line 1 Invalid column
name ‘UMAR’.
SELECT “UMAR”
4 Characters Enclosed
within single quotes:
is treated as Literal
Example:
SET
QUOTED_IDENTIFIER
ON
GO
SELECT ‘UMAR’
Characters Enclosed
within single quotes:
is treated as Literal
Example:
SET
QUOTED_IDENTIFIER
ON
GO
SELECT ‘UMAR’
5 How to find all the
objects which are
created with SET
QUTOED_IDENTIFIER
ON/OFF:
Below Statement can be
used to find all the
objects created with SET
QUTOED_IDENTIFIER
setting as ON:
SELECT
OBJECT_NAME
(object_id) FROM
sys.sql_modules WHERE
uses_quoted_identifier =
1
How to find all the
objects which are
created with SET
QUTOED_IDENTIFIER
ON/OFF:
Below Statement can be
used to find all the objects
created with SET
QUTOED_IDENTIFIER
setting as OFF:
SELECT OBJECT_NAME
(object_id) FROM
sys.sql_modules WHERE
uses_quoted_identifier = 0
4.Difference between DateTime and DateTime2 DataType
S.No DateTime DateTime2[(n)]
1 Min Value: 1753-01-01
00:00:00
Min Value: 0001-01-01
00:00:00
2 Max Value:
9999-12-31
23:59:59.997
Max Value:
9999-12-31
23:59:59.9999999
3 Storage Size:
8 Bytes
Storage Size:
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:
Declare @now datetime
Usage:
Declare @now datetime2(7)
5 Current Date and Time
function:
GetDate() – It returns
DB Current Date and
Time of DateTime Data
Type
Example: SELECT
GETDATE()
Result: 2011-09-16
13:23:18.767
Current Date and Time
function:
SYSDATETIME()- It returns
DB Current Date and Time
of DateTime2 Data Type
Example: SELECT
SYSDATETIME()
Result: 2011-09-16
13:23:18.7676720
6 +/- days: +/- days:
WORKS
Example: DECLARE
@nowDateTime
DATETIME =
GETDATE()
SELECT
@nowDateTime + 1
Result: 2011-09-17
13:44:31.247
FAILS – Need to use only
DateAdd function
Example: DECLARE
@nowDateTime2
DATETIME2=
SYSDATETIME()
SELECT
@nowDateTime2+1
Result: Msg 206, Level 16,
State 2, Line 2
Operand type clash:
datetime2 is incompatible
with int
7 Compliance:
Is not an ANSI/ISO
compliant
Compliance:
Is an ANSI/ISO compliant
1.Difference between Correlated subquery and Nested subquery
S.No Correlated subquery Nested subquery
1 Correlated subquery
runs once for each row
selected by the outer
query. It contains a
reference to a value from
the row selected by the
outer query.
Nested subquery runs only
once for the entire nesting
(outer) query. It does not
contain any reference to
the outer query row.
2 Correlated subquery
follows down to top
approach i.e., main
query is executed
first(even though
parenthesis are present)
and then child query.
We can also say: in a
Correlated
subquery,Inner query
condition is used in the
outer query
Nested subquery follows
top-down approach i.e.,
child query is executed first
and then parent .
We can also say:In a
subquery
Outer query condition is
used in the the inner query.
4 Example:
select e1.empname,
e1.basicsal, e1.deptno
from emp e1
where e1.basicsal =
(select max(basicsal)
from emp e2 where
e2.deptno = e1.deptno)
Example:
select empname, basicsal,
deptno from emp
where (deptno, basicsal) in
(select deptno,
max(basicsal) from emp
group by deptno)
2.Difference between Weak Entity Set and Strong Entity Set
S.No Weak Entity Set Strong Entity Set
1 An entity set which does not
possess sufficient attributes
to form a primary key is
known as a weak entity set.
An entity set which does have a
primary key is called a strong entity
set.
2 Member of a weak entity set
is a subordinate entity.
Member of a strong entity set is a
dominant entity.
3 Example:
Specific
Person,Company,Event,Plant
Example:
Set of all
Persons,Companies,Trees,Holidays
3.Difference between char and varchar data types in Sql Server
S.No Char Varchar
1 Fixed length memory
storage
Variable length memory
storage(Changeable)
2 CHAR takes up 1 byte
per character
VARCHAR takes up 1 byte
per character, + 2 bytes to
hold length information
3 Use Char when the
data entries in a
column are expected to
be the same size like
phone number
Use Varchar when the data
entries in a column are
expected to vary
considerably in size like
address
4 Ex: Ex:
Declare test
Char(100);
test="Test" -
Then "test" occupies
100 bytes first four
bytes with values and
rest with blank data
Declare test VarChar(100);
test="Test" -
Then "test" occupies only
4+2=6 bytes. first four bytes
for value and other two bytes
for variable length
information.
4.Difference between Sql Server 2005 and Sql Server 2008
S.No Sql Server 2005 Sql Server 2008
1 XML datatype is
introduced.
XML datatype is used.
2 Cannot encrypt the
entire database.
Can encrypt the entire
database introduced in 2008.
3 Datetime is used for
both date and time.
Date and time are seperately
used for date and time
4 No table datatype is
included.
Table datatype introduced.
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
in the specified table
Returns the number of rows
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
in a Table. So these
cannot be re-used.
database and can be
applied to any number of
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
scanning is done to get
the data. In case, there
are huge number of
data in a table, it
becomes an overhead.
Here in the first, index is
created in the table. It then
uses the index to get to the
data that we wanted. It
increases the performance.
Difference between SQL and T-SQL in SQL Server
S.No SQL T-SQL
1 SQL stands for Structured
Query Language
T-SQL stands for Transact
SQL
2 ANSI/ISO(American
National Standards
Institute) standard
database query language
This is implementing in
SQL SERVER. T-SQL can
have one or more queries.
3 Set of queries submitted
individually to the server.
It is a batch program, and
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
of organized data
Database schema
describes the structure and
organization of data in a
database system
2 The database holds the
records, fields and cells
of data
Schema contains
Databases and describes
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.No OLTP OLAP
1 Abbreviation:
OLTP stands for Online
transactional processing .
Abbreviation:
OLAP stands for Online
analytical processing .
2 Meaning:
OLTP is designed to efficiently
process high volumes of
transactions, instantly recording
business events (such as a
sales invoice payment) and
reflecting changes as they
occur.
Meaning:
OLAP is designed for analysis
and decision support, allowing
exploration of often hidden
relationships in large amounts of
data by providing unlimited
views of multiple relationships at
any cross-section of defined
business dimensions.
3 Used in: Used in:
ERP, TX system, Client Server
Architecture, Desktop
application
Data warehouse application -
MOLAP, ROLAP, HOLAP
4 Data Provision:
Current data
Data Provision:
Current and historical data
5 Type of Database
Transactions:
Short database transactions
Type of Database
Transactions:
Long database transactions
6 Type of update/insert/delete:
Online update/insert/delete
Type of update/insert/delete:
Batch update/insert/delete
7 Normalization/Denomalization:
Normalization is promoted (1st
normal form, second normal
form and third normal form).
Normalization/Denomalization:
Denormalization is
promoted (Dimension and Fact
design).
8 Volume of Transactions:
High volume of transactions
Volume of Transactions:
Low volume of transactions
9 Transaction Recovery
Needed:
Transaction recovery is
necessary
Transaction Recovery
Needed:
Transaction recovery is not
necessary
10 Amount of Index Requirement:
Less Index
Amount of Index Requirement:
More Index
11 Amount of Join Requirement:
More Joins
Amount of Join Requirement:
Less Joins
12 Model:
Adopts an entity
relationship(ER) model
Model:
Adopts star, snowflake or fact
constellation model and a
subject-oriented database
design
13 Orientation:
Customer-oriented, used for
data analysis and querying by
clerks, clients and IT
professionals
Orientation:
Market-oriented, used for data
analysis by knowledge workers(
managers, executives, analysis)
14 Source:
Daily transactions.
Source:
OLTP
15 Motive:
Faster insert, updates, deletes
and improve data quality by
reducing redundancy.
Motive:
Faster analysis and search by
combining tables.
16 SQL complexity:
Simple and Medium.
SQL complexity:
Highly complex due to analysis
and forecasting.
2.Difference between DTS and SSIS
S.No DTS SSIS
1 DTS stands for Data
Transformation Services
SSIS stands for Sql Server
Integration Services
2 DTS is a set of objects
using an ETS tool to
extract, transform, and
load information to or
from a database
SSIS is an ETL tool
provided by Microsoft to
extra data from different
sources.
3 DTS was originally part
of the Microsoft SQL
Server 2000
SSIS is a component of the
Microsoft SQL Server 2005
4 Uses Activex Script Uses Scripting Language
5 No Deployment wizard
is available
Deployment wizard is
available
6 Limited Set of
Transformation available
Huge of Transformations
available
7 Does not support BI
Functionality
Completely supports end to
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
through Enterprise
manager
SSIS can develop through
Business Intelligence
Development Studio (BIDS,
nothing but new version of
VS IDE)
11 We can deploy only at
local server
It can be deployed using
multiple server using BIDS
12 Designer contains
Single Pane
SSIS designer contains 4
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
values are static, not
controlled at runtime.
It can be controlled
dynamically using
configuration
Difference between rdl and rdlc
S.No rdl rdlc
1 It stands for Report
Definition Language
It stands for Report
Definition Language, Client
Side
2 Created by Sql server
with reporting services
Created by Visual studio
3 Runs on server side Runs on client side
4 Requires values for all
elements such as query
text
Does not require to have
values for all elements such
as query text
5 Takes less time to
produce large data in
reports
Takes more time to produce
large data in reports
6 As runs in server license
of the reporting services
not needed
As runs in local license of
the reporting services not
needed
Difference between Control Flow and Data Flow in SSIS
S.No Control Flow Data Flow
1 The smallest unit in
Control Flow is called
task.
The smallest unit in Data
Flow is called component.
2 In Control Flow , tasks
require completion
(success, failure or
completion) before
moving to next task.
In Data Flow , one
component will not wait for
other component to finish,
all of them will work
together in processing and
managing data in streaming
way.
Difference Between Star Schema and Snowflake Schema
S.N
o
Star Schema Snowflake Schema
1 Data Structure:
De-Normalized Data Structure
Data Structure:
Normalized Data Structure
2 Dimension:
Category wise Single Dimension
Table
Dimension:
Dimension table split into many
pieces
3 Data dependency & redundancy:
More data dependency and
Data dependency & redundancy:
Less data dependency and No
redundancy redundancy
4 Join:
No need to use complicated join
Join:
Complicated Join
5 Query Result:
Query Results Faster
Query Result:
Some delay in Query Processing
6 Parent Table:
No Parent Table
Parent Table:
It may contain Parent Table
7 DB Structure:
Simple DB Structure
DB Structure:
Complicated DB Structure
8 Sample:
http://blog-
mstechnology.blogspot.in/2010/06/
bi-dimensional-model-star-
schema.html
Sample:
http://blog-
mstechnology.blogspot.in/2010/06/
bi-dimensional-model-snowflake-
schema.html
Differences between Merge and Union All transformations in SSIS
S.No Merge Union All
1 Number of inputs
allowed:
Merge transformation
can accept only two
inputs.
Number of inputs
allowed:
Union all can take more
than two inputs.
2 Data to be sorted or
not before Merge
transformation:
Data has to be sorted
before Merge
Transformation.
Data to be sorted or not
before Union All
transformation:
Union all does not have any
condition like Merge.
Difference between MOLAP, ROLAP and HOLAP in SSAS
MOLAP ROLAP HOLAP
MOLAP stands for
Multidimensional Online
Analytical Processing
ROLAP stands
for Relational Online
Analytical Processing
HOLAP stands for Hybrid
Online Analytical
Processing
The MOLAP storage mode
causes the aggregations of
the partition and a copy of
its source data to be stored
in a multidimensional
structure in Analysis
Services when the partition
is processed.
The ROLAP storage mode
causes the aggregations of
the partition to be stored in
indexed views in the
relational database that
was specified in the
partition’s data source.
The HOLAP storage mode
combines attributes of both
MOLAP and ROLAP. Like
MOLAP, HOLAP causes
the aggregations of the
partition to be stored in a
multidimensional structure
in an SQL Server Analysis
Services instance.
This MOLAP structure is
highly optimized to
maximize query
performance. The storage
location can be on the
computer where the
partition is defined or on
another computer running
Analysis Services. Because
a copy of the source data
resides in the
multidimensional structure,
queries can be resolved
without accessing the
partition’s source data.
Unlike the MOLAP storage
mode, ROLAP does not
cause a copy of the source
data to be stored in the
Analysis Services data
folders. Instead, when
results cannot be derived
from the query cache, the
indexed views in the data
source are accessed to
answer queries.
HOLAP does not cause a
copy of the source data to
be stored. For queries that
access only summary data
in the aggregations of a
partition, HOLAP is the
equivalent of MOLAP.
Query response times can
be decreased substantially
by using aggregations. The
data in the partition’s
MOLAP structure is only as
current as the most recent
processing of the partition.
Query response is
generally slower with
ROLAP storage than with
the MOLAP or HOLAP
storage modes. Processing
time is also typically slower
with ROLAP. However,
ROLAP enables users to
view data in real time and
can save storage space
when you are working with
large datasets that are
infrequently queried, such
as purely historical data.
Queries that access source
data—for example, if you
want to drill down to an
atomic cube cell for which
there is no aggregation
data—must retrieve data
from the relational
database and will not be as
fast as they would be if the
source data were stored in
the MOLAP structure. With
HOLAP storage mode,
users will typically
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
 Provides maximum
query performance,
because all the required
data (a copy of the detail
data and calculated
aggregate data) are stored
in the OLAP server itself
and there is no need to refer
to the underlying relational
database.
 All the calculations
are pre-generated when the
cube is processed and
stored locally on the OLAP
server hence even the
complex calculations, as a
part the query result, will be
performed quickly.
 MOLAP uses
compression to store the
data on the OLAP server
and so has less storage
requirements than relational
databases for same amount
of data.
 MOLAP does not
need to have a permanent
connection to the underlying
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.
Pros
 Ability to view the
data in near real-time.
 Since ROLAP does
not make another copy of
data as in case of MOLAP,
it has less storage
requirements. This is very
advantageous for large
datasets which are queried
infrequently such as
historical data.
 In ROLAP mode,
the detail data is stored on
the underlying relational
database, so there is no
limitation on data size that
ROLAP can support or
limited by the data size of
relational database. In
nutshell, it can even handle
huge volumes of data.
Pros
 HOLAP balances
the disk space
requirement, as it only
stores the aggregate data
on the OLAP server and
the detail data remains in
the relational database. So
no duplicate copy of the
detail data is maintained.
 Since HOLAP does
not store detail data on the
OLAP server, the cube and
partitions would be smaller
in size than MOLAP cubes
and partitions.
 Performance is
better than ROLAP as in
HOLAP the summary data
are stored on the OLAP
server and queries can be
satisfied from this summary
data.
 HOLAP would be
optimal in the scenario
where query response is
required and query results
are based on aggregations
on large volumes of data.
Cons
 With MOLAP mode,
you need frequent
processing to pull refreshed
data after last processing
resulting in drain on system
resources.
Cons
 Compared to
MOLAP or HOLAP the
query response is
generally slower because
everything is stored on
relational database and not
Cons
 Query performance (response
time) degrades if it has to drill through
the detail data fromrelational data store,
in this case HOLAP performs very much
like ROLAP.
 Latency; just after the
processing if there is any
changes in the relational
database it will not be
reflected on the OLAP
server unless re-processing
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.
locally on the OLAP server.
 A permanent
connection to the
underlying database must
be maintained to view the
cube data.
Difference between Full Load and Incremental Load
S.No Full Load Incremental Load
1 Truncates all rows and
loads from scratch.
New records and updated
ones are loaded.
2 Requires more time. Requires less time.
3 Can easily be
guaranteed.
Difficult. ETL must check for
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.

Contenu connexe

Tendances

Tendances (20)

Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Sql DML
Sql DMLSql DML
Sql DML
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Triggers
TriggersTriggers
Triggers
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Introduction to Oracle Data Guard Broker
Introduction to Oracle Data Guard BrokerIntroduction to Oracle Data Guard Broker
Introduction to Oracle Data Guard Broker
 
Database index
Database indexDatabase index
Database index
 
Good sql server interview_questions
Good sql server interview_questionsGood sql server interview_questions
Good sql server interview_questions
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 

Similaire à SQL Differences SQL Interview Questions

Sql Server Difference FAQs Part One
Sql Server Difference FAQs Part OneSql Server Difference FAQs Part One
Sql Server Difference FAQs Part One
Umar Ali
 
SQL dabatase interveiw pdf for interveiw preparation
SQL dabatase  interveiw pdf for interveiw preparationSQL dabatase  interveiw pdf for interveiw preparation
SQL dabatase interveiw pdf for interveiw preparation
kumarvikesh2841998
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
maxpane
 

Similaire à SQL Differences SQL Interview Questions (20)

Sql Server Difference FAQs Part One
Sql Server Difference FAQs Part OneSql Server Difference FAQs Part One
Sql Server Difference FAQs Part One
 
Database testing
Database testingDatabase testing
Database testing
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
SQL Server Difference FAQs-2
SQL Server Difference FAQs-2SQL Server Difference FAQs-2
SQL Server Difference FAQs-2
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
MSSQL Queries.pdf
MSSQL Queries.pdfMSSQL Queries.pdf
MSSQL Queries.pdf
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questions
 
SQL dabatase interveiw pdf for interveiw preparation
SQL dabatase  interveiw pdf for interveiw preparationSQL dabatase  interveiw pdf for interveiw preparation
SQL dabatase interveiw pdf for interveiw preparation
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Data Structure Notes unit 1.docx
Data Structure Notes unit 1.docxData Structure Notes unit 1.docx
Data Structure Notes unit 1.docx
 
MSSQL_Book.pdf
MSSQL_Book.pdfMSSQL_Book.pdf
MSSQL_Book.pdf
 
Adv.+SQL+PPT+final.pptx
Adv.+SQL+PPT+final.pptxAdv.+SQL+PPT+final.pptx
Adv.+SQL+PPT+final.pptx
 
Sql wksht-7
Sql wksht-7Sql wksht-7
Sql wksht-7
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
SQL
SQLSQL
SQL
 
Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
 
Sql interview q&a
Sql interview q&aSql interview q&a
Sql interview q&a
 

Dernier

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Dernier (20)

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

SQL Differences SQL Interview Questions

  • 1. 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 deallocating the data pages and logs the deallocation. Removes one row at a time and records an entry in the transaction 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 key in a table. We can have more than one unique key in a table. 4 Primary key can be made foreign key into another table. Unique key cannot be made foreign 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 records in the table It sorts and maintain a separate storage 2 There can be only one Clustered index per table We can have 249 non-clustered indexes in a table 3 The leaf nodes contain data The leaf node contains pointer to
  • 2. data 4 To create clustered index Sql server required more memory because the leaf pages in the tree structure will maintain actual data . To create non-clustered index Sql server requires less memory because the leaf pages will contain pointers to actual data 5 By using clustered index retrieving data is more faster,when we compare with non-clustered index. By using non-clustered index retrieving data is slower than clustered index. 1 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 in a Select statement User Defined Function can be used in a Select statement 2 Stored procedure supports Deferred Name Resolution User Defined Function does not support Deferred Name Resolution 3 Stored Procedures are generally used for performing Business Logic User Defined Functions are generally used for Computations 4 Stored Procedure need not return a value User Defined Functions should return a value 5 Stored Procedures can return any datatype User Defined Functions cannot return Image 6 Stored Procedures can accept more number of input parameters than User Defined Functions. Stored Procedures can have upto 21000 input parameters User Defined Functions accept lesser number of input parameters than Stored Procedures. UDF can have upto 1023 input parameters 7 Stored Procedures can use Temporary Tables & table variables. Temporary Tables cannot be used in a User Defined Function it uses table variables. 8 Stored Procedures can execute Dynamic SQL User Defined Functions cannot execute Dynamic SQL
  • 3. 9 Stored Procedure supports error handling User Defined Function does not support error handling. RAISEERROR or @@ERROR are not allowed in UDFs 10 Non-deterministic functions can be used in Stored Procedures. Stored Procedures can call functions. Non-deterministic functions cannot be used in User Defined Functions (UDFs). For example, GETDATE() cannot be used in User Defined Functions(UDFs) function can't call a Stored Procedures. 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 functions It can contain aggregate functions 4 It can be used in select, delete ,insert etc. It is used only in select clause 6. What are the differences between Union and UnionAll? S.No Union UnionAll 1 This is used to eliminate duplicate rows It will not eliminate duplicate rows 2 This selects only distinct rows It selects all the values 3 It can be used to combine any number of queries It can be used to combine maximum of 2 queries 4 It cannot contain aggregate functions It can contain aggregate functions 5 Union is slower than UnionAll UnionAll is faster than Union 6 Output is in sorted order Example : Output is not in sorted order Example :
  • 4. SELECT Col FROM @Table1 UNION SELECT Col FROM @Table2 Result: 1 2 3 5 SELECT Col FROM @Table1 UNION ALL SELECT Col FROM @Table2 Result: 1 2 3 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 table-level processing Cursors are used for row-level processing 8) Difference between Primary Key and Foreign Key S.No Primary Key Foreign Key 1 Primary key uniquely identify a record in the table. Foreign key is a field in the table that is primary key in another table. 2 Primary Key cannot accept null values. Foreign key can accept multiple null values. 3 By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. While Foreign key is non-clustered index. 4 We can have only one Primary key in a table. We can have more than one foreign key in a table. 1. What are the differences between Instead of Triggers and After Triggers?
  • 5. S.No Instead of Triggers After Triggers 1 Each table or view can have one INSTEAD OF trigger for each triggering action (UPDATE, DELETE, and INSERT) A table can have several AFTER triggers for each triggering action. 2 INSTEAD OF triggers fire in place of the triggering action and before constraints are processed. AFTER triggers fire after the triggering action (INSERT, UPDATE, 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 directly used in the SELECT clause. Output of the User-Defined Functions can be directly used in the SELECT 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 Triggers We can pass parameter in Stored Procedures 3 We can write a Stored procedure within a Trigger We cannot write a Trigger within a Stored Procedure 4 Triggers are implicitly fired whenever insert, update or delete operations take place on table Stored Procedures need to be explicitly called by the programmer 5 Triggers can only be implemented on Tables or Views Stored procedures can be written for the Database 6 We cannot schedule a trigger. Stored procedures can be scheduled through a job to execute on a predefined time
  • 6. 7 We cannot use the print command inside a trigger. We can use the Print commands inside the stored procedure for debugging purpose 8 We cannot call a trigger from these files. We can call a stored procedure from 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 table. Example : CREATE TABLE Table test_Identity ( [ID] int Identity (1,1), [Product Name] varchar(50) ) Sequence is an object. Example : CREATE SEQUENCE [dbo].[Sequence_ID] AS [int] START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 1000 NO CYCLE NO CACHE 3 If we need a new ID from an identity column we need to insert and then get new ID. Example : Insert into [test_Identity] Values (‘SQL Server’) In the sequence, we do not need to insert new ID, we can view the new ID directly. Example : SELECT NEXT VALUE FOR dbo.[Sequence_ID]
  • 7. GO SELECT @@IDENTITY AS ‘Identity’ –OR Select SCOPE_IDENTITY() AS ‘Identity’ 4 We cannot perform a cycle in identity column. Meaning, we cannot restart the counter after a particular interval. In the sequence, we can simply add one property to make it a cycle. Example : ALTER SEQUENCE [dbo].[Sequence_ID] CYCLE; 5 We cannot cache Identity column property. Sequence can be easily cached by just setting cache property of sequence. It also improves the performance. Example : ALTER SEQUENCE [dbo].[Sequence_ID] CACHE 3; 6 We cannot remove the identity column from the table directly. The sequence is not table dependent so we can easily remove it Example : Create table dbo.[test_Sequence] (
  • 8. [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 maximum value in identity column it is based on the data type limit. Here we can set up its maximum value. Example : ALTER SEQUENCE [dbo].[Sequence_ID] MAXVALUE 2000; 8 We can reseed it but cannot change the step size. We can reseed as well as change the step size. Example :
  • 9. Example : DBCC CHECKIDENT (test_Identity, RESEED, 4) ALTER SEQUENCE [dbo].[Sequence_ID] RESTART WITH 7 INCREMENT BY 2; 9 We cannot generate range from identity. We can generate a range of 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 create and back up data. But the table variable involves the effort when we usually create the normal tables. 2 Temp table result can be used by multiple users. But the table variable can be used by the current user only. 3 Temp table will be stored in the tempdb. It will make network traffic. When we have large data in the temp table then it has to work across the database. A Performance issue will exist. But a table variable will store in the physical memory for some of the data, then later when the size increases it will be moved to the tempdb. 4 Temp table can do all the DDL operations. It allows creating the indexes, dropping, altering, etc.., Whereas table variable won't allow doing the DDL operations. But the table variable allows us to create the clustered index only. 5 Temp table can be used But the table variable can
  • 10. for the current session or global. So that a multiple user session can utilize the results in the table. be used up to that program. (Stored procedure) 6 Temp variable cannot use the transactions. When we do the DML operations with the temp table then it can be rollback or commit the transactions. But we cannot do it for table variable. 7 Functions cannot use the temp table. More over we cannot do the DML operation in the functions . But the function allows us to use the table variable. But using the table variable we can do that. 8 The stored procedure will do the recompilation (can't use same execution plan) when we use the temp variable for every sub sequent calls. Whereas the table variable won't do like that. 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 a msg_id is passed to RAISERROR, the ID must be defined in sys.messages. The error_number parameter does not have to be defined in sys.messages. 2 The msg_str parameter can contain printf formatting styles. The message parameter does not accept printf style formatting. 3 The severity parameter There is no severity
  • 11. specifies the severity of the exception. parameter. The exception severity is always set to 16. .Difference between Database Mail and SQL Mail S.No Database Mail SQL Mail 1 Based on SMTP (Simple Mail Transfer Protocol). Based on MAPI (Messaging Application Programming Interface). 2 Introduced in Sql Server 2005. Used prior versions of Sql Server 2005. 3 No need to install Outlook. Require Outlook to be installed. 4 More secure than Sql mail. Less secure than Database 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 Azure Storage platform. It is an SQL Server that has been configured to be hosted on top of the Windows Azure in a high availability mode. 2 It comprises flexible or schema-less entities. No referential integrity between the tables, and no custom indexes. It comprises standard SQL Tables with indexes and referential integrity. 3 It can scale massive amounts of data due to the partition key. It may not scale as far as Azure Table storage. 4 Can be thought as single spreadsheet. Look familiar to any .Net developer who has used Sql server 2008 prior.
  • 12. 3.Difference between DBMS and RDBMS S.No DBMS RDBMS 1 Stands for DataBase Management System Stands for Relational DataBase Management System 2 In dbms no relationship concept It is used to establish the relationship concept between two database objects, i.e, tables 3 It supports Single User only It supports multiple users 4 It treats Data as Files internally It treats data as Tables internally 5 It supports 3 rules of E.F.CODD out off 12 rules It supports minimum 6 rules of E.F.CODD 6 It requires low Software and Hardware Requirements. It requires High software and hardware requirements. 7 DBMS is used for simpler business applications RDBMS is used for more complex applications. 8 DBMS does not impose any constraints or security with regard to data manipulation RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY 9 In DBMS Normalization process will not be present In RDBMS, normalization process will be present to check the database table consistency 10 There is no enforcement to use foreign key concept compulsorily in DBMS Although the foreign key concept is supported by both DBMS and RDBMS but its only RDBMS that enforces the rules
  • 13. 11 FoxPro, IMS are Examples SQL Server, Oracle are examples 4.Difference between SQL Server 2000 and SQL Server 2005 S.No SQL Server 2000 SQL Server 2005 1 Query Analyser and Enterprise manager are separate. Both are combined as SSMS(Sql Server management Studio). 2 No XML datatype is used. .XML datatype is introduced. 3 We can create maximum of 65,535 databases. We can create 2(pow(20))-1 databases. 4 Exception Handling mechanism is not available Exception Handling mechanism is available 5 There is no Varchar(Max) data type is not available Varchar(Max) data type is introduced. 6 DDL Triggers is not available DDL Triggers is introduced 7 DataBase Mirroring facility is not available DataBase Mirroring facility is introduced 8 RowNumber function for paging is not available RowNumber function for paging is introduced 9 Table fragmentation facility is not available Table fragmentation facility is introduced 10 Full Text Search facility is not available Full Text Search facility is introduced 11 Bulk Copy Update facility is not available Bulk Copy Update facility is introduced
  • 14. 12 Data Encryption concept is not introduced .Cannot encrypt the entire database 13 Cannot compress the tables and indexes. Can Compress tables and indexes.(Introduced in 2005 SP2) 14 No varchar(max) or varbinary(max) is available. Varchar(max) and varbinary(max) is used. 15 Data Transformation Services(DTS) is used as ETL tool SQL Server Integration Services(SSIS) is started 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 INSERT and BCP uses COPY instead (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 1433 Default listening on 5432 8 datatype: varchar(max) datatype: text
  • 15. 9 Key is clustered by default key is not clustered by default (and it is enforced by a constraint and not an an index!) 10 User Defined Data Types Domains 11 user: sa user: postgres 12 No such thing NATURAL and USING joins 13 SELECT TOP 10 * FROM t SELECT * FROM t LIMIT 10 14 Query plans read from right to left Query plan read from left to right 15 Estimate Query Plan: CTRL+L Estimate Query Plan: F7 2.Difference between Cross Join and Full Outer Join S.No Cross Join Full Outer Join 1 No join conditions are specified. A combination of both left 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 product of two tables. Assigns NULL for unmatched fields. 3.Difference between SQL Server and Oracle S.No SQL Server Oracle 1 SQL History: IBM introduced Oracle History: Oracle Corp is the leading
  • 16. structured Query Language (SQL) as the language to interface with its prototype relational database management system; System R. Oracle Corporation introduced the first commercially available SQL relational database management system in 1979. Today, SQL has become an industry standard, and Oracle Corporation clearly leads the world in 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. supplier for S/w products, headquartered in Redwood shores, California, USA. It was founded by Larry Ellison, Bob Miner and Ed Oates in 1977. Now they have 43,000 Employees in 150 countries. Oracle first commercial RDBMS was built in 1979, and it is the first to support the SQL. Oracle is the first S/w company to develop and deploy 100 % Internet- enabled enterprise Software. 2 SQL (Structure Query Language): When a user wants to get some information from any DB file, he can issue a query. Structured query language (SQL), pronounced “Sequel”, is the set of commands that all programs and users must use to access data within the Oracle. SQL is a high performance fault tolerant data base management system. The database is mostly Oracle (RDBMS): Oracle is fastest and easiest way to create applications in MS windows. It provides the ability to store and access data. Whether you are experienced or new to windows in programming, Oracle provides you with the complete set of tools to simplify rapid application development. The Oracle refers to the method used to create the graphical user inter face. There is no need to write numerous lines of code to describe the
  • 17. maintained by SQL language, which is conceded as the heart of the RDBMS. appearance and location of inter face elements. 3 SQL Technology: SQL is divided into four parts: DDL (Data Definition Language): Create, Alter, Drop, Rename, Truncate. DML (Data Manipulate Language): Select, Update and Delete, Insert, Into. DCL (Data Control Language): Grant, Revoke TCL (Transaction Control Language): Commit, Rollback. Oracle Technology: Oracle DB structure is divided into two parts, one is called Physical structure (these files define the operating system that make up the DB, each Oracle DB is made by three types of files, data-files, redo logs file-controls file) and the other is called Logical structure (these files define the logical areas of storage like schema, table spaces, segments and extents). 4 Advantages:  Provides easy access to all data.  Flexibility in data molding.  Reduced data storage and redundancy.  Provides a high- level manipulation language.  SQL can save data in common PC file formats that can be imported into other application (like Ms- Excel). Advantages:  Data consistency  Integration of data  Easy file generation  Increased security  Easy updating of records  No wastage of time  Enforcement of standards  Controlled data redundancy  Reduce the total expenditures  Searching of particular data is easy
  • 18.  SQL is not case sensitive.  It can enter one or more lines.  Tabs and indents can be used to make code more readable.  Can be used by a range of users.  It is a nonprocedural language (English-like language).  Dispose of heavy files and register work  The work of three persons is reduced to one  Instant intimation of modification of information 5 Differences:  SQL is a tool for all DB like DBMS, RDBMS, T-SQL, and SQL Plus.  SQL maintains different RDBMS.  SQL is combination of different commands and functions that why, SQL is worked for Oracle DB as a command prompt shell (SQL is the command prompt shell, where we can communicate with any DB). Differences:  Oracle Corp is the world’s leading supplier of S/w products.  Oracle is the platform, where we develop and implement different DB designs and software.  Oracle is the combination of different S/w products, where they work together for designing DB.  Oracle works with different front and back end products/tools (like SQL). 4.Difference between View and Stored Procedure S.No View Stored Procedure 1 Does not accepts parameters Accept parameters 2 Can be used as a building block in large Cannot be used as a building block in large
  • 19. query. query. 3 Can contain only one single Select query. Can contain several statement like if, else, loop etc. 4 Cannot perform modification to any table. Can perform modification to one or several tables. 5 Can be used (sometimes) as the target for Insert, update, delete queries. Cannot be used as the target for Insert, update, delete queries. 5.Difference between IN and EXISTS S.No IN EXISTS 1 Returns true if specified value matches any value in the sub query or a list. Return true if sub query contain any rows. 2 The sub query will run first and then only outer query. The Outer query will ran first and then only sub query. 3 IN is slower than EXISTS. The IN is used in the widely For Static variables for eg: select name from table where ID in (Select ID from table2). Exists is faster than IN.The Outer query will run first and then only inner query.So it will reduce the over head. The Exists is useful mostly in IF conditional statements. 4 Example: SELECT id, [Name] FROM dbo.tablea WHERE id IN (SELECT id FROM dbo.tableb) Example: SELECT id, [Name] FROM dbo.tablea AS a WHERE EXISTS (SELECT id2 FROM dbo.tableb WHERE id2 = a.id)
  • 20. 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 disk Check for available memory and removed Buffer pool (execution plan/compile plan/ Data pages /Memory objects) 3 Default, Occurs approximately every 1 minute Occurs depending upon memory pressure and resource availability 4 Can be managed with sp_confige -recovery interval option It is lazy, Sql server manages by its own. 5 Does not check the memory pressure Monitor the memory pressure and try maintain the available free memory. 6 Crash recovery process will be fast to read log as data file is updated. No role in recovery 7 Occurs for any DDL statement Occurs per requirement 8 Occurs before Backup/Detach command Occurs per requirement 9 Depends upon the configuration setting, we can control. Works on Least recent used pages and removed unused plans first, no user control. 10 For simple recovery it flush the tlog file after 70% full. No effect on recovery model. 11 Can manually /Forcefully run command “Checkpoint” No command for Lazy Writer
  • 21. 12 Very Less performance impact No performance impact 2.Difference between Mirroring and Log Shipping S.No Mirroring Log Shipping 1 Principle can have single mirror Multiple stand by servers can be possible. 2 Generally good to have 10 DB’s for one server No limit 3 No data loss and can be used as high availability like Clustering May be some data loss as per schedule. And secondary server takes some manual work and time to be primary 4 Read log read and transfer the committed transaction through endpoints. Transfer the log back up and restored at standby server. 5 Only committed transaction Committed as well as uncommitted and whole log backup restores. 6 PAGE repair is possible if principle database page gets corrupt N/A 7 Mirrored DB can only be accessed using snapshot DB Secondary server can be reporting server (read-only) 8 Principle and Mirror server should have same edition Primary and secondary server should be compatible server for restore. 9 Require FULL recovery model Require FULL or Bulk- Logged recovery model 10 Requires Sql Server Enterprise edition for Sql
  • 22. 2005 SP1 or higher – Enterprise or Developer Editions Server 2000 and even Standard edition for 2005 can works 11 Immediate data moved depending on SEND and WAIT queue Can control the flow of data by scheduling jobs 12 As Immediate data moves, user error reflects at mirrored DB As delay in data transfer can avoided user error. 3.Difference between Change Track and Change Data Capture – CDC in SQL Server 2008 S. No Change Track Change Data Capture 1 It is about fact: It captures only the fact as the tracking table has changed. It does 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 It is about the Data: Change data capture provides historical change information for a user table by capturing both the fact that DML changes were made and the actual data that was changed. 2 Storage: Internal tables are placed on the same Storage: When change data capture is enabled for a database, a few things are added to the database,
  • 23. filegroup as the parent entity. You could use thesys.internal_tabl es catalog view to show all the internal tables and parent entities. For example: select name, object_name(parent_i d) as parent_object from sys.internal_tables including a new schema (calledcdc), some metadata tables, and a trigger to capture Data Definition Language (DDL) events. The two function names are, respectively,fn_cdc_get_all_changes_ andfn_cd c_get_net_changes_, with the capture instance name appended. Note that (like the change tracking feature) this functionality requires the table to have aprimary key or other unique index. 3 Supported on “Simple” recovery model also. It is recommended that you usesnapshot isolation when change tracking is enabled. Snapshot isolation itself can add significant workload overhead and requires much more careful management of tempdb. Prevents Log truncation. Forces full logging of some bulk operations. One major point to note here is that once change data capture is enabled, the transaction log behaves just as it does withtransactional replication—the log cannot be truncated until the log reader has processed it. This means a checkpoint operation, even in SIMPLE recovery mode,will not truncate the log unless it has already been processed by the log reader. 4 It uses synchronous tr acking mechanism. once a database is enabled for change tracking, a version numberis instituted, which allows ordering of operations Change Data Capture (CDC) uses theasynchronous process that reads the transaction log. 5 Change Tracking has minimal impact on the system. It has almost nil impact as it asynchronous mechanism reads from the transaction log.
  • 24. 6 It uses TempDB heavil y It uses transaction log. 7 DDL 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. No such DDL restriction 8 SQL Agent not needed t requires SQL Agent to be running. 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 required to enable: SYSADMIN Permission required to enable: DBOwner 4.Difference between Index Rebuild and Index Reorganize in SQL Server 2005 S.No Index Rebuild Index Reorganize 1 Index Rebuild drops the existing Index and Recreates the index from Index Reorganize physically reorganizes the leaf nodes of the index.
  • 25. scratch. 2 Rebuild the Index when an index is over 30% fragmented. Reorganize the Index when an index is between 10% and 30% fragmented. 3 Rebuilding takes more server resources and uses locks unless you use the ONLINE option available in 2005 Enterprise and Development editions. Always prefer to do Reorganize the Index. 4 T-SQL for Rebuilding all Indexes of a particular table. USE AdventureWorks; GO ALTER INDEX ALL ON HumanResources.Employee REBUILD GO T-SQL for Reorganize all Indexes of a particular table. USE AdventureWorks; GO ALTER INDEX ALL ON HumanResources.Employee REORGANIZE 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 defined SP in one database i.e available to only that database directly.i.e we cannot call it from some other DB’s directly System defined sp are available in master DB.These sp’s can be directly called from any DB 2 UDSP will be used to fulfill the user requirements SDSP will be used for managing sql server
  • 26. 1.Difference between Constraints and Triggers S.No Constraints Triggers 1 Once we define some constraint in a table they will be stored along with table definition It will be stored as separate object 2 Constraints will do memory location to table comparison. Triggers will do table to table comparison.For this triggers will use magic tables(inserted,deleted). 3 In the order of precedence first Constraints will be fired In the order of precedence only after Constraints is fired,then only Triggers will be fired 4 Performance wise Constraints will not give best performance because memory location to table comparison is slower than table to table comparison. Performance wise triggers will give best performance because table to table comparison is faster than memory location to table comparison. 5 Constraints cannot start a chain reaction as like triggers - for instance each delete, update action etc. can trigger off another function Triggers are used to carry out tasks which cant be done using constraints. For eg:-A change in the "sal" column of a table should change the "tax" column in another table.This cant be done using constraints.It has to be done using triggers.Thats where the importance of triggers lie. 6 Constraint is used for column Trigger is used for table 7 Constraints are predefined business Trigger is a user defined business rule for which user
  • 27. rules in which all the organizations follow this constraints without any modification. is responsible for logic for business rule 8 Constraints are used to maintain the integrity and atomicity of database .In other words it can be said they are used to prevent invalid data entry . the main 5 constraints are NOT NULL,PRIMARY KEY,FOREIGN KEY,UNIQUE KEY and CHECK Triggers are basically stored procedures which automatically fired when any insert,update or delete is issued on table 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 Formatting Purposes. Convert can be used for Formatting Purposes.For example Select convert (varchar, datetime, 101) 3 Cast cannot convert a datetime to specific format Convert can be used to convert a datetime to specific format 4 Usage of CAST: USE Sample GO SELECT SUBSTRING(Name, 1, 30) AS ProductName, Usage of CONVERT: USE Sample GO SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice
  • 28. ListPrice FROM Production.Product WHERE CAST(ListPrice AS int) LIKE '3%'; GO FROM Production.Product WHERE CAST(int, ListPrice) LIKE '3%'; GO 3.Difference between CUBE and ROLLUP S.No CUBE ROLLUP 1 It is an additional switch to GROUP BY clause. It can be applied to all aggregation functions to return cross tabular result sets. It is an extension to GROUP BY clause. It’s used to extract statistical and summarized information from result sets. It creates groupings and then applies aggregation functions on them. 2 Produces all possible combinations of subtotals specified in GROUP BY clause and a Grand Total. Produces only some possible subtotal combinations Difference between SQL Server 2008 and SQL Server 2012 S.No SQL Server 2008 SQL Server 2012 1 Maximum number of concurrent connections: The Maximum number of concurrent connections to SQL Server 2008 is 32767. Maximum number of concurrent connections: SQL server 2012 has unlimited concurrent connections. 2 Precision used for spatial calculations: The SQL Server 2008 uses 27 bit bit precision for spatial calculations. Precision used for spatial calculations: The SQL Server 2012 uses 48 bit precision for spatial calculations 3 TRY_CONVERT() and FORMAT() TRY_CONVERT() and FORMAT()
  • 29. functions: TRY_CONVERT() and FORMAT() functions are not available in SQL Server 2008 functions: TRY_CONVERT() and FORMAT() functions are newly included in SQL Server 2012 4 ORDER BY Clause with OFFSET / FETCH options: ORDER BY Clause does not have OFFSET / FETCH options as in SQL Server 2012 ORDER BY Clause with OFFSET / FETCH options: ORDER BY Clause now have OFFSET / FETCH options to use paging to 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: SQL Server 2008 is code named as Katmai. Code Name: SQL Server 2012 is code named as Denali In SQL Server 2008, audit is an Enterprise-only feature. Only available in Enterprise, Evaluation, and Developer Edition. In SQL Server 2012,support for server auditing is expanded to include all editions of SQL Server. 7 Sequence Object: Sequence is not available in SQL Server 2008 Sequence Object: Sequence is included in SQL Server 2012.Sequence is a user defined object that generates a
  • 30. 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, FullName nvarchar(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 Capability: The Full Text Search in SQL Server 2008 does not allow us to search and index data stored in extended properties or metadata. Full Text Search Capability: The Full Text Search in SQL Server 2012 has been enhanced by allowing us to search and index data stored in extended properties or metadata. Consider a PDF
  • 31. 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: Analysis Services in SQL Server does not have BI Semantic Model (BISM) concept. BISM Model: Analysis Services will include a new BI Semantic Model (BISM). BISM is a 3-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 codenamed as Kilimanjaro SQL Server 2012 is codenamed as Denali 2 In SQL Server 2008 R2 , In SQL Server 2012, server
  • 32. rebooting is requisite for OS patching , hence server down time is high down time is reduced by 50% , hence OS patching is not rebooting n times. 3 SQL Server 2008 R2 does not have this feature of availability groups, hence fast recovery is not possible. In SQL Server 2012, high availability and disaster recovery factor has been introduced which duplicates the data and rapidly recovers the loss. 4 SQL Server 2008 R2 is slow compared to SQL Server 2012. In SQL Server 2012, the performance is 10 times faster than the predecessor. 5 However buffer rate is less because there is no data redundancy in SQL Server 2008 R2 Buffer rate is high in SQL Server 2012 because of data compression. 6 Data visualization is not supported in SQL Server 2008 R2 Data visualization tool is available in SQL Server 2012.This allows snapshots of data. 7 Spatial features are not supported more in SQL Server 2008 R2. Instead a traditional way for geographical elements have been set in SQL Server 2008 R2. Support for persistent computed columns and extra geographical approach is possible with spatial features in SQL Server 2012. Difference between SET and SELECT in SQL Server S.No SET SELECT 1 Is it ANSI Standard ? SET is ANSI Standard for value assignment to variables. Is it ANSI Standard ? SELECT is Non-ANSI Standard for value assignment to variables. 2 Variable Assignment: Variable Assignment:
  • 33. SET can be used to assign value to one variable at a time. DECLARE @i INT, @j INT, @k INT SET @i = 10,@j = 20,@k = 30 It gives error: Msg 102, Level 15, State 1, Line 5 Incorrect syntax near ‘,’. SELECT can be used to assign values to multiple variables in a single SELECT statement. The below query using SELECT is valid: 1 2 3 4 5 DECLARE @i INT, @j INT, @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 when query returns more then one value: When assigning from a query that returns more than one value, SET will fail with an error. The below query using set will fail: 1 2 3 DECLARE @i INT SET @i = (SELECT n FROM (VALUES Behaviour of SELECT when query returns more then one value: When assigning from a query that returns more than one value, SELECT will assign the last value returned by the query and hide the fact that the query returned more than one row. The below query using select will execute successfully: 1
  • 34. (10),(20),(30)) AS List(n)) Error: Msg 512, Level 16, State 1, Line 5 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 2 3 4 5 DECLARE @i INT SELECT @i = n FROM (VALUES (10),(20),(30)) AS List(n) SELECT @i Output: 30 (1 row(s) affected) 4 Behaviour of SET when query does not return any rows: If the variable is initially assigned a value following is the behavior of variable assignment for SET, Assigns null if the query does not return any rows. The output of the below statement will be NULL 1 2 3 4 5 6 7 DECLARE @i INT SET @i = 1 SET @i = (SELECT n FROM (VALUES (10),(20),(30)) AS List(n) WHERE 1=2) SELECT @i Behaviour of SELECT when query does not return any rows: If the variable is initially assigned a value following is the behavior of variable assignment for SELECT, Retains the initially assigned value and does not assign null if the query does not return any rows. The output of the below statement will be 1 1 2 3 4 5 6 7 DECLARE @i INT SET @i = 1 SELECT @i = n FROM (VALUES (10),(20),(30)) AS List(n) WHERE 1=2 SELECT @i Output:
  • 35. Output: NULL (1 row(s) affected) 1 (1 row(s) affected) 5 Performance: Set does not provide better performance over select when used for assigning values to multiple variables at the same time. Assigning values to multiple variables using SET: 1 2 3 4 5 6 7 DECLARE @i INT, @j INT, @k INT SET @i = 10 SET @j = 20 SET @k = 30 Performance: Select has better performance over set when used for assigning values to multiple variables at the same time. Assigning values to multiple variables using Select: 1 2 3 4 5 DECLARE @i INT, @j INT, @k INT SELECT @i = 10,@j = 20,@k = 30 6 When to use ? Following are few scenarios for using SET 1. If we are required to assign a single value directly to variable and no query is involved to fetch value. 2. NULL assignments are expected (NULL returned in result set) 3. Standards are meant to be follow for any planned migration When to use ? Using SELECT is efficient and flexible in the following few cases. 1. Multiple variables are being populated by assigning values directly 2. Multiple variables are being populated by single source (table , view) 3. Less coding for assigning multiple variables 4. Use this if we need to get @@ROWCOUNT and
  • 36. 4. Non scalar results are expected and are required to be handled @ERROR for last statement executed 1.Difference between VARCHAR and NVARCHAR in SQL Server S.N o Varchar[(n)] NVarchar[(n)] 1 Basic Definition: Non-Unicode Variable Length character data type. Example: DECLARE @FirstName AS VARCHAR(50) = ‘UMAR’ SELECT @FirstName Basic Definition: UNicode Variable Length character data type. It can store both non- Unicode and Unicode (i.e. Japanese, Korean etc) characters. Example: DECLARE @FirstName AS NVARCHAR(50)= ‘UMAR’ SELECT @FirstName 2 No. of Bytes required for each character: It takes 1 byte per character Example: DECLARE @FirstName AS VARCHAR(50) = ‘UMAR’ SELECT @FirstName AS FirstName,DATALENGTH(@FirstN ame) AS Length Result: FirstName Length UMAR 4 No. of Bytes required for each character: It takes 2 bytes per Unicode/Non- Unicode character. Example: DECLARE @FirstName AS NVARCHAR(50)= ‘UMAR’ SELECT @FirstName AS FirstName,DATALENGTH(@FirstN ame) AS Length Result: FirstName Length UMAR 8 3 Optional Parameter n range: Optional Parameter n value can be from 1 to 8000.Can store maximum 8000 Non-Unicode characters. Optional Parameter n range: Optional Parameter n value can be from 1 to 4000.Can store maximum 4000 Unicode/Non-Unicode characters
  • 37. 4 If Optional Parameter n is not specified in the variable declaration or column definition: If Optional parameter value is not specified in the variable declaration or column definition then it is considered as 1. Example: DECLARE @firstName VARCHAR =‘UMAR’ SELECT @firstName FirstName,DATALENGTH(@firstNa me) Length Result: FirstName Length U 1 If Optional Parameter n is not specified in the variable declaration or column definition: If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 2 Example: DECLARE @firstName NVARCHAR =‘UMAR’ SELECT @firstName FirstName,DATALENGTH(@firstNa me) Length Result: FirstName Length U 2 5 If Optional Parameter n is not specified in while using CAST/CONVERT functions: If Optional Parameter n is not specified in while using CAST/CONVERT functions: When this optional parameter n is not specified while using the CAST/CONVERT functions, then it is considered as 30. Example: DECLARE @firstName VARCHAR(35) =‘UMAR ASIA INDIA TAMIL NADU CUDDALORE’ SELECT CAST(@firstName AS VARCHAR) FirstName,DATALENGTH(CAST(@ firstName AS VARCHAR)) Length Result: FirstName Length UMAR ASIA INDIA TAMIL NADU CUD 30 When this optional parameter n is not specified while using the CAST CONVERT functions, then it is considered as 30. Example: DECLARE @firstName NVARCHAR(35) =‘UMAR ASIA INDIA TAMIL NADU CUDDALORE’ SELECT CAST(@firstName AS NVARCHAR) FirstName,DATALENGTH(CAST(@ firstName AS NVARCHAR)) Length Result: FirstName Length UMAR ASIA INDIA TAMIL NADU CUD 60
  • 38. 7 Which one to use? If we know that data to be stored in the column or variable doesn’t have any Unicode characters. Which one to use? If we know that data to be stored in the column or variable can have Unicode characters. 8 Storage Size: Takes no. of bytes equal to the no. of Characters entered plus two bytes extra for defining offset. Storage Size: Takes no. of bytes equal to twice the no. of Characters entered plus two bytes extra for defining offset. 2.Difference between SQL Server and MySQL S.No SQL Server MySQL 1 Current Date and Time: SELECT GETDATE() Current Date and Time: SELECT NOW() Optionally: Use CURDATE() for the date only. 2 Limiting Results: SELECT TOP 10 * FROM table WHERE id = 1 Limiting Results: SELECT * FROM table WHERE id = 1 LIMIT 10 3 Date Field Default Value: DATETIME DEFAULT GETDATE() Date Field Default Value: DATETIME fields cannot have a default value, i.e. "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:
  • 39. LEN() CHARACTER_LENGTH() Aliases: CHAR_LENGTH(), LENGTH() 5 Character Replace: REPLACE() works case insensitively Character Replace: REPLACE() works case sensitively 6 Trim Functions: LTRIM() and RTRIM() Trim Functions: TRIM() 7 String Concatenation: CONCATENATION USING + (Does not automatically cast operands to compatible types) String Concatenation: CONCAT(string, string), which accepts two or more arguments. (Automatically casts values into types which can be concatenated) 8 Auto Increment Field Definition: tablename_id INT IDENTITY PRIMARY KEY Auto Increment Field Definition: tablename_id INTEGER AUTO_INCREMENT PRIMARY KEY 9 Get a List of Tables: SP_TABLES Get a List of Tables: SHOW TABLES 10 Get Table Properties: HELP tablename Get Table Properties: DESCRIBE tablename 11 Get Database Version: SELECT @@VERSION Get Database Version: SELECT VERSION() 12 Recordset Paging: Recordset paging done by client side- Recordset Paging: Add to end of SQL: "LIMIT " & ((intCurrentPage-
  • 40. ADO (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 Inserted Record: SET NOCOUNT ON; INSERT INTO...; SELECT id=@@IDENTITY; SET NOCOUNT OFF; Get ID of Newest Inserted Record: Two step process: 1. Execute your statement: objConn.Execute("INSERT INTO...") 2. Set objRS = objConn.Execute("SELECT LAST_INSERT_ID() AS ID") 14 Get a Random Record: SELECT TOP 1 * FROM Users ORDER BY NEWID() Get a Random Record: SELECT * FROM Users ORDER BY RAND() LIMIT 1 15 Generate a Unique GUID: SELECT NEWID() Generate a Unique GUID: SELECT UUID() 16 Licensing: SQL Server is not an open source and payment has to be made to use SQL Server. Licensing: MySQL is available for free since MySQL is an open source. 17 View Support: SQL Server offers indexed views which are much more powerful, performance wise. View Support: MySQL offers only updateable views.
  • 41. 18 XML Support: SQL Server supports XML. XML Support: MySQL does not support XML. 19 Security: SQL Server provides column level security. Security: MySQL provides only table level security. 20 Certiication for Security: SQL Server has C2 compliant certification. Database security is verified by third party. Certiication for Security: MySQL does not offer any certification for security. 21 Support for Triggers: SQL Server provides triggers. Support for Triggers: Earlier versionsof MySQL does not support triggers. Only MySQL 5.0 supports triggers. 22 Support for UDF: User defined functions are supported in SQL Server. Support for UDF: User defined functions are not supported in MySQL. 23 Support for Cursors: Cursor feature is available in SQL Server. Support for Cursors: Cursor feature is not available in MySQL. 24 Support for SPs and Joins: Stored procedures and full join facility is not offered in MySQL. Support for SPs and Joins: Stored procedures and full join facility are offered in SQL Server. 25 Support for Import/Export Functions: Import and export are extensively supported in MySQL. Support for Import/Export Functions: Import and Export functions have very limited support in MySQL. 26 Support for Transaction: Transaction support is Support for Transaction: Transaction support is very much limited in MySQL.
  • 42. extensively and fully offered in SQL Server. 27 Support for Replication: Replication support is extensively and fully offered in SQL Server. Support for Replication: Replication support is very much limited in MySQL. 28 Support for auto tuning: Auto tuning is supported in SQL Server. Support for auto tuning: Auto tuning is not supported in MySQL. 29 Support for job scheduling and profiling: Job scheduling and profiling are available in SQL Server. Support for job scheduling and profiling: Job scheduling and profiling are not available in MySQL. 30 Support for online backup and clustering: Online backup support and clustering support is extensive and complete in SQL Server. Support for online backup and clustering: Online backup support and clustering support is limited in MySQL. 31 Support for Log shipping and SAN: Log Shipping and Storage Area Network support is available in SQL Server. Support for Log shipping and SAN: Log Shipping and Storage Area Network support is not available in MySQL. 32 Support for OLAP Services, Data Reporting and Data Mining: OLAP Services, Data Reporting and Data Mining are supported in SQL Server. Support for OLAP Services, Data Reporting and Data Mining: OLAP Services, Data Reporting and Data Mining are not supported in MySQL.
  • 43. 3.Difference between SET QUOTED_IDENTIFIER ON and SET QUOTED_IDENTIFIER OFF in SQL Server S.No SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER OFF 1 Characters Enclosed within double quotes: is treated as Identifier Characters Enclosed within double quotes: is treated as Literal 2 Try using Characters Enclosed within double quotes as identifier: Works Example: Below statement to create a table with table name “Table” succeeds. SET QUOTED_IDENTIFIER ON GO CREATE TABLE dbo.”Table” (id int,”Function” VARCHAR(20)) GO Try using Characters Enclosed within double quotes as identifier: Fails Example: Below statement to create a table with table name “Table” Fails. SET QUOTED_IDENTIFIER OFF GO CREATE TABLE dbo.”Table” (id int,”Function” VARCHAR(20)) GO Error Message: Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ‘Table’. 3 Try using Characters Enclosed within double quotes as Literal: Fails Example: Below statement fails. SET QUOTED_IDENTIFIER ON GO Try using Characters Enclosed within double quotes as Literal: Works Example: Below Statement Works. SET QUOTED_IDENTIFIER OFF GO
  • 44. SELECT “BIRADAR” Error Message: Msg 207, Level 16, State 1, Line 1 Invalid column name ‘UMAR’. SELECT “UMAR” 4 Characters Enclosed within single quotes: is treated as Literal Example: SET QUOTED_IDENTIFIER ON GO SELECT ‘UMAR’ Characters Enclosed within single quotes: is treated as Literal Example: SET QUOTED_IDENTIFIER ON GO SELECT ‘UMAR’ 5 How to find all the objects which are created with SET QUTOED_IDENTIFIER ON/OFF: Below Statement can be used to find all the objects created with SET QUTOED_IDENTIFIER setting as ON: SELECT OBJECT_NAME (object_id) FROM sys.sql_modules WHERE uses_quoted_identifier = 1 How to find all the objects which are created with SET QUTOED_IDENTIFIER ON/OFF: Below Statement can be used to find all the objects created with SET QUTOED_IDENTIFIER setting as OFF: SELECT OBJECT_NAME (object_id) FROM sys.sql_modules WHERE uses_quoted_identifier = 0 4.Difference between DateTime and DateTime2 DataType S.No DateTime DateTime2[(n)] 1 Min Value: 1753-01-01 00:00:00 Min Value: 0001-01-01 00:00:00
  • 45. 2 Max Value: 9999-12-31 23:59:59.997 Max Value: 9999-12-31 23:59:59.9999999 3 Storage Size: 8 Bytes Storage Size: 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: Declare @now datetime Usage: Declare @now datetime2(7) 5 Current Date and Time function: GetDate() – It returns DB Current Date and Time of DateTime Data Type Example: SELECT GETDATE() Result: 2011-09-16 13:23:18.767 Current Date and Time function: SYSDATETIME()- It returns DB Current Date and Time of DateTime2 Data Type Example: SELECT SYSDATETIME() Result: 2011-09-16 13:23:18.7676720 6 +/- days: +/- days:
  • 46. WORKS Example: DECLARE @nowDateTime DATETIME = GETDATE() SELECT @nowDateTime + 1 Result: 2011-09-17 13:44:31.247 FAILS – Need to use only DateAdd function Example: DECLARE @nowDateTime2 DATETIME2= SYSDATETIME() SELECT @nowDateTime2+1 Result: Msg 206, Level 16, State 2, Line 2 Operand type clash: datetime2 is incompatible with int 7 Compliance: Is not an ANSI/ISO compliant Compliance: Is an ANSI/ISO compliant 1.Difference between Correlated subquery and Nested subquery S.No Correlated subquery Nested subquery 1 Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query. Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row. 2 Correlated subquery follows down to top approach i.e., main query is executed first(even though parenthesis are present) and then child query. We can also say: in a Correlated subquery,Inner query condition is used in the outer query Nested subquery follows top-down approach i.e., child query is executed first and then parent . We can also say:In a subquery Outer query condition is used in the the inner query.
  • 47. 4 Example: select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno) Example: select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno) 2.Difference between Weak Entity Set and Strong Entity Set S.No Weak Entity Set Strong Entity Set 1 An entity set which does not possess sufficient attributes to form a primary key is known as a weak entity set. An entity set which does have a primary key is called a strong entity set. 2 Member of a weak entity set is a subordinate entity. Member of a strong entity set is a dominant entity. 3 Example: Specific Person,Company,Event,Plant Example: Set of all Persons,Companies,Trees,Holidays 3.Difference between char and varchar data types in Sql Server S.No Char Varchar 1 Fixed length memory storage Variable length memory storage(Changeable) 2 CHAR takes up 1 byte per character VARCHAR takes up 1 byte per character, + 2 bytes to hold length information 3 Use Char when the data entries in a column are expected to be the same size like phone number Use Varchar when the data entries in a column are expected to vary considerably in size like address 4 Ex: Ex:
  • 48. Declare test Char(100); test="Test" - Then "test" occupies 100 bytes first four bytes with values and rest with blank data Declare test VarChar(100); test="Test" - Then "test" occupies only 4+2=6 bytes. first four bytes for value and other two bytes for variable length information. 4.Difference between Sql Server 2005 and Sql Server 2008 S.No Sql Server 2005 Sql Server 2008 1 XML datatype is introduced. XML datatype is used. 2 Cannot encrypt the entire database. Can encrypt the entire database introduced in 2008. 3 Datetime is used for both date and time. Date and time are seperately used for date and time 4 No table datatype is included. Table datatype introduced. 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 in the specified table Returns the number of rows 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
  • 49. associated with columns in a Table. So these cannot be re-used. database and can be applied to any number of 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 scanning is done to get the data. In case, there are huge number of data in a table, it becomes an overhead. Here in the first, index is created in the table. It then uses the index to get to the data that we wanted. It increases the performance. Difference between SQL and T-SQL in SQL Server S.No SQL T-SQL 1 SQL stands for Structured Query Language T-SQL stands for Transact SQL 2 ANSI/ISO(American National Standards Institute) standard database query language This is implementing in SQL SERVER. T-SQL can have one or more queries. 3 Set of queries submitted individually to the server. It is a batch program, and 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
  • 50. SQL in Microsoft SQL Server. Difference between Database and Schema S.No Database Schema 1 Database is a collection of organized data Database schema describes the structure and organization of data in a database system 2 The database holds the records, fields and cells of data Schema contains Databases and describes 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.No OLTP OLAP 1 Abbreviation: OLTP stands for Online transactional processing . Abbreviation: OLAP stands for Online analytical processing . 2 Meaning: OLTP is designed to efficiently process high volumes of transactions, instantly recording business events (such as a sales invoice payment) and reflecting changes as they occur. Meaning: OLAP is designed for analysis and decision support, allowing exploration of often hidden relationships in large amounts of data by providing unlimited views of multiple relationships at any cross-section of defined business dimensions. 3 Used in: Used in:
  • 51. ERP, TX system, Client Server Architecture, Desktop application Data warehouse application - MOLAP, ROLAP, HOLAP 4 Data Provision: Current data Data Provision: Current and historical data 5 Type of Database Transactions: Short database transactions Type of Database Transactions: Long database transactions 6 Type of update/insert/delete: Online update/insert/delete Type of update/insert/delete: Batch update/insert/delete 7 Normalization/Denomalization: Normalization is promoted (1st normal form, second normal form and third normal form). Normalization/Denomalization: Denormalization is promoted (Dimension and Fact design). 8 Volume of Transactions: High volume of transactions Volume of Transactions: Low volume of transactions 9 Transaction Recovery Needed: Transaction recovery is necessary Transaction Recovery Needed: Transaction recovery is not necessary 10 Amount of Index Requirement: Less Index Amount of Index Requirement: More Index 11 Amount of Join Requirement: More Joins Amount of Join Requirement: Less Joins 12 Model: Adopts an entity relationship(ER) model Model: Adopts star, snowflake or fact constellation model and a subject-oriented database design
  • 52. 13 Orientation: Customer-oriented, used for data analysis and querying by clerks, clients and IT professionals Orientation: Market-oriented, used for data analysis by knowledge workers( managers, executives, analysis) 14 Source: Daily transactions. Source: OLTP 15 Motive: Faster insert, updates, deletes and improve data quality by reducing redundancy. Motive: Faster analysis and search by combining tables. 16 SQL complexity: Simple and Medium. SQL complexity: Highly complex due to analysis and forecasting. 2.Difference between DTS and SSIS S.No DTS SSIS 1 DTS stands for Data Transformation Services SSIS stands for Sql Server Integration Services 2 DTS is a set of objects using an ETS tool to extract, transform, and load information to or from a database SSIS is an ETL tool provided by Microsoft to extra data from different sources. 3 DTS was originally part of the Microsoft SQL Server 2000 SSIS is a component of the Microsoft SQL Server 2005 4 Uses Activex Script Uses Scripting Language 5 No Deployment wizard is available Deployment wizard is available 6 Limited Set of Transformation available Huge of Transformations available
  • 53. 7 Does not support BI Functionality Completely supports end to 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 through Enterprise manager SSIS can develop through Business Intelligence Development Studio (BIDS, nothing but new version of VS IDE) 11 We can deploy only at local server It can be deployed using multiple server using BIDS 12 Designer contains Single Pane SSIS designer contains 4 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 values are static, not controlled at runtime. It can be controlled dynamically using configuration Difference between rdl and rdlc S.No rdl rdlc 1 It stands for Report Definition Language It stands for Report Definition Language, Client Side 2 Created by Sql server with reporting services Created by Visual studio 3 Runs on server side Runs on client side
  • 54. 4 Requires values for all elements such as query text Does not require to have values for all elements such as query text 5 Takes less time to produce large data in reports Takes more time to produce large data in reports 6 As runs in server license of the reporting services not needed As runs in local license of the reporting services not needed Difference between Control Flow and Data Flow in SSIS S.No Control Flow Data Flow 1 The smallest unit in Control Flow is called task. The smallest unit in Data Flow is called component. 2 In Control Flow , tasks require completion (success, failure or completion) before moving to next task. In Data Flow , one component will not wait for other component to finish, all of them will work together in processing and managing data in streaming way. Difference Between Star Schema and Snowflake Schema S.N o Star Schema Snowflake Schema 1 Data Structure: De-Normalized Data Structure Data Structure: Normalized Data Structure 2 Dimension: Category wise Single Dimension Table Dimension: Dimension table split into many pieces 3 Data dependency & redundancy: More data dependency and Data dependency & redundancy: Less data dependency and No
  • 55. redundancy redundancy 4 Join: No need to use complicated join Join: Complicated Join 5 Query Result: Query Results Faster Query Result: Some delay in Query Processing 6 Parent Table: No Parent Table Parent Table: It may contain Parent Table 7 DB Structure: Simple DB Structure DB Structure: Complicated DB Structure 8 Sample: http://blog- mstechnology.blogspot.in/2010/06/ bi-dimensional-model-star- schema.html Sample: http://blog- mstechnology.blogspot.in/2010/06/ bi-dimensional-model-snowflake- schema.html Differences between Merge and Union All transformations in SSIS S.No Merge Union All 1 Number of inputs allowed: Merge transformation can accept only two inputs. Number of inputs allowed: Union all can take more than two inputs. 2 Data to be sorted or not before Merge transformation: Data has to be sorted before Merge Transformation. Data to be sorted or not before Union All transformation: Union all does not have any condition like Merge. Difference between MOLAP, ROLAP and HOLAP in SSAS MOLAP ROLAP HOLAP MOLAP stands for Multidimensional Online Analytical Processing ROLAP stands for Relational Online Analytical Processing HOLAP stands for Hybrid Online Analytical Processing
  • 56. The MOLAP storage mode causes the aggregations of the partition and a copy of its source data to be stored in a multidimensional structure in Analysis Services when the partition is processed. The ROLAP storage mode causes the aggregations of the partition to be stored in indexed views in the relational database that was specified in the partition’s data source. The HOLAP storage mode combines attributes of both MOLAP and ROLAP. Like MOLAP, HOLAP causes the aggregations of the partition to be stored in a multidimensional structure in an SQL Server Analysis Services instance. This MOLAP structure is highly optimized to maximize query performance. The storage location can be on the computer where the partition is defined or on another computer running Analysis Services. Because a copy of the source data resides in the multidimensional structure, queries can be resolved without accessing the partition’s source data. Unlike the MOLAP storage mode, ROLAP does not cause a copy of the source data to be stored in the Analysis Services data folders. Instead, when results cannot be derived from the query cache, the indexed views in the data source are accessed to answer queries. HOLAP does not cause a copy of the source data to be stored. For queries that access only summary data in the aggregations of a partition, HOLAP is the equivalent of MOLAP. Query response times can be decreased substantially by using aggregations. The data in the partition’s MOLAP structure is only as current as the most recent processing of the partition. Query response is generally slower with ROLAP storage than with the MOLAP or HOLAP storage modes. Processing time is also typically slower with ROLAP. However, ROLAP enables users to view data in real time and can save storage space when you are working with large datasets that are infrequently queried, such as purely historical data. Queries that access source data—for example, if you want to drill down to an atomic cube cell for which there is no aggregation data—must retrieve data from the relational database and will not be as fast as they would be if the source data were stored in the MOLAP structure. With HOLAP storage mode, users will typically experience substantial differences in query times depending upon whether the query can be resolved from cache or aggregations versus from the source data itself.
  • 57. Pros  Provides maximum query performance, because all the required data (a copy of the detail data and calculated aggregate data) are stored in the OLAP server itself and there is no need to refer to the underlying relational database.  All the calculations are pre-generated when the cube is processed and stored locally on the OLAP server hence even the complex calculations, as a part the query result, will be performed quickly.  MOLAP uses compression to store the data on the OLAP server and so has less storage requirements than relational databases for same amount of data.  MOLAP does not need to have a permanent connection to the underlying 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. Pros  Ability to view the data in near real-time.  Since ROLAP does not make another copy of data as in case of MOLAP, it has less storage requirements. This is very advantageous for large datasets which are queried infrequently such as historical data.  In ROLAP mode, the detail data is stored on the underlying relational database, so there is no limitation on data size that ROLAP can support or limited by the data size of relational database. In nutshell, it can even handle huge volumes of data. Pros  HOLAP balances the disk space requirement, as it only stores the aggregate data on the OLAP server and the detail data remains in the relational database. So no duplicate copy of the detail data is maintained.  Since HOLAP does not store detail data on the OLAP server, the cube and partitions would be smaller in size than MOLAP cubes and partitions.  Performance is better than ROLAP as in HOLAP the summary data are stored on the OLAP server and queries can be satisfied from this summary data.  HOLAP would be optimal in the scenario where query response is required and query results are based on aggregations on large volumes of data. Cons  With MOLAP mode, you need frequent processing to pull refreshed data after last processing resulting in drain on system resources. Cons  Compared to MOLAP or HOLAP the query response is generally slower because everything is stored on relational database and not Cons  Query performance (response time) degrades if it has to drill through the detail data fromrelational data store, in this case HOLAP performs very much like ROLAP.
  • 58.  Latency; just after the processing if there is any changes in the relational database it will not be reflected on the OLAP server unless re-processing 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. locally on the OLAP server.  A permanent connection to the underlying database must be maintained to view the cube data. Difference between Full Load and Incremental Load S.No Full Load Incremental Load 1 Truncates all rows and loads from scratch. New records and updated ones are loaded. 2 Requires more time. Requires less time. 3 Can easily be guaranteed. Difficult. ETL must check for 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.
  • 59. 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.