Ilovepdf Merged Merged

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.

com/

SQL Questions Set-01


1. What is SQL?
Ans: It is a computer language aimed to store, manipulate, and
retrieve data stored in relational databases.

2. What is the Difference Between SQL, PL\SQL, T-SQL, and


MYSQL?
Ans: SQL is a Programming Language. The SQL which is applied in an
Oracle database is called PL\SQL. The SQL which is applied in an MS
SQL Server database is called T-SQL(Transaction SQL) and MYSQL is
the RDBMS Database.

3. What is RDBMS?
Ans: RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems like
MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The
data in RDBMS is stored in database objects called tables. A table is a
collection of related data entries and consists of columns and rows.

4. What are structure and Unstructured data?


Ans: Structured data is data that has been predefined and formatted
to a set structure before being placed in data storage, which is often
referred to as schema-on-write. The best example of structured data is
the relational database: the data has been formatted into precisely
defined fields, such as credit card numbers or addresses, in order to be
easily queried with SQL.

Unstructured data is data stored in its native format and not processed
until it is used, which is known as schema-on-read. It comes in a
myriad of file formats, including email, social media posts,
presentations, chats, IoT sensor data, and satellite imagery.

5. What is SQL Server Management studio?


Ans: SQL Server Management Studio (SSMS) is an integrated
environment for managing any SQL infrastructure. Use SSMS to
access, configure, manage, administer, and develop all components of
SQL Server, Azure SQL Database, Azure SQL Managed Instance, SQL
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-01


Server on Azure VM, and Azure Synapse Analytics. SSMS provides a
single comprehensive utility that combines a broad group of graphical
tools with many rich script editors to provide access to SQL Server for
developers and database administrators of all skill levels.

6. What is different between Server and Database?


Ans: The main difference between a Server and a Database is that a
Server provides services to other programs and connected devices,
which are often known as ‘clients’. On the other hand, the Database is
responsible for back-end data processing. It helps to store, organize,
manage, and access data on a computer system.

7. What is the difference between System Database and a


user-defined database?
Ans: System databases are the databases that are installed during
the SQL Server installation. System databases consist of Master,
MSDB, TempDB, and Model. These databases will maintain and provide
more information about the SQL server system like logins, databases,
linked servers, jobs, schedules, reports, report data sources, etc.
User databases are the database where we will create for storing the
data and the user starts to work with the data.

8. How many types of systems define databases in MS SQL


Server?
Ans: There are four types of system-defined databases in MS SQL
Server.
1 Master
2. TempDB
3. Model
4. Msdb
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-01


9. Describe all system databases.

Ans: Master Database:

Model Database:

● It is used as the template for all databases created on the system.


● The model database must always exist on a server system

MSDB Database: It is used by SQL server agents for scheduling alerts and
jobs

Tempdb Database:

•It holds the temporary tables and temporary stored procedures

•It is recreated every time the SQL server started

•Temporary tables and stored procedures dropped automatically.

10. What are tables and fields in the database?


Ans: A table is a set of organized data in the form of rows and
columns. It enables users to store and display records in the structure
format. It is similar to worksheets in the spreadsheet application. Here
rows refer to the tuples, representing the simple data item, and
columns are the attribute of the data items present in a particular row.
Columns can categorize as vertical, and Rows are horizontal.
Fields are the components to provide the structure for the table. It
stores the same category of data in the same data type. A table
contains a fixed number of columns but can have any number of rows
known as the record. It is also called a column in the table of the
database. It represents the attribute or characteristics of the entity in
the record.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-01


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-02

1. How many types of SQL Language? OR What are the subsets of


SQL?
Ans: The following are the five types of SQL Languages:

● Data definition language (DDL): It defines the data structure that


consists of commands like CREATE, ALTER, DROP, etc.

● Data manipulation language (DML): It is used to manipulate


existing data in the database. The commands in this category are
SELECT, UPDATE, INSERT, etc.

● Data control language (DCL): It controls access to the data stored


in the database. The commands in this category include GRANT and
REVOKE.

● Transaction Control Language (TCL): It is used to deal with the


transaction operations in the database. The commands in this category
are COMMIT, ROLLBACK, SET TRANSACTION, SAVEPOINT, etc.

● Data Query Language (DQL): The commands of SQL that are used
to retrieve data from the database are collectively called DQL. So all
Select statements come under DQL

2. What is the purpose of DDL Language?

Ans: DDL stands for Data definition language. It is the subset of a database
that defines the data structure of the database when the database is created. For
example, we can use the DDL commands to add, remove, or modify tables. It
consists of the following commands: CREATE, ALTER and DELETE database
objects such as schema, tables, indexes, view, sequence, etc.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-02

3. What is the purpose of DML Language?

Ans: The commands of SQL that are used to insert data into the database,
modify the data of the database, and delete data from the database are
collectively called DML. Examples include Insert, Update and Delete. This
impacts the Data structure.

4. What is Data Query Language (DQL)?


Ans: The commands of SQL that are used to retrieve data from the
database are collectively called DQL. So all Select statements come
under DQL.

5. What is Data Control Language (DCL)?


Ans: The commands of SQL that are used to control the access to data
stored in the database are collectively called DCL and examples
include Grant and Revoke.

6. What is Transaction Control Language (TCL)?


Ans: The commands of SQL that are used to control the transactions
made against the database are collectively called TCL and examples
include Commit & Rollback.

7. What is the difference between TRUNCATE, DELETE and DROP?


Ans:
TRUNCATE
► TRUNCATE is a DDL command
► TRUNCATE is executed using a table lock and the whole table is locked to
remove all records.
► We cannot use the Where clause with TRUNCATE.
► TRUNCATE removes all rows from a table.
► Minimal logging in the transaction log, so it is performance-wise faster.
► TRUNCATE TABLE removes the data by deallocating the data pages used
to store the table data and
records only the page deallocations in the transaction log.
► Identify column is reset to its seed value if the table contains an identity
column.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-02

► To use Truncate on a table you need at least ALTER permission on the


table.
► Truncate uses less transaction space than Delete statement.
► Truncate cannot be used with indexed views.

DELETE:
► DELETE is a DML command.
► DELETE is executed using a row lock, each row in the table is locked for
deletion.
► We can use the where clause with DELETE to filter & delete specific
records.
► The DELETE command is used to remove rows from a table based on the
WHERE conditions.
► It maintains the log, so it is slower than truncates.
► The DELETE statement removes rows one at a time and records an entry
in the transaction log
for each deleted row.
► Identity of column keep DELETE retains the identity.
► To use Delete you need DELETE permission on the table.
► Delete uses more transaction space than a Truncate statement.
► The delete can be used with indexed views.

DROP:
► The DROP command removes a table from the database.
► All the tables' rows, indexes, and privileges will also be removed.
► No DML triggers will be fired.
► The operation cannot be rolled back.
► DROP and TRUNCATE are DDL commands, whereas DELETE is a DML
command.
► DELETE operations can be rolled back (undone), while DROP and
TRUNCATE operations cannot be rolled back.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-02

7. Which is faster Truncate or Delete? Give the reason.


Ans: Truncate is faster than delete because Truncate maintains minimal
logging in the transaction log.

8. What is the difference between CHAR and VARCHAR?


Ans: CHAR is a fixed-length string data type, so any remaining space in the
field is padded with blanks. CHAR takes up 1 byte per character. So, a
CHAR(100) field (or variable) takes up 100 bytes on a disk, regardless of the
string it holds.

VARCHAR is a variable-length string data type, so it holds only the


characters you assign to it. VARCHAR takes up 1 byte per character, + 2
bytes to hold length information. For example, if you set a VARCHAR(100)
data type = ‘Jen’, then it would take up 3 bytes (for J, E, and N) plus 2
bytes, or 5 bytes in all.

9. What is the difference between VARCHAR and NVARCHAR?


Ans:
VARCHAR :

● It is a variable-length data type


● Used to store non-Unicode characters
● Occupies 1 byte of space for each character

NVARCHAR:

● It is a variable-length data type


● Used to store Unicode characters
● Occupies 2 bytes of space for each character
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-02

10. What does N mean in SQL?


Ans: You might wonder what the N stands for? N stands for National
Language Character Set and is used to specify a Unicode string. When
using Unicode data types, a column can store any character defined by
the Unicode Standard, which includes all of the characters defined in
the various character sets. Note that Unicode data types take twice as
much storage space as non-Unicode data types.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-03

1. What is the syntax used to comment on single lines and Multiple Line?
Ans:
Single lines comments: --Today is the 2nd session
Multiple Line comments:
/*
Today is
the 2nd
Session
*/

2. Write the syntax to create the ‘Training’ Database.


Ans: CREATE DATABASE Training

3. Create an employee table and insert the below data.

Ans: create table employee


(
EmpID int,
FirstName varchar(100),
LastName varchar(100),
Salary int,
Address varchar(100)
);

insert into employee values(1,'Mohan','Chauhan',22000,'Delhi')


insert into employee values(2,'Asif','Khan',15000,'Delhi')
insert into employee values(3,'Bhuvnesh','Shankya',19000,'Noida')
insert into employee values(4,'Deepak','Kumar',19000,'Noida')
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-03

4. Add additional column MobileNumber on Employee table and add data on the
same column.
Ans: alter table employee add MobileNumber Bigint;

update employee
set MobileNumber = 0406309415
where EmpID = 1

update employee
set MobileNumber = 0452238834
where EmpID = 2

update employee
set MobileNumber =0403070636
where EmpID = 3

update employee
set MobileNumber = 0412356789
where EmpID = 4

5. How to Remove the address column from the employee table.


Ans:
alter table employee
drop column address

6. Write a query to Update Firstname = Ragu and LastName = Shayam for empID
=2.
Ans:
update employee
set FirstName='ragu',
LastName='Shayam'
where empid=2;

7. Write a query to Remove empid = 4 from the table.


Ans: delete from employee where EmpID=4

8. Write a query to update DimEmployee to store 500 length characters for the
column Title.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-03

Ans:

Alter table DimEmployee


Alter column Title varchar(500)

9. Create a duplicate table of DimCustomer With data.


Ans: Select * into DimCustomerDup from DimCustomer

10. Create a duplicate table of DimCustomer without any data.


Ans:
Select * into DimCustomer_Dup from DimCustomer where 2=3
Note: We can put any false condition in where clause
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-04

1. Create an employee table and make an EMPID column as an


identity column and insert some values.
Ans:

CREATE TABLE Emp


(
Emp_ID INT Identity(1,1),
Emp_name Varchar(100),
Emp_Sal int
)

INSERT INTO Emp VALUES ('Anees',1000)


INSERT INTO Emp VALUES ('Rick',1200)
INSERT INTO Emp VALUES ('John',1100);
INSERT INTO Emp VALUES ('Stephen',900);
INSERT INTO Emp VALUES ('Maria',1400);
INSERT INTO Emp VALUES ('Karan',1500);
INSERT INTO Emp VALUES ('Tarrio',1700);

2. Write a Query to Truncate the Employee table


Ans: truncate Employee

3. Write a query to drop the Employee table.


Ans: Drop table Employee

4. Write a query to update the DimCustomer table to set YearlyIncome = 60000 for
the CustomerKey = 11002 and roll back the update.
Ans:

Begin Transaction
Update DimCustomer
Set YearlyIncome = 60000
Where CustomerKey = 11002

Rollback

5. Create a new table from the existing table DimCustomer withName


DimCustomerBachelors without using create keyword.
Ans: Select * into DimCustomerBachelors from DimCustomer where 1=2
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-04

6. Differences Between @@IDENTITY Vs SCOPE_IDENTITY() Vs


IDENT_CURRENT in SQL?
Ans:

SCOPE_IDENTITY is:

SCOPE_IDENTITY returns the last IDENTITY value inserted into an IDENTITY


column in the same scope.
SCOPE_IDENTITY returns the last identity value generated for any table in the
current session and the current scope.
A scope is a module; a Stored Procedure, trigger, function, or batch.
Thus, two statements are in the same scope if they are in the same Stored
Procedure, function, or batch.
The SCOPE_IDENTITY() function will return the NULL value if the function is invoked
before any insert statements into an identity column occur in the scope.

What IDENT_CURRENT is
IDENT_CURRENT is:
IDENT_CURRENT returns the last identity value generated for a specific table in any
session and any scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified
table.

