0% found this document useful (0 votes)
152 views20 pages

SQL Simplified For All 1716213668

Uploaded by

Anmol Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
152 views20 pages

SQL Simplified For All 1716213668

Uploaded by

Anmol Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

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
IN JUST 10 PAGES
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
KEYWORDS CREATE TABLE
Data is representation of raw facts, CREATE - to create a new database object such as a
measurements, figures, or concepts in a table.
formalized manner that have no specific
meaning. CREATE TABLE
department ( did
Information is processed (organized or varchar(20),
classified) data, which has some meaningful name varchar(20) NOT NULL,
values. CONSTRAINT PK_DEPT PRIMARY
KEY(did)
Database is an organized collection of data
stored and accessed electronically in a computer );
system. INSERT DATA
DBMS are software systems that enable users INSERT INTO department
to store, retrieve, define and manage data in a
VALUES ('D1', 'Management'),
database easily.
('D2', 'IT'),
RDBMS is a type of DBMS that stores data in a ('D3', 'Sales'),
row-based table structure which connects related ('D4', 'HR')
data elements.
did name
SQL is a database query language used for D1 Managemen
storing and managing data in RDBMS. t
D2 IT
DATA TYPES
D3 Sales
Data type is a data rule applicable to a particular D4 HR
column. NULL, CHAR, VARCHAR, INT, DATE, FLOAT,
BOOLEAN CREATE “employee” TABLE
CONSTRAINTS CREATE TABLE
employee ( eid int,
Constraints are limitations or restrictions name varchar(20) UNIQUE,
applied to a column in a table, they are join_date date NOT NULL,
important to maintain data integrity among
department char(2)
tables.
CHECK (dep IN ('D1', 'D2', 'D3')),
CHECK - control the values being inserted. salary int,
manager int,
NOT NULL - ensure that NULL value has not CONSTRAINT PK_ID PRIMARY KEY(eid),
inserted. UNIQUE – ensure that every column CONSTRAINT FK_DID FOREIGN
KEY(department)
value is unique. PRIMARY KEY – ensure that all REFERENCES department(did)
values are UNIQUE and
NOT NULL
FOREIGN KEY - create a parent-child r/ship b/n
tables
COMMANDS
Data Definition Language (DDL) );
DCAT | DROP, CREATE, ALTER, TRUNCATE
eid name join_date dep salary manager
Data Query Language (DQL) 101 David 2009-07-14 D1 50000 None
SELECT
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 Jack 2014-09-19 D3 8000 101
107 Tom 2015-11-12 None 5000 116
Transaction Control Language (TCL) 108 Lily 2016-07-28 D3 1000 106
COMMIT, SAVEPOINT, ROLLBACK
.

PREREQUISITES CREATE “project” TABLE


Watch the ff. video to install PostgreSQL
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
CREATE TABLE proj_name varchar(20),
project ( job_description
person varchar(100)
varchar(20),
);
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
person proj_name 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 DELETE
Alicia Inventory manage products that are in storage or transitFROM Backup WHERE name
Ryan Ecommerce = 'Lily';
advertising and marketing efforts of a company
Ellen Inventory manage overall operations and help employees
Delete Alex and Robbi’s record
CREATE “sale” TABLE DELETE from Backup
CREATE TABLE sale ( WHERE name IN ('Alex', 'Robbi');
category varchar(20), Delete all records OR Truncate the whole backup
brand varchar(20), data
name varchar(50) NOT NULL, DELETE FROM Backup;
quantity int CHECK (quantity TRUNCATE TABLE Backup;
>= 0), price float NOT NULL,
stock boolean, DROP TABLE
CONSTRAINT PK_CITY PRIMARY Drop Backup table
KEY(name) DROP TABLE Backup;
);
ALTER TABLE
category brand name quantity price Rename
stock sale table to ‘sales’
Phone Apple iPhone 13 4 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
Laptop Apple MacBook Pro 13 3 2000.0 True ‘dept’ ALTER TABLE
Laptop Apple MacBook Air 2 1200.0 True employee RENAME COLUMN
Laptop Dell XPS 13 1 2000.0 False dep TO dept;
Laptop Dell XPS 15 2 2300.0 True
Tablet Apple iPad 7th gen 3 560.0 False Alter dept column data type
DUPLICATE
Tablet
TABLE
Samsung Galaxy Tab A7 2 220.0 True ALTER TABLE employee
Duplicate employee Table with Data ALTER COLUMN dept TYPE VARCHAR(2);
CREATE table Backup AS
Add new column ‘Gender’
SELECT *
ALTER TABLE employee
FROM employee;
ADD COLUMN Gender VARCHAR(20);
Duplicate employee Table without Data
CREATE table Replica AS Add new constraint GEN to Gender column
SELECT * ALTER TABLE employee
FROM employee ADD CONSTRAINT GEN
WHERE 1=2; CHECK (Gender IN ('M',
'F'));
UPDATE DATA
Remove GEN constraint
Update manager of ALTER TABLE
Tom UPDATE employee DROP
employee SET CONSTRAINT GEN;
manager = 106
Remove Gender
WHERE name =
column ALTER TABLE
'Tom';
employee DROP
Update department and salary of Lily COLUMN Gender;
UPDATE employee
DCL COMMANDS
SET dep = 'D3', salary = 5000
WHERE name = 'Lily'; Grant single privilege
GRANT SELECT ON Users TO 'Test';
Grant multiple privilege
GRANT INSERT, UPDATE ON Users TO 'Test';
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
Grant ALL privilege
GRANT ALL ON Users TO 'Test'; https://platform.stratascratch.com/coding/
9688- churro-activity-date?
Revoke single privilege . code_type=1
REVOKE SELECT ON Users TO 'Test'; .

https://platform.stratascratch.com/
Revoke multiple privilege coding/1000 3-lyft-driver-wages?
REVOKE INSERT, UPDATE ON Users TO code_type=1
'Test';
.

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


REVOKE ALL ON Users TO 'Test'; 9924- find-libraries-who-havent-
provided-the-email- address-in-2016-
TCL COMMANDS but-their-notice-preference- definition-
is-set-to-email?code_type=1
BEGIN and COMMIT Transaction
BEGIN; Fetch employees not in department D2
DELETE FROM and name either starts with ‘j’ or not end
employee WHERE with ‘y’
name = ‘Lily’; LIKE – STARTING, LIKE – ENDING, NOT IN, NOT LIKE, OR
COMMIT; SELECT name, dept
FROM employee
ROLLBACK to last commit WHERE dept NOT IN ('D2')
ROLLBACK; AND (name LIKE ('j%') OR name NOT LIKE
SAVEPOINT Transaction ('%y'));
SAVEPOINT point;
name dept
ROLLBACK to specific saved point David D1
ROLLBACK point; Sam D1
Jack D3
OPERATORS
.

Fetch three employees who earn more than https://platform.stratascratch.com/coding/


10000 Comparison (=, >, <, <=, >=, !=), 9972- find-the-base-pay-for-police-
captains?code_type=1
Order by and Limit SELECT name, salary
FROM employee .

WHERE salary > https://platform.stratascratch.com/


10000 ORDER BY coding/1002 6-find-all-wineries-which-
name LIMIT 3; produce-wines-by- possessing-aromas-
of-plum-cherry-rose-or- hazelnut?
name salary code_type=1
Alex 20000
Alicia 30000 DATE FUNCTIONS
David 50000 Fetch employee data who join on April
Extract year, month, day, hour, minute, second from
Fetch products in stock with price range 1000 date
to 1500 Between, Order by (Descending) SELECT *
AND, IN FROM employee
SELECT name, brand, price stock WHERE EXTRACT(MONTH FROM join_date) =
FROM sales '04';
WHERE price BETWEEN 1000 AND 1500
AND stock IN ('1') ORDER eid name join_date dep salary manager
BY name DESC; 104 Alex 2012-04-15 D2 20000 102

name brand price stock Fetch todays date


iPhone 12 Apple 1100.0 True To_Char convert number & date to a character
MacBook Air Apple 1200.0 True string.
Galaxy Note 20 Samsung 1200.0 True
SELECT TO_CHAR(CURRENT_DATE, 'Month dd,
yyyy')
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
AS todays_date;

todays_date
October 10, 2022
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
DISTINCT name
Fetch all brands in sales table Alicia
SELECT DISTINCT brand David
Ellen
FROM sales;
Ryan
brand Sam
Apple Fetch only employees who work on projects
Samsung SELECT name
Dell FROM employee
.
INTERSECT
https://platform.stratascratch.com/coding/ SELECT person
9650- find-the-top-10-ranked-songs-in- FROM project;
2010?code_type=1
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
CASE WHEN salary >= 30000 THEN 'High' project
WHEN salary BETWEEN 10000 AND 30000 SELECT person
THEN 'Mid'
FROM project
WHEN salary < 10000 THEN
EXCEPT
'Low' END AS Range
SELECT name
FROM employee
FROM employee;
ORDER BY 2
DESC; person
Ellen
name salary Range
David 50000 High Ryan
Sam 40000 High JOIN
Alicia 30000 High
Alex 20000 Mid
Robbi 10000 Mid
Jack 8000 Low
Tom 5000 Low
Lily 5000 Low

https://platform.stratascratch.com/coding/ INNER JOIN


9726- classify-business-type?
. code_type=1 Fetch all IT employees name wrt their
department SELECT E.name, D.name as
.
department FROM employee E
https://platform.stratascratch.com/coding/
9781- find-the-rate-of-processed- INNER JOIN department D
tickets-for-each- type?code_type=1 ON E.dept = D.did
WHERE D.name = 'IT';

SET
Fetch employees from Management & involve on
projects
SELECT name
FROM employee .

WHERE dept = https://platform.stratascratch.com/


'D1' UNION coding/1008 7-find-all-posts-which-
were-reacted-to-with-a- heart?
SELECT person code_type=1
FROM project;
name department
Alicia IT
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
Alex IT
Robbi IT
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
. Fetch all employee with their correlated projects
https://platform.stratascratch.com/coding/
9913- order-details?code_type=1

https://platform.stratascratch.com/coding/
9894- employee-and-manager-salaries?
.
code_type=1

https://platform.stratascratch.com/
coding/1007 8-find-matching-hosts-and-
guests-in-a-way-that- they-are-both-of-
the-same-gender-and- nationality?
code_type=1

https://platform.stratascratch.com/
coding/1032 2-finding-user-purchases?
code_type=1

LEFT OUTER JOIN


Fetch all project name with respected employee
name
SELECT E.name, P.proj_name
FROM project P
LEFT JOIN employee E
ON E.name =
P.person;
name proj_name
David Ecommerce
Sam Inventory
Alicia Inventory
None Ecommerce
None Inventory
.

https://platform.stratascratch.com/coding/
9891- customer-details?code_type=1

RIGHT OUTER JOIN


Fetch all employee name wrt projects they are
working
SELECT E.name, P.proj_name
FROM project P
RIGHT JOIN employee
E ON E.name =
P.person;
name Proj_name
Alex None
Alicia Inventory
David Ecommerce
Jack None
Lily None
Robbi None
Sam Inventory
Tom None

FULL OUTER JOIN (LEFT JOIN UNION RIGHT


JOIN)
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT E.name,
P.proj_name FROM
project P
FULL JOIN employee
E ON E.name =
P.person;
name Proj_name
None Ecommerce
None Inventory
Alex None
Alicia Inventory
David Ecommerce
Jack None
Lily None
Robbi None
Sam Inventory
Tom None

CROSS JOIN
Give 500 bonus for all employees
CREATE “Advance” TABLE
bonus
500

SELECT E.name, E.salary,


A.bonus, (E.salary +
A.bonus) as Net_Salary
FROM employee E
CROSS JOIN Advance A;
name salary bonus Net_Salary
David 50000 500 50500
Sam 40000 500 40500
Alicia 30000 500 30500
Alex 20000 500 20500
Robbi 10000 500 10500
Jack 8000 500 8500
Tom 5000 500 5500
Lily 5000 500 5500

SELF JOIN
Fetch all employee name with their
manager SELECT E.name, M.name
as Manager FROM employee as M
JOIN employee as
E ON M.eid =
E.manager;
name Manager
Sam David
Alicia Sam
Alex Sam
Robbi Sam
Jack David
Tom Jack
Lily Jack
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
NATURAL JOIN FROM -> JOIN -> WHERE -> GROUP BY ->
SQL will Decide What Is the Join Condition by HAVING
Itself. -> SELECT -> DISTINCT -> ORDER BY ->
 If there is no matching column name LIMIT
between two tables it will perform
CROSS JOIN.
 If there is one common column
between two tables It will perform
INNER JOIN.
 If there is more than one common column
between two tables It will perform INNER
JOIN with ALL common columns.

CONCATINATE
Create a mail address for all employees using
their name and department with lowercase &
@tcs.in domain. SELECT DISTINCT
(LOWER(E.name)||'.
'||LOWER(SUBSTRING(D.name, 0,
6))||'@tcs.in') AS Email, E.name
AS Emp_name,
D.name AS
Department
FROM employee E
JOIN department D ON D.did = E.dept;
Email Emp_name Department
[email protected] David Management
[email protected] Sam Management
[email protected] Alicia IT
[email protected] Alex IT
[email protected] Robbi IT
[email protected] Jack Sales
[email protected] Lily Sales
.

https://platform.stratascratch.com/coding/
9942- largest-olympics?code_type=1

GROUP BY AND AGGREGATION FUNCTIONS


Fetch total employee, min, max, average & total
salary of each department which have less than
3 employees. Count, Min, Max, Avg, Sum,
Group by, Having
SELECT D.name, COUNT(1) AS emp,
MIN(E. salary) AS Min,
MAX(E. salary) AS
Max, AVG(E. salary)
AS Avg, SUM(E.
salary) AS Total
FROM employee E
JOIN department D ON D.did = E.dept
GROUP BY D.name
HAVING COUNT(1) < 3;
Name emp Min Max Avg Total
Management 2 40000 50000 45000 90000
Sales 2 5000 8000 6500 13000

ORDER OF EXECUTION
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
https://platform.stratascratch.com/
coding/1012 8-count-the-number-of-
movies-that-abigail- breslin-nominated-
for-oscar?code_type=1

https://platform.stratascratch.com/
coding/1029 9-finding-updated-
records?code_type=1
.

https://platform.stratascratch.com/
coding/1017 6-bikes-last-used?
code_type=1

https://platform.stratascratch.com/
coding/1006 1-popularity-of-hack?
. code_type=1
.

https://platform.stratascratch.com/coding/
9992- find-artists-that-have-been-on-
spotify-the-most- number-of-times?
code_type=1
.

https://platform.stratascratch.com/coding/
9622- number-of-bathrooms-and-
bedrooms?code_type=1
.

https://platform.stratascratch.com/coding/
9653- count-the-number-of-user-events-
performed-by- macbookpro-users?
code_type=1

https://platform.stratascratch.com/
coding/1015 6-number-of-units-per-
. nationality?code_type=1

https://platform.stratascratch.com/
coding/1004 8-top-businesses-with-most-
. reviews?code_type=1
.

https://platform.stratascratch.com/coding/
9915- highest-cost-orders?code_type=1

https://platform.stratascratch.com/
coding/1004 9-reviews-of-categories?
. code_type=1

https://platform.stratascratch.com/coding/
9991- top-ranked-songs?code_type=1
.

https://platform.stratascratch.com/coding/
9728- inspections-that-resulted-in-
violations?code_type=1

https://platform.stratascratch.com/coding/
9782- customer-revenue-in-march?
. code_type=1

UNNEST AND STRING_TO_ARRAY


Fetch occurrence of words in job description which is
> 1 STRING_TO_ARRAY splits a string on a specified
delimiter character and returns an array.
UNNEST convert array in to records.
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT SELECT name, salary,
UNNEST(string_to_array(job_description, ' ')) dept FROM employee
AS word, COUNT(1) AS counter WHERE (dept, salary) IN (
FROM project SELECT dept,
GROUP BY word MAX(salary) FROM
HAVING COUNT(1) > 1 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
SCALAR SUB QUERY https://platform.stratascratch.com/
coding/1007 7-income-by-title-and-
Fetch name and salary of employee who earn
gender?code_type=1
more than average of total salary .

.
The sub query always returns one row and one https://platform.stratascratch.com/coding/
column 9897- highest-salary-in-department?
SELECT name, code_type=1
salary FROM
employee WHERE https://platform.stratascratch.com/coding/
salary > ( 9814- counting-instances-in-text?
SELECT AVG(salary) code_type=1
FROM employee
CORRELATED SUBQUERY
);
Find the employees in each department who earn
name salary more than the average salary in that
David 50000 department
Sam 40000 sub query which is related to outer query like
Alicia 30000 recursion.
SELECT name, dept,
. salary FROM employee
https://platform.stratascratch.com/ E1 WHERE salary > (
coding/1030 8-salaries-differences? SELECT AVG(salary)
code_type=1 FROM employee E2
WHERE E2.dept =
E1.dept
. );
https://platform.stratascratch.com/
coding/1035 3-workers-with-the-highest- name dept salary
salaries?code_type=1 David D1 50000
MULTIPLE ROW SUB QUERY Alicia D2 30000
The sub query always returns multiple row. Jack D3 8000
.

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


