sql differences sql interview questions

83
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?

Upload: mlr-institute-of-technology

Post on 15-Apr-2017

160 views

Category:

Education


24 download

TRANSCRIPT

Page 1: SQL Differences  SQL Interview Questions

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

Page 2: SQL Differences  SQL Interview Questions

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.

Page 3: SQL Differences  SQL Interview Questions

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 :SELECT ColFROM @Table1

Output is not in sorted order

Example :SELECT ColFROM @Table1

Page 4: SQL Differences  SQL Interview Questions

UNIONSELECT ColFROM @Table2

Result:1235

UNION ALLSELECT ColFROM @Table2

Result:12325

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 KeyS.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

A table can have several AFTER triggers for each triggering action.

Page 5: SQL Differences  SQL Interview Questions

triggering action (UPDATE, DELETE, and INSERT)

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

Page 6: SQL Differences  SQL Interview Questions

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 2012S.No Identity Sequence

1 Dependant on table. Independent from table.

2 Identity is a property in a table.

Example :

CREATE TABLE Tabletest_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 toinsert and then get new ID.

Example :

Insert into [test_Identity] Values (‘SQL Server’)

GO

SELECT @@IDENTITY

In the sequence, we do not need to insert new ID, we can view the new ID directly.

Example :

SELECT NEXT VALUEFOR dbo.[Sequence_ID]

Page 7: SQL Differences  SQL Interview Questions

AS ‘Identity’

–OR

Select SCOPE_IDENTITY() AS ‘Identity’

4 We cannot perform a cycle in identity column. Meaning, we cannot restart the counter after aparticular 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 ofsequence. 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)

Page 8: SQL Differences  SQL Interview Questions

)

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 isbased 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.

Example :

DBCC CHECKIDENT (test_Identity, RESEED,

We can reseed as well as change the step size.

Example :

ALTER SEQUENCE [dbo].[Sequence_ID]

Page 9: SQL Differences  SQL Interview Questions

4) RESTART WITH 7

INCREMENT BY 2;

9 We cannot generate range from identity.

We can generate a range of sequencevalues from a sequence object with the help of sp_sequence_get_range.

2.Difference between Temp table and Table variableS.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 for the current session or global. So that a multiple user session can utilize the results in the table.

But the table variable can be used up to that program. (Stored procedure)

Page 10: SQL Differences  SQL Interview Questions

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 specifies the severity of the exception.

There is no severity parameter. The exception severity is always set to 16.

.Difference between Database Mail and SQL Mail

Page 11: SQL Differences  SQL Interview Questions

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

Page 12: SQL Differences  SQL Interview Questions

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

Page 13: SQL Differences  SQL Interview Questions

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

Page 14: SQL Differences  SQL Interview Questions

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 Domains

Page 15: SQL Differences  SQL Interview Questions

Types

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 structured Query Language (SQL) as the language to interface with its prototype relational database

Oracle History:

Oracle Corp is the leading supplier for S/w products, headquartered in Redwood shores, California, USA. It was founded by Larry Ellison, Bob Miner and Ed

Page 16: SQL Differences  SQL Interview Questions

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.

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 maintained by SQL language, which is conceded as the heart of the RDBMS.

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 appearance and location of inter face elements.

3 SQL Technology: Oracle Technology:

Page 17: SQL Differences  SQL Interview Questions

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 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). SQL is not case sensitive. It can enter one or more lines. Tabs and indents can be used to make code more readable.

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 Dispose of heavy files and register work The work of three persons is reduced to one Instant intimation of modification of information

Page 18: SQL Differences  SQL Interview Questions

Can be used by a range of users. It is a nonprocedural language (English-like language).

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 query.

Cannot be used as a building block in large 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.

Page 19: SQL Differences  SQL Interview Questions

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.tableaWHERE id IN (SELECT idFROM dbo.tableb)

Example:

SELECT id,[Name]FROM dbo.tablea AS aWHERE EXISTS (SELECT id2FROM dbo.tablebWHERE id2 = a.id)

1.Difference between Checkpoint and Lazy Writer

S.No CheckPoint Lazy Writer

1 Flush dirty pages to Disk Flush dirty pages to disk

2 Flush only Data pages to Check for available memory

Page 20: SQL Differences  SQL Interview Questions

disk 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

Page 21: SQL Differences  SQL Interview Questions

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 2005 SP1 or higher – Enterprise or Developer Editions

Enterprise edition for Sql Server 2000 and even Standard edition for 2005 can works

11 Immediate data moved depending on SEND and

Can control the flow of data by scheduling jobs

Page 22: SQL Differences  SQL Interview Questions

WAIT queue

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.

Page 23: SQL Differences  SQL Interview Questions

2 Storage: Internal tables are placed on the same filegroup as the parent entity. You could use thesys.internal_tables catalog view to show all the internal tables and parent entities. For example: select name, object_name(parent_id) as parent_object from sys.internal_tables

Storage: When change data capture is enabled for a database, a few things are added to the database, 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_cdc_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.

Page 24: SQL Differences  SQL Interview Questions

4 It uses synchronous tracking 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 heavily

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

