SQL Server Database Interview Questions and Answers

SQL Server Database Interview Questions and Answers

1) You have two columns in source table in which the col1 may contain duplicate values, All the duplicate values in col2 will be transformed as comma separated in the column col2 of target table Answer --Select Query in table
Query: select * from tbl1 

col1col2
ax    
by    
cz    
am    
bn    
Solution:

Select col1, STRING_AGG(col2,',') Result 

from tbl1 group by col1  --OR 

select col1, STRING_AGG (col2,',') WITHIN GROUP (ORDER BY col2 ) Result from tbl1 group by col1 

Output:
col1Result
ax    ,m    
bn    ,y    
cz    

2) Reading a source file with salary prefix $, in the target the Sal column must store in number.
Answer:
select * from source;

empnoenamejobmanageridfiredatesalarydeptno
7369SmithClerk790212/17/1980$80020
7499AllenSalesman76982/12/1981$1,30030

select *, replace (salary,'$','') salary_without_$ from source
Output:
empnoenamejobmanageridfiredatesalarydeptnosalary_without_$
7369SmithClerk790212/17/1980$80020800
7499AllenSalesman76982/12/1981$1,300301300

Date: - 20-02-2022 
3) How to produce rows in target table with every row as sum of all previous rows in source table? 
Answer: 
select * from prerowsum;
idsal
1200
2300
3500
4560

Solution:
select t1.id, sum(t2.sal) Total_Sum--, t1.id,t1.sal,t2.sal 
from prerowsum t1 
inner join prerowsum t2 on t1.id>=t2.id 
group by t1.id 

--OR 

select id,sal,sum(sal) over(order by id)  Next_Sal
from prerowsum;

--OR 

with t1 as (
select id ,sal,ISNULL(lag(sal,1) over (order by sal),0) Next_Sal from prerowsum) 
select id,sal,cast(next_sal as int)Next_Salary,sal+cast(next_sal as int) from t1 

Output: 
idTotal_Sum
1200
2500
31000
41560


Query: --4) How do you load unique records into one target table and duplicate records into different target table? */
Answer: 
--For duplicate row:- 
select col1, count(*) Duplicate_Rows from tbl1 group by col1 having count(*)>1 
output:
col1Duplicate_Rows
a2
b2

--For Unique Records:- 
select col1, count(*) Unique_Records from tbl1 group by col1 having count(*)=1 
--/*output: 
col1Unique_Records
c1

Query: --5) How do you load first and last records into target table 
Answer: 
use Interview 
Select * from FirstLastRow 
idnameprizecompany
1Alex10000C1
2Mary13000C1
3Noor4000C2
4Kunal2000C2
5Constance9000C3
6Nicole12000C3
7Fred10000C1

--first record union
Select top 1 * from FirstLastRow 
--last record 
Select top 1 * from FirstLastRow order by id desc  
idnameprizecompany
1Alex10000C1

idnameprizecompany
7Fred10000C1

----- About Subquery create the employee table: - 
--Subquery: - 
It is an SQL query which is placed inside another SQL query.
Scalar Subquery: - Which have one row and one column
MultiRow Subquery: - 
a) Which have one row and multiple column 
b) Which have one column and multiple column 
Correlated Subquery: - where inner subquery is dependent on outer query
Example:
use Interview --database name is Interview 
--Create table query: 
create table emp_subquery ( emp_id int primary key identity (101,1) NOT NULL, emp_name nvarchar(50), dept_name nvarchar(50), salary decimal (18,2) ) 

--Select Query on table:- 
select * from emp_subquery
emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
102RajkumarHR8103.385/17/2022
103AkbarIT4630.55/17/2022
104DorvinFinance7524.565/17/2022
105RohitHR5788.135/17/2022
106RajeshFinance5788.135/17/2022
107MohitAdmin6366.945/17/2022
108KrishnaHR6945.755/17/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022
111SitaFinance2894.065/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022

Query --6) Find the employees who's salary is more than the average salary earned by all employees
Answer: 
--a) Find average salary earned by all the employees 
select avg(salary) from emp_subquery 
Output: 
avg_salary
13856.36692

use Interview 
--b) Employee who's salary is more than the avg salary: - 
--First way: - with Subquery select * from emp_subquery 
--outer query / main query where salary > (select avg(salary) from emp_subquery); 
--(query) Called Inner query / Subquery/ Standalone SQL query (because it's independent query)

--Second way: - with subquery as table 
Query: select a.* from emp_subquery a, (select avg(salary) salary from emp_subquery)b where a.salary>b.salary
Output: 

--OR

--Third way: - by using join operator 
select a.* from emp_subquery a join (select avg(salary) salary from emp_subquery)b on a.salary>b.salary 
--Output: 
emp_idemp_namedept_namesalaryGETDATE
112RamFinance926105/17/2022
114ShivaHR157506/5/2022

Query: --7) Find the employee who earn the highest salary in each department 
Answer: 
select * from emp_subquery order by dept_name 
Answer:  
emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
107MohitAdmin6366.945/17/2022
104DorvinFinance7524.565/17/2022
111SitaFinance2894.065/17/2022
112RamFinance926105/17/2022
106RajeshFinance5788.135/17/2022
114ShivaHR157506/5/2022
105RohitHR5788.135/17/2022
102RajkumarHR8103.385/17/2022
108KrishnaHR6945.755/17/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022
103AkbarIT4630.55/17/2022

--a) first find max salary in each department:- 
select dept_name,max(salary) Max_Sal from emp_subquery group by dept_name 
/*Output:- 
select * from emp_subquery where (salary) in (select dept_name,max(salary) sal from emp_subquery group by dept_name ) 
dept_nameMax_Sal
Admin6366.94
Finance92610
HR15750
IT7524.56
/*If we use = in place of (in) then It'll through an error messagbelow:low :- 
Error Message: - Msg 512, Level 16, State 1, Line 154 Subquery returned more than 1 value. This is not permitted when the subquery follows =,!=, <, <=, >, >= or when the subquery is used as an expression. 
*/
*/

select distinct a.* from emp_subquery a, (select max(salary) sal from emp_subquery group by dept_name) b where a.salary=b.sal 
--OR 
select distinct a.* from emp_subquery a 
join (select max(salary) sal from emp_subquery group by dept_name) b on a.salary=b.sal 
Output: 
emp_idemp_namedept_namesalaryGETDATE
104DorvinFinance7524.565/17/2022
107MohitAdmin6366.945/17/2022
110RadheIT7524.565/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022

--Multiple Row:- 1 Column and Multiple Row 
Query: --8) Find department who don't have any employee? 
create table department_subquery ( dept_id int primary key identity (1,1), dept_name nvarchar(50), location nvarchar(100) ) 

--Multiple Row Subquery:- 
Query: --9) Find department who don't have any employee? 
Select * from emp_subquery 
emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
102RajkumarHR8103.385/17/2022
103AkbarIT4630.55/17/2022
104DorvinFinance7524.565/17/2022
105RohitHR5788.135/17/2022
106RajeshFinance5788.135/17/2022
107MohitAdmin6366.945/17/2022
108KrishnaHR6945.755/17/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022
111SitaFinance2894.065/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022
Select * from department_subquery
dept_iddept_nameslocation
1HRBangalore
2ITBangalore
3FinanceMumbai
4MarketingBanglore
5SalesMumbai
6AdminHydrabad
7QuantityKarnataka
8SalesAhemdabad

Answer: 
use Interview 
select distinct dept_names 
from department_subquery 
where dept_names not in (select distinct dept_name from emp_subquery) 
dept_names
Marketing
Quantity
Sales

--OR 

--Find the department who have not any employee 
select d.* from department_subquery d 
where not exists (select * from emp_subquery e where d.dept_names = e.dept_name) 
dept_iddept_nameslocation
4MarketingBanglore
5SalesMumbai
7QuantityKarnataka
8SalesAhemdabad

--Correlated Subquery: - --
Query10) Find employees in each department who earn more than the average salary in that department? 
use Interview 
Answer: 
select a.*,b.salary 
from emp_subquery a, (select dept_name,avg(salary) salary from emp_subquery group by dept_name) b 
where a.dept_name=b.dept_name and a.salary>b.salary 
emp_idemp_namedept_namesalaryGETDATEsalary
107MohitAdmin6366.945/17/20226077.535
112RamFinance926105/17/202227204.1875
114ShivaHR157506/5/20229401.178
109SunitaHR10418.635/17/20229401.178
110RadheIT7524.565/17/20226077.53

--Correlated Subquery where inner query related to outer query: - 
select * from emp_subquery a where a.salary> (select avg(Salary) from emp_subquery b where a.dept_name=b.dept_name) 
emp_idemp_namedept_namesalaryGETDATE
107MohitAdmin6366.945/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022

--Note :- 
--1) We cannot correlate subquery standalone/independently
--2) For every single record which is processed by outer query the correlated subquery is executed.

--Date: - 06-03-2022
--Nested Sub Query: - query inside have another subquery have another subquery called nested subquery.
Example:  
--Table create 
create table sales_Nested_subquery
(
store_id int,
store_name nvarchar(50),
product_name nvarchar(50),
quantity int,
price int
)


select * from sales_Nested_subquery;
store_idstore_nameproduct_namequantityprice
1Apple Store 1iPhone 13 Pro11000
1Apple Store 1MacBook pro 1436000
1Apple Store 1AirPods Pro2500
2Apple Store 1iPhone 13 pro22000
3Apple Store 1iPhone 12 Pro1750
3Apple Store 1MacBook pro 1412000
3Apple Store 3MacBook pro 1412000
3Apple Store 3MacBook Air44400
3Apple Store 3iPhone 1321800
3Apple Store 3AirPods Pro3750
4Apple Store 4iPhone 12 Pro21500
4Apple Store 4MacBook pro 1613500

--Q 11) Find Stores who's sales where better than the average sales accros all stores.
--a) Find the total sales for each store.
Select store_name,sum(price) total_Sales from sales_Nested_subquery 
group by store_name
store_nametotal_Sales
Apple Store 112250
Apple Store 38950
Apple Store 45000


--b) find avg sales for all the stores.
Select store_name,avg(price*quantity) avg_Sales
from sales_Nested_subquery
group by store_name
store_nameavg_Sales
Apple Store 14458
Apple Store 36362
Apple Store 43250

--Q12) Find Stores who's sales where better than the average sales accross all stores.
--a) Find the total sales for each store.
Select store_name,sum(price) total_Sales from sales_Nested_subquery 
group by store_name
store_nametotal_Sales
Apple Store 112250
Apple Store 38950
Apple Store 45000

--b) find avg sales for all total sales.
Select avg(total_sales) avg_sales
from (Select store_name,sum(price) total_Sales from sales_Nested_subquery 
group by store_name)x
avg_sales
8733

--c) compare a) & b) 
select *
from (Select store_name,sum(price) total_Sales from sales_Nested_subquery 
group by store_name)total_sales
join 
(Select avg(total_sales) avg_sales
from (Select store_name,sum(price) total_Sales from sales_Nested_subquery 
group by store_name)x)average_Sales
on total_sales.total_Sales>average_Sales.avg_sales

--OR 

--Implementation by using with clause: - 
with Sales as 
(Select store_name,sum(price) total_Sales from sales_Nested_subquery group by store_name)
select *
from Sales t1
join 
(Select avg(total_sales) avg_sales
from Sales)t2
on t1.total_Sales>t2.avg_sales

store_nametotal_Salesavg_sales
Apple Store 1122508733
Apple Store 389508733

--d) Subquery with Having Clause :- 
--Q 13) Find the stores who have sold more units than the average units sold by all stores.
select * from sales
store_idstore_nameproduct_namequantityprice
1Apple Store 1iPhone 13 Pro11000
1Apple Store 1MacBook pro 1436000
1Apple Store 1AirPods Pro2500
2Apple Store 2iPhone 13 pro22000
3Apple Store 1iPhone 12 Pro1750
3Apple Store 1MacBook pro 1412000
3Apple Store 3MacBook pro 1412000
3Apple Store 3MacBook Air44400
3Apple Store 3iPhone 1321800
3Apple Store 3AirPods Pro3750
4Apple Store 4iPhone 12 Pro21500
4Apple Store 4MacBook pro 1613500
3Apple Store 3MacBook pro 1412000
3Apple Store 3MacBook Air44400
3Apple Store 3iPhone 1321800
3Apple Store 3AirPods Pro3750
4Apple Store 4iPhone 12 Pro21500
4Apple Store 4MacBook pro 1613500



Answer: 
select store_name, sum(quantity) Total_Qty 
from sales
group by store_name
having sum(quantity)>(select avg(quantity) avg_unit from Sales)

store_nameTotal_Qty
Apple Store 18
Apple Store 320
Apple Store 46

Date: - 11-03-2022
---We can use subquery in below command such as: -
/*
i) Insert
ii) Update
iii) Delete
*/
--Insert 
select * into Insert_table_check from (select store_name, sum(quantity) Total_Qty 
from sales
group by store_name
having sum(quantity)> (select avg(quantity) avg_unit from Sales)) a
Answer: 
select * from Insert_table_check
store_nameTotal_Qty
Apple Store 18
Apple Store 320
Apple Store 46

--Q.14) Insert data to employee history table. Make sure not insert duplicate records.
--created table to insert data into history table by using subquery: - 
create table employee_history_Insert_subquery
(
emp_id int,
emp_name nvarchar(50),
dept_name nvarchar(50),
salary decimal (18,2),
location nvarchar(50)
)

Select * from emp_subquery
emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
102RajkumarHR8103.385/17/2022
103AkbarIT4630.55/17/2022
104DorvinFinance7524.565/17/2022
105RohitHR5788.135/17/2022
106RajeshFinance5788.135/17/2022
107MohitAdmin6366.945/17/2022
108KrishnaHR6945.755/17/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022
111SitaFinance2894.065/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022

select * from department_subquery
dept_iddept_nameslocation
1HRBangalore
2ITBangalore
3FinanceMumbai
4MarketingBanglore
5SalesMumbai
6AdminHydrabad
7QuantityKarnataka
8SalesAhemdabad


insert into employee_history_Insert_subquery
Select e.emp_id,e.emp_name,d.dept_names,e.salary,d.location 
from emp_subquery e join department_subquery d 
on e.dept_name=d.dept_names 
where not exists (select * from employee_history_Insert_subquery eht --To avoid duplicate record insert
                   where eht.emp_id=e.emp_id)
order by e.emp_id
emp_idemp_namedept_namesalarylocationhire_date_yyyy_mm_dd
101MohanAdmin4000Hydrabad10/25/2010
107MohitAdmin5500Hydrabad8/15/2009
104DorvinFinance6500Mumbai8/28/2009
106RajeshFinance5000Mumbai5/20/2012
111SitaFinance2500Mumbai11/16/2017
105RohitHR3000Bangalore3/31/2006
102RajkumarHR3000Bangalore8/15/2018
108KrishnaHR4000Bangalore9/15/2022
109SunitaHR7000Bangalore2/28/2021
110ReenaIT6500Bangalore8/19/2019
103AkbarIT4000Bangalore1/26/2022

--Note:- 
--1) First time query execution It'll show message "(24 rows affected)"
--2) Second and more than one time query execute than it'll show message "(0 rows affected)".
--3) If you try to update identity field than It'll show message:- 
--update department_subquery set dept_id=8, dept_names='Quantity', location='Karnataka' where dept_id=7
----Message:- 
----Msg 8102, Level 16, State 1, Line 400
----Cannot update identity column 'dept_id'.