@@IDENTITY is:
@@IDENTITY returns the last identity value generated for any table in the current
session, across all scopes.
After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY
contains the last identity value generated by the statement.
If the statement did not affect any tables with identity columns, @@IDENTITY returns
NULL.
If multiple rows are inserted, generating multiple identity values, @@IDENTITY
returns the last identity value generated.
The @@IDENTITY value does not revert to a previous setting if the INSERT or
SELECT INTO statement or bulk copy fails, or if the transaction is rolled back.

Differences

The differences between them are:

SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in


that they return values inserted into IDENTITY columns.
SCOPE_IDENTITY and @@IDENTITY will return the last identity values generated
in any table in the current session.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-04

However, SCOPE_IDENTITY returns values inserted only within the current scope;
@@IDENTITY is not limited to a specific scope. A scope is a module; a Stored
Procedure, trigger, function, or batch.

7. What are the different types of database management systems?


Ans: The database management systems can be categorized into several types.
Some of the important lists are given below:

● Hierarchical databases (DBMS)


● Network databases (IDMS)
● Relational databases (RDBMS
● Object-oriented databases
● Document databases (Document DB)
● Graph databases
● ER model databases
● NoSQL databases

8. What is Normalization in a Database?


Ans: Normalization is used to minimize redundancy and dependency by organizing
fields and table of a database.

There are some rules of database normalization, which is commonly known as Normal
From, and they are:

● First normal form(1NF)


● Second normal form(2NF)
● Third normal form(3NF)
● Boyce-Codd normal form(BCNF)

9. What are the disadvantages of not performing database


Normalization?

Ans: The major disadvantages are:

The occurrence of redundant terms in the database causes the waste of space in the disk.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-04

Due to redundant terms, inconsistency may also occur. If any change is made in the data of
one table but not made in the same data of another table, then inconsistency will occur. This
inconsistency will lead to the maintenance problem and effects the ACID properties as well.

10. What is Denormalization in a Database?

Ans: Denormalization is a technique used by database administrators to optimize the


efficiency of their database infrastructure. The denormalization concept is based on
Normalization, which is defined as arranging a database into tables correctly for a
particular purpose. This method allows us to add redundant data into a normalized
database to alleviate issues with database queries that merge data from several
tables into a single table. It adds redundant terms into the tables to avoid complex
joins and many other complex operations.

Denormalization doesn't mean that normalization will not be done. It is an optimization


strategy that takes place after the normalization process.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-05

1. What are Constraints?


Ans: Constraints are rules and restrictions applied on a column or a table such that
unwanted data can't be inserted into tables. This ensures the accuracy and reliability of
the data in the database. We can create constraints on single or multiple columns of any
table. Constraints maintain the data integrity and accuracy in the table.

2. How many types of constraints are available?


Ans: There are 6 types of constraints:
● Not Null Constraint
● Check Constraint
● Default Constraint
● Unique Constraint
● Primary Key Constraint
● Foreign key Constraint

3. What is Not Null Constraint?


Ans: A Not null constraint restricts the insertion of null values into a column. If we are
using a Not Null Constraint for a column then we cannot ignore the value of this column
during an insert of data into the table.

4. What is Check Constraint?


Ans: A Check constraint checks for a specific condition before inserting data into a table.
If the data passes all the Check constraints then the data will be inserted into the table
otherwise the data for insertion will be discarded. The CHECK constraint ensures that all
values in a column satisfy certain conditions.

5. What is Default Constraint?


Ans: Specifies a default value for when a value is not specified for this column. If in an
insertion query any value is not specified for this column then the default value will be
inserted into the column.

6. What is a Unique Key Constraint?


Ans: It ensures that each row for a column must have a unique value. It is like a Primary
key but it can accept only one null value. In a table, one or more columns can contain a
Unique Constraint.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-05

7. What is Primary Key Constraint?


Ans: A Primary key constraint is applied for uniquely identifying rows in a table. It cannot
contain Null values and the rest of the table data should be unique. While creating a
table if we do not specify a name to the constraint, SQL Server automatically assigns a
name to the constraint.

8. What is Foreign Key Constraint?


Ans: A Foreign Key Constraint is used to establish a relationship between two tables
where one column is a Primary Key of the table and the other column from the other
table is referenced to the Primary Key column. A Foreign Key column can also have
reference to the Unique Key column of another table.

9. What is Composite Primary Key?


Ans: Multiple columns can participate in the Primary Key which is referred to as a
composite primary key.

10. What is the difference between Primary key and Unique Key Constraint?
Ans:
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-05


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-06

1. Write a SQL query to create a Courses table with the following column and insert some
data and create constraints.

Column: CourseID, CourseName

Apply the Primary Key with the identity on CourseID and Apply Not null on
CourseName.

Ans:

create table course

courseid int primary key identity,

coursename varchar(100) not null,

);

insert into course(coursename)values('asp.net')

insert into course(coursename)values('java')

insert into course(coursename)values('c++')

insert into course(coursename)values('vb.net')

insert into course(coursename)values('sql')

2. Create a Student table with the following columns and insert some data and create
constraints.

Column: StudentID, StudentName, RollNumber , ContactNumber, Address, Country ,


CourseID
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-06

Apply Primary key on StudentID

Apply Not null on RollNumber and RollNumber should always be greater than 500.

Apply Unique key on ContactNumber

Apply Default constraints on the Country column.

Apply foreign key on CourseID reference table Courses

Ans:

create table student

studentid int primary key,

rollnumber varchar(100) not null check(rollnumber>500),

contactnumber varchar(100) unique,

country varchar(100) default('AUSTRALIA'),

courseid int foreign key references course(courseid),

);

insert into
student(studentid,rollnumber,contactnumber,country,courseid)values(11,'501','12345678'
,'INDIA',1)

insert into
student(studentid,rollnumber,contactnumber,courseid)values(12,'600','043070556',2)

insert into
student(studentid,rollnumber,contactnumber,country,courseid)values(13,'506','37543092
2','AUSTRALIA',3)
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-06

insert into
student(studentid,rollnumber,contactnumber,country,courseid)values(14,'507','56734556'
,'SPAIN',4)

insert into
student(studentid,rollnumber,contactnumber,country,courseid)values(15,'508','04522388
34','U.S',5)

3. Create a Feedetails table with the following columns and insert some data and
create constraints.

Column: StudentID, CourseID, TotalFee, AmountPaid, AmountDue

Apply foreign key on StudentID reference table Student

Apply foreign key on CourseID reference table Courses

Apply Not null on TotalFee

Ans:

create table feedetails

studentid int foreign key references student(studentid),

courseid int foreign key references course(courseid),

totalfee int not null,

amountpaid int,

amountdue int

);
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-06

insert into
feedetails(studentid,courseid,totalfee,amountpaid,amountdue)values(11,1,1000,500,500)

insert into
feedetails(studentid,courseid,totalfee,amountpaid,amountdue)values(12,2,3000,1000,2000)

insert into
feedetails(studentid,courseid,totalfee,amountpaid,amountdue)values(13,3,1000,600,400)

insert into
feedetails(studentid,courseid,totalfee,amountpaid,amountdue)values(14,4,5000,500,3500)

insert into
feedetails(studentid,courseid,totalfee,amountpaid,amountdue)values(15,5,1000,300,500)

4. DROP check Constraint which is created on RollNumber in the student table

Ans: alter table student drop constraint CK__student__rollnum__398D8EEE

5. Can we drop or delete data from the Parents table before deleting from child?

Ans: No, First need to drop or delete from the child, then you need to from the Parents.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-07


1. What are Temporary Tables in SQL?
Ans: A temporary table in SQL Server, as the name suggests, is a database
table that exists temporarily on the database server. A temporary table
stores a subset of data from a normal table for a certain period of time.

2. What are the use cases of Temporary Tables ?


Ans: Temporary tables are particularly used to store data for a temporary point of view.
Temporary tables are useful when you have a large number of Joins. you can use
minimum join and store it in a temporary table and again use temp tables to join another
table.

3. Which Database Temporary tables store?


Ans: Temporary tables are stored inside “tempdb” which is a system database.

4. What are Different Types of Temporary Tables available in SQL?


Ans: SQL Server provides two types of temp tables based on the behavior and scope of
the table.These are:
► Local Temp Table
► Global Temp Table

5. Explain Local Temp Table?


Ans:

Local temp tables are only available to the current connection for the
user; and they are automatically deleted when the user disconnects
from instances. Local temporary table name is started with hash ("#")
sign.
Syntax:
CREATE TABLE #LocalTempTable(
UserID int,
UserName varchar(50),
UserAddress varchar(150))

6. Explain Global Temp Table?


Ans:
Global Temporary tables name starts with a double hash ("##"). Once this
table has been created by a connection, like a permanent table it is then
available to any user by any connection. It can only be deleted once all
connections have been closed.
Syntax:
CREATE TABLE ##NewGlobalTempTable(
UserID int,
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-07


UserName varchar(50),
UserAddress varchar(150))

7. What are Variables In SQL?


Ans: variable is an object that can hold a single data value of a specific type. The name
must have a single @ as the first character.
Syntax:
Declare @Salary int
Select @Salary = Salary from Employee where EMPID = 4
update Employee
set Salary = @Salary
where EMPID = 1

8. What is Table Variable In SQL?


