0% found this document useful (0 votes)
46 views

SQLTraining

Uploaded by

Mayank Ghatpande
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

SQLTraining

Uploaded by

Mayank Ghatpande
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 51

a2 To be able to create a process which will make every employee learn SQL in 1 week

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

Reference Material Kudvenkat Videos https://www.youtube.com/watch?v=SXmVym6L8dw&list=PLAC325451207E3105

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

Measurement KPI - Anurag Bora

# of Question Solved Practice


Basic Intermediate Advanced Tricks
Done Max Done Max Done Max Done Max Hours Spent (Max:8)
Day 1 0 25 /8
Day 2 0 21 0 20 /8
Day 3 0 5 0 10 /8
Day 4 0 15 /8
Day 5 0 10 /12

# of Question Solved Test


Basic (15) Intermediate(15) Advanced(15) Tricks(10)
Done Max Done Max Done Max Done Max # of hours spent
Day 1 5 5 /4
Day 2 5 5 /4
Day 3 5 /4
Day 4 5 /4
Day 5
Day 6 10 10 10 10 3 5 /12
Day 7 10 10 /12

Measurement KPI - Abhishek Mishra

# of Question Solved Practice


Basic Intermediate Advanced Tricks
Done Max Done Max Done Max Done Max Hours Spent (Max:8)
Day 1 25 25 4/8
Day 2 7 20 3/8
Day 3 18 5 5 10 7/8
Day 4 10 15 8/8
Day 5 10 10 6/12

# of Question Solved Test


Basic (15) Intermediate(15) Advanced(15) Tricks(10)
Done Max Done Max Done Max Done Max # of hours spent
Day 1 5 5 2/4
Day 2 5 5 3/4
Day 3 0 5 3 /4
Day 4 5 4/4
Day 5
Day 6 10 10 9 10 3 5 10/12
Day 7 10 10 7/12

Measurement KPI - Vanishree K

# of Question Solved Practice


Basic Intermediate Advanced Tricks
Done Max Done Max Done Max Done Max Hours Spent (Max:8)
Day 1 25 25 4/8
Day 2 20 20 3/8
Day 3 5 5 10 10 7/8
Day 4 11 15 /8
Day 5 10 10 /12

# of Question Solved Test


Basic (15) Intermediate(15) Advanced(15) Tricks(10)
Done Max Done Max Done Max Done Max # of hours spent
Day 1 5 5 2/4
Day 2 5 5 3/4
Day 3 0 5 /4
Day 4 5 /4
Day 5
Day 6 10 10 9 10 3 5 /12
Day 7 10 10 /12
Measurement KPIs, e)

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

Find the 2nd,3rd, nth maximum salary.

Write an query to get the 50% records from a table.


fetch the average salary of employee in each department.
find the
The departments
name that have
of the employee lessare
who than five people
getting moreinthan
it. average salary of all the
employees.

Add a flag column for employee as old who joined before 2020 and others as new
in the table.

If gender is M then keep as M, if F then keep as F. If gender is marked as ‘m’


change to ‘M’, ‘f’ to F. All other values should be labeled ‘Unknown’ .
Find the department name for each empployee.
Write an query to fetch the list of employees with the same salary

arrange the name of the employee on the basis of their salary from highst to
lowest.

find the top 4th to 9th highest salary.

Show the last record of the table.


Query the two first names in table with the shortest and longest first names, as
well as their respective lengths.
Find the Manager id for each employee
Find the full name of all the managers and their Id
Get the second maximum salary with employee first name.
Difference in where and having Clause
Diff in Row number and Rank window function

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

Last_name Gender Join_date Dept_ID Salary City Dept_nam Manager_id


Arora Female 14-02-2020 1 100000 Bangalore HR 3
Verma Female 14-06-2011 2 80000 Delhi Admin 4
Singhal Male 14-02-2020 1 300000 Mumbai HR 3
Singh Male 14-02-2020 2 500000 Gurugram Admin 4
Bhati Male 14-06-2011 2 500000 Hyderabad Admin 4
Diwan Male 14-06-2011 3 200000 Chennai Account 6
Kumar Male 14-01-2020 3 75000 Kolkata Account 6
Chauhan Female 14-04-2011 1 90000 Bangalore HR 3

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

2. windows Delete all the duplicate records in a table

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

5. Date and string Calculate how old each publisher is Publisher