--ii) Update with Subquery: -  check link to know how to write subquery with update statement as below link :-  Click Here 
/* Perform an update with a correlated subquery
USE AdventureWorks;
UPDATE d 
SET Name =
(
 SELECT Name FROM
 BackupOfAdventureWorks.HumanResources.Department 
 WHERE DepartmentID = d.DepartmentID
)
FROM HumanResources.Department d;

--Perform an update using JOIN

USE AdventureWorks;
UPDATE d 
SET d.Name = bd.Name 
FROM HumanResources.Department d
JOIN BackupOfAdventureWorks.HumanResources.Department bd
ON bd.DepartmentID = d.DepartmentID;
*/

--Q 15) Give 10% increment to all employees in Bangalore location based on the maximum salary earned by an employee in each department. Only consider employees in employee_history table. */
Answer: - 
--select * from emp_subquery where dept_name ='Admin' order by dept_name
--select * from employee_history_Insert_subquery where location='Hyderabad'
--select * from department_subquery where location='Hyderabad'

emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
107MohitAdmin6366.945/17/2022


-----------------------1st way try
begin tran
Update emp_subquery 
set salary = (select max(salary)+(max(salary)*0.1) 
              from employee_history_Insert_subquery eh 
  where eh.dept_name=dept_name 
)
where dept_name in (select dept_names from department_subquery where location='Hydrabad')
and emp_id in (select emp_id from employee_history_Insert_subquery)
Output: 
/*
(2 rows affected)
(2 rows affected)
Completion time: 2023-07-16T16:47:08.1111763+05:30
*/

rollback;

/*
Commands completed successfully.
Completion time: 2023-07-16T16:48:23.9702571+05:30
*/
---------------2nd Way tries
select * from emp_subquery
begin tran
update emp_subquery 
set salary = (select salary*0.1+salary from (
select dept_name,salary,ROW_NUMBER() over(partition by dept_name order by salary desc) rn
from employee_history_Insert_subquery 
where location='Hydrabad' and emp_id=emp_id and dept_name=dept_name)a
where a.rn=1

           )
where dept_name=(select eh.dept_name from employee_history_Insert_subquery eh where eh.emp_id=emp_id and location='Bangalore')

/* Output:- 
(13 rows affected)
Msg 512, Level 16, State 1, Line 403
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

Completion time: 2023-07-16T16:49:21.0005520+05:30
*/
--Delete with Subquery:- 
select * from emp_subquery
select * from department_subquery

--Q. 16) Delete all departments who don't have any employees

begin tran
delete from department_subquery 
where dept_names in (
select distinct d.dept_names
from department_subquery d
where not exists (select * 
                                                                    from emp_subquery e 
                                                                    where d.dept_names=e.dept_name
                                                                   )
   )

/*
(4 rows affected)
Completion time: 2023-07-16T16:50:38.6090850+05:30
*/

select * from department_subquery


rollback;
/*
Commands completed successfully.
Completion time: 2023-07-16T16:51:23.5804246+05:30
*/

 
-- ******* Different SQL Clause where subquery is allow:-
/*
a) Select Clause
b) Form Clause: - above example
c) Where Clause:- check Q3) example 
d) Having Clause :- check Q 13) 
*/

--a) Subquery with Select Clause:- We'll understand it by the below example.
--Q17) Fetch all employees details and add remark to those employees who earn more than the average pay.
use Interview
select * from emp_subquery
emp_idemp_namedept_namesalaryGETDATE
101MohanAdmin5788.135/17/2022
102RajkumarHR8103.385/17/2022
103AkbarIT4630.55/17/2022
104DorvinFinance7524.565/17/2022
105RohitHR5788.135/17/2022
106RajeshFinance5788.135/17/2022
107MohitAdmin6366.945/17/2022
108KrishnaHR6945.755/17/2022
109SunitaHR10418.635/17/2022
110RadheIT7524.565/17/2022
111SitaFinance2894.065/17/2022
112RamFinance926105/17/2022
114ShivaHR157506/5/2022