Page 25: SQL Differences  SQL Interview Questions

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 scratch.

Index Reorganize physically reorganizes the leaf nodes of the index.

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.

T-SQL for Reorganize all Indexes of a particular table.

Page 26: SQL Differences  SQL Interview Questions

USE AdventureWorks; GO ALTER INDEX ALL ON HumanResources.Employee REBUILD GO

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.ewe 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).

Page 27: SQL Differences  SQL Interview Questions

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 memorylocation 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 rules in which all theorganizations follow this constraints without anymodification.

Trigger is a user defined business rule for which user 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 areNOT NULL,PRIMARY

Triggers are basically stored procedures which automatically fired when any insert,update or delete is issued on table

Page 28: SQL Differences  SQL Interview Questions

KEY,FOREIGN KEY,UNIQUE KEY and CHECK

2.Difference between Cast and Convert in SQL Server

S.No Cast Convert

1 Cast is ANSII Standard Convert is Specific to SQL SERVER

2 Cast cannot be used for 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 SampleGOSELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPriceFROM Production.ProductWHERE CAST(ListPrice AS int) LIKE '3%';GO

Usage of CONVERT:

USE SampleGOSELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPriceFROM Production.ProductWHERE 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

It is an extension to GROUP BY clause. It’s

Page 29: SQL Differences  SQL Interview Questions

can be applied to all aggregation functions to return cross tabular result sets.

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 2012S.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() functions:  TRY_CONVERT() and FORMAT() functions are not available in SQL Server 2008

TRY_CONVERT() and FORMAT() 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 30: SQL Differences  SQL Interview Questions

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, LastNameFROM Person.PersonORDER BY BusinessEntityIDOFFSET 10 ROWSFETCH 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.

Page 31: SQL Differences  SQL Interview Questions

Here is an example using Sequence.

/****** Create Sequence Object ******/CREATE SEQUENCE MySequenceSTART WITH 1INCREMENT 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 FullName1 Umar Ali

Page 32: SQL Differences  SQL Interview Questions

2 John Peter3 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 ModelBusiness LogicData 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

Page 33: SQL Differences  SQL Interview Questions

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 , rebooting is requisite for OS patching , hence server down time is high

In SQL Server 2012, server 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

Support for persistent computed columns and extra geographical approach is possible with

Page 34: SQL Differences  SQL Interview Questions

geographical elements have been set in SQL Server 2008 R2.

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:SET can be used to assign value to one variable at a time.

DECLARE @i INT,@j INT,@k INTSET @i = 10,@j = 20,@k = 30

It gives error:

Msg 102, Level 15, State 1, Line 5Incorrect syntax near ‘,’.

Variable Assignment:SELECT can be used to assign values to multiple variables in a single SELECT statement.

The below query using SELECT is valid:12345DECLARE @i INT,@j INT,@k INTSELECT @i = 10,@j = 20,@k = 30

Output:Command(s) completed successfully.

The below query using SET is not valid:12345

Page 35: SQL Differences  SQL Interview Questions

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:123DECLARE @i INTSET @i = (SELECT n FROM (VALUES (10),(20),(30)) AS List(n))

Error:

Msg 512, Level 16, State 1, Line 5Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

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 returnedmore than one row.

The below query using select will execute successfully:12345DECLARE @i INTSELECT @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

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

Page 36: SQL Differences  SQL Interview Questions

statement will be NULL1234567DECLARE @i INTSET @i = 1SET @i = (SELECT n FROM (VALUES (10),(20),(30)) AS List(n) WHERE 1=2)SELECT @i

Output:

NULL

(1 row(s) affected)

statement will be 11234567DECLARE @i INTSET @i = 1SELECT @i = n FROM (VALUES (10),(20),(30)) AS List(n) WHERE 1=2SELECT @i

Output:

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:1234567DECLARE @i INT,@j INT,@k INTSET @i = 10SET @j = 20SET @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:12345DECLARE @i INT,@j INT,@k INTSELECT @i = 10,@j = 20,@k = 30

Page 37: SQL Differences  SQL Interview Questions

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 migration4. Non scalar results are expected and are required to be handled

When to use ?Using SELECT is efficient and flexible in the following few cases.

1. Multiple variables are being populated by assigning values directly2. Multiple variables are being populated by single source (table , view)3. Less coding for assigning multiple variables4. Use this if we need to get @@ROWCOUNT and @ERROR for last statement executed

1.Difference between VARCHAR and NVARCHAR in SQL ServerS.No

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:

No. of Bytes required for each character:

It takes 2 bytes per Unicode/Non-Unicode character.

Page 38: SQL Differences  SQL Interview Questions

DECLARE @FirstName AS VARCHAR(50) = ‘UMAR’SELECT @FirstName AS FirstName,DATALENGTH(@FirstName) AS Length

Result:FirstName LengthUMAR 4

Example:DECLARE @FirstName AS NVARCHAR(50)= ‘UMAR’SELECT @FirstName AS FirstName,DATALENGTH(@FirstName) AS Length

Result:FirstName LengthUMAR 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(@firstName) Length