functions
Return pub_name and estd of those publishers, whose month of an establishment is equal to
the addition of 8 and modulus of the month part of the current date divided by 12. Pub_id Pub_name
joins Write a SQL query to find all numbers that appear at least three times consecutively.
Id Name
1 Joe
The Employee table holds all employees including their managers. Every employee has an Id,
and there is also a column for the manager Id. Given the Employee table, write a SQL query 2 Henry
that finds out employees who earn more than their managers.
3 Sam
4 Max
ID Record_date
1 2015-01-01
Given a Weather table, write a SQL query to find all dates’ Ids with higher temperature
compared to its previous (yesterday’s) dates. 2 2015-01-02
3 2015-01-03
4 2015-01-04
Table 1- Candidate
Id Name
1A
Write a sql to find the name of the winning candidate
Write a sql to find the name of the winning candidate 2B
3C
4D
5E
How many delivered/placed orders for every year (O/P: Year, Delivered Orders, Placed Four tables with respect to transactions are available:
Window function Orders) Table A: Order Date, City, Order ID, Customer ID, Amount Paid, D
Status (Placed/Delivered/Cancelled)
How many delivered/placed orders for every year on a state level Table B: City – State Mapping
What is the latest updated price of each item ID Table C: Order ID, Item ID, Quantity, Order Date
Table D: Item ID, Updated Date, Price
After creating a filtered table from a given table, how do we make a permanent table out of
that filtered table i.e. so that it is accessible to other users?
Find second and third largest salary using :
(a)Rank Function
(b)without using rank function
Write a query to extract top 25% of records based on salary
If there are 11 teams , and each team plays with every other team only once .How many
matches will be played? Write an sql query to display all the matches
Write a query to display the cumulative revenue in the transaction table.
.Get the article types generating revenue more than average revenue for an article type.
Get the frequency distribution of Number of items vs No.of orders, like
1 items are in how many orders, 2 items are in how many orders and so on
Calculate the difference between the first purchase date and second purchase date for each
customer
String and date Write a query to get the First day of the current month.
function
Extract the First, Middle and Last Name from Name column
Objective is to clean noise from data (column name - gender) : If gender is M then keep as
Case when M, if F then keep as F. If gender is marked as ‘m’ change to ‘M’, ‘f’ to F. All other values
should be labelled ‘Unknown’

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

Update Write Query to swap columns value. ID


1
2
3
Topics
Joins- self join, left join, inner join, outer join, cross join
SQL Aggregate functions- sum, minmax, avg, count, groupby, having
Data types, string and
Subquries
date functions
Window functions
Cases-Case when, if statements
Sql Union, UnionAll
Sql joins with comparision operators

Regular expressions, wildcards


SQL Constraints
Comparision functions and operators
Logical operators
Case operator,
Control flow functions ifnull(),
nullif(),if()
Cast functions- changing date format
Partitioning- Range partitioning, list partitioning, column
SQL Views, constraints
Indexes
Stored Procedures
Common Table Expressions (CTE)

Find duplicate records in a table


Group By , Having
Aggregation Query to find maximum salary from each department
(GROUP BY with
COUNT,
SUM,Max,Min,
Avg)

Joins Self join find the manager name for the employee where empid and managerid are on the
same table
Intermediate
Output Logic

End_date Start_date End_date


2015-10-02 2015-10-28 2015-10-29
2015-10-03 2015-10-30 2015-10-31
2015-10-04 2015-10-13 2015-10-15
2015-10-14 2015-10-01 2015-10-04
2015-10-15
2015-10-29
2015-10-31

MRP
ble 1 (Movie release data)

Release_dat
Genre
e
able 2 (Movie rental data)
Spend_amo
Movie_id
unt

Publisher

country Est_date

Salary Manager Id Employee


70000 3 Joe
80000 4
60000 Null
90000 Null
Temperature
10
25
20
30
Table 2- Vote
Id CandidateId
1 2
2 4
3 3
4 2
5 5
s with respect to transactions are available:
e, City, Order ID, Customer ID, Amount Paid, Delivery
atus (Placed/Delivered/Cancelled)
Table B: City – State Mapping
: Order ID, Item ID, Quantity, Order Date
ble D: Item ID, Updated Date, Price

seat_id
3
4
5

quesdtion_id answer_id q_num timestamp


285 null 1 123
285 124124 1 124
369 null 2 125
369 null 2 126

action_date user_id days_elapsed


12-02-2020 1 6
13-02-2020 2 3
11-02-2020 3 0
14-02-2020 4 Null
15-02-2020
15-02-2020
18-02-2020
19-02-2020
transaction_dat user_id superuser_da
e te
12-02-2020 1 14-02-2020
13-02-2020 3 15-02-2020
14-02-2020 2 17-02-2020
15-02-2020 4 Null
16-02-2020
17-02-2020
16-02-2020
15-02-2020
Order table Output table
quantity date sku sum(quantity)

Name ID
AA AA
BB BB
CC CC

nge partitioning, list partitioning, column partitioning