select *,
(select avg(salary) from emp_subquery) as 'AVG_SALES',
case when salary>(select avg(salary) from emp_subquery) then 'Higer_Than_Average_Sales' End as Remarks
from emp_subquery

emp_idemp_namedept_namesalaryGETDATEAVG_SALESRemarks
101MohanAdmin5788.135/17/202213856.36692NULL
102RajkumarHR8103.385/17/202213856.36692NULL
103AkbarIT4630.55/17/202213856.36692NULL
104DorvinFinance7524.565/17/202213856.36692NULL
105RohitHR5788.135/17/202213856.36692NULL
106RajeshFinance5788.135/17/202213856.36692NULL
107MohitAdmin6366.945/17/202213856.36692NULL
108KrishnaHR6945.755/17/202213856.36692NULL
109SunitaHR10418.635/17/202213856.36692NULL
110RadheIT7524.565/17/202213856.36692NULL
111SitaFinance2894.065/17/202213856.36692NULL
112RamFinance926105/17/202213856.36692Higer_Than_Average_Sales
114ShivaHR157506/5/202213856.36692Higer_Than_Average_Sales


--Date:- 16-03-2022

--Merge Statement: - 

create table mergeA
(
  e_id int,
  e_name nvarchar(50),
  e_salary decimal(18,2),
  e_age int,
  e_gender nvarchar(10),
  e_dept nvarchar(20)
)

create table mergeB
(
  e_id int,
  e_name nvarchar(50),
  e_salary decimal(18,2),
  e_age int,
  e_gender nvarchar(10),
  e_dept nvarchar(20)
)


Select * from mergeSrc

e_ide_namee_salarye_agee_gendere_dept
1Sam9300040MaleOperations
2Bob8000021MaleSupport
3Amme1300025FemaleAnalytics
4Joff1120027FemaleContact
7Adam1000028MaleContent
8Jeff8500037MaleTech

Select * from mergeTgt
e_ide_namee_salarye_agee_gendere_dept
9Ram10000025MaleIT
9Ram10000025MaleIT
9Ram10000025MaleIT
9Ram10000025MaleIT
5Matt15900033MaleSales
9Ram10000025MaleIT
6Joff1120027FemaleContact
9Ram10000025MaleIT
1Sam9300040MaleOperations
2Bob8000021MaleSupport
3Amme1300025FemaleAnalytics
4Joff1120027FemaleContact
7Adam1000028MaleContent
8Jeff8500037MaleTech


--Merge command using :- 
merge mergeTgt as T
using mergeSrc as S
on T.e_id=S.e_id
when matched 
then update set t.e_salary=s.e_salary, t.e_age=s.e_age
when not matched by target
then insert (e_id,e_name,e_salary,e_age,e_gender,e_dept)
values(s.e_id,s.e_name,s.e_salary,s.e_age,s.e_gender,s.e_dept);

/*
(6 rows affected)
Completion time: 2023-08-12T17:09:46.4191890+05:30
*/
select * from mergeTgt_bkp_16_03_2022
Select * from mergeTgt

e_ide_namee_salarye_agee_gendere_dept
1Sam9500040MaleOperations
2Bob8000021MaleSupport
3Amme12500025FemaleAnalytics
4Julia11200030MaleAnalytics
5Matt15900033MaleSales
8Jeff11200027MaleOperations

e_ide_namee_salarye_agee_gendere_dept
9Ram10000025MaleIT
9Ram10000025MaleIT
9Ram10000025MaleIT
9Ram10000025MaleIT
5Matt15900033MaleSales
9Ram10000025MaleIT
6Joff1120027FemaleContact
9Ram10000025MaleIT
1Sam9300040MaleOperations
2Bob8000021MaleSupport
3Amme1300025FemaleAnalytics
4Joff1120027FemaleContact
7Adam1000028MaleContent
8Jeff8500037MaleTech


--SavePoint:

 create table savepoint
 (
  id int,
  name nvarchar(20)
 )



