Professional Documents
Culture Documents
Ilovepdf Merged Merged
Ilovepdf Merged Merged
Ilovepdf Merged Merged
com/
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.
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.
Model Database:
MSDB Database: It is used by SQL server agents for scheduling alerts and
jobs
Tempdb Database:
● 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
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/
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.
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/
NVARCHAR:
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
*/
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
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;
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/
Ans:
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
SCOPE_IDENTITY is:
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
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.
There are some rules of database normalization, which is commonly known as Normal
From, and they 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/
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 the difference between Primary key and Unique Key Constraint?
Ans:
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/
1. Write a SQL query to create a Courses table with the following column and insert some
data and create constraints.
Apply the Primary Key with the identity on CourseID and Apply Not null on
CourseName.
Ans:
);
2. Create a Student table with the following columns and insert some data and create
constraints.
Apply Not null on RollNumber and RollNumber should always be greater than 500.
Ans:
);
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/
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.
Ans:
amountpaid int,
amountdue int
);
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/
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)
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/
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))
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'
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/
10. Explain one real time scenario of ISNULL and Null Function?
Ans:
Update DimCustomer set MiddleName = '' where CustomerKey between 11010 and
11040
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'
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
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/
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 @@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/
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/
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
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:
Update DimCustomer
Set FullName = FirstName+' '+LastName
Where Gender = 'M'
https://www.youtube.com/c/pandeyguruji One-to-one Training:https://pandeyguruji.graphy.com/
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/
6. Find the average UnitPrice of each SalesOrder and sort the data in descending
order based on SalesOrderNumber.(FactInternetSales)
Ans:
8. Find the list of Customers who purchase more than one product.
(FactInternetSales).
Ans:
9. Find the list of product information which paid the 10th highest tax
amount.(FactInternetSales).
Ans:
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:
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/
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.
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.
2. What is @@FETCH_STATUS?
Ans: Returns the status of the last cursor FETCH statement issued against any cursor
currently opened by the connection.
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
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/
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
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);
OPEN emp_cursor
WHILE @@FETCH_STATUS = 0
BEGIN
print ' ' + CAST(@EmployeeKey as varchar(10)) +' '+ cast(@FirstName
as varchar(20))+' '+ cast(@LastName as varchar(20))
END
CLOSE emp_cursor;
DEALLOCATE emp_cursor;
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/
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.
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
end
Go
-- To execute
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:
if Exists (Select null from sys.objects where name = 'WitoutparameterExp' and type = 'p')
drop proc WitoutparameterExp
go
if Exists (Select null from sys.objects where name = 'WitoutparameterExp' and type = 'p')
drop proc WitoutparameterExp
go
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/
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 ed.EmpID = @EmpID
Ans:
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,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
1. Create Output parameter stored procedure and execute it. Take an example.
Ans:
(
[Studentid] [int] IDENTITY(1,1) NOT NULL,
[Firstname] [nvarchar](200) NOT NULL,
[Lastname] [nvarchar](200) NULL,
[Email] [nvarchar](100) NULL
)
---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/
--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:
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/
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
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
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
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
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 parameterExp3 3
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
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
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
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/
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
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/
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
if charindex(',',@Englisheducation) > 0
begin
Print 'Error.Please must supply single value.'
return
End
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
Declare @min int, @max int,@Yearlyincome money, @Totalchildren int, @Customerkey int
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
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
end
Go
5. Developed a stored procedure to take the data from the CSV file and update a core
table using the dynamic SQL concept.
Ans:
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/
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:
return @email;
End
Select dbo.UpdateEmailAddress(11001)
Ans:
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/
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
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.
Ans: There are three main characteristics that make triggers different than stored procedures:
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.
● 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/
● FOR or AFTER [INSERT, UPDATE, DELETE]: These types of triggers are executed
● INSTEAD OF [INSERT, UPDATE, DELETE]: Contrary to the FOR (AFTER) type, the
this type of trigger replaces the firing statement. This is very useful in cases
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
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/
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
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.
Ans:
All the triggers can be enabled/disabled on the table using the statement:
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.
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.
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.
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.
Set @a = 1
Set @b = 1000
While @a<= @b
Begin
Insert into SELLERS(JOINING_DATE)
Select GETDATE()+@a
Set @a = @a+1
End
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
--1.
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
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
Ans:
If Exists ( Select null from Sysobjects Where Name = 'Department' and type = 'U')
Drop table Department
If Exists ( Select null from Sysobjects Where Name = 'EmployeeDetails' and type = 'U')
Drop table EmployeeDetails
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:
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: