You are on page 1of 15

SQL SIMPLIFIED FOR ALL

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

PREREQUISITEs CREATE "project" TABLE


Watch the ff. video to install PostgreSQL DBMS
www.youtube.com/watch=CTOpoiJPn9M&t=1058s
CREATE TABLE project (
upyter Use the ff. video to connect DB to Jupyter notebook
person varchar(20),
www.y.outube.com/watchv=LhKi- -CCfY proj name varchar(20),
You can get all the queries in my Github repo job_description varchar(100)
www.github.com/bemnetdey/SQL/blob/main/s.ipynb
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
person projname job description DELETE DATA
David Ecommerce generate and manage sales via online channels
Sam Inventory manage location and pricing of inventory Delete Lily's record
Alicia Inventory manage products that are in storage or transit DELETE FROM Backup
Ryan Ecommerce advertising and marketing efforts of a companyY WHERE name = "Lily
Ellen Inventory manage overall operations and help employees
Delete Alex and Robbi's record
CREATE "sale" TABLE DELETEfrom Backup
WHERE name IN (Alex', 'Robbi);
CREATE TABLE sale(
category varchar(20), Delete all records OR Truncate the whole backup data
DELETE FROM Backup;
brand varchar(20),
name varchar(50) NOT NULL, TRUNCATE TABLE Backup;

quantity int CHECK (quantity > = 0), DROP TABLE


price float NOT NULL
Drop Backup table
stock boolean,
DROP TABLE Backup
CONSTRAINT PK_CITY PRIMARY KEY(name)
ALTER TABLE

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

Python Machine Deep SQL


Learning Learning

Power Bi Tableau Statistics Interview


QnA PDF

DATA SCIENCE & ANALYTICS

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';

Revoke ALL privilege https://platform.stratascratch.com/coding/9924-


REVOKE ALL ON Users TO Test; find-libraries-who-havent-provided-the-email-
address-in-2016-but-their-notice-preference
TCL COMMANDS definition-is-set-to-email?code type=l

BEGIN and COMMIT Transaction


Fetch employees not in department D2 and
BEGIN;
name either starts with j' or not end with 'y'
DELETE FROM employee LIKE STARTING, LIKE ENDING, NOT IN, NOT LIKE, OR
WHERE name = "Lily SELECT name, dept
COMMIT; FROM employee
ROLLBACK to last commit WHERE dept NOT IN (D2)
ROLLBACK; AND (name LIKE (J%) OR name NOT LIKE (%y);

SAVEPOINT Transaction name dept


SAVEPOINT point; David D1
Sam D1
ROLLBACK to specific saved point Jack D3
ROLLBACK point;
OPERATORS https://platform.stratascratch.com/coding/9972-
find-the-base-pay-for-police-
Fetch three employees who earn more than 10000 captainsècode typel
Comparison (,>, <, =, >=,=), Order by and Limit
SELECT name, salary
FROM employee https://platform.stratascratch.com/coding/1002
WINE
NE6-find-all-wineries- which-produce-wines-by-
WHERE salary> 10000 pOssessing-aromas-of-plum-cherry-rose-or
MAGAZINE
ORDER BY name hazelnut?code type=1
LIMIT 3;
DATE FUNCTIONS
name salary
Alex 20000 Fetch employee data who join on April
Alicia Extract year, month, day, hour, minute, second from date
30000
SELECT
David 50000
FROM employee
=
Fetch products in stock with price range 1000 to 1500 WHERE EXTRACT(MONTH FROM join_date) '04';
Between, Order by (Descending) AND, IN
SELECT name, brand, price stock eid name join_date dep salary manager
FROM sales 104 Alex 2012-04-15 D2 20000 102
WHERE price BETWEEN 1000 AND 1500
AND stock IN (1) Fetch todays date
ORDER BY name DESC;
To_Char convert number & date to a character string.
SELECT TO_CHAR(CURRENT_DATE, "Month dd, yyyy)
name brand price stock AS todays_date
iPhone 12 Apple 1100.0 True
MacBook Air Apple 1200.0 True todays_date
Galaxy Note 20 Samsung 1200.0 True October 10, 2022
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
DISTINCT name
Alicia
Fetch all brands in sales table
David
SELECT DISTINCT brand
Ellen
FROM sales;
Ryan
brand Sam
Apple Fetch only employees who work on projects
Samsun9 SELECT name
Dell FROM employee
INTERSECT
https://platform.stratascratch.com/coding/9650- SELECT person
find-the-top-10-ranked-songs-in- FROM project;
20102code type=l
name
Alicia
CASE STATEMENT
David
Categorize employees based on their salary Sam
SELECT name, salary,
Fetch person who is not an employee but work on project
CASE WHEN salary > = 30000 THEN High' SELECT person
WHEN salary BETWEEN 10000 AND 30000 THEN 'Mid'
FROM project
WHEN salary< 10000 THEN 'Low
EXCEPT
END AS Range
FROM employee
SELECTname
FROM employee;
ORDER BY 2 DESC;
person
name salary Range
Ellen
David 50000 High
Sam 40000 High Ryan
Alicia 30000 High JOIN
Alex 20000 Mid
Robbi 10000 Mid
LEFT RIGHT
Jack 8000 Low
JOIN JOIN
Tom 5000 Low
Lily 5000 Low
B) INNER
JOIN
(AB FULL
JOIN
https://platform.stratascratch.com/coding/9726-
classify-business-type?code type=l INNER JOIN
Fetch all IT employees name wrt their department
SELECT E.name, D.name as department
https://platform.stratascratch.com/coding/9781 FROM employee E
find-the-rate-of-processed-tickets-for-each
type?code type=l INNER JOIN department D
ON E.dept = D.did
WHERE D.name = 'IT;
SET
name department
Fetch employees from Management & involve on projects
Alicia IT
SELECT name
Alex IT
FROM employee
Robbi IT
WHERE dept = 'D1'|
UNION https://platform.stratascratch.com/coding/1008
SELECT person Z-find-all-posts-which-were- reacted-to-with-a
FROM project; heart@code type=l
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev

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

LEFT OUTER JOIN CROSS JOIN


Fetch all project name with respected employee name Give 500 bonus for all employees
SELECT E.name, P.proj_name
CREATE"Advance'" TABLE
FROM project P
LEFT JOIN employee E bonus
ON E.name = P.person; 500

name proj_name SELECT E.name, E.salary, A.bonus,


David Ecommerce (E.salary + A.bonus) as Net_Salary
Sam Inventoryy
FROM employee E
Alicia Inventory CROSS JIN Advance A;
None Ecommerce
None Inventory name salary bonus Net_Salary
David 50000 500 50500

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 Emp_name Department


https://platform.stratascratch.com//coding/9653-
david.manag@tcs.in David Management
count-the-number-of-user-events-performed-by-
sam.manag@tcs.in Sam Management macbookpro-users?code type=1
alicia.it@tcs.in Alicia IT

alex.it@tcs.in Alex IT
https://platform.stratascratch.com/coding/1015
robbi.it@tcs.in Robbi IT 6-number-of-units-per-nationalityRcode type=l
jack.sales@tcs.in Jack Sales
lily.sales@tcs.in 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

GROUP BY AND AGGREGATION FUNCTIONS


Fetch total employee, min, max, average & total salary
a https://platform.stratascratch.com/coding/9915-
highest-cost-orders?code type=El

of each department which have less than 3 employees.


Count, Min, Max, Avg, Sum, Group by, Having https://platform.stratascratch.com/coding/1004
yalpas
9-revie ws-of-categories?code type=l
SELECT D.name, COUNT(1) AS enmp,
MINE. salary) AS Min,
MAX(E. salary) AS Max, https://plarform.stratascratch.com/coding/9991-
AVG(E. salary) AS Avg top-ranked-songsfcode type=
SUME. salary) AS Total
FROM employee E https://platform.stratascratch.com/coding/9728-
JOIN department D ON D.did = E.dept inspections-that-resulted-in-
violations&code typeEl
GROUP BY D.name
HAVING COUNT(1) < 3;
https://platform.stratascratch.com/coding/9782-
Name emp Min Max Avg Total CUstomer-revenue-in-marchécode typel
Management 2 40000 50000 45000 90000
Sales 2 5000 8000 6500 13000
UNNEST AND STRING_TO_ARRAY
ORDER OF EXECUTION Fetch occurrence of words in job description which is >1|
STRING TO_ARRAY splits a string on a specified delimiter
FROM->JOIN -> WHERE -> GROUP BY -> HAVING
character and returns an array.
->SELECT -> DISTINCT-> ORDER BY -> LIMIT UNNEST convert array in to records.
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT UNNEST(string_to_array(job_description, ")) SELECT name, salary, dept
AS word, COUNT(1) AS counter FROM employee
FROM project WHERE (dept, salary) IN
GROUP BY word SELECTdept, MAX(salary)
HAVING COUNT(1) > 1 FROM employee
ORDER BY counter DESC; GROUP BY dept

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

Find department which do not have any employees https://platform.stratascratch.com/coding/9663-


One column multiple rows find-the-most-profitable-company-in-the-
SELECT F financial-sector-of-the-entire-world-along-with-
its-continenfêcode type=l
FROM department
WHERE did NOT IN (

SELECT DISTINCT(dept) https://platform.stratascratch.com/coding/1006


yelps O-top-cool-votes?code type=l
FROM employee
WHERE dept IS NOT NULL
https://platform.stratascratch.com/codina/1030
O-premium-vs-freemiumfcode type=l
did department
D4 HR
NESTED SUBQUERY
Find brand which sales are better than the average of
Employees who earn highest salary in each department total sales across all brands
Multiple column multiple rows The sub qvery has another sub query.
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT
https://platform.stratascratch.com/coding/1006
FROM 4-highest-energy-consumptionècode type=l
SELECT brand, SUM(price) AS Total_Sales
FROM sales orce
salesforce
https:l/platform.stratascratch.com/coding/9905-
GROUP BY brand) sales highest-target-under-manager?code typel
JOIN (
SELECT AVG(Total_Sales) AS SALES https://platform.stratascratch.com/coding/1035
FROM 2-Users-by-Gvg-session-timeicode typeET
SELECT brand, SUM(price) AS Total_Sales
FROM sales
https://platform.stratascratch.com/coding/1028
GROUP BY brand) X S-CICceptaince-rate-by-date?code type=
AVG_SALES
ON SALES.Total_Sales> AVG_SALES.Sales;
https://platform.stratascratch.com/coding/1028
brand Total_Sales SALES 4-popularity-percentage?code type=l
Apple 6160.0 4326.666666666666
https://platform.stratascratch.com/coding/9632-
WE CAN USE DIFFERENT CLAUSES INSIDE SUB QUERIES
host-popularity-rental-prices?code type=l1
[WITH (CTE), SELECT, FROM, WHERE, HAVING]

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

FROM Total_Sales TS 101 David D1 1


102 Sam D1 2
JOIN AVG_SALES AV
103 Alicia D2
ON TS. TSPB > AV.ASPAB;
104 Alex D2 2

brand TSPB ASPAB 105 Robbi D2 5 3

Apple 106 Jack D3 5 1


6160.0 4326.666666666666
108 Lily D3 7 2
ADVANTAGES OF USING WITH CLAUSE 107 Tom None 1

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

INSERT, UPDATE, DELETE] 101 David 2009-07-14 D1


103 Alicia 2011-05-11 D2
106 Jack 2014-09-19 D3
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
RANK and DENSE_RANK name dept salary P_SAL N_SAL P_Co N_Co

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

105 Robbi D2 20000 5 4

106 Jack D3 8000 6 FIRST_VALUE and LAST_VALUE


107 Tom None 5000 7 Query to display the most & least expensive product
108 Lily D3 5000 7 under each category (corresponding to each record)
FIRST_VALUE extracts first record of the partition.
LAST_VALUE extracts last record of the partition.

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

Laptop XPS 15 2300 XPS 15 XPS 15

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

Phone SamsungGalaxy$21 1100 Apple iPhone 12 MIDRANGE


Tablet Samsung Galaxy Tab A7 220 SamsungGalaxy S21 CHEAP

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

Python Machine Deep SQL


Learning Learning

Power Bi Tableau Statistics Interview


QnA PDF

DATA SCIENCE & ANALYTICS

COMBO COURSE

Available at just
25994 (033742) R7999 ($99.99).

You might also like