Query
Name
1
2
3
Topics Questions
Salary Table
id
Query to display the comparison result (higher/lower/same) of the average
1
salary of employees in a department to the company’s average salary.
2
3
Pivot Table or Case When Pivot the Occupation column in OCCUPATIONS so that each Name is sorted Name
alphabetically and displayed underneath its corresponding Occupation. The Abhishek
output column headers should be Doctor, Professor, Singer, and Actor, Ravi
respectively.
Shiva
Note: Print NULL when there are no more names corresponding to an
occupation.
Custome
Order_ID
r_ID
Query to find monthly level customer with highest purchase? c1 o1
c1 o1
c1 o1
Query to find order and the sequence of purchase for every customer
C1 o2
C1 o2
Query to find no of orders whose sp is greater than 500?
Address Table
Query to find how many orders are placed where order value is more Address_ID
than 500 for every city? A1

Query to find customer with highest purchase?


Advance Sub Queries

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

How to delete records from parent as well as child table

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 average order value for every customer?

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

Rides Table AccetedRides Table


ride_id user_id Request at ride_id drive_id ride_duration ride_distance
6 75 12/9/2019 10 1 38 63
1 54 2/4/2020 12 7 96 73

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

User Table Order Table


join_date brand order_id date item_id buyer_id seller_id
1/1/2020 LG 1 1/2/2020 4 1 2
2/10/2020 Samsung 2 1/8/2020 1 2 3

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

Hackers Table Submission Table


name date id hacker_id score
Rose 6/1/2016 1 1578 15
Angela 6/1/2016 2 20703 0
Frank 6/2/2016 3 1578 20
Patrick 6/2/2016 4 44065 50

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

Transaction Table Customer Table


Product_
Date
ID
MRP Quantity Customer_ID Gender
20190101 p1 100 2 C1 F
20190101 p2 200 1 C1 M
20190101 p3 500 1
20190103 p1 100 1 Product Table
Product_ID brand
p1 Nike
p2 Roadster
p3 Puma
p1 Mast & Harbor
Employee Table
id Name Salary Date
1 joe 50000 6/1/2016
2 henry 75000 6/1/2016
3 sam 60000 6/2/2016
4 max 90000 6/2/2016
Events
Join_date user_id type access_date
14-2-2020 1 F1 01-03-2020
14-2-2020 2 F2 02-03-2020
15-2-2020 2P 12-03-2020
15-2-2020 3 F2 15-03-2020
16-2-2020 5 F2 15-02-2020

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

Day Cancellation Rate


10/1/2013 0.33
10/2/2013 0
10/3/2013 0.5
month working_percentage
1 0
2 25

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

date hacked_id nameno_of_submission


6/1/2016 1578 Rose 2
6/2/2016 44065 Patrick 2

Id Month Salary
1 1 20

Department Employee Salary


IT max 90000
IT joe 50000
Sales henry 75000
Sales sam 60000

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

Sender Receiver Amount Transaction_Dat


e
5 2 10 12-02-2020
From the following table of transactions between two 1 3 15 13-02-2020
Group By , users, write a query to return the change in net 2 1 20 13-02-2020
Full Join worth for each user, ordered by decreasing net 2 3 25 14-02-2020
change. 3 1 20 15-02-2020
Aggregation 3 2 15 15-02-2020
(GROUP BY 1 4 5 16-02-2020
with COUNT, Date Items
SUM,Max,Mi 01-01-2020 apple
n, Avg) 01-01-2020 apple
From the following table containing a list of dates and 01-01-2020 pear
Groip By, items ordered, write a query to return the most frequent
Rank() item ordered on each date. Return multiple items in the 01-01-2020 pear
case of a tie. 01-02-2020 pear
01-02-2020 pear
01-02-2020 pear
01-02-2020 orange
games_play
player_id device_id event_date
1 2 2016-03-01 ed 5
Joins inner join Write a SQL query that reports the device that is first 1 2 2016-05-02 6
logged in for each player. 2 3 2017-06-25 1
3 1 2016-03-02 0
3 4 2018-07-03 5
N P
You are given a table, BST, containing two columns: N and P, 1 2
where N represents the value of a node in Binary Tree, and P is 3 2
the parent of N. Write a query to find the node type of Binary
Tree ordered by the value of the node. Output one of the 6 8
following for each node: 9 8
Root: If node is root node.
Leaf: If node is leaf node. 2 5
Inner: If node is neither root nor leaf node. 8 5
5 null
Conditional
Statement Case When A B C

Write a query identifying the type of each record in the TRIANGLES


table using its three side lengths. Output one of the following
statements for each record in the table:
Equilateral: It's a triangle with sides of equal length.
Isosceles: It's a triangle with sides of equal length.
Scalene: It's a triangle with sides of differing lengths.
Conditional
Statement Case When

Write a query identifying the type of each record in the TRIANGLES 20 20 23


table using its three side lengths. Output one of the following
statements for each record in the table:
Equilateral: It's a triangle with sides of equal length. 20 20 20
Isosceles: It's a triangle with sides of equal length.
Scalene: It's a triangle with sides of differing lengths. 20 21 22
Not A Triangle: The given values of A, B, and C don't form a triangle.

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

You might also like