SQLTraining
SQLTraining
Process should be able to define a) Topics to learn, b) Example to solve, c) Level of Knowledge, d) Measurement KPIs, e)
Goal 2 Intervention required
Level
Beginner
Intermediate
Advanced
Trick Questions
Hands on Practice and Test (Expected Time to Learn)
# of hours required Total
B I A T
# of Questions 40 40 40 20 12 hours/day 84 hours
To be Solved during learning
25 25 25 10 8 hours/day 56 hours
(including
Test (Hands theory)without
on sessio
15 15 15 10 4 hours/day 28 hours
help)
Flow to be followed
3
4
325451207E3105
Topics Functions
Primary Key
Keys -
Constraints
Composite Key
UPDATE
CRUD
Delete
Alter
STRING FUNCTION
Basic Retrieval DISTINCT
CONCATENATE
IN
Where
AND, IN
BETWEEN
Filtering NULL
(DISTINCT, NOT NULL
WHERE, AND,
OR, IN, NOT IN)
LIKE FUNCTION
REGEXP
DATE FUNCTION
Max
Max
Aggregation
(GROUP BY Nth Maximum Value
with COUNT,
Count
SUM,Max,Min,
Avg) Avg
Count,Group By, Having
HAVING
Conditional st
atements (CAS
E - WHEN - CASE WHEN
THEN - ELSE -
END)
JOIN
Joins Self join
Formatting
(LIMIT, ORDER
BY, casting as ORDER BY
an integer, float,
or date,
CONCAT,
COALESCE)
LENGTH
Miscellaneous
SUBQUERY
Basic SQL
Questions
What is primary key and foreign key
what are the different type of constraint
what is composite key E_id First_name
what is difference in DROP , TRUNCATE and DELETE 1 Monika
Increase the salary of employee who is in department id 44 by 5k. 2 Niharika
Update the city name to bangalore where department id is 22. 3 Vishal
delete the employee records whose salary is less than 1000 4 Amitabh
Drop the city column from employee table 5 Vivek
Change the salary column name to E_salary in employee table. 6 Vipul
Write a query to find the first name of employee removing white spaces if present. 7 Satish
Write a query to fetch the unique departments from the table. 8 Geetika
Find the full name of the employee
find the details of the employee of id 3,4,5,10,11 Department Table
Employees who is getting more than 20000.
find the details of employee where dept is 33,44,55 and salary is more than 10000. Dept_ID Dept_name
find the employee full name whose salary is between 5000 and 15000 1 HR
find the employee id where department id is null 2 Admin
Find the first name of employee whose last name is not null 3 Account
find the first_name of the employee who has 'a' at the end of their name
find the first_name of the employee who has 'or' in their name
find the
Write anLast_name
SQL queryof tothe employee
print details ofwho
the has 't' as second
employees whoseletter in their name
FIRST_NAME ends
with ‘h’the
Query and
listcontains six alphabets.
of employee names ending with vowels (a, e, i, o, u) from table. Your result
cannot contain duplicates.
Write an query to print details of the employees who have joined in Feb’2014
find the name the of employee who gets highest salary and lowest salary
Add a flag column for employee as old who joined before 2020 and others as new
in the table.
arrange the name of the employee on the basis of their salary from highst to
lowest.
Perform inner join on both the tables and get the output.
Output of case when null = null then true else false end
What is cross join and what will be the total number of rows in table having 10 rows and
another table having 15 rows?
Basic SQL
Input Output Logic
Employee
Department Table
Manager_id
3
4
6
Table1 Table2
1 1
2 2
3 Null
Null Null
Query
Intermediate
Topics Functions Questions Input
STATION
Field Type
Query the two cities in STATION with the shortest and longest CITY names, as well as their ID Number
respective lengths (i.e.: number of characters in the name). If there is more than one smallest City VARCHAR(21)
or largest city, choose the one that comes first when ordered alphabetically.where LAT_N is
the northern latitude and LONG_W is the western longitude State VARCHAR(2)
Lat_N NUMBER
1. String function STRING FUNCTION Long_W NUMBER
Id Value
1 4
2 7
Find the median of the Value column from table 3 2
4 2
5 9
6 8
7 3
Task_id Start_date
You are given a table, Projects, containing three columns: Task_ID, Start_Date and End_Date. 1 2015-10-01
It is guaranteed that the difference between the End_Date and the Start_Date is equal to 1 2 2015-10-02
day for each row in the table.If the End_Date of the tasks are consecutive, then they are part
of the same project. Samantha is interested in finding the total number of different projects 3 2015-10-03
1. Subquery completed. 4 2015-10-13
Write a query to output the start and end dates of projects listed by the number of days it
5 2015-10-14
took to complete the project in ascending order. If there is more than one project that have 6 2015-10-28
the same number of completion days, then order by the start date of the project.
7 2015-10-30
3. joins Retrieve the most expensive books of each language from table books Book_name Language
Write a query to find month over month retention rate
You are given a table, Functions, containing two columns: X and Y. Two pairs (X1, Y1) and (X2,
Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.
Write a query to output all such symmetric pairs in ascending order by the value of X. List the \\
rows such that X1 ≤ Y1.
Score
Write a SQL query to rank scores. If there is a tie between two scores, both should have the
same ranking. Note that after a tie, the next ranking number should be the next consecutive
integer value. In other words, there should be no “holes” between ranks.
1 3.5
Write a SQL query to rank scores. If there is a tie between two scores, both should have the 2 3.65
same ranking. Note that after a tie, the next ranking number should be the next consecutive 3 4
integer value. In other words, there should be no “holes” between ranks.
4 3.85
5 4
6 3.65
4. case when
Create a release_label for each genre based on the days between releases. A) if days between
the latest 2 movie release <=30 days, then 'Back-to-back' release B) if days between the latest Table 1 (Movie release data)
2 movie release> month then 'Late release' refer-Table:1
Display 'days_since_last_rental' for every customer's transaction (difference in days since last
transaction) Movie_id movie_title
Generate the customer share for for each genre. Customer share= Total customers who
purchased movie of genre/Total customers Table 2 (Movie rental data)
Get the most bought genre by the top 10 most profitable customers Rental_date cust_id
Order Table:
Cust_id,
For every city how many orders are placed where order value is more than 500?
order_id,
Sellingprice,
MRP,Quantit
y City
What is the total revenue for male female customers on a day level.(Output columns:-
date, total_revenue_male, total_revenue_female
Pick out the number of new users each day for Jan and Feb. Customer_id,
date, gmv,
city.
seat_id free
Several friends at a cinema ticket office would like to reserve consecutive available seats.
query all the consecutive available seats order by the seat_id using the following cinema
table?
1 1
Several friends at a cinema ticket office would like to reserve consecutive available seats. 2 0
query all the consecutive available seats order by the seat_id using the following cinema
table? 3 1
4 1
5 1
Get the highest answer rate question from a table survey_log with these columns: uid, action, uid action
question_id, answer_id, q_num, timestamp. 5 show
uid means user id; action has these kind of values: “show”, “answer”, “skip”; answer_id is not 5 answer
null when action column is “answer”, while is null for “show” and “skip”; q_num is the 5 show
numeral order of the question in current session.
5 skip
Write a sql query to identify the question which has the highest answer rate.
user_id action
1 Start
1 Cancel
From the following table of user actions, write a query to return for each user 2 Start
the time elapsed between the last action and the second-to-last action, in 2 Publish
ascending order by user ID 3 Start
3 Cancel
4 Start
1 Publish
Left
Join,row_number() user_id product_id
1 101
A company defines its super users(repetitive user) as those who have made 2 105
at least two transactions. From the following table, write a query to return, for 1 111
each user, the date when they become a super user, ordered by oldest super
3 121
users first. Users who are not super users should also be present in the
table. 1 101
2 105
4 101
3 105
Find quantities sold for last 7 days and that should reflect in each column for each skuid ( note
: data is updated till current date) Order table
date sku
Joins Self join find the manager name for the employee where empid and managerid are on the
same table
Intermediate
Output Logic
MRP
ble 1 (Movie release data)
Release_dat
Genre
e
able 2 (Movie rental data)
Spend_amo
Movie_id
unt
Publisher
country Est_date
seat_id
3
4
5
Name ID
AA AA
BB BB
CC CC
Table 1
id client_id
1 1
Write a SQL query to find the cancellation rate of requests with unbanned users 2 2
(both client and driver must not be banned) each day between "2013-10-01" and 3 3
"2013-10-03". Cancellation rate is computed by dividing the number of canceled
(by client or driver) requests with unbanned users by the total number of Table 2
requests with unbanned users on that day User_id Banned
1 No
2 Yes
Drivers Table
Query to report the percentage of working drivers(working_percentage) for each
month of 2020 where percentage_month = driver that accepted at least one ride
during month / available drivers during month * 100.
Query to report the percentage of working drivers(working_percentage) for each
driver_id join_date
month of 2020 where percentage_month = driver that accepted at least one ride
during month / available drivers during month * 100. 10 10/12/2019
2 2/1/2020
Visits
Query to find how many users visited the bank and didn’t do any transactions user_id
1
2
Stadium Table
Query to display the records with three or more rows with consecutive id's, and id
the number of people is greater than or equal to 100 for each.
1
2
User Table
user_id
Query to find for each user, whether the brand of the second item (by date) 1
they sold is their favorite brand. If a user sold less than two items, report the
answer for that user as no. 2
How many delivered/placed orders for every year (O/P: Year, Delivered Orders,
Advance Joins Placed Orders)
Find out the retention rate month over month Order Date
How many delivered/placed orders for every year on a city level 1/1/2020
2/10/2020
What is the latest updated price of each item ID
Find out the price of each Item ID in table C based on order date and update
date
Order_ID
1
For each year, at a state level, find the number of delivered orders and average
number of items
Hackers Table
id
Query to print total number of unique hackers who made at least submission 1578
each day (starting on the first day of the contest), and find 20703
the hacker_id and name of the hacker who made maximum number of 35396
submissions each day. If more than one such hacker has a maximum number of 44065
submissions, print the lowest hacker_id. The query should print this information
for each day of the contest, sorted by the date.
Id
1
2
Query to get the cumulative sum of an employee’s salary over a period of 3
1
months but exclude the most recent month.
Employee Table
id Name
1 joe
2 henry
Query to find employees who earn the top three salaries in each of the 3 sam
department. 4 max
CustomerID
6
5
3
Write a query to find out "CustomerName" who did highest "purchase" along with 9
"purchase" value 8
Transaction Ta
Custome
Order_ID
r_ID
Window Functions In the month of Jan and Dec, how many orders were placed, what is the total c1 o1
revenue, average selling price. Table must be in a day level. c1 o1
c1 o1
What is the total revenue for male female customers on a day level. C1 o2
(Output columns:- date, total_revenue_male, total_revenue_female
What is the top 5 selling brands each month.
Query to find the cummulative sum of monthly sales without using self join
Miscellaneous
Column has value blue and red, write a query to update the value blue=red and
red=blue in one query
Procedure
Procedure
Procedure performance suddenly very slow in the same data size, what is the
problem and how will you fix?
Delete Cascade
Users Table
User_id Name
1 Jon
2 Jane
Given the following two tables, return the fraction of users, rounded 3 jill
to two decimal places, who accessed feature two (type: F2 in 4 Josh
events table) and upgraded to premium within the first 30 days of 5 jean
Advance Joins signing up.
Customer Retention problem – What is the count of new customer and old customer Sales
from the sales data? order_id Ord_date
Write a query to find the total revenue for each state and do handle null states as for
some districts, states are missing.
Write a query to find sum of average revenue for every customer in the month of
January?
Advanced SQL
Inputs
Salary Table Employee Table
employee_id amount pay_date id department_id
1 9000 1/3/2020 1 1
2 6000 1/3/2020 2 2
3 7000 1/3/2020 3 2
Occupation
Doctor
Doctor
Actor
Order Table
Product_ Address_I
Date MRP Selling_Price Quantity
ID D
20190101 p1 100 80 2 Null
20190101 p2 200 150 1 A1
20190101 p3 500 400 1 A1
20190103 p1 100 80 1 A2
20190103 p4 400 400 1 A2
Product Table
Address Table Category Product Product_Id
Zipcode City State Apparel Shirt p1
560103 Bangalore Karnatka Apparel tshirt p2
Apparel jeans p3
Apparel jacket p4
Footwear Shoes p5
Footwear Slipper 1200
Footwear Heels 7000
Table 1
driver_id city_id Request at Status
10 1 10/1/2013 Completed
11 1 10/1/2013 cancelled_by_driver
12 6 10/2/2013 cancelled_by_client
Table 2
Role
client
driver
Visits Transactions
visit_date user_id transaction_date amount
2/1/2020 1 2/1/2020 120
2/1/2020 2 2/3/2020 22
Stadium Table
visit_date people
1/1/2017 10
1/2/2017 109
item_id item_brand
Item Table
1 LG
Table A Table B
City id customer_id amount paid delivery status City State
Jaipur 1 3 5000 Placed Jaipur Rajasthan
Mysore 2 4 10000 Delivered Mysore Karnataka
Table D
Item_ID Quantity Order Date Itemid updated_date Price
Table C
2 4 1/1/2020 2 1/1/2020 5000
Month Salary
1 20
1 20
2 30
Employee Table Department Table
Salary DeptId id Name
50000 1 1 IT
75000 2 2 Sales
60000 2
90000 1
CustomerNam date CustomerI purchase
e D
A 20190101 3 1456
F 20190101 5 1190
C 20190101 6 1158
R 20190101 3 1973
G
User
user_id Revenue Quantity User_id District Mobile
Expected Output Logic Query
pay_month department_id comaprison
Mar-20 1 higher
Mar-20 2 lower
Abhishek Shiva
Ravi Null
transaction_count visits_count
1 2
0 0
1 0
id visit_date people
2 1/2/2017 109
Seller_id 2nd_item_fav_brand
1 no
2 yes
3 yes
4 no
Id Month Salary
1 1 20
CustomerNa Purchase
C 3429
Desired Output
upgrade_rate
0.33
dis-state-mapping
District States
Tricky
Topics Function Questions Input
Replace How to replace multiple commas from input string abc,,,dddd,,,,,,dde,,2lmdl3emf,cewec,,,,,
Write a query to get occurance of a character in a string in 'sanjeev' find number of occurance of 'e'
Basic retrieval Emp ID Date Present
SELECT From Replace ,Len 1 1,2,3
Write a query to get attendance count.
2 2,4,5,6
3 1,2,4,5,7,9
13 14 30
y
Desired Output Logic Query
abc,dddd,dde,2lmdl3emf,cewec,
2
Emp ID Total Days
1 3
2 4
3 6
User net_change
1 20
3 5
4 5
5 -10
2 -20
date item
01-01-2020 apple
01-01-2020 pear
01-02-2020 pear
player_id device_id
1 2
2 3
3 1
Node Type
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
Type of Tringle
Isosceles
Equilateral
Scalene
Not A Triangle
Segment Function Questions Inpu
user_id
1
1
From the following table of user actions, write a 2
query to return for each user the time elapsed 2
between the last action and the second-to-last
action, in ascending order by user ID 3
3
4
1
Intermediate Left Join,row_number()
user_id
1
A company defines its super users(repetitive user) 2
as those who have made at least two transactions. 1
From the following table, write a query to return, for 3
each user, the date when they become a super user,
ordered by oldest super users first. Users who are 1
not super users should also be present in the table. 2
4
3
friends
user_id
1
Using the following two tables, write a query to return 1
page recommendations to a social media user based
Advance Inner Join, Left Join on the pages that their friends have liked, but that 1
they have not yet marked as liked. Order the result 2
by ascending user ID 3
3
4
4
Mobile
user_id
1
With the following two tables, return the fraction of 2
FULL JOIN,Case
Advance users who only visited mobile, only visited web, and
When,SUM 3
visited both.
4
9
2
10
Input
Joins Desired Output
action action_date user_id days_elapsed
Start 12-02-2020 1 6
Cancel 13-02-2020 2 3
Start 11-02-2020 3 0
Publish 14-02-2020 4 Null
Start 15-02-2020
Cancel 15-02-2020
Start 18-02-2020
Publish 19-02-2020
product_id transaction_date user_id superuser_dat
e
101 12-02-2020 1 14-02-2020
105 13-02-2020 3 15-02-2020
111 14-02-2020 2 17-02-2020
121 15-02-2020 4 Null
101 16-02-2020
105 17-02-2020
101 16-02-2020
105 15-02-2020
friends Likes Desired Output
friend user_id page_likes user_id recommended
_page
2 1 A 2 B
3 1 B 2 C
4 1 C 3 A
1 2 A 4 A
1 3 B 4 C
4 3 C
1 4 B
3
Mobile Web Desired Output
Mobile
page_url user_id page_url Web Fraction both Fraction
Fraction
A 6 A 0.3 0.4 0.3
B 2 B
C 3 C
A 7 A
B 4 B
C 8 C
B 5 B
Logic Query