Result:FirstName LengthU 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(@firstName) Length

Result:FirstName LengthU 2

5 If Optional Parameter n is notspecified in while using

If Optional Parameter n is notspecified in while using

Page 39: SQL Differences  SQL Interview Questions

CAST/CONVERT functions:

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 LengthUMAR 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 LengthUMAR 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

Page 40: SQL Differences  SQL Interview Questions

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:

LEN()

Character Length:

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

String Concatenation:

CONCAT(string, string),

Page 41: SQL Differences  SQL Interview Questions

USING + (Does not automatically cast operands to compatible types)

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-ADO (very involved)

Recordset Paging:

Add to end of SQL: "LIMIT " & ((intCurrentPage-1)*intRecsPerPage) & ", " & intRecsPerPageLIMIT: 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...;

Get ID of Newest Inserted Record:

Two step process:1. Execute your statement:

Page 42: SQL Differences  SQL Interview Questions

SELECT id=@@IDENTITY; SET NOCOUNT OFF;

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.

Page 43: SQL Differences  SQL Interview Questions

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 extensively and fully offered in SQL Server.

Support for Transaction:Transaction support is very much limited in MySQL.

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.

Page 44: SQL Differences  SQL Interview Questions

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 Try using Characters

Page 45: SQL Differences  SQL Interview Questions

Enclosed within double quotes as identifier:

WorksExample: Below statement to create a table with table name “Table” succeeds.SET QUOTED_IDENTIFIER ON GOCREATE TABLE dbo.”Table”(id int,”Function” VARCHAR(20)) GO

Enclosed within double quotes as identifier:

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

3 Try using Characters Enclosed within double quotes as Literal:

FailsExample: Below statement fails.SET QUOTED_IDENTIFIER ONGOSELECT “BIRADAR”Error Message:Msg 207, Level 16, State 1,Line 1 Invalid column name ‘UMAR’.

Try using Characters Enclosed within double quotes as Literal:

WorksExample: Below Statement Works.SET QUOTED_IDENTIFIER OFFGOSELECT “UMAR”

4 Characters Enclosed within single quotes:

is treated as LiteralExample:SET QUOTED_IDENTIFIER ON

Characters Enclosed within single quotes:

is treated as LiteralExample:SET QUOTED_IDENTIFIER ONGO

Page 46: SQL Differences  SQL Interview Questions

GOSELECT ‘UMAR’

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

Page 47: SQL Differences  SQL Interview Questions

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 bytesFor 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:

WORKSExample: DECLARE @nowDateTime DATETIME = GETDATE()SELECT @nowDateTime + 1Result: 2011-09-17 13:44:31.247

+/- days:

FAILS – Need to use only DateAdd functionExample: DECLARE @nowDateTime2 DATETIME2= SYSDATETIME()SELECT @nowDateTime2+1Result: Msg 206, Level 16, State 2, Line 2Operand type clash: datetime2 is incompatible with int

7 Compliance: Compliance:

Page 48: SQL Differences  SQL Interview Questions

Is not an ANSI/ISO compliant

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 subqueryOuter 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

Page 49: SQL Differences  SQL Interview Questions

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 ServerS.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: Declare test Char(100); test="Test" - Then "test" occupies 100 bytes first four bytes with values and rest with blank data

Ex: 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

Page 50: SQL Differences  SQL Interview Questions

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 ServerS.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 RuleS.No Check Constraint Rule

1 Check constraint is associated with columns in a Table. So these cannot be re-used.

Rules are defined with in a 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_RANGEas

Page 51: SQL Differences  SQL Interview Questions

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

Difference between a table scan and an index scan in SQL Server DatabaseS.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

Page 52: SQL Differences  SQL Interview Questions

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:

ERP, TX system, Client Server Architecture, Desktop application

Used in:

Data warehouse application - MOLAP, ROLAP, HOLAP

4 Data Provision:

Current data

Data Provision:

Current and historical data

Page 53: SQL Differences  SQL Interview Questions

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

Page 54: SQL Differences  SQL Interview Questions

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 Huge of Transformations

Page 55: SQL Differences  SQL Interview Questions

Transformation available 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 Flowb) Data Flowc) 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 rdlcS.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

Page 56: SQL Differences  SQL Interview Questions

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.No

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

Page 57: SQL Differences  SQL Interview Questions

3 Data dependency & redundancy:More data dependency and redundancy

Data dependency & redundancy:Less data dependency and No 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

Page 58: SQL Differences  SQL Interview Questions

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

Page 59: SQL Differences  SQL Interview Questions

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 Cons Cons

Page 60: SQL Differences  SQL Interview Questions

With MOLAP mode, you need frequent processing to pull refreshed data after last processing resulting in drain on system resources. 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.

Compared to MOLAP or HOLAP the query response is generally slower because everything is stored on relational database and not locally on the OLAP server. A permanent connection to the underlying database must be maintained to view the cube data.

Query performance (response time) degrades if it has to drill through the detail data from relational data store, in this case HOLAP performs very much like ROLAP.

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.

Page 61: SQL Differences  SQL Interview Questions

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.