select * from savepoint
idname
1Ram
2Shyam
3Krishna
4Mohan
5Kanha

begin transaction
insert into savepoint values(3,'Krishna')

select * from savepoint
----id name
----1 Ram
----2 Shyam
----3 Krishna

rollback--Not commited then does the rollback  
select * from savepoint
 /*
 id name
1 Ram
2 Shyam
 */
-----Commit 
begin transaction
insert into savepoint values(3,'Krishna')
commit 
--Can not rollback after commit.
select * from savepoint

rollback
/*
Msg 3903, Level 16, State 1, Line 633
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
*/
select * from savepoint
--delete from savepoint where id=4

----------------Savepoint
begin transaction
insert into savepoint values(5,'Mukesh')
save tran save1

--id name
--1 Ram
--2 Shyam
--3 Krishna
--4 Mohan
________________________________________

   ---Date :- 22-03-2022
Select * from savepoint

begin transaction
insert into savepoint values(5,'Kanha');
save tran sp1;
commit

begin transaction
insert into savepoint values(6,'vishnu');
save tran sp2;

--not comminted 
begin transaction
insert into savepoint values(7,'Vinit');
save tran sp3;

begin transaction
insert into savepoint values(8,'Vinit');
save tran sp4;

select * from savepoint; 

--not commited 
--Without savepoint did the transaction:- 
insert into savepoint values(9,'Harsh');

--Now if we rollback then last row which is inserted without under transaction then it'll be roll back only
select * from savepoint;
/*output:- 
id name
1 Ram
2 Shyam
3 Krishna
4 Mohan
5 Kanha
6 vishnu
7 Kranti
*/
--After rollback without using savepoint name;
rollback; --It'll rollback all the tranaction with is not commited whatever is savepoint or without transaction.

select * from savepoint;
/*
Result :- 
id name
1 Ram
2 Shyam
3 Krishna
4 Mohan
5 Kanha
*/

Query: --18) WAQ an SQL query to report the different between number of apples and oranges sold each day.
Note: Return the result table ordered by sale_date in format('YYYY-MM-DD')
--Expected Result: 
/*
sale_date   diff
2020-05-01   2
2020-05-02   0
2020-05-03   20
2020-05-04   -1
*/

Solution: 
Create table Sale 
(
sale_date date,
--fruit varchar(10) --default 'apples','oranges'
fruit varchar(10) constraint fruit_chk check (fruit in ('apples','oranges')),
sold_num int,
primary key(sale_date, fruit)
)


Select * from Sale;
sale_datefruitsold_num
5/1/2020apples10
5/1/2020oranges8
5/2/2020apples15
5/2/2020oranges15
5/3/2020apples20
5/3/2020oranges0
5/4/2020apples15
5/4/2020oranges16

Select sale_date, diff from(
Select *,sold_num-lead(sold_num,1) over(partition by sale_date order by sale_date) diff
from Sale)a where diff is not null

--OR 

select a.sale_date, a.sold_num-b.sold_num as diff
from 
(Select sale_date,fruit,sold_num
from Sale where fruit='apples')a inner join 
(Select sale_date,fruit,sold_num
from Sale where fruit='oranges')b on a.sale_date=b.sale_date

sale_datediff
5/1/20202
5/2/20200
5/3/202020
5/4/2020-1


Exist Operator and Joins Operator Difference:-

Select * from customers;
customer_idcustomer_namecustomer_email
1Shashankabc@gmail.com
2Rahulaaa@gmail.com
3Ajayklm@gmail.com
4Nitinpoc@gmail.com
5Naveenmnc@gmail.com

Select * from orders;
order_idcustomer_idamountstatus
1011550Delivered
1022350Delivered
1031220Cancelled
1043660Delivered
1053300Delivered

--Is the Shashank placed any order or not 
Select c.customer_id, c.customer_name, c.customer_email, o.order_id,o.amount,o.status
from customers c
Left join orders o on c.customer_id=o.customer_id 
where c.customer_name='Shashank' and o.order_id is not null
customer_idcustomer_namecustomer_emailorder_idamountstatus
1Shashankabc@gmail.com101550Delivered
1Shashankabc@gmail.com103220Cancelled