Ans:
Table variables are objects similar to temporary tables and were introduced in
SQL Server 2000. A table variable is declared using the table data type.
Syntax:
Declare @Employee table (empid int, EmpName Varchar(100))
insert into @Emp3(empid,EmpName) values (1,'Deepak’)
select * from @Emp3
Table variables do not work independently. Need to select entire statement and
execute it.

9. What is the Difference Between Temporary Table and Table Variable?


Ans:
Table variable (@table) is created in the memory. Whereas, a Temporary table (#temp) is
created in the tempdb database. However, if there is a memory pressure the pages
belonging
to a table variable may be pushed to tempdb.
❖ Table variables cannot be involved in transactions, logging or locking. This makes
@table faster then #temp. So the table variable is faster than the temporary table.
❖ Temporary Tables are not allowed in User Defined Functions. Table Variables can be
used in User Defined Functions.
❖ Temporary tables are allowed CREATE INDEXes whereas Table variables aren’t
allowed CREATE INDEX instead they can have index by using Primary Key or Unique
Constraint.
❖ We can use the drop statement in the temp table but we can’t use the drop statement
in the table variable.

10. Which is faster: Temporary Table or Table Variable?


Ans: Table Variable
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-08


1. Write a query to find the list of all tables which are created by the users.
Ans: Select * from sys.tables

2. Write a query to find the list of all objects which are available in the Database.
Ans: Select * from sys.objects

3. Write a query to find the list of all Stored Procedures Which are available in the
Database.
Ans: Select * from sys.objects Where type = 'p'

4. Write a query to list all Object names and Types.


Ans: Select Distinct type_desc,type from sys.objects order by 1

5. Find the customer details which have English education as Bachelors and English
Occupation is Professional.(Table: DimCustomer).
Ans:
Select * from DimCustomer where EnglishEducation = 'Bachelors' and
EnglishOccupation = 'Professional'

6. Find the list of employees whose title is Marketing Assistant or department is Tool
Design.(Table:DimEmployee).
Ans:
Select * from DimEmployee where Title = 'Marketing Assistant' or DepartmentName =
'Tool Design'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-08


7. Write a query to order FactInternetSales in Descending order based on Order
date.(Table:FactInternetSales)
Ans:
Select * from FactInternetSales order by OrderDate desc

8. What is the default order in order by clauses? Ascending or Descending


Ans: Ascending

9. What is the difference between ISNULL and Null Function?


Ans:
The ISNULL function considers both null values as well as empty values.
Null functions consider only null values.

10. Explain one real time scenario of ISNULL and Null Function?
Ans:
Update DimCustomer set MiddleName = '' where CustomerKey between 11010 and
11040

Select * from DimCustomer where ISNULL(MiddleName,'') = ''

Select * from DimCustomer where MiddleName is null


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-09


1. Find the list of the customer details that don't have a middle name.(Table:
DimCustomer).
Ans: Select * from DimCustomer where ISNULL(MiddleName,'') = ''

2. Find the customer details from 11100 to 11350.(Table: DimCustomer).


Ans: Select * from DimCustomer where CustomerKey between 11100 and 11350

3. Find the list of the employee which firstName starting with


‘P’.(Table:DimEmployee).
Ans: Select * from DimEmployee where FirstName like 'P%'

4. Find the list of the employee which firstName starting with ‘S’ and LastName
ending with ‘D’.(Table:DimEmployee).
Ans: Select * from DimEmployee where FirstName like 'S%' and LastName like '%D'

5. Find the customer details which address contain ‘Park Glenn’.


(Table:DimCustomer).
Ans: Select * from DimCustomer where AddressLine1 like '%Park Glenn%'

6. Find the maximum, Minimum and average tax amount for the internet
sales.(Table:FactInternetSales).
Ans: Select Max(TaxAmt) as MaximumTax, Min(TaxAmt) as MinimumTax, Avg(TaxAmt)
as AverageTax from FactInternetSales

7. Find the Maximum and Minimum UnitPrice on each order date.(Table:


FactInternetSales).
Ans: Select OrderDate, MAX(UnitPrice) as MaxUnitPriceByDate from FactInternetSales
Group by OrderDate

9. Find the Average Yearly income of the English Education High School(Table:
DimCustomer)
Ans: Select EnglishEducation,Avg(YearlyIncome) as AvgYearlyIncome from
DimCustomer
Group by EnglishEducation
Having EnglishEducation = 'High School'

10. How Many total issues were raised in the Holidays.(Table: FactCallCenter).
Ans: Select WageType,Sum(IssuesRaised) As TotalIssue from FactCallCenter
Group by WageType
Having WageType = 'holiday'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-10


1. How many total calls in the AM shift (Table: FactCallCenter).
Ans:
Select Shift,Sum(Calls) As TotalCalls from FactCallCenter
Group by Shift
Having Shift = 'AM'

2. Find the Ship date of Order number SO43700(Table: FactInternetSales)


Ans: Select * from FactInternetSales
Where SalesOrderNumber = 'SO43700'

3. Find the Buyer information which is Management in occupation or ‘Partial Co’ in


education.(Table: ProspectiveBuyer)
Ans:
Select * from ProspectiveBuyer
Where Occupation = 'Management'
Or Education = 'Partial Co'

4. Find the total number of employees working in the ‘Engineering’


department.(Table:Dimemployee)
Ans: Select COUNT(*) from Dimemployee
Where DepartmentName = 'Engineering'

5. Find the list of employees who are still associated with the
company.(Table:Dimemployee)
Ans: Select * from Dimemployee Where ISNULL(EndDate,'') = ''

6. What is the difference between Count(*) and Count(ColumnName)?


Ans: Count(*) will give a total count but Count(ColumnName) will exclude the null
values.

7. Find the total count of Married and Single customers.


Ans: Select MaritalStatus, Count(CustomerKey) as MaritalStatus_Count from
Dimcustomer Group By MaritalStatus

8. What are Aggregate Functions?


Ans:
Aggregate functions are built into sql server functions.
2. Aggregate functions are applied to sets of records rather than to a single record.
3. Aggregate functions performs a computation on a set of values rather than on a
single value.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-10


4. Aggregate functions are used to summarize data.
5. Aggregate functions perform a calculation on a set of values and return a single
Value.

9. What is Having Clause in SQL?


Ans: The Having clause can be used only with a Select statement. If you use
the Having clause with an update or delete query in SQL, it will not work.
10. What is Difference between Having and Where Clause?
Ans:
WHERE:
● We can use the WHERE clause with SELECT, INSERT, UPDATE, and DELETE
clauses.
For Example, it works fine for "Update Mas_Employee Set Salary = 1500 WHERE Id
=1".
● The WHERE clause is used for filtering rows and it applies to each and every row.
● The WHERE clause is used before the GROUP BY clause.
● We can't use aggregate functions in the where clause unless it is in a subquery
contained
in a HAVING clause.
HAVING
● The HAVING clause can only be used with a SELECT query. This means if you want
to
perform the INSERT, UPDATE and DELETE clause and it will return an error. For
Example "Update Mas_Employee Set Salary = 1500 Having Id =1" Query will be
generated an error like "Incorrect syntax near the keyword 'HAVING'. ".
● The HAVING clause is used to filter groups in SQL.
● The HAVING clause is used after the GROUP BY clause.
● We can use an aggregate function in the HAVING clause.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-11

1. What is the difference between GETDATE() and GETUTCDATE()?


Ans:
GETDATE(): Returns the current system timestamp as a DateTime
Syntax: Select GETDATE()
GETUTCDATE(): Returns the current database Server timestamp as a
DateTime.

2. Explain the DATEADD() function?


Ans: This function adds a number (a signed integer) to a datepart of an
input date, and returns a modified date/time value.
Syntax: SELECT DATEPART(year, GETDATE())
SELECT DATEPART(DAY, GETDATE())
SELECT DATEPART(MONTH, GETDATE())
Example: Select DATEPART(year, BirthDate) As BirthYear ,BirthDate,* from
DimEmployee

3. Explain the DATEDIFF() function?


Ans: This function returns the difference between two dates.
Example: Select DATEDIFF(YEAR, BirthDate,getdate()) As Age ,* from
DimEmployee

4. Explain the DATENAME() function?


Ans: This function returns a character string representing the specified
datepart of the specified date.
Syntax: DATENAME ( datepart , date )
Example: SELECT DATENAME(dw, getdate()) AS 'Today Is'
SELECT DATENAME(dw, '2021-02-15')
SELECT DATENAME(dw, HireDate), * from DimEmployee

5. What is the EOMONTH() function?


Ans: This function returns the last day of the month containing a
specified date.
Example: Select EOMONTH('2021-02-15')
Select EOMONTH(getdate())

6. What is @@DATEFIRST?
Ans: This function returns the current value of SET DATEFIRST, for
a specific session.

7. What is ISDATE()?
Ans: Returns 1 if the expression is a valid DateTime value; otherwise, 0.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-11


8. Write a Query to display today's date and end of month date?
Ans:
Select Getdate() as 'Today Date', EOMONTH(Getdate()) as 'EOM Date'

9. Write a Query to display today’s day and end of month day.


Ans:
Select DATENAME(dw, Getdate()) as 'Today Day',
DATENAME(dw, EOMONTH(Getdate())) as 'EOM Day'

10. Write a query to display the last working date of this month?
Ans: Select EOMONTH(getdate())
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-12


1. Write a query to generate the report and in the report need to display an additional
column as ReportGeneratedDate.
Ans: Select *,GETDATE() as ReportGeneratedDate from FactInternetSales

2. Employeekey = 10 resigned today and as per the company policy the notice period
is 90 days. Write a query to find the last working days.
Ans:
SELECT DATEADD(day,90,GETDATE()) LastWorkingDays, * from dimemployee
where EmployeeKey = 10

3. Write a query to display BirthDay,BirthMonth and BirthYear from the BirthDate


column using DimEmployee table.
Ans:

Select DATEPART(DAY, BirthDate) As BirthDay ,


DATEPART(MONTH, BirthDate) BirthMonth,
DATEPART(year, BirthDate) BirthYear,
BirthDate,* from DimEmployee

4. Find the Employee information which Birth Year is 1974


Ans:
Select * from DimEmployee Where DATEPART(year, BirthDate) = 1974

5. Find the Employee information who was born in december.


Ans: Select * from DimEmployee where DATEPART(MONTH, BirthDate) = 12

6. Find the Employee information who joined in 2007 in the organization.


Ans:

Select DATEPART(year, HireDate) As HireDate ,BirthDate,*


from DimEmployee where DATEPART(year, HireDate) = 2007

7. Write a query to find the age of all employees.


Ans:
Select DATEDIFF(YEAR, BirthDate,getdate()) As Age ,* from DimEmployee

8. Find the Employee information who have greater or equal to 10 years of


experience in the organization.
Ans:
Select * from DimEmployee
where DATEDIFF(YEAR, HireDate,getdate()) >= 10
9. Find the list of employees who joined on Monday.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-12


Ans: SELECT * from DimEmployee where DATENAME(dw, HireDate) = 'Monday'

10. Write a query to display joining days of all employees.


Ans:
SELECT DATENAME(dw, HireDate) joiningDays, * from DimEmployee
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-16

1. Write a query to find the BirthDay, BirthMonth and BirthYear of the employee by
using DimEmployeeTable.
Ans:
Select DATENAME(dw, BirthDate) as BirthDay,DATENAME(month, BirthDate) as
BirthMonth, DATENAME(YEAR, BirthDate) as BirthYear,* from DimEmployee

2. Find the details of an employee who has more than five years tenure in the
organization.
Ans:
Select * from DimEmployee where DATEDIFF(YEAR, HireDate,getdate()) > 5

3. Find the details of the employee who is more than 30 years old in age.
Ans: Select * from DimEmployee where DATEDIFF(YEAR, BirthDate,getdate())>30

4. Find the details of Customer who made the first purchase. Use the DimCustomer
table.
Ans:
Declare @DateFirstPurchase Datetime
Select @DateFirstPurchase = Min(DateFirstPurchase) from DimCustomer
Select * from DimCustomer where DateFirstPurchase=@DateFirstPurchase

5. Write the query to split the values from the column FrenchEducation Column from
the DimCustomer before values of ‘+’ symbol if available.
Ans:
Select SUBSTRING(FrenchEducation,1,CHARINDEX('+',FrenchEducation)-1),
FrenchEducation,* from DimCustomer where FrenchEducation like '%+%'

6. Add a new column FullName in the DimCustomer table and update the fullname
for the Male customer only.
Ans:

Alter table DimCustomer


add FullName varchar(100)

Select FullName,* from DimCustomer

Update DimCustomer
Set FullName = FirstName+' '+LastName
Where Gender = 'M'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-16


7. Write the query to find the monthly income of the customer.
Ans:
Select (YearlyIncome/12) as MonthlyIncome, * from DimCustomer

8. Write the query to find the age when the employee joins the organization.
Ans:
Select DATEDIFF(YEAR, BirthDate,HireDate), * from DimEmployee

9. Write the query to find the first 10 letters from the address and also find the total
length of the address from the DimCustomer table.
Ans:
Select Left(AddressLine1,10) as First10Letter, LEN(AddressLine1) as TotalLength, *
from DimCustomer

10. Find the maximum and minimum Yearly income of the Management
Englishoccupation.
Ans:
Select EnglishOccupation, Max(YearlyIncome) as MaximumIncome, Min(YearlyIncome)
as MinimumIncome
from DimCustomer
Group by EnglishOccupation
having EnglishOccupation = 'Management'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-17

1. Find the Average Yearly income of the Gestión Spanishoccupation.


Ans:
Select SpanishOccupation, AVG(YearlyIncome) as AvgIncome
from DimCustomer
Group by SpanishOccupation
having SpanishOccupation = 'Gestión'

2. Find the total number of Bachelors EnglishEducation customers.


Ans: Select EnglishEducation, Count(1) as TotalCount
from DimCustomer
Group by EnglishEducation
having EnglishEducation = 'Bachelors'

3. Find the 07th Highest Yearly income of the customer.


Ans:
select DENSE_RANK() over (order by yearlyincome desc) As Rank_Test,* into #HSalary
from dimcustomer

Select * from #HSalary where Rank_Test=7

4. Find the 06th Highest Yearly income of the customer of Bachelors


EnglishEducation.
Ans:

select DENSE_RANK() over (Partition by EnglishEducation order by yearlyincome desc)


As Rank_Test,* into #HSalary1 from dimcustomer

Select * from #HSalary1 where EnglishEducation= 'Bachelors' and Rank_Test=6

5. Find the list of customers that don't have a middle name.


Ans:
Select * from DimCustomer where ISNULL(MiddleName,'') = ''

6. Find the average UnitPrice of each SalesOrder and sort the data in descending
order based on SalesOrderNumber.(FactInternetSales)
Ans:

Select SalesOrderNumber, Avg(UnitPrice) from FactInternetSales


Group by SalesOrderNumber
order by 1 desc
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-17


7. Find the list of Product which is order more than 50 times.(FactInternetSales)
Ans:
Select ProductKey,Count(*) from FactInternetSales
Group by ProductKey

8. Find the list of Customers who purchase more than one product.
(FactInternetSales).
Ans:

Select ProductKey,CustomerKey,Count(*) from FactInternetSales


Group by ProductKey,CustomerKey
having Count(*) >1

9. Find the list of product information which paid the 10th highest tax
amount.(FactInternetSales).
Ans:

select DENSE_RANK() over (order by taxamt desc) As Rank_Test,* into


#FactInternetSales from FactInternetSales

Select * from #FactInternetSales where Rank_Test=10

10. Find the list of products which have shiping day on Monday.(FactInternetSales)
Ans:
Select DATENAME(dw,ShipDate), * from FactInternetSales where
DATENAME(dw,ShipDate) = 'Monday'

11. Find the list of products which sales amount greater than average sales amount.
Ans:

declare @avg int


select @avg = AVG(SalesAmount)from FactInternetSales

Select * from FactInternetSales where SalesAmount>@avg


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-18

1. What is Joins in SQL?


Ans: Joins are used to relate one or more tables in SQL Server. Joins are a part of a
SQL Statement that retrieves rows from a table or tables according to specified
conditions.

2. How Many types of Joins in SQL?


Ans:
Types of Joins:
● Inner join
● Left outer join
● Right outer join
● Full outer join
● Cross join
● Self Join

3. What is Inner Join in SQL?


Ans: Inner join produces a data set that includes rows from the left table,
matching rows from the right table.

4. What is Left outer join in SQL?


Ans: Left join selects data starting from the left table and matching
rows in the right table. The left join returns all rows from the left table and the
matching rows from the right table. If a row in the left table does not have a
matching row in the right table, the columns of the right table will have nulls.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-18

5. What is Right outer join in SQL?


Ans: The right join or right outer join selects data starting from the right table. It is a
reversed version of the left join.

6. What is Full outer join?


Ans: The full outer join or full join returns a result set that contains all
rows from both left and right tables, with the matching rows from both sides
where available. In case there is no match, the missing side will have NULL
Values.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-18

7. What is Cross join?


Ans: The CROSS JOIN joined every row from the first table (T1) with
every row from the second table (T2). In other words, the cross join returns a
Cartesian product of rows from both tables.

8. Explain the self Join?


Ans: A self join allows you to join a table to itself. It helps query hierarchical
data or compare rows within the same table.
A self join uses the inner join or left join clause. Because the query that uses the
self join references the same table, the table alias is used to assign different
names to the same table within the query.

9. What is a hash Join in SQL? how to use it?


Ans: This kind of join has two inputs like all the join algorithms, first is the build input i.e.
outer table and the second is probe input i.e. inner table. The query optimizer allows the
roles so that the smaller of the above two inputs is the build input. The Variant of hash
join can do deduplication i.e. removal and grouping, such as Sum (col1) Group-By Id.
These updates are used only for one input and for both the build and probe parts.

10. What is Merge Join in SQL?


Ans: The Merge join (also known as sort-merge join) is a join process that is used in the
application of a Relational Database Management System. The basic trick of a join
process is to find each unique value of the join attribute, the set of tuples in every
relation that outputs that value.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-21

1. What is Index in SQL?


Ans: SQL Indexes are used in relational databases to quickly retrieve data. They are
similar to indexes at the end of the books whose purpose is to find a topic
quickly. SQL provides Create Index, Alter Index, and Drop Index commands that
are used to create a new index, update an existing index, and delete an index in
SQL Server.

2. How many types of Index in SQL?


Ans:
SQL Server supports two types of indexes:
1. Clustered Index
2. Non-Clustered Index.

3. What is Clustered Index?


Ans:
B-Tree (computed) clustered index is the index that
will arrange the rows physically in the memory in sorted order. When the
Primary Key is created automatically and the Clustered Index is created.
An advantage of a clustered index is that searching for a range of values
will be fast. A clustered index is internally maintained using a B-Tree data
structure leaf node of the b tree of clustered indexes that will contain the
table data; you can create only one clustered index for a table.

4. What is a Non-Clustered Index?


Ans:
Non-clustered Index:
● When a Unique Key is created automatically, a Non-clustered Index is
created.
● A non-clustered index is an index that will not arrange the rows physically in
the memory in sorted order.
● An advantage of a non-clustered index is searching for the values that are in a
range will be fast.
● You can create a maximum of 999 non-clustered indexes on a table, which is
254 up to SQL Server 2005.
● A non-clustered index is also maintained in a B-Tree data structure but leaf
nodes of a B-Tree or non-clustered index contain the pointers to the pages
that contain the table data and not the table data directly.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-21


5. What is the Difference between Scan and Seek Operation?
Ans:

6. What is the difference between Table Scan, Index Scan, And Index Seek?
Ans:
Table Scan
● It is a very simple process. While performing table scan, the query engine starts from
the physical beginning of the table and it goes through every row into the table. If a row
matches with the criteria then it includes that into the result set.
● It is the fastest way to retrieve the data especially when there is quite a small table.
● For a small table, a query engine can load all the data in a one-shot but from a large
table it is not possible i.e. more IO and more time will be required to process those large
data.
● Generally, a full table scan is used when a query doesn’t have a WHERE clause i.e. all
data.

Index Scan
● When you have a clustered index and your query needs all or most of the records (i.e.
query without where or having clause) then it uses an index scan.
● Index scan works similar to the table scan during the query optimization process. The
query optimizer takes a look at the available index and chooses one of the best, based
on JOINs and WHERE clauses.
● As the right index is being chosen, the SQL query processing engine will navigate the
tree structure to the pointer of the data which matches the criteria and further extracts
only the needed/required records.
● The key difference between Table Scan and Index Scan is that data is stored in the
index tree, the query processor knows it when it reaches the end of the current it is
looking for. Then it can send the query or move on to the next range of data.
An index scan is slightly faster than the Table scan but significantly slower than an Index.

Index Seek
● When the search criterion matches the index well enough which can navigate directly
to particular points into the data, this is known as the Index seek.
● The index seeks the fastest way to retrieve the data in the database.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-21


● For example, the following query will use the Index seek which can be confirmed by
checking the execution plan of the query
● The query optimizer can use an index directly to go to the 3rd employee id and fetch
the data.

7. What is Estimated vs. Actual Query Execution Plans?


Ans:
The Estimated Query Plans are created without execution and contain an approximate
Execution Plan. This can be used on any T-SQL code without actually running the query.
So for example, if you had an UPDATE query you could get the Estimated Query Plan
without actually running the UPDATE.
The Actual Query Plans are created after we sent the query for processing and it
contains the steps that were performed

8. Can you please provide a list of the properties Execution Plans?


Ans:

● Physical Operation: the physical operation performed.


● Logical Operation: the logical operation that is executed by the physical operation.
● Actual Number of Rows: the actual number of rows returned by the operator.
● Estimated I/O Cost: this value shows I/O usage. However, it is a relative value so you
can only see how it compares to other operator's value in the Query Plan. The larger the
number the more resources are used.
● Estimated CPU Cost: this value shows CPU usage. It is also a relative value so you
can
see only if it is larger then any other operator's in the Query Plan.
● Number of Executions: how many times the operation was performed to fulfill the
query.
● Estimated Number of Executions: how many times the operation should be performed
to fulfill the query.
● Estimated Operator Cost: you can see this percentage under the operator icon. This is
the total amount of the I/O and CPU estimated costs therefore it is also a relative value.
● Estimated Subtree Cost: this is the total cost of this operator and all preceding
operators.
● Estimated Number of Rows: the estimated number of rows returned by the query. This
value is based on the statistics.
● Estimated Row Size: the estimated length of rows returned by the query. This value is
also based on the statistics.
● Actual Rebinds: these values show how many times the Init() method was called.
● Actual Rewinds: these values show how many times the Init() method was called.
● Ordered: this is a Boolean value showing whether the rows are ordered in the
operation.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-21


● NodeID: every operator in the Execution Plan has a unique NodeID. This is an ordinal
value. If they are zero then the Actual Number of Rows and the Estimated Number of
Rows are comparable.

9. What is a heap table?


Ans:
A heap table is a special type of table that does not have a clustered index defined on it.
With a heap structure, the table data is not stored in any particular order. Heap tables
can be used when the data coming into the table is random and has no natural order but
non-clustered indexes should always be created on heap tables. If there are no
non-clustered indexes defined when the table is queried all the data would have to be
scanned and sorted in almost all cases leading to very poor performance.

10. What is the Covering index?


Ans: A covering index is an index which is made up of all (or more) of the columns
required to satisfy a query as key columns of the index. When a covering index can be
used to execute a query, fewer IO operations are required since the optimizer no longer
has to perform extra lookups to retrieve the actual table data.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-22


1. What are Views in SQL?
Ans: A view is a virtual table whose contents are defined by a query. Like a table, a view
consists of a set of named columns and rows of data. Unless indexed, a view does not
exist as a stored set of data values in a database. The rows and columns of data come
from tables referenced in the query defining the view and are produced dynamically
when the view is referenced.

Views are virtual tables that hold data from one or more tables. It is stored in the
database. A view does not contain any data itself, it is a set of queries that are applied
to one or more tables that are stored within the database as an object. Views are used
for security purposes in databases. Views restrict the user from viewing certain columns
and rows. In other words, using a view we can apply the restriction on accessing
specific rows and columns for a specific user. A view can be created using the tables of
the same database or different databases. It is used to implement the security
mechanism in the SQL Server.

2. What is the DML Query In View?


Ans: We can use SQL VIEW to insert, update and delete data in a
single SQL table. We need to note the following things regarding this.
● We can use DML operation on a single table only
● VIEW should not contain Group By, Having, Distinct clauses
● We cannot use a subquery in a VIEW in SQL Server

3. List the Conditional Control Statements in SQL?


Ans: Case Statements & IF...ELSE Statements is the Conditional Control Statements in
SQL.

4. What are the Case Statements?


Ans: CASE statement to evaluate a condition and return one or more
result expressions. CASE can be used in any statement or clause that allows a valid
expression. For example, you can use CASE in statements such as SELECT, UPDATE,
DELETE, and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and
HAVING.
Example:
Select Case When MaritalStatus = 'M' then 'Married'
when MaritalStatus = 'S' then 'UnMarried' else 'Data Not Provided' end As
Derrived_MaritalStatus,MaritalStatus,* from DimEmployee

5. What are the IF...ELSE Statements?


Ans: The IF...ELSE statement is a control-flow statement that allows
you to execute or skip a statement block based on a specified condition.
Example:
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-22


Declare @salaryA money , @salaryB money
Select @salaryA = YearlyIncome from DimCustomer Where CustomerKey = 11006
Select @salaryB = YearlyIncome from DimCustomer Where CustomerKey = 11007
If @salaryA = @salaryB
Begin
Print 'Both yearliIncome is Equal'
End
Else
begin
Print 'Both yearliIncome is Not Equal'
End

6. Explain the while loop in SQL?


Ans: Sets a condition for the repeated execution of an SQL statement or
statement block. The statements are executed repeatedly as long as the specified
The condition is true. The execution of statements in the WHILE loop can be controlled
from inside the loop with the BREAK and CONTINUE keywords.

7. Can we use For Loop in SQL?


Ans: No

8. WHAT IS CURSOR?
Ans: A cursor is a database object which is used to retrieve data from a result set one
row at a time. The cursor can be used when the data needs to be updated row by row.

9. List the Types of Cursors in SQL.


Ans:
Types of Cursors in SQL
1. Implicit Cursor: Whenever DML operations such as INSERT, UPDATE, and DELETE
are processed in the database, implicit cursors are generated automatically and used by
the framework. These types of cursors are used for internal processing and can’t be
controlled or referred from another code area.
2. Explicit Cursor: This type of cursor is generated whenever data is processed by a
user through an SQL block. Generally, the use of the SELECT query triggers the
creation of an explicit cursor and can hold more than one row but process just one at a
time.

10. What is the CURSOR LIFE CYCLE?


Ans:
► Declaring Cursor
A cursor is declared by defining the SQL statement.
► Opening Cursor
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-22


A cursor is opened for storing data retrieved from the result set.
► Fetching Cursor
When a cursor is opened, rows can be fetched from the cursor one by one or in a block
to do data manipulation.
► Closing Cursor
The cursor should be closed explicitly after data manipulation.
► Deallocating Cursor
Cursors should be deallocated to delete cursor definition and release all the system
resources associated with the cursor.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-23


1. WHY USE CURSORS?
Ans: In relational databases, operations are made on a set of rows. For example, a
SELECT statement returns a set of rows which is called a result set. Sometimes the
application logic needs to work with a row at a time rather than the entire result set at
once. This can be done using cursors.

2. What is @@FETCH_STATUS?
Ans: Returns the status of the last cursor FETCH statement issued against any cursor
currently opened by the connection.

3. What are CURSOR LIMITATIONS?


Ans:
❖ A cursor is a memory resident set of pointers -- meaning it occupies
memory from your system that may be available for other processes.
❖ The cursors are slower because they update tables row by row.

4. Create any table and apply CLUSTERED index.


Ans:

CREATE TABLE Employee_Index


(
Emp_ID INT ,
Emp_name Varchar(100),
Emp_Sal int
)
INSERT INTO Employee_Index VALUES (1,'Anees',1000)
INSERT INTO Employee_Index VALUES (5,'Rick',1200)
INSERT INTO Employee_Index VALUES (4,'John',1100);
INSERT INTO Employee_Index VALUES (2,'Stephen',900);
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-23


INSERT INTO Employee_Index VALUES (3,'Maria',1400)

Create CLUSTERED index IX_Employee_Index on Employee_Index(Emp_ID)

5. Create any table and apply a Non cluster index.


Ans:
CREATE TABLE Employee_NonCIndex
(
Emp_ID INT ,
Emp_name Varchar(100),
Emp_Sal int
)
INSERT INTO Employee_NonCIndex VALUES (1,'Anees',1000)
INSERT INTO Employee_NonCIndex VALUES (5,'Rick',1200)
INSERT INTO Employee_NonCIndex VALUES (4,'John',1100);
INSERT INTO Employee_NonCIndex VALUES (2,'Stephen',900);
INSERT INTO Employee_NonCIndex VALUES (3,'Maria',1400)

Create NONCLUSTERED index IX_Employee_NonCIndex on


Employee_NonCIndex(Emp_ID)

6. Write a Query to display 'M' as 'Married' and 'S' as 'UnMarried' from the
MaritalStatus using the DimEmployee table.
Ans:
Select Case When MaritalStatus = 'M' then 'Married'
when MaritalStatus = 'S' then 'UnMarried' else 'Data Not Provided' end As
Derrived_MaritalStatus,MaritalStatus,*
from DimEmployee

7. Write a query to Print A to Z in SQL using a while loop.


Ans:
Declare @a int, @b int
Set @a = 65
Set @b = 90

While @a <= @b
Begin
Select CHAR(@a)
Set @a = @a+1
End
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-23


8. Write a query to update Suffix column three letters if Gender is Male and update
four letters if Gender is Female.(Use DimCustomer table )
Ans:

select * into TestDimCustomer from DimCustomer

Select * from TestDimCustomer

Declare @max int, @min int, @emiladdress Nvarchar(1000), @Gender varchar(10)

Select @max = MAX(customerKey),@min = MIN(CustomerKey) from


TestDimCustomer

While @min <= @max


Begin
Select @emiladdress = EmailAddress, @Gender = Gender from
TestDimCustomer Where CustomerKey = @min

If @Gender = 'M'
Begin
Update TestDimCustomer
Set Suffix = left(@emiladdress,3)
Where CustomerKey = @min
End

If @Gender = 'F'
Begin
Update TestDimCustomer
Set Suffix = left(@emiladdress,4)
Where CustomerKey = @min
End

set @min = @min+1


End

9. Write a query to print the EmployeeKey, FirstName and LastName using Cursor.
Ans:
DECLARE @EmployeeKey int ,@FirstName varchar(20), @LastName varchar(20),
@message varchar(max);

PRINT '-------- DimEmployee DETAILS --------';


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-23


DECLARE emp_cursor CURSOR FOR
SELECT EmployeeKey,FirstName,LastName
FROM DimEmployee
order by EmployeeKey;

OPEN emp_cursor

FETCH NEXT FROM emp_cursor


INTO @EmployeeKey,@FirstName ,@LastName

print 'EmployeeKey FirstName LastName'

WHILE @@FETCH_STATUS = 0
BEGIN
print ' ' + CAST(@EmployeeKey as varchar(10)) +' '+ cast(@FirstName
as varchar(20))+' '+ cast(@LastName as varchar(20))

FETCH NEXT FROM emp_cursor


INTO @EmployeeKey,@FirstName ,@LastName

END
CLOSE emp_cursor;
DEALLOCATE emp_cursor;

10. Which is better performance wise Cursor or While loop?


Ans: While Loop.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-24


1. What are Stored Procedures?
Ans: A stored procedure is nothing more than prepared SQL code that you save so you
can reuse the code over and over again. So if you think about a query that you write
over and over again, instead of having to write that query each time you would save it as
a stored procedure and then just call the stored procedure to execute the SQL code that
you saved as part of the stored procedure.

2. Why use stored procedures and advantages of stored procedures?


Ans:
A stored procedure is a group of Transact-SQL statements compiled into a single
execution plan.
Stored Procedures are coding blocks in database servers. It is a pre-compiled entity i.e.
it is compiled at once and can be used again and again.
With help of stored procedures, a group of SQL statements can be executed
sequentially.
To supply data to the procedure we must have to use parameters in the procedure.
Stored procedures use parameters mapping concepts.
In parameter mapping front-end and procedure parameters names, type and
direction must be the same, and where front-end parameter length should be less than
or equal to procedure parameter length (then only can map parameters).
To return any value from the procedure we use a return statement.

3. How many types Of Stored Procedures?


Ans:
User-Defined Stored procedure: The user-defined stored procedures are created by
users and stored in the current database
system Stored Procedure: The system stored procedure has names prefixed with sp_.
It manages SQL Server through administrative tasks. Which databases store system
stored procedures are master and msdb database.

4. What is Parameter in Stored Procedures?


Ans:
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-24

5. What are the purposes and advantages of stored procedures?


Ans:
Purposes and advantages of stored procedures:
● Manage, control and validate data
● It can also be used for access mechanisms
● Large queries can be avoided
● Reduces network traffic since they need not be recompiled
● Even though the stored procedure itself may be a complex piece of code, we need not
write it over and over again. Hence stored procedures increase the reusability of code
● Permissions can be granted for stored procedures. Hence, increases security.

6. Determine when to use stored procedures to complete SQL Server tasks?


Ans:
● If a large piece of code needs to be performed repeatedly, stored procedures are ideal
● When hundreds of lines of SQL code need to be sent; it is better to use stored
procedure
through a single statement that executes the code in a procedure, rather than by
sending
hundreds of lines of code over the network.
● When security is required.

7. Explain About The Process Which Takes Place To Execute A Stored Routine?
Ans:
CREATE PROCEDURE and CREATE FUNCTION statements are used to create stored
routines. It can act as a function or a procedure. A procedure can be called by using a
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-24


call statement and passing output with the help of output variables. It can call other
Stored routines and it can be called from the inside of a statement.

8. Where The Procedures Are Stored In the Database?


Ans: A stored procedure is a subroutine available to applications accessing a relational
database system. Stored procedures (sometimes called a proc, sproc, StoPro, or SP)
are actually stored in the database data dictionary

9. Does Storing Of Data In Stored Procedures Increase The Access Time? Explain?
Ans: Data stored in stored procedures can be retrieved much faster than the data stored
in SQL database. Data can be precompiled and stored in Stored procedures. This
reduces the time gap between query and compiling as the data has been pre-compiled
and stored in the procedure. To avoid the repetitive nature of the database statement,
caches are used.

10. What Are The Uses Of Stored Procedure?


Ans: Stored procedures are often used for data validation and as access control
mechanisms. The logic applied in applications can be centralized and stored in
applications. Complex procedures and functionalities which require a huge amount of
data processing and logic implementation access their data by procedures. Data is
stored in these procedures and accessed by procedures.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-25

1. Developed a stored procedure to find the age of employees.


Input Parameter: EmpID
Table: DimEmployee
Ans:

Create procedure sp1


@EmpID int
as
begin
Select datediff(Year,BirthDate,getdate()) as Age,* from DimEmployee
where EmployeeKey=@EmpID
end
---To Execute
exec sp1 4

2. Developed a stored procedure to find the born year of the employee.


Input Parameter: EmpID
Ans:
Create procedure sp2
@EmpId int
as
begin
select year(birthdate) as BornYear,* from DimEmployee
where EmployeeKey=@EmpId
End
Go
--To execute
Exec sp2 1

3. Developed a stored procedure to find the born Day of the employee.


Ans:
Create procedure sp3
@EmpId int
as
begin
select Day(birthdate) as BornDay,* from DimEmployee
where EmployeeKey=@EmpId
End
Go
--To execute
Exec sp3 1
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-25


4. Developed a stored procedure to update YearlyIncome based on the below
condition based on EnglishEducation column
Input Parameter: CustomerKey, IncrementValue
Condition: Bachelors no update and Print Message - No Update for Bachelors
Ans:

Create procedure sp4(


@customerkey int ,
@increment_value int)
as
begin
Declare @EnglishEducation varchar(100)
Select @EnglishEducation = EnglishEducation from DimCustomer where CustomerKey
= @customerkey

If @EnglishEducation = 'Bachelors'
Begin
Print 'No update for Bachelors'
return
End
If @EnglishEducation <> 'Bachelors'
Begin
update DimCustomer set YearlyIncome =YearlyIncome+ @increment_value where
CustomerKey = @customerkey
End
--Display Result

Select * from DimCustomer where CustomerKey = @customerkey

end
Go
-- To execute

exec sp4 @customerkey=11015,@increment_value=10000

5. Developed a stored procedure to extract the values after ‘\’ on the LoginID
column. Example: for adventure-works\guy1 need to display only guy1
Ans:

Create procedure sp5


@empid int
as
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-25


begin
select substring(LoginId,charindex('\',LoginId)+1,Len(LoginId)) , * from DimEmployee
where EmployeeKey=@empId
end
Go
--- to execute
exec sp5 @empid= 2

6. Write a query to drop the stored procedure if already Exists.


Ans:

if Exists (Select null from sys.objects where name = 'WitoutparameterExp' and type = 'p')
drop proc WitoutparameterExp
go

7. Developed a Without parameter stored procedure and execute it.


Ans:

if Exists (Select null from sys.objects where name = 'WitoutparameterExp' and type = 'p')
drop proc WitoutparameterExp
go

Create procedure WitoutparameterExp


As
Begin

Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary


from EmployeeDetails ed
Inner Join EmpSalary e on e.EmpID = ed.EmpID

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID

End
go

--
exec WitoutparameterExp
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-25


8. How to check the code of the stored procedure?
Ans: Sp_helptext stored procedure Name
Example: Sp_helptext WitoutparameterExp

9. Developed a with parameter stored procedure and execute it.


Ans:
if Exists (Select 1 from sys.objects where name = 'parameterExp' and type = 'p')
drop proc parameterExp
go
Create procedure parameterExp(@EmpID int)
As
Begin

Set nocount on

Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary


from EmployeeDetails ed
Inner Join EmpSalary e on e.EmpID = ed.EmpID
Where ed.EmpID = @EmpID

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where ed.EmpID = @EmpID

set nocount off


End
go

--run the specedure


Exec parameterExp 3

Exec parameterExp @EmpID = 4


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-25


10. How can stop Rows affected message?
Example:

Ans:

Using Set nocount on and Set nocount off

Example:

if Exists (Select 1 from sys.objects where name = 'parameterExp' and type = 'p')
drop proc parameterExp
go
Create procedure parameterExp(@EmpID int)
As
Begin

Set nocount on

Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary


from EmployeeDetails ed
Inner Join EmpSalary e on e.EmpID = ed.EmpID
Where ed.EmpID = @EmpID

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where ed.EmpID = @EmpID

set nocount off


End
go
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26

1. Create Output parameter stored procedure and execute it. Take an example.
Ans:

CREATE TABLE tbl_Students

(
[Studentid] [int] IDENTITY(1,1) NOT NULL,
[Firstname] [nvarchar](200) NOT NULL,
[Lastname] [nvarchar](200) NULL,
[Email] [nvarchar](100) NULL
)

insert into tbl_Students (Firstname, lastname, Email)


Values('Vivek', 'Johari', 'vivek@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)


Values('Pankaj', 'Kumar', 'pankaj@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)


Values('Amit', 'Singh', 'amit@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)


Values('Manish', 'Kumar', 'manish@abc.comm')

Insert into tbl_Students (Firstname, lastname, Email)


Values('Abhishek', 'Singh', 'abhishek@abc.com')
go

Select * from tbl_Students

---Creating proc
if Exists (Select 1 from sys.objects where name = 'GetstudentnameInOutputVariable'
and type = 'p')
drop proc GetstudentnameInOutputVariable
go
Create PROC GetstudentnameInOutputVariable
(
@studentid INT, --Input parameter , Studentid of the student
@studentname VARCHAR(200) OUT -- Out parameter declared with the help of
OUT keyword
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname FROM tbl_Students WHERE
studentid=@studentid
END
Go

--execution
Declare @studentname VARCHAR(200)
Exec GetstudentnameInOutputVariable 2, @studentname output
select @studentname

2. Create Two Output parameter stored procedures and execute them. Take an
example.
Ans:

if Exists (Select 1 from sys.objects where name = 'GetstudentnameInOutputVariable' and


type = 'p')
drop proc GetstudentnameInOutputVariable
go
Create PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT, --Input parameter , Studentid of the student


@studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END

Go

-- execution
Declare @Studentname as nvarchar(200) -- Declaring the variable to collect the
Studentname
Declare @Studentemail as nvarchar(50) -- Declaring the variable to collect the
Studentemail
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


Execute GetstudentnameInOutputVariable 1 , @Studentname output, @Studentemail
output
select @Studentname,@Studentemail -- "Select" Statement is used to show the
output from Procedure
go

3. Develop a Stored procedure is used to Insert value into the table tbl_students.
Ans:

if Exists (Select 1 from sys.objects where name = 'InsertStudentrecord' and type = 'p')
drop proc InsertStudentrecord
go
Create Procedure InsertStudentrecord
(
@StudentFirstName Varchar(200),
@StudentLastName Varchar(200),
@StudentEmail Varchar(50)
)
As
Begin
Insert into tbl_Students (Firstname, lastname, Email)
Values(@StudentFirstName, @StudentLastName,@StudentEmail)
End
go

Exec InsertStudentrecord 'Mukesh','Pandey','mpandey@gmail.com'

4. How to call multiple stored procedures in single stored procedure? Explain with
real-time example?
Ans:
--1st Stored Procedure

if Exists (Select 1 from sys.objects where name = 'parameterExp1' and type = 'p')
drop proc parameterExp1
go
Create procedure parameterExp1(@EmpID int)
As
Begin
Set nocount on

Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary


from EmployeeDetails ed
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


Inner Join EmpSalary e on e.EmpID = ed.EmpID
Where ed.EmpID = @EmpID

set nocount off


End
go
exec parameterExp1 1

--2nd Stored Procedure

if Exists (Select 1 from sys.objects where name = 'parameterExp2' and type = 'p')
drop proc parameterExp2
go
Create procedure parameterExp2(@DeptID int)
As
Begin
Set nocount on

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where d.DepartID = @DeptID

set nocount off


End
go

---3rd Stored Procedure

if Exists (Select 1 from sys.objects where name = 'parameterExp3' and type = 'p')
drop proc parameterExp3
go
Create procedure parameterExp3(@EmpID int)
As
Begin
Set nocount on

declare @DeptID int

Select @DeptID = ed.DeptID


from EmployeeDetails ed
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where ed.EmpID = @EmpID

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where ed.EmpID = @EmpID

exec parameterExp1 @EmpID

exec parameterExp2 @DeptID

set nocount off


End
go

exec parameterExp3 3

5. Developed a stored procedure based on the below requirements.

1. Input parameter is Gender and must pass single value if user pass multiple
values or
Null or empty Values will pre-validate the SP and throw an error.
2. If TotalChildren column value is greater than or equal to 3 then update
YearlyIncome
with double

Ans:

If Exists (Select 1 from sys.objects where name = 'UpdatebyGender' and type = 'p')
drop proc UpdatebyGender
go

Create Proc dbo.UpdatebyGender(


@Gender varchar(10)
)
As
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


Begin

-- Validate Null or empty Values

if Isnull(@Gender,'') = ''
Begin
Print'Error.Null or Empty is the Invalid Parameter, Please must pass the Values Either
M or F'
return -- Stop exec the SP
end

-- Validate Multiple values


if CHARINDEX(',',@Gender)>0
Begin
Print'Erro.Invalid Parameter, Please must pass single value'
return
end

Create table #dimcustomer_dup (id int identity, Customerkey int, Yearlyincome money ,
Totalchildren int )
Insert into #dimcustomer_dup (Customerkey,Yearlyincome,Totalchildren)
Select Customerkey,Yearlyincome,Totalchildren
from dimcustomer_dup Where Gender = @Gender

create Clustered index IX_#dimcustomer_dup on #dimcustomer_dup(Customerkey)

Declare @min int, @max int,@Yearlyincome money, @Totalchildren int, @Customerkey


int

Select @min = min(ID), @max = max(ID) from #dimcustomer_dup

While @max >= @min


Begin

Select @Customerkey = Customerkey,@Yearlyincome = Yearlyincome,


@Totalchildren = Totalchildren from #dimcustomer_dup where id = @min

If @Totalchildren >=3
Begin
Update dimcustomer_dup
Set Yearlyincome = 2*@Yearlyincome
Where Customerkey = @Customerkey
end
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-26


Else
begin
Print cast(@Customerkey as Varchar(100))+ ' having less than three children.
And number of children having ' + cast( @Totalchildren as varchar(100))
End

Set @min = @min+1

end
--Insert into
#dimcustomer_Result(Customerkey,Yearlyincome_OLD,Yearlyincome_new,Totalchildren
)
select d.CustomerKey,t.Yearlyincome as
Previous_Yearlyincome,d.YearlyIncome as Updated_YearlyIncome,d.TotalChildren
from dimcustomer_dup d
Join #dimcustomer_dup t on t.Customerkey = d.CustomerKey

end
Go

Select * from dimcustomer_dup

Exec UpdatebyGender @Gender = 'M'


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27

1. Create a stored procedure to make Parameters Optional.


Ans:

If Exists (Select 1 from sys.objects where name = 'OptionalparameterExp' and type = 'p')
drop proc OptionalparameterExp
go
Create procedure OptionalparameterExp(
@EmpID int=Null
)
As
Begin

Set nocount on

If isNull(@EmpID,'') = ''
Begin
Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary
from EmployeeDetails ed
Inner Join EmpSalary e on e.EmpID = ed.EmpID

Select ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID

End
Else
Begin
Select ed.EmpID, e.EmpName,ed.DeptID,e.Empsalary
from EmployeeDetails ed
Inner Join EmpSalary e on e.EmpID = ed.EmpID
Where ed.EmpID = @EmpID

Select
ed.EmpID,ed.EmpName,Empsalary,ed.DeptID,d.DepartmentName
from EmployeeDetails ed
inner Join EmpSalary e on e.EmpID = ed.EmpID
Inner Join Department d on d.DepartID = ed.DeptID
Where ed.EmpID = @EmpID
End
set nocount off
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


End
go

Exec OptionalparameterExp null

2. Write a syntax to Transaction Management & Exception Handling in SQL.


Ans:
BEGIN TRY
-- Do something to throw an error
END TRY
BEGIN CATCH
-- Do something to handle the error
END CATCH

3. How to validate parameters in Stored Procedure?


Ans:

if Exists (Select 1 from sys.objects where name = 'EnglishEduCount' and type = 'p')
drop proc EnglishEduCount
go
Create proc EnglishEduCount (@Englisheducation varchar(100))
as
begin

--checking if Multiple values pass by the user

if charindex(',',@Englisheducation) > 0
begin
Print 'Error.Please must supply single value.'
return
End

if not exists(Select 1 from DimCustomer where EnglishEducation = @Englisheducation)


begin
Print'Error.Must pass the correct values and values shoud be used High
School,Partial High School,Partial College,Graduate Degree and Bachelors '
--Select Distinct EnglishEducation from DimCustomer
return
end
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


Select EnglishEducation, count(CustomerKey) as Totalcount from DimCustomer
group by EnglishEducation
having EnglishEducation = @Englisheducation
End

4. Develop a stored procedure based on the below requirements.


1. Input parameter is Gender and must pass single value if the user passes
multiple values than will pre-validate the SP and throw an error.
2. If TotalChildren column value is greater than or equal to 3 than update
YearlyIncome with double
Ans:

Create Proc dbo.UpdatebyGender(


@Gender varchar(10)
)
As
Begin

if CHARINDEX(',',@Gender)>0
Begin
Print'Invalid Parameter'
return
end

Create table #dimcustomer_dup (id int identity, Customerkey int, Yearlyincome money ,
Totalchildren int )
Insert into #dimcustomer_dup (Customerkey,Yearlyincome,Totalchildren)
Select Customerkey,Yearlyincome,Totalchildren
from dimcustomer_dup Where Gender = @Gender

create index IX_#dimcustomer_dup on #dimcustomer_dup(Customerkey)

--Create table #dimcustomer_Result (Customerkey int, Yearlyincome_OLD money


,Yearlyincome_new money, Totalchildren int )

Declare @min int, @max int,@Yearlyincome money, @Totalchildren int, @Customerkey int

Select @min = min(ID), @max = max(ID) from #dimcustomer_dup

While @max >= @min


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


Begin
--set @Customerkey = null
Set @Yearlyincome = null
set @Totalchildren = null
Select @Customerkey = Customerkey,@Yearlyincome = Yearlyincome,@Totalchildren =
Totalchildren from #dimcustomer_dup where id = @min

If @Totalchildren >=3
Begin
BEGIN TRY
BEGIN TRANSACTION
--SELECT 1/0
----update statement
Update dimcustomer_dup
Set Yearlyincome = 2*@Yearlyincome
Where Customerkey = @Customerkey

commit transaction

Print'Script updated seccessfully'

End Try
Begin Catch
Rollback Tran
Print ' ERNumber: ' + CAST(ERROR_NUMBER() as varchar)
Print ' Error_Severity: ' + CAST(ERROR_SEVERITY() as varchar)
Print ' Error_State : ' + CAST(ERROR_STATE() as varchar)
Print ' Error_Procedure: ' + CAST(ERROR_PROCEDURE() as
varchar(500))
Print ' Error_Line : ' + CAST(ERROR_LINE() as varchar)
Print ' Error_Message:' + CAST(ERROR_MESSAGE()as varchar(500))
End Catch

end
Else
begin
Print'Customer having less than three children. And number of children having' +
cast( @Totalchildren as varchar(100))
End

Set @min = @min+1


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


end
--Insert into
#dimcustomer_Result(Customerkey,Yearlyincome_OLD,Yearlyincome_new,Totalchildren)
select d.CustomerKey,t.Yearlyincome,d.YearlyIncome,d.TotalChildren
from dimcustomer_dup d
Join #dimcustomer_dup t on t.Customerkey = d.CustomerKey

end
Go

Select * from dimcustomer_dup

Exec UpdatebyGender 'M'

5. Developed a stored procedure to take the data from the CSV file and update a core
table using the dynamic SQL concept.
Ans:

-- Update table using file

if exists (Select null from dbo.SysObjects where name = N'UpdateTable_UsingFile' and


type = N'P')
Begin
Drop Proc dbo.UpdateTable_UsingFile
End
Go

Create Procedure dbo.UpdateTable_UsingFile(


@SourcePath Nvarchar(4000))
As
Begin

Declare @SQL NVARCHAR(4000),@DT datetime

Set @DT = GetUTCdate()

if object_id('tempdb..#tmpFileData') is not null drop table #tmpFileData


Create table #tmpFileData(EmployeeKey int,FirstName Varchar(400), LastName
Varchar(400),Phone bigint)
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


Set @sql = 'BULK INSERT #tmpFileData FROM ''' + @SourcePath + ''' WITH (
FIRSTROW = 2,DATAFILETYPE = ''char'',FIELDTERMINATOR = '','',
ROWTERMINATOR =''\n'' )'
EXEC(@sql)

--select * from #tmpFileData

BEGIN TRY
BEGIN TRAN

Update e
set e.Phone = t.Phone
from dimemployee e
Join #tmpFileData t on t.EmployeeKey = e.EmployeeKey

Commit Tran

End Try
Begin Catch
Rollback Tran
Print ' ERNumber: ' + CAST(ERROR_NUMBER() as varchar)
Print ' Error_Severity: ' + CAST(ERROR_SEVERITY() as
varchar)
Print ' Error_State : ' + CAST(ERROR_STATE() as varchar)
Print ' Error_Procedure: ' + CAST(ERROR_PROCEDURE() as
varchar(500))
Print ' Error_Line : ' + CAST(ERROR_LINE() as varchar)
Print ' Error_Message:' + CAST(ERROR_MESSAGE()as
varchar(500))
End Catch

--Output
Select *
from DimEmployee e
Join #tmpFileData t on t.EmployeeKey = e.EmployeeKey

End

Go
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-27


Exec dbo.UpdateTable_UsingFile
@SourcePath = 'E:\Youtube\Crack SQL Interview\Using Dynamic Query to update
table\Test1.csv' -- change path here
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


1. What are User-Defined Functions?
Ans: Like functions in programming languages, SQL Server user-defined functions are
routines that accept parameters, perform an action, such as a complex calculation, and
return the result of that action as a value. The return value can either be a single scalar
value or a result set.

2. Why use user-defined functions?


Ans:
● They allow modular programming.
You can create the function once, store it in the database, and call it any number of
times in your program. User-defined functions can be modified independently of the
program source code.
● They allow faster execution.
Similar to stored procedures, Transact-SQL user-defined functions reduce the
compilation cost of Transact-SQL code by caching the plans and reusing them for
repeated executions. This means the user-defined function does not need to be
reparsed and reoptimized with each use resulting in much faster execution times.
CLR functions offer a significant performance advantage over Transact-SQL functions
for computational tasks, string manipulation, and business logic. Transact-SQL functions
are better suited for data-access intensive logic.
● They can reduce network traffic.
An operation that filters data based on some complex constraint that cannot be
expressed in a single scalar expression can be expressed as a function. The function
can then be invoked in the WHERE clause to reduce the number of rows sent to the
client.

3. Explain the types of functions in SQL?


Ans:
1. Scalar Function: User-defined scalar functions return a single data value of the type
defined in the RETURNS clause. For an inline scalar function, the returned scalar value
is the result of a single statement. For a multistatement scalar function, the function body
can contain a series of Transact-SQL statements that return a single value. The return
type can be any data type except text, text, image, cursor, and timestamp.
2. Inline Table-valued Function: The user-defined inline table-valued function returns a
table variable as a result of actions performed by the function. The value of the table
variable should be derived from a single SELECT statement.
3. Multi-Statement Table-Valued Function: The user-defined multi-statement
table-valued function returns a table variable as a result of actions performed by the
function. In this, a table variable must be explicitly declared and defined whose value
can be derived from multiple SQL statements.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


4. Write a function that takes one input value, a ProductID, and returns a single data
value, the aggregated quantity of the specified product in inventory.
Ans:

IF OBJECT_ID (N'dbo.ufnGetInventoryStock', N'FN') IS NOT NULL


DROP FUNCTION ufnGetInventoryStock;
GO
CREATE FUNCTION dbo.ufnGetInventoryStock(@ProductID int)
RETURNS int
AS
-- Returns the stock level for the product.
BEGIN
DECLARE @ret int;
SELECT @ret = SUM(p.Quantity)
FROM Production.ProductInventory p
WHERE p.ProductID = @ProductID
AND p.LocationID = '6';
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;
Go

Select dbo.ufnGetInventoryStock(ProductID ),* from Production.ProductInventory

5. Create a function to get emp full name?


Ans:

Create function fnGetEmpFullName


(
@FirstName varchar(50),
@LastName varchar(50)
)
returns varchar(101)
As
Begin
return (Select @FirstName + ' '+ @LastName);
End

--Calling the above created function


Select dbo.fnGetEmpFullName(FirstName,LastName) as FullName, * from Employee
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


Select dbo.fnGetEmpFullName(FirstName,LastName) as FullName,* from DimEmployee

6. Develop a The function takes one input parameter, a customer (store) ID, and
returns the columns ProductID, Name, and the aggregate of year-to-date sales as
YTD Total for each product sold to the store.
Ans:

IF OBJECT_ID (N'Sales.ufn_SalesByStore', N'IF') IS NOT NULL


DROP FUNCTION Sales.ufn_SalesByStore;
GO
CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)
RETURNS TABLE
AS
RETURN
(
SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'Total'
FROM Production.Product AS P
JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID
JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID
JOIN Sales.Customer AS C ON SH.CustomerID = C.CustomerID
WHERE C.StoreID = @storeid
GROUP BY P.ProductID, P.Name
);
go
SELECT * FROM Sales.ufn_SalesByStore (602);

7. Developed a function that takes a single input parameter, an EmployeeID, and


returns a list of all the employees who report to the specified employee directly or
indirectly.
Ans:

IF OBJECT_ID (N'dbo.ufn_FindReports', N'TF') IS NOT NULL


DROP FUNCTION dbo.ufn_FindReports;
GO
CREATE FUNCTION dbo.ufn_FindReports (@InEmpID INTEGER)
RETURNS @retFindReports TABLE
(
EmployeeID int primary key NOT NULL,
FirstName nvarchar(255) NOT NULL,
LastName nvarchar(255) NOT NULL,
JobTitle nvarchar(50) NOT NULL,
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


RecursionLevel int NOT NULL
)
--Returns a result set that lists all the employees who report to the
--specific employee directly or indirectly.*/
AS
BEGIN
WITH EMP_cte(EmployeeID, OrganizationNode, FirstName, LastName, JobTitle,
RecursionLevel) -- CTE name and columns
AS (
SELECT e.BusinessEntityID, e.OrganizationNode, p.FirstName, p.LastName,
e.JobTitle, 0 -- Get the initial list of Employees for Manager n
FROM HumanResources.Employee e
INNER JOIN Person.Person p
ON p.BusinessEntityID = e.BusinessEntityID
WHERE e.BusinessEntityID = @InEmpID
UNION ALL
SELECT e.BusinessEntityID, e.OrganizationNode, p.FirstName, p.LastName,
e.JobTitle, RecursionLevel + 1 -- Join recursive member to anchor
FROM HumanResources.Employee e
INNER JOIN EMP_cte
ON e.OrganizationNode.GetAncestor(1) = EMP_cte.OrganizationNode
INNER JOIN Person.Person p
ON p.BusinessEntityID = e.BusinessEntityID
)
-- copy the required columns to the result of the function
INSERT @retFindReports
SELECT EmployeeID, FirstName, LastName, JobTitle, RecursionLevel
FROM EMP_cte
RETURN
END;
GO

SELECT EmployeeID, FirstName, LastName, JobTitle, RecursionLevel


FROM dbo.ufn_FindReports(1);

8. Create a function to update EmailAddress of a combination of the first letter of the


first name and all letters of the Last name in lower case.
Ans:

Create function UpdateEmailAddress


(
@CutomerKey int
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


)
returns varchar(2000)
As
Begin
Declare @email varchar(2000), @Login varchar(100)
set @Login = null
Select @Login = Lower(left(FirstName,1)) + Lower(LastName) from DimCustomer where
Customerkey = @CutomerKey
Select @email = Stuff(EmailAddress,1,CHARINDEX('@a',EmailAddress)-1,@Login)
from DimCustomer where Customerkey = @CutomerKey

return @email;
End

Select dbo.UpdateEmailAddress(11001)

9. Create a function to Function to split string into rows


Input: '123,456,678,876' or '123|456|678|876'
Output:
Values
123
456
678
876

Ans:

if exists (Select null from dbo.SysObjects where name = N'cfn_BreakStringIntoRows'


and type in ('F', 'TF'))
Begin
Drop function dbo.cfn_BreakStringIntoRows
End
Go

Create function dbo.cfn_BreakStringIntoRows (@CommadelimitedString varchar(max),


@SplitChar char(1))
returns @Result table (Value nVarchar(4000))
As
Begin
Declare @IntLocation int
While (CharIndex(@SplitChar, @CommadelimitedString, 0) > 0)
Begin
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


Set @IntLocation = CharIndex(@SplitChar, @CommadelimitedString, 0)
Insert into @Result(Value)
--LTRIM and RTRIM to ensure blank spaces are removed
Select rtrim(ltrim(SubString(@CommadelimitedString,0,@IntLocation)))
Set @CommadelimitedString = Stuff(@CommadelimitedString, 1,
@IntLocation, '')
End

Insert into @Result (Value)


Select rtrim(ltrim(@CommadelimitedString))--LTRIM and RTRIM to ensure blank
spaces are removed
return
End
Go

10. Write a stored procedure to call a function in the procedure.


Ans:

if exists (Select null from dbo.SysObjects where Name =


N'UpdateEmailAddress_MultipleParameter' and Type = N'P')
Drop Proc dbo.UpdateEmailAddress_MultipleParameter
Go

Create proc UpdateEmailAddress_MultipleParameter


(
@CustomerKey Varchar(4000)
)
As
Begin
Set nocount on
-- Store all parameter values
Create table #ParameterID (CustomerKey Int)
Insert into #ParameterID
Select distinct Value from dbo.cfn_BreakStringIntoRows(@CustomerKey,',')

Create index IX_#ParameterID on #ParameterID(CustomerKey)

-- If Customer Key name not found or invalid customer key used.


if exists (Select null from #ParameterID t
left join DimCustomer d on d.CustomerKey = t.CustomerKey
where d.CustomerKey is null)
Begin
Print 'Error. CustomerKey provided is not valid.'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-28


return
End

BEGIN TRY
BEGIN TRAN

Update d
Set d.EmailAddress = dbo.UpdateEmailAddress(d.CustomerKey)
from DimCustomer d
Join #ParameterID t on t.CustomerKey = d.CustomerKey

commit transaction
End Try
Begin Catch
Rollback Tran
Print ' ERNumber: ' + CAST(ERROR_NUMBER() as varchar)
Print ' Error_Severity: ' + CAST(ERROR_SEVERITY() as varchar)
Print ' Error_State : ' + CAST(ERROR_STATE() as varchar)
Print ' Error_Procedure: ' + CAST(ERROR_PROCEDURE() as
varchar(500))
Print ' Error_Line : ' + CAST(ERROR_LINE() as varchar)
Print ' Error_Message:' + CAST(ERROR_MESSAGE()as varchar(500))
End Catch

--Print Result
Select *
from DimCustomer d
Join #ParameterID t on t.CustomerKey = d.CustomerKey
Set nocount off
End
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-29

1. What are the differences between functions and procedures in SQL Server?
Ans:

Stored Procedures are pre-compiled objects which are compiled for the first time and its
compiled format is saved which executes (compiled code) whenever it is called. But Function is
compiled and executed every time when it is called.

BASIC DIFFERENCE

1. The function must return a value but in Stored Procedure, it is optional (Procedure can
return zero or n values).
2. Functions can have only input parameters whereas Procedures can have input/output
parameters.
3. A Function can be called from Procedure whereas Procedures cannot be called from
Function
4. From a procedure, we can call another procedure or a function whereas from a function
we can call another function but not a procedure.

ADVANCE DIFFERENCE

1. The procedure allows SELECT as well as DML (INSERT/UPDATE/DELETE) statement


in it whereas Function allows only SELECT statement in it.
2. Procedures cannot be utilized in a SELECT statement whereas Function can be
embedded in a SELECT statement.
3. Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section whereas Function can be.
4. Functions that return tables can be treated as a row set. This can be used in JOINs with
other tables
5. The exception can be handled by a try-catch block in a procedure whereas a try-catch
block cannot be used in a Function.
6. We can go for Transaction Management in Procedure whereas we can’t go into
Function.
7. We call a procedure using EXECUTE/ EXEC command whereas a function is called by
using the SELECT command only.
8. Stored procedures support deferred name resolution. For example, while writing a stored
procedure that uses table names, for example, table1, table2, etc. but these tables do
not exist in the database is allowed during the creation of the stored procedure but
runtime throws error whereas functions do not support deferred name resolution.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-29

2. What is Trigger?

Ans: The trigger is a piece of procedural code, like a stored procedure that is only executed
when a given event happens. There are different types of events that can fire a trigger. Just to
name a few, the insertion of rows in a table, a change in a table structure, and even a user
logging into a SQL Server instance.

3. What are the main characteristics of trigger?

Ans: There are three main characteristics that make triggers different than stored procedures:

● Triggers cannot be manually executed by the user.

● There is no chance for triggers to receive parameters.

● You cannot commit or roll back a transaction inside a trigger.

The fact that it's impossible to use parameters on triggers is not a limitation to receiving
information from the firing event. As you will see further on, there are alternatives to obtain
information about the firing event.

4. How many classes of triggers are in SQL Server?

Ans: There are two classes of triggers in SQL Server:

● DDL (Data Definition Language) triggers. This class of triggers fires upon eventsthat change
the structure (like creating, modifying, or dropping a table), or in certain server-related events
like security changes or statistics update events.

● DML (Data Modification Language) triggers. This is the most used class of triggers. In this
case, the firing event is a data modification statement; it could be an insert, update or delete
statement either on a table or a view.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-29


5. How many types of DML Triggers?

Ans: DML triggers have different types:

● FOR or AFTER [INSERT, UPDATE, DELETE]: These types of triggers are executed

after the firing statement ends (either an insert, update or delete).

● INSTEAD OF [INSERT, UPDATE, DELETE]: Contrary to the FOR (AFTER) type, the

INSTEAD OF triggers executes instead of the firing statement. In other words,

this type of trigger replaces the firing statement. This is very useful in cases

where you need to have cross-database referential integrity.

6. What is The Importance of SQL Server Triggers?

Ans: One of the fundamental characteristics of relational databases is data consistency. This

means that the information stored in the database must be consistent at all times for

every session and every transaction. The way relational database engines like SQL

Server implement this is by enforcing constraints like primary keys and foreign keys. But

sometimes that is not enough.

7. How Do I Know Which Rows Were Updated, Inserted, or Deleted using a SQL Server
DML Trigger?

Ans:

In the case of DML triggers, there are two virtual tables during the execution of the

trigger that holds the data being affected by the trigger execution. Those tables are

named inserted and deleted and they have the same table structure as their base table.

Something to keep in mind is that the inserted and deleted tables are not always

available together (i.e. you can have the inserted table, but not the deleted table or vice versa).
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-29

8. What is the SQL Server Trigger Usage Scenarios?

Ans: There are two clear scenarios when triggers are the best choice: auditing and enforcing

business rules. By using a trigger, you can keep track of the changes on a given table by

writing a log record with information about who made the change and what was

changed in the table.

9. What is MAGIC TABLE in triggers?

Ans: These are the special kind of table which is created inside of a trigger when we perform insert,
update and delete operations. The Magic tables are invisible tables or virtual tables. We can see them
only with the help of TRIGGERS in SQL Server. The Magic tables are those tables that allow us to hold
INSERTED, DELETED, and UPDATED values during insert delete and update DML operations on a table
in SQL Server.

Basically, there are two types of magic tables in SQL Server namely INSERTED and DELETED magic
table.

10. How can Enabled or Disabled Trigger in SQL?

Ans:

All the triggers can be enabled/disabled on the table using the statement:

Enable all Triggers: ALTER TABLE Employee_Test ENABLE TRIGGER ALL

Disable all Triggers: ALTER TABLE Employee_Test DISABLE TRIGGER All

ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-29


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-30

1. List out the SQL Server Performance Tuning Tips which need to follow to increase
the performance of code.
Ans:

1. Never use Select * Statement - Need to use all required column names.
2. USE Common Table Expressions (CTEs) instead of Temp table: We should prefer a
CTE over the temp table because temp tables are stored physically in a TempDB which
is deleted after the session ends. While CTEs are created within memory. Execution of
CTE is very fast as compared to the temp tables and very lightweight too
3. Use UNION ALL instead of UNION.
4. Use Count (1) instead of Count (*) and Count (Column_Name).
5. Use Stored Procedure.
6. Use Between instead of In.
7. Never Use ” Sp_” for User Define Stored Procedure
8. Practice using Schema Name: Select EMPID from dbo.employee,
Exex dbo.UpdateTable_UsingFile
9. Try to Avoid Cursors - use while loop.
10. SET NOCOUNT ON.
11. Use Try–Catch.
12. Remove Unused Index.
13. Always create an index on the table.
14. Use Alias Name.
15. Use Transaction Management.
16. Use the correct Index Name format while creating an index.
17. Drop Index before Bulk Insertion of Data.
18. Avoid Loops in Coding.
19. Avoid Correlated sub-Query or Sub Queries, use join instead of Subquery.
20. Minimize the number of Join.

2. What are ACID Properties?


Ans:
Atomic(ity) - The principle that each transaction is 'all-or-nothing', i.e., it either succeeds
or it fails, regardless of external factors such as power loss or corruption. On failure or
success, the database is left in either the state in which it was in prior to the transaction
or a new valid state. The transaction becomes an indivisible unit.
Consistency - The principle that the database executes transactions in a consistent
manner, obeying all rules (constraints).
Isolation - This property means that each transaction is executed in isolation from
others and that concurrent transactions do not affect the transaction. SQL Server has
five levels of transaction isolation depending on the requirements of the database.
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-30


Durability - This property means that the data written to the database is durable, i.e. it is
guaranteed to be in storage and will not arbitrarily be lost, changed, or overwritten unless
specifically requested. More formally, it means that once a transaction is committed, no
event can 'un-commit' the transaction - it is written and cannot be changed
retrospectively unless by another transaction.

3. What is Dirty Read?


Ans: A Dirty read is a situation when a transaction reads data that has not yet
been committed. For example, Let’s say transaction 1 updates a row and leaves it
uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls
back the change, transaction 2 will have read data that is considered never to have
existed.

4. What is Non Repeatable read?


Ans: Non Repeatable read occurs when a transaction reads the
same row twice and gets a different value each time. For example, suppose
transaction T1 reads data. Due to concurrency, another transaction T2 updates the
same data and commit, Now if transaction T1 rereads the same data, it will retrieve a
different value.

5. What is Phantom Read?


Ans: Phantom Read occurs when two same queries are executed, but the
rows retrieved by the two, are different. For example, suppose transaction T1 retrieves
a set of rows that satisfy some search criteria. Now, Transaction T2 generates some
new rows that match the search criteria for transaction T1. If transaction T1
re-executes the statement that reads the rows, it gets a different set of rows this time.

6. What is Deadlock?
Ans: A deadlock occurs when 2 processes are competing for exclusive access to a
resource but is unable to obtain exclusive access to it because the other process is
preventing it. This results in a standoff where neither process can proceed. The only way
out of a deadlock is for one of the processes to be terminated. SQL Server automatically
detects when deadlocks have occurred and take action by killing one of the processes
known as the victim.

7. How do I know if I have a deadlock?


Ans: the first sign you will have of a deadlock is the following error message which will
be displayed to the user who owns the process that was selected as the deadlock victim.

Msg 1205, Level 13, State 51, Line 6


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-30


Transaction (Process ID 62) was deadlocked on lock resources with another process and
has been chosen as the deadlock victim. Rerun the transaction.

The other user whose process was not selected as the victim will be most likely be completely
unaware that their process participated in a deadlock.

8. How SQL Server handles deadlocks?


Ans: The lock manager in SQL Server automatically searches for deadlocks, this
thread which is called the LOCK_MONITOR looks for deadlocks every 5 seconds. It
looks at all waiting locks to determine if there are any cycles. When it detects a deadlock
it chooses one of the transactions to be the victim and sends a 1205 error to the client
which owns the connection. This transaction is then terminated and rolled back which
releases all the resources on which it held a lock, allowing the other transaction involved
in the deadlock to continue.

If there are a lot of deadlocks SQL Server automatically adjusts the frequency of the deadlock
search, and back up to 5 seconds if deadlocks are no longer as frequent.

9. How does SQL Server choose the victim?


Ans:
There are a couple of factors that come into play here. The first is the deadlock priority.
The deadlock priority of a transaction can be set using the following command:

SET DEADLOCK_PRIORITY LOW;


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-30

10. How to minimize deadlocks


Ans:

Here are a couple of tips to minimize deadlocks

1. Always try to hold locks for as short a period as possible.


2. Always access resources in the same order
3. Ensure that you don’t have to wait on user input in the middle of a transaction. First, get
all the information you need and then submit the transaction
4. Try to limit lock escalation, by using hints such as ROWLOCK etc
5. Use READ COMMITTED SNAPSHOT ISOLATION or SNAPSHOT ISOLATION
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-31


1. Given a table SELLERS with 3 column SELLER_ID, COUNTRY, and
JOINING_DATE, write a query to identify a number of sellers per country and order
it in descending order of no. of sellers.
Ans:
Create table SELLERS(SELLER_ID int identity(1,1),COUNTRY varchar(100),JOINING_DATE
datetime)

Declare @a int, @b int

Set @a = 1
Set @b = 1000

While @a<= @b
Begin
Insert into SELLERS(JOINING_DATE)
Select GETDATE()+@a
Set @a = @a+1
End

Select * from SELLERS

Update SELLERS
Set COUNTRY = 'India'
Where SELLER_ID between 1 and 300

Update SELLERS
Set COUNTRY = 'USA'
Where SELLER_ID between 301 and 600

Update SELLERS
Set COUNTRY = 'UK'
Where SELLER_ID between 601 and 900

Update SELLERS
Set COUNTRY = 'SA'
Where SELLER_ID between 901 and 1000

Select * from SELLERS

--1.

Select COUNTRY,count(SELLER_ID) as number_Of_sellers from SELLERS


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-31


Group by COUNTRY
order by 2 desc

2. For the table in question 1 write a query to extract all sellers who joined on a
Monday.
Ans: Select Datename(MONTH,JOINING_DATE), * from SELLERS where
Datename(MONTH,JOINING_DATE) = 'December'

3. Given a table EMPLOYEE with two columns EMP_ID and SALARY, how can we
extract alternate rows from a table?
Ans:

Select row_number() over (order by empid desc) as Ranking ,* into #test from
EmployeeTest

Select * from #test where Ranking%2<>0

4. find distinct values without using distinct keywords?


Ans:
Select * from (Select *, row_number() over (Partition by
EmpID,EmpName,Empsalary,DeptID order by empid desc) as Ranking
from EmpSalary) k where k.Ranking>1

5. Given a table EMPLOYEE with two columns EMP_ID and SALARY, extract the
employees with the 3rd highest salary.
Ans:

Select dense_rank() over (order by Salary desc) as Ranking ,* into #test4 from
EmployeeTest

Select * from #test4 where Ranking=3

6. What is wrong with this SQL query? Correct it so it executes properly.


SELECT SELLER_ID, YEAR(JOINING_DATE) BILLINGYEAR
FROM SELLERS
WHERE JOINING_DATE >= 2010;

Ans: it's correct.


https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-31


7. Assume a schema of EMP ( ID, NAME, DEPTID ) , DEPT ( ID, NAME).
If there are 10 records in the EMP table and 5 records in the DEPT table, how many
rows will be displayed in the result of the following SQL query:
SELECT * FROM EMP, DEPT

Ans:

If Exists ( Select null from Sysobjects Where Name = 'Department' and type = 'U')
Drop table Department

CREATE TABLE Department


(
DepartID int,
DepartmentName VARCHAR(30)
)

Insert Into Department(DepartID,DepartmentName) values (1,'IT')


Insert Into Department(DepartID,DepartmentName) values (2,'HR')
Insert Into Department(DepartID,DepartmentName) values (3,'Marketing')
Insert Into Department(DepartID,DepartmentName) values (4,'Operation')
Insert Into Department(DepartID,DepartmentName) values (5,'Admin')

If Exists ( Select null from Sysobjects Where Name = 'EmployeeDetails' and type = 'U')
Drop table EmployeeDetails

CREATE TABLE EmployeeDetails


(
EmpID INT ,
EmpName VARCHAR(80),
DeptID INT
)

Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (1,'Ram',1)


Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (2,'Sohan',2)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (3,'Rohan',3)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (4,'Shareen',4)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (5,'Mukesh',6)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (6,'Rakesh',null)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (7,'Mohan',5)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (8,'Shyam',3)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (9,'Ghnashayam',4)
Insert into EmployeeDetails (EmpID,EmpName,DeptID) Values (10,'Radhe',7)
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/

SQL Questions Set-31


SELECT * FROM EmployeeDetails, Department

8. Consider a table EMPLOYEE with columns EMP_ID and SALARY with unknown
number of records. Write a query to extract top 25% of the records based on
salary?
Ans:

select DENSE_RANK() over (order by yearlyincome desc) As Rank_Test,* into test8


from dimcustomer

declare @max int

Select @max = (max(Rank_Test)/4) from test8

Select * from test8 where Rank_Test between 1 and @max

9. Consider a table EMPLOYEE with columns EMP_ID, DEPT_NO, and SALARY. Write
a query to extract all employees who have
salaries higher than the avg. of their department.
Ans:

select *
from EmployeeTest e
Join (Select Department,Avg(salary) as AVGSalary from EmployeeTest
Group by Department) s on s.Department = e.Department
where e.salary>s.AVGSalary

10. Consider a table EMPLOYEE with columns EMP_ID and SALARY. Write a select
query to output a rank against each record. The rank must be based on the
salary(rank 1 for the highest salary)
Ans:

Select dense_rank() over (order by Salary desc) as Ranking ,* from EmployeeTest

You might also like