One column multiple rows 9663- find-the-most-profitable-
SELECT * company-in-the- financial-sector-of-the-
FROM department WHERE entire-world-along-with- its-continent?
did NOT IN ( code_type=1
SELECT DISTINCT(dept) https://platform.stratascratch.com/
FROM employee coding/1006 0-top-cool-votes?
WHERE dept IS NOT NULL . code_type=1
); https://platform.stratascratch.com/
coding/1030 0-premium-vs-freemium?
code_type=1

NESTED SUBQUERY
Employees who earn highest salary in each
department Multiple column multiple rows Find brand which sales are better than the
average of total sales across all brands
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
The sub query has another sub query.
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT *
FROM ( https://platform.stratascratch.com/
SELECT brand, SUM(price) AS coding/1006 4-highest-energy-
consumption?code_type=1
Total_Sales FROM sales
.

.
GROUP BY brand) https://platform.stratascratch.com/coding/
sales JOIN ( 9905- highest-target-under-manager?
SELECT AVG(Total_Sales) AS code_type=1
SALES FROM (
SELECT brand, SUM(price) AS https://platform.stratascratch.com/
Total_Sales FROM sales coding/1035 2-users-by-avg-session-
GROUP BY brand) X . time?code_type=1
) AVG_SALES
https://platform.stratascratch.com/
ON SALES.Total_Sales > AVG_SALES.Sales; coding/1028 5-acceptance-rate-by-
brand Total_Sales SALES . date?code_type=1
Apple 6160.0 4326.666666666666
https://platform.stratascratch.com/
coding/1028 4-popularity-percentage?
WE CAN USE DIFFERENT CLAUSES INSIDE SUB QUERIES
. code_type=1
[WITH (CTE), SELECT, FROM, WHERE, HAVING]
Why do we write same query twice let’s use "with" https://platform.stratascratch.com/coding/
9632- host-popularity-rental-prices?
clause? Step 1: Find total sales per each brand
code_type=1
(TSPB)
.

Step 2: Find average sales wrt all brands WINDOW /ANALYTIC/ FUNCTION
(ASPAB) Step 3: Find brand where TSPB >
Whenever we are using a window function, we
ASPAB
1. can create partitions using by grouping then
WITH Total_Sales (brand, TSPB) AS 2. apply any window function to each of those
(SELECT S.brand, SUM(price) AS partitions.
TSPB FROM sales S ROW NUMBER
GROUP BY S.brand), Give roll number to all employees with and without
AVG_SALES (ASPAB) AS dept
(SELECT AVG(TSPB) AS SELECT E.eid, E.name, E.dept,
ASPAB ROW_NUMBER() OVER() AS Roll,
FROM ROW_NUMBER() OVER(PARTITION BY dept) AS
Total_Sales) Rp
SELECT * FROM employee E;
FROM Total_Sales
TS JOIN eid name dept Roll Rp
AVG_SALES AV 101 David D1 1 1
ON TS. TSPB > AV.ASPAB; 102 Sam D1 2 2
103 Alicia D2 3 1
brand TSPB ASPAB 104 Alex D2 4 2
Apple 6160.0 4326.666666666666 105 Robbi D2 5 3
106 Jack D3 6 1
ADVANTAGES OF USING WITH CLAUSE 108 Lily D3 7 2
 Easily readable 107 Tom None 8 1
 Easier to maintain and debug
 Improvement of performance Fetch 1st employees from each dept to join the
