Learneverythingai - 1
Learneverythingai - 1
Learneverythingai - 1
By Bemnet Girma
linkedin.com/in/bemnetdev
15+ Topics
70+ Practice Queries
50 SQL Query Questions from 15+ Companies
110+ Frequently Asked SQL Interview Questions
a G
airbnb
yR DOORDASH
Forbes yelp ESPT
IN JUST 10 PAGES
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
KEYWORDSs CREATE TABLE
Data is representation of raw facts, measurements, CREATE to create a new database object such as a table.
figures, or concepts in a formalized manner that have no CREATE TABLE department (
specific meaning.
did varchar(20),
Information is processed (organized or classified) data, name varchar(20) NOT NULL,
which has some meaningful values. CONSTRAINT PK_DEPT PRIMARY KEY(did)
Database an organized collection of data stored and
acessed electronically in a computer system.
INSERT DATA
DBMS are software systems that enable users to store,
retrieve, define and manage data in a database easily. INSERT INTO department VALUES
(D1, 'Management')
RDBMS is a type of DBMS that stores data in a row-based
table structure which connects related data elements. (D2, T).
(D3, 'Sales),
SQL isa database query language used for storing and ('D4', 'HR)
managing data in RDBMS.
did name
DATA TYPES
D1 Management
Data type is a data rule applicable to a particular column. D2 IT
NULL, CHAR, VARCHAR, INT, DATE, FLOAT, BOOLEAN D3 Sales
D4 HR
cONSTRAINTS
CREATE "employee" TABLE
Constraints are limitations or restrictions applied to a
column in a table, they are important to maintain data
integrity among tables.
CREATE TABLE employee(
eid int,
CHECK control the values being inserted.
name varchar(20) UNIQUE,
NOT NULL ensure that NULL value has not inserted. join_date date NOT NULL,
department char(2)
UNIQUE- ensure that every column value is unique.
CHECK (dep IN ('D1, 'D2', 'D3),
PRIMARY KEY - ensure that all values are UNIGQUE and salary int,
NOT NULL
manager int,
FOREIGN KEY create a parent-child r/ship b/n tables CONSTRAINT PK_ID PRIMARY KEY(eid),
CONSTRAINT FK_DID FOREIGN KEY(department)
COMMANDS
REFERENCES department(did)
Data Definition Language (DDL)
DCAT I DROP, CREATE, ALTER, TRUNCATE
eid name join_date dep salary manager
Data Query Language (DOL)
SELECT 101 David 2009-07-14 D1 50000 None
102 Sam 2010-06-24 D1 40000 101
Data Manipulation Language (DML)
103 Alicia 2011-05-11 D2 30000 102
UMID UPDATE, MERGE, INSERT, DELETE
104 Alex 2012-04-15 D2 20000 102
Data Control Language (DCL) 105 Robbi 2013-08-14 D2 20000 102
GRANT and REVOKE 106 2014-09-19 D3 8000 101
Jack
Transaction Control Language (TCL) 107 Tom 2015-11-12 None 5000 116
COMMIT, SAVEPOINT, ROLLBACK 108 Lily 2016-07-28 D3 1000 106
category brand name quantity price stock Rename sale table to 'sales
Phone Apple iPhone 13 1300.0 False ALTER TABLE sale
Phone Apple iPhone 12 6 1100.0 True
RENAME TO sales;
Phone Samsung Galaxy Note 20 5 1200.0 True
Phone Samsung Galaxy S21 4 1100.0 False Rename dep column to 'dept
Laptop Apple MacBook Pro 13 3 2000.0 True employee
ALTER TABLE
Laptop Apple MacBook Air 2 1200.0 True RENAME COLUMN dep TO dept;
Laptop Dell XPS 13 2000.0 False
Laptop Dell XPS 15 2300.0 True Alter dept column data type
Tablet Apple iPad 7th gen S60.0 False ALTER TABLE employee
Tablet Samsung Galaxy Tab A7 220.0 True ALTER COLUMN dept TYPE VARCHAR(2);
DUPLICATE TABLE Add new column 'Gender
Duplicate employee Table with Data ALTER TABLE
employee
CREATE table Backup AS ADD COLUMN Gender VARCHAR(20);
SELECT
Add new constraint GEN to Gender column
FROM employee ALTER TABLE employee
Duplicate employee Table without Data ADD CONSTRAINT GEN
CREATE table Replica AS CHECK (Gender IN (M', F));
SELECT
Remove GEN constraint
FROM employee ALTER TABLE employee
WHERE 1=2;
DROP CONSTRAINT GEN;
UPDATE DATA
Remove Gender column
Update manager of Tom ALTER TABLE employee
UPDATE employee DROP COLUMN Gender
SETmanager 106 DCL COMMANDS
WHERE name = Tom;
Grant single privilege
Update department and salary of Lily
GRANT SELECT ON Users TO Test'
UPDATE employee
= Grant multiple privilege
SET dep 'D3', salary 5000
WHERE name = "Lily; GRANT INSERT, UPDATE ON Users TO Test;
LEARN EVERYTHING AI DIWALI SALE
Build your career as a
Data Scientist from scratch with
DATA SCIENCE & ANALYTICS
COMBO cOURSE
PYTHON sQL MACHINELEARNING DEEP LEARNINNG
STATISTICcS POWERBI TABLEAU
COURSE FEATURES O-
Grab thiscombo courseat
Hands-on Practical Experience
1-1 Doubt Clearance
Course Completion certificate
Real world Capstone projects
26994 7999
Interview QNAs PDE
No prior coding experience required
ENROLL NOW
One time payment, lifetime access
Follow me on
Shivam Modi
Founder & CEO
www.learneverythingai.com
in
SALE
DIWALI
COMBO COURSE
Available at just
25994 (033742) R7999 ($99.99).
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
Grant ALL privilege
https://platform.stratascratch.com/coding/9688
GRANT ALL ON Users TO Test; churro-activity-datelcode type=l
Revoke single privilege
REVOKE SELECT ON Users TO Test
https://platform.stratascratch.com/coding/1000
Revoke multiple privilege 3-lyft-driver-wages?code typel
REVOKE INSERT, UPDATE ON Users TO Test';
a https://platform.stratascratch.com/coding,/9913
order-details?code type=l
SELECT E.name,
FROM project P
FULLJOIN employeeE
P.proj_name
ON E.name = P.person;
https://platform.stratascratch.com/coding/9894-
employee-cinc.-manager-salariesicode type name Proj_namne
None Ecommerce
None Inventory
https://platform.stratascratch.com/coding/100z Alex None
8-find-matching-hosts-and-quests-in-q-way-that- Alicia Inventory
they-are-both-of-the-same-gender-and- David Ecommerce
nationalityicode type=l
Jack None
Lily None
a https://platform.stratascratch.com/coding/1032
2-finding-USer-purchases?code type=
Robbi
Sam
Tom
None
Inventory
None
a https://platform.stratascratch.com/coding/9891-
CUstomer-detailsfcode type=l
Sam
Alicia
Alex
40000
30000
20000
500
500
500
40500
30500
20500
Robbi 10000 500 10500
RIGHT OUTER JOIN Jack 8000 500 8500
Fetch all employee name wrt projects they are working 5000
Tom 500 5500
SELECT E.name, P.proj_name
Lily 5000500 5500
FROM project P
RIGHT JOIN employee E SELF JOIN
ON E.name = P.person; Fetch all employee name with their manager
SELECT E.name, M.name as Manager
name Proj_name
Alex None
FROM employee as M
Alicia Inventory
JoIN employee as E
David ON M.eid = E.manager;
Ecommerce
Jack None name Manager
Lily None David
Sam
Robbi None Alicia Sam
Sam Inventory Alex Sam
Tom None Robbi Sam
Jack David
FULL OUTER JOIN (LEFT JOIN UNION RIGHT JOIN) Tom Jack
Fetch all employee with their correlated projects Lily Jack
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
NATURAL JOIN https://platform.stratascratch.com/coding/10112
SQL will Decide What Is the Join Condition by Itself. 8-cOunt-the-number-of-movies-that-abigail-
If there is no matching column name between two breslin-nominated-for-oscar?code type=l
tables wll perform
it CROSS JOIN.
f there is one common column between twwo https://platform.stratascratch.com/coding/1029
tables It will perform INNER JOIN. 9-finding-updated-records?code type=1
If there is more than one common column between
two tables It will perform INNER JOIN with ALL
https://platform.stratascratch.com/coding/1017
common columns. 6-bikes-last-used?code type=l
CONCATINATE
https://platform.stratascratch.com/coding/1006
Create a mail address for all employees using their 1-popularity-of-hack?code type=l
name and department with lowercase & @tcs.in domain.
SELECT DISTINCT (LOWER(E.name)|.
TILOWER(SUBSTRING(D.name, 0, 6))||'@tcs.in') https://platform.stratascratch.com/coding/9992-
AS Email, E.name find-artists-that-have-been-on-spotify-the-most:
number-of-timesRcode type=l
AS Emp name, D.name
AS Department https://platform.stratascratch.com/coding/9622-
FROM employee E
number-of-bathrooms-and-
JOIN department D ON D.did = E.dept; bedrooms2code type=l
[email protected] Alex IT
https://platform.stratascratch.com/coding/1015
[email protected] Robbi IT 6-number-of-units-per-nationalityRcode type=l
[email protected] Jack Sales
[email protected] Lily Sales
https://platform.stratascratch.com/coding/1004
yelp 8-top-businesses-with-most-reviews?code type=l
E https://platform.stratascratch.com/coding/9942-
largest-olympic code type=l
word counter
manage 4 name salary dept
and 4 David 50000 D1
of 2 Alicia 30000 D2
Jack 8000 D3
SUBQUERIES
https://platform.stratascratch.com/coding/100Z
SCALAR sUB QUERY
Z-income-by-fifle-and-genderècode type=
Fetch name and salary of employee who earn more than
average of total salary
The sub query always returns one row and one column
https://platform.stratascratch.com/coding/9897-
SELECT name, salary highest-salary-in-department2code type=
FROM employee
WHERE salary> ( https://platform.stratascratch.com/coding/9814
SELECT AVG(salary) cOunting-instances-in-textêcode type=l
FROM employee
CORRELATED SUBQUERY
Find the employees in each department who earn more
name salary than the average salary in that department
David 50000 sub query which is related to outer query like recursion.
Sam 40000 SELECT name, dept, salary
Alicia 30000 FROM employee E1
WHERE salary>(
SELECT AVG(salary)
https://platform.stratascratch.com/coding/1030
8-salaries-differences?code type=l FROM employee E2
WHERE E2.dept = E1.dept
https://platform.stratascratch.com/coding/1035
3-workers-with-the -highe st-salaries?code type=l name dept salary
David D1 50000
Alicia D2 30000
MULTIPLE ROW SUB QUERY
The sub query always returns multiple row. Jack D3 8000
Why do we write same query twice let's use "with clause? WINDOW JANALYTIC/ FUNCTION
Step 1: Find total sales per each brand (TSPB)
Step 2: Find average sales wrt all brands (ASPAB) Whenever we are using a window function, we
1. can create partitions using by grouping then
Step 3: Find brand where TSPB> ASPAB
2. apply any window function to each of those partitions.
WITH Total_Sales (brand, TSPB) AAS
ROW NUMBER
(SELECTS.brand, SUM(price) AS TSPB
Give roll number to all employees with and without dept
FROM sales S
SELECT E.eid, E.name, E.dept,
GROUP BY S.brand),
ROW_NUMBERO OVERO AS Roll,
AVG_SALES (ASPAB) AS
ROWNUMBER) OVER(PARTITION BY dept) AS Rp
(SELECT AVG(TSPB) AS ASPAB
FROM employee E;
FROM Total_Sales)
SELECT eid name dept Roll Rp
Easily readable
Fetch 1st employees from each dept to join the company
Easier to maintain and debug SELECT FROM (
Improvement of performance
SELECT E.eid, E.name, E.join_date, E.dept,
USE WITH CLAUSE WHEN YOU ARRE ROWNUMBER) OVER(PARTITION BY dept)
trying to use a particular subquery multiple times. AS RNO
writing a very complex SQL query and it becomes FROM employee E) XX
difficult to read and understand. WHERE X.RNO<2;
interested in a particular record from big table data.
eid name Join_date dept RNO
SQL COMMANDS WHICH ALLOW SUB QUERIES 107 Tom 2015-11-12 None 1
Rank all employees in each department based on their David D1 50000 None 40000 None HIGH
salary with and without duplicate rank skipping Sam D1 40000 50000 30000 LOW HIGH
SELECT E.eid, E.name, E.dept, E.salary, Alicia D2 30000 40000 20000 LOW HIGH
Alex D2 20000 30000 20000 LOW SAME
RANK) OVER(ORDER BY salary DESC) AS RNK,
DENSE RANK) OVER(ORDER BY salary DESC) AS Dr Robbi D2 20000 20000 8000 SAME HIGH
Jack D3 8000 20000 5000 LOW HIGH
FROM employee E;
Tom None 5000 8000 5000 LOW SAME
eid name dept salary RNK Dr Lily D3 5000 5000 None SAME None
101 David D1 50000 1 1
102
103
104
Sam
Alicia
Alex
D1
D2
D2
40000
30000
20000
2
3
4
a https://platform.stratascratch.com/coding/1031
9-monthly-percentage-difference?code type=l
F https://platform.stratascratch.com/coding,/9680-
most-profitable-companiesècode type=l
SELECT category, name, price,
FIRST_VALUE(name)
OVER(PARTITION BY category
https://platform.stratascratch.com/coding/1015 ORDER BY price DESC) AS Expensive,
9-ranking-most-active-guests?code type=l LAST_VALUE(name)
OVER(PARTITION BY category
https://platform.stratascratch.com/coding/1004 ORDER BY price DESC) AS Cheap
yelp ó-top-5-states-with-5-star FROM sales;
businesses?code type=l
categorY name price Expensivee Cheap
a https://platform.stratascratch.com/coding/514
markefing-campaign-success-
advanced?codetype=
Laptop
Laptop
Laptop
MacBook Pro
XPS 13
MacBook Air
2000
2000
1200
XPS 15
XPS 15
XPS 15
XPS 13
XPS 13
MacBook Air
Phone iPhone 13 1300 iPhone 13 iPhone 13
LAG and LEAD Phone Galaxy Note 1200 iPhone 133 Galaxy Note
Fetch a query to display if the salary of an employee is Phone iPhone 12 1100 iPhone 13 iPhone 12
higher, lower or equal to previous and next employee Phone Galaxy $21 1100 iPhone 13 Galaxy S21
LAG extracts previous record. Tablet ipad 7th gen 560 ipad 7th gen ipad 7th gen
LEADextracts the next record. Tablet Galaxy Tab A7 220 ipad 7th gen Galaxy Tab A7
WITH COMP AS (
SELECT E.eid, E.name, E.dept, E.salary, But, the above result is not correct for cheap column. That
is b/c of default frame clause SQL is using. What is frame?
LAG(salary) OVER(ORDER BY eid) AS P_SAL
LEAD(salary) OVER(ORDER BY eid) AS N_SAL
FROM employee E) FRAME CLAUSE
Fetch least expensive product of each category
SELECT,
Inside each partitions we can again create some subset of
CASE WHEN salary > P_SAL THEN 'HIGH'
records which is called as frames. So basically a frame is
WHEN salary « P_SAL THEN 'LOW' a subset of a partition.
WHEN salary P_SAL THEN 'SAME'
END P_Co, NB: Default FRAME CLAUSE is RANGE BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW. This
CASE WHEN salary > N_SAL THEN 'HIGH'
means our frame is all records between first record and
WHEN salary < N_SAL THEN 'LOw current record.
WHEN salary = N_SAL THEN 'SAME
END N_Co Not every window function will really be impacted by this
FROM COMP; default FRAME CLAUSE, It generally impacts the last_value,
nth_value and almost all aggregate functions.
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT category, brand, name, price, SELECT brand, namne,
FIRST_VALUE(name) OVER(PARTITION BY Category CASE WHEN X.BUCKETS = 1
THEN 'EXPENSIVVE
SELECT category, brand, name, price WHEN X.BUCKETS = 2 THEN 'MIDRANGE
FROM ( WHEN X.BUCKETS =3 THEN 'CHEAP
SELECT END PRICE RANGE
LAST_VALUE(name) FROM(
OVER(PARTITION BY Category SELECT
ORDER BY price DESC NTILE(3)
RANGE BETWEEN UNBOUNDED PRECEDING OVER(ORDER BY price DESC) AS BUCKETS
AND UNBOUNDED FOLLOWING) AS cheap FROM sales
FROM sales) X WHERE category '"Phone) X;
WHERE NAME = cheap; brand name PRICE RANGE
category brand name Price Apple iPhone 13 EXPENSIVE
Laptop Apple MacBook Air 1200 SamsungGalaxy Note 20 EXPENSIVE
force
salesforc
https:/Llplatform.stratascratch.com/codina/9917. CUME DIST/CUMMULATIVE DISTRIBUTION/
gverage-salariesècode type=l Fetch all products which are constituting the first 30% of
the data in products table based on price
DIFFERENCE BETWEEN ROWS AND RANGE It identify the distribution percentage of each record wrt
We can use the interchangeably unless that particular all the rows. Value of CUM_DIST is in range b/n 0 & 1.
row has some other rows with duplicated values. SELECT brand, category, name, (cd||%) AS cd
rows between unbounded preceding and current row FROM (
For ROWS, LAST_VALUE is the exact current row SELECT ROUND(
range between unbounded preceding and current row CUME_DISTO
.For RANGE, LAST_VALUE is the last row
OVER(ORDER BY price DESC)::numeric*100,2) AS cd
category name Price last_by_range last_by_rows FROM sales) X
Phone iPhone 13 1300 iPhone 13 iPhone 13 WHERE cd <= 30;
Phone Galaxy Note 20 1200 Galaxy Note 20 Galaxy Note 20
category brand name cd
Phone iPhone 12 1100 Galaxy S21 iPhone 12
Laptop Dell XPS 15 10%
Phone Galaxy $21 1100 Galaxy $21 Galaxy $21
Laptop Apple MacBook Pro 13 30%
NTH_VALUE Laptop Dell PS 13 30%
Fetch the 2nd most expensive product of each category
It access Nth record of the partition PERCENT_RANK It is
like percentile.
SELECT category, brand, name, price Write a Query to identify how much percentage more
FROM ( expensive is "iPhone 13" when compared to all products
SELECT *
SELECT category, brand, name, Perc
FROM (
NTH_VALUE(name, 2)
SELECT
OVER(PARTITION BY category
PERCENT RANKO
ORDER BY price DESC
OVER(ORDER BY price) AS PER_RANK,
RANGE BETWEEN UNBOUNDED PRECEDING
ROUND(PERCENT_RANKO
AND UNBOUNDED FOLLOWING) AS cheap
OVER(ORDER BY price)::numeric*100,2) AS Perc
FROM sales) X
FROM sales) X
WHERE NAME = cheap;
WHERE name = "iPhone 13;
category brand name Price
Laptop Apple MacBook Pro 13 2000 category brand name perc
Phone SamsungGalaxy Note 20 1200 Phone Apple iPhone 13 66.67
Tablet Samsung Galaxy Tab A7 220
FREQUENTLY ASKED SQL INTERVIEW QUESTIONS
NTILE
Segregate all phones into expensive, midrange & cheap https://www.edureka.co/bloa/interview
It segregate records of the partition into N no. of buckets Guestions/sql-interview-questions
LEARN EVERYTHING AI DIWALI SALE
Build your career as a
Data Scientist from scratch with
DATA SCIENCE & ANALYTICS
COMBO COURSSE
PYTHON sQL MACHINE LEARNING DEEP LEARNING
STATISTIcs POWER BI TABLEAU
COURSE FEATURESo-
Grab this combo courseat
Hands-on Practical Experience
1-1 Doubt Clearance
Course Completion certificate
Real world Capstone projects
269947999
Interview QnAs PDE ENROLL NOW
No prior coding experience required
One time payment, lifetime access
Follow me on
Shivam Modi
Founder & CEO
www.learneverythingai.com
in
SALE
DIWALI
COMBO COURSE
Available at just
25994 (033742) R7999 ($99.99).