--- OR

Select distinct c.*
from customers c
Left join orders o on c.customer_id=o.customer_id 
where c.customer_name='Shashank' --and o.order_id is not null
--using left or right join if you remove the right and left table column from the select statement then appeared NULL will not display becasue the column which don't have value appear NULL by deafult but if you remove those column then null will be not appear becasue NULL will appear only for those column which contain the NULL value. 
customer_idcustomer_namecustomer_emailorder_idamountstatus
1Shashankabc@gmail.com101550Delivered

--OR 

--Query using Exist operator in SQL :- 
Select *
from customers c
where exists (Select order_id from orders o where c.customer_id=o.customer_id and  c.customer_name='Shashank'
)

customer_idcustomer_namecustomer_email
1Shashankabc@gmail.com

--Explaination about Exist Operator: - 
--Exists operator checks if any record matches with another table, then it''ll show thosrecordsrd one time only not a multiple time like as join do and to fix it we can use the distinct keyword using joins operator.
--Exists work like as switch because after got one match then if is it again match the matching breaks.
Q. ) 
Tables Description: - (user_id, time_stamp) is the primary key for this table.
Each row contains information about the login time for the user with ID user_id.

Question: WAQ to report the latest login for all users in the year 2020.
Do not include the users who did not login in 2020.

The query result is in the following example: 
Select * from Logins
+-----------+------------------------+
|user_id | time_stamp |
+-----------+------------------------|
|2 |2019-08-25 07:59:08.000 |
|2 |2020-01-16 02:49:50.000 |
|6 |2019-03-07 00:18:15.000 |
|6 |2020-06-30 15:06:07.000 |
|6 |2021-04-21 14:06:06.000 |
|8 |2020-02-01 05:10:53.000 |
|8 |2020-12-30 00:46:50.000 |
|14 |2019-07-14 09:00:00.000 |
|14 |2021-01-06 11:59:59.000 |
+------------+-----------------------+

Query Solution:  
with t as (
Select user_id,time_stamp, row_number() over (partition by user_id order by time_stamp desc)rn 
from Logins
where year(time_stamp)='2020')
Select user_id, time_stamp last_stamp
from t
where rn=1  order by time_stamp desc;

OR 

Select user_id,max(time_stamp)
from Logins
where year(time_stamp)='2020'
group by user_id;

Output: 
+-----------+------------------------+
|user_id | last_stamp |
+-----------+------------------------|
| 8 |2020-12-30 00:46:50.000 |
| 6 |2020-06-30 15:06:07.000 |
| 2 |2020-01-16 02:49:50.000 |
+------------+-----------------------+

--Problem Statment:- 
/*
Remove all reversed number pairs from given table, keep only one (random if somthing exists)
*/
Select * from number_pairs

|A | B |
-----------
|1 | 2 |
|3 | 2 |
|2 | 4 |
|2 | 1 |
|5 | 6 |
|4 | 2 |
-----------
Solution :- 

Select t1A A, t1B B from (
Select t1.A t1A,t1.B t1B
from number_pairs t1
inner join number_pairs t2 on t2.B=t1.A  and t2.A=t1.B)t
where t1A < t1B
union
select * from number_pairs t1
where not exists 
(Select *
from number_pairs t2 where t2.B=t1.A  and t2.A=t1.B)

OR 

Select t1.A as A , t1.B as B
from number_pairs t1
left join number_pairs t2 on t2.B=t1.A  and t2.A=t1.B
where t1.A < t2.A
union
Select t1.A as A , t1.B as B
from number_pairs t1
left join number_pairs t2 on t2.B=t1.A  and t2.A=t1.B
where t2.A IS NULL
/*
A B
1 2
2 4
3 2
5 6
*/
----------------------------------------------- Exit -----------------------------------------------

Comments

Post a Comment

Popular Post

SQL Server Database Details