company
USE WITH CLAUSE WHEN YOU ARE SELECT * FROM (
 trying to use a particular subquery multiple SELECT E.eid, E.name, E.join_date,
times. E.dept, ROW_NUMBER()
 writing a very complex SQL query and it OVER(PARTITION BY dept) AS RNO
becomes difficult to read and understand. FROM employee E) X
 interested in a particular record from big WHERE X.RNO < 2;
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 1
103 Alicia 2011-05-11 D2 1
106 Jack 2014-09-19 D3 1
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
RANK and DENSE_RANK COMP;
Rank all employees in each department based
on their salary with and without duplicate
rank skipping SELECT E.eid, E.name, E.dept,
E.salary,
RANK() OVER(ORDER BY salary DESC) AS
RNK, DENSE_RANK() OVER(ORDER BY salary
DESC) AS Dr
FROM employee E;
eid name dept salary RNK Dr
101 David D1 50000 1 1
102 Sam D1 40000 2 2
103 Alicia D2 30000 3 3
104 Alex D2 20000 4 4
105 Robbi D2 20000 5 4
106 Jack D3 8000 6 5
107 Tom None 5000 7 6
108 Lily D3 5000 7 6

https://platform.stratascratch.com/coding/
9680- most-profitable-companies?
.
code_type=1

https://platform.stratascratch.com/
coding/1015 9-ranking-most-active-
. guests?code_type=1
.

https://platform.stratascratch.com/
coding/1004 6-top-5-states-with-5-
star- businesses?code_type=1

https://platform.stratascratch.com/
coding/514- marketing-campaign-
success- advanced?code_type=1

LAG and LEAD


Fetch a query to display if the salary of an
employee is higher, lower or equal to previous
and next employee LAG extracts previous
record.
LEAD extracts the next record.
WITH COMP AS (
SELECT E.eid, E.name, E.dept, E.salary,
LAG(salary) OVER(ORDER BY eid) AS
P_SAL, LEAD(salary) OVER(ORDER BY eid)
AS N_SAL
FROM employee E)
SELECT *,
CASE WHEN salary > P_SAL THEN
'HIGH' WHEN salary < P_SAL
THEN 'LOW' WHEN salary =
P_SAL THEN 'SAME'
END P_Co,
CASE WHEN salary > N_SAL THEN
'HIGH' WHEN salary < N_SAL
THEN 'LOW' WHEN salary =
N_SAL THEN 'SAME'
END N_Co
FROM
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
name dept salary P_SAL N_SAL P_Co N_Co
David D1 50000 None 40000 None HIGH
Sam D1 40000 50000 30000 LOW HIGH
Alicia D2 30000 40000 20000 LOW HIGH
Alex D2 20000 30000 20000 LOW SAME
Robbi D2 20000 20000 8000 SAME HIGH
Jack D3 8000 20000 5000 LOW HIGH
Tom None 5000 8000 5000 LOW SAME
Lily D3 5000 5000 None SAME None
.

https://platform.stratascratch.com/
coding/1031 9-monthly-percentage-
difference?code_type=1

FIRST_VALUE and LAST_VALUE


Query to display the most & least expensive
product under each category (corresponding
to each record) FIRST_VALUE extracts first
record of the partition.
LAST_VALUE extracts last record of the
partition. SELECT category, name,
price, FIRST_VALUE(name)
OVER(PARTITION BY category
ORDER BY price DESC) AS
Expensive, LAST_VALUE(name)
OVER(PARTITION BY category
ORDER BY price DESC) AS
Cheap FROM sales;
category name price Expensive Cheap
Laptop XPS 15 2300 XPS 15 XPS 15
Laptop MacBook Pro 2000 XPS 15 XPS 13
Laptop XPS 13 2000 XPS 15 XPS 13
Laptop MacBook Air 1200 XPS 15 MacBook Air
Phone iPhone 13 1300 iPhone 13 iPhone 13
Phone Galaxy Note 1200 iPhone 13 Galaxy Note
Phone iPhone 12 1100 iPhone 13 iPhone 12
Phone Galaxy S21 1100 iPhone 13 Galaxy S21
Tablet ipad 7th gen 560 ipad 7th gen ipad 7th gen
Tablet Galaxy Tab A7 220 ipad 7th gen Galaxy Tab A7

But, the above result is not correct for cheap


column. That is b/c of default frame clause SQL is
using. What is frame?

FRAME CLAUSE
Fetch least expensive product of each category
Inside each partitions we can again create some
subset of records which is called as frames. So
basically a frame is a subset of a partition.

NB: Default FRAME CLAUSE is RANGE BETWEEN


UNBOUNDED PRECEDING AND CURRENT ROW.
This
means our frame is all records between first record
and current record.

Not every window function will really be impacted by


this 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, cheap It segregate records of the partition into
FIRST_VALUE(name) OVER(PARTITION BY N no. of buckets
category SELECT category, brand, name, price
FROM (
SELECT *,
LAST_VALUE(name)
OVER(PARTITION BY category
ORDER BY price DESC
RANGE BETWEEN UNBOUNDED
PRECEDING AND UNBOUNDED
FOLLOWING) AS cheap
FROM sales) X
WHERE NAME =
cheap;
category brand name Price
Laptop Apple MacBook Air 1200
Phone Samsung Galaxy S21 1100
Tablet Samsung Galaxy Tab A7 220
.

https://platform.stratascratch.com/coding/
9917- average-salaries?code_type=1

DIFFERENCE BETWEEN ROWS AND RANGE


We can use the interchangeably unless that
particular row has some other rows with
duplicated values.
rows between unbounded preceding and current row
 For ROWS, LAST_VALUE is the exact current
row
range between unbounded preceding and current row
 For RANGE, LAST_VALUE is the last row
category name Price last_by_range last_by_rows
Phone iPhone 13 1300 iPhone 13 iPhone 13
Phone Galaxy Note 20 1200 Galaxy Note 20 Galaxy Note 20
Phone iPhone 12 1100 Galaxy S21 iPhone 12
Phone Galaxy S21 1100 Galaxy S21 Galaxy S21

NTH_VALUE
Fetch the 2nd most expensive product of each
category It access Nth record of the partition
SELECT category, brand, name,
price FROM (
SELECT *,
NTH_VALUE(name,
2)
OVER(PARTITION BY category
ORDER BY price DESC
RANGE BETWEEN UNBOUNDED
PRECEDING AND UNBOUNDED
FOLLOWING) AS cheap
FROM sales) X
WHERE NAME =
cheap;
category brand name Price
Laptop Apple MacBook Pro 13 2000
Phone Samsung Galaxy Note 20 1200
Tablet Samsung Galaxy Tab A7 220
NTILE
Segregate all phones into expensive, midrange &
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT brand, name,
CASE WHEN X.BUCKETS = 1 THEN 'EXPENSIVE'
WHEN X.BUCKETS = 2 THEN 'MIDRANGE'
WHEN X.BUCKETS = 3 THEN 'CHEAP'
END PRICE_RANGE
FROM (
SELECT *,
NTILE(3)
OVER(ORDER BY price DESC) AS BUCKETS
FROM sales
WHERE category = 'Phone') X;
brand name PRICE_RANGE
Apple iPhone 13 EXPENSIVE
Samsung Galaxy Note 20 EXPENSIVE
Apple iPhone 12 MIDRANGE
Samsung Galaxy S21 CHEAP

CUME_DIST / CUMMULATIVE DISTRIBUTION /


Fetch all products which are constituting the first
30% of the data in products table based on price
It identify the distribution percentage of each record
wrt all the rows. Value of CUM_DIST is in range
b/n 0 & 1. SELECT brand, category, name,
(cd||'%') AS cd FROM (
SELECT *, ROUND(
CUME_DIST()
OVER(ORDER BY price DESC)::numeric*100,2)
AS cd FROM sales) X
WHERE cd <= 30;
category brand name cd
Laptop Dell XPS 15 10%
Laptop Apple MacBook Pro 13 30%
Laptop Dell XPS 13 30%

PERCENT_RANK - It is like percentile.


Write a Query to identify how much percentage
more expensive is "iPhone 13" when compared to all
products SELECT category, brand, name, Perc
FROM (
SELECT *,
PERCENT_RANK()
OVER(ORDER BY price) AS PER_RANK,
ROUND(PERCENT_RANK()
OVER(ORDER BY price)::numeric*100,2) AS Perc
FROM sales) X
WHERE name = 'iPhone 13';
category brand name perc
Phone Apple iPhone 13 66.67
.

FREQUENTLY ASKED SQL INTERVIEW QUESTIONS


https://www.edureka.co/blog/
interview- questions/sql-interview-
questions

You might also like