0% found this document useful (0 votes)
70 views11 pages

SQL Simplified

This document provides a summary of SQL concepts and commands in 10 pages. It covers topics such as data types, constraints, SQL commands for data definition, manipulation, and control. Examples of creating tables, inserting and deleting data, joining tables, and altering table structures are given. The prerequisites for following along include installing PostgreSQL and connecting it to Jupyter notebooks. Key SQL concepts are simplified for beginners to learn SQL quickly.

Uploaded by

Harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
70 views11 pages

SQL Simplified

This document provides a summary of SQL concepts and commands in 10 pages. It covers topics such as data types, constraints, SQL commands for data definition, manipulation, and control. Examples of creating tables, inserting and deleting data, joining tables, and altering table structures are given. The prerequisites for following along include installing PostgreSQL and connecting it to Jupyter notebooks. Key SQL concepts are simplified for beginners to learn SQL quickly.

Uploaded by

Harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

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, 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 is an organized collection of data stored and );
accessed 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', 'IT'),
('D3', 'Sales'),
SQL is a 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
Constraints are limitations or restrictions applied to a CREATE “employee” TABLE
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 UNIQUE and salary int,
NOT NULL
manager int,
FOREIGN KEY - create a parent-child r/ship b/n tables CONSTRAINT PK_ID PRIMARY KEY(eid),
COMMANDS CONSTRAINT FK_DID FOREIGN KEY(department)
REFERENCES department(did)
Data Definition Language (DDL) );
DCAT | DROP, CREATE, ALTER, TRUNCATE
eid name join_date dep salary manager
Data Query Language (DQL)
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 Jack 2014-09-19 D3 8000 101
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?v=CTOpojJPn9M&t=1058s
CREATE TABLE project (
Use the ff. video to connect DB to Jupyter notebook
person varchar(20),
www.youtube.com/watch?v=LhKj-_-CCfY proj_name varchar(20),
You can get all the queries in my Github repo job_description varchar(100)
www.github.com/bemnetdev/SQL/blob/main/s.ipynb
);
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
Alicia Inventory manage products that are in storage or transit DELETE FROM Backup
Ryan Ecommerce advertising and marketing efforts of a company WHERE name = 'Lily';
Ellen Inventory manage overall operations and help employees
Delete Alex and Robbi’s record
CREATE “sale” TABLE DELETE from Backup
WHERE name IN ('Alex', 'Robbi');
CREATE TABLE sale (
category varchar(20), Delete all records OR Truncate the whole backup data
brand varchar(20), DELETE FROM Backup;
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 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 ‘dept’
Laptop Apple MacBook Pro 13 3 2000.0 True ALTER TABLE employee
Laptop Apple MacBook Air 2 1200.0 True
RENAME COLUMN dep TO dept;
Laptop Dell XPS 13 1 2000.0 False
Laptop Dell XPS 15 2 2300.0 True Alter dept column data type
Tablet Apple iPad 7th gen 3 560.0 False ALTER TABLE employee
Tablet Samsung Galaxy Tab A7 2 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;
SET manager = 106
DCL COMMANDS
WHERE name = 'Tom';
Grant single privilege
Update department and salary of Lily
GRANT SELECT ON Users TO 'Test';
UPDATE employee
SET dep = 'D3', salary = 5000 Grant multiple privilege
WHERE name = 'Lily'; GRANT INSERT, UPDATE ON Users TO 'Test';
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-date?code_type=1
.
Revoke single privilege
REVOKE SELECT ON Users TO 'Test'; .

https://platform.stratascratch.com/coding/1000
Revoke multiple privilege 3-lyft-driver-wages?code_type=1
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=1

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_type=1
Comparison (=, >, <, <=, >=, !=), Order by and Limit
SELECT name, salary .

https://platform.stratascratch.com/coding/1002
FROM employee 6-find-all-wineries-which-produce-wines-by-
WHERE salary > 10000 possessing-aromas-of-plum-cherry-rose-or-
ORDER BY name hazelnut?code_type=1
LIMIT 3;
DATE FUNCTIONS
name salary
Alex 20000 Fetch employee data who join on April
Alicia 30000 Extract year, month, day, hour, minute, second from date
David 50000 SELECT *
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
To_Char convert number & date to a character string.
ORDER BY name DESC;
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
Fetch all brands in sales table Alicia
David
SELECT DISTINCT brand
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/9650- SELECT person
find-the-top-10-ranked-songs-in- FROM project;
2010?code_type=1
name
CASE STATEMENT Alicia
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'
WHEN salary < 10000 THEN 'Low'
FROM project
END AS Range EXCEPT
FROM employee SELECT name
FROM employee;
ORDER BY 2 DESC;
person
name salary Range
David 50000 High Ellen
Sam 40000 High Ryan
Alicia 30000 High JOIN
Alex 20000 Mid
Robbi 10000 Mid
Jack 8000 Low
Tom 5000 Low
Lily 5000 Low

https://platform.stratascratch.com/coding/9726-
classify-business-type?code_type=1 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=1 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 7-find-all-posts-which-were-reacted-to-with-a-
FROM project; heart?code_type=1
SQL SIMPLIFIED FOR ALL linkedin.com/in/bemnetdev
SELECT E.name, P.proj_name
.

https://platform.stratascratch.com/coding/9913-
order-details?code_type=1 FROM project P
FULL JOIN employee E
ON E.name = P.person;
https://platform.stratascratch.com/coding/9894-
employee-and-manager-salaries?code_type=1 name Proj_name
. None Ecommerce
.
None Inventory
https://platform.stratascratch.com/coding/1007 Alex None
8-find-matching-hosts-and-guests-in-a-way-that- Alicia Inventory
they-are-both-of-the-same-gender-and- David Ecommerce
nationality?code_type=1
Jack None
Lily None
.
Robbi None
https://platform.stratascratch.com/coding/1032
2-finding-user-purchases?code_type=1 Sam Inventory
Tom 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 Inventory FROM employee E
Alicia Inventory
CROSS JOIN Advance A;
None Ecommerce
None Inventory name salary bonus Net_Salary
David 50000 500 50500
.
Sam 40000 500 40500
https://platform.stratascratch.com/coding/9891-
customer-details?code_type=1 Alicia 30000 500 30500
Alex 20000 500 20500
Robbi 10000 500 10500
RIGHT OUTER JOIN Jack 8000 500 8500
Fetch all employee name wrt projects they are working Tom 5000 500 5500
SELECT E.name, P.proj_name Lily 5000 500 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
FROM employee as M
Alex None
Alicia Inventory JOIN employee as E
David Ecommerce ON M.eid = E.manager;
Jack None name Manager
Lily None Sam David
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/1012
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=1
tables it will perform CROSS JOIN.
 If there is one common column between two 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=1
CONCATINATE
https://platform.stratascratch.com/coding/1006
Create a mail address for all employees using their 1-popularity-of-hack?code_type=1
name and department with lowercase & @tcs.in domain. .

SELECT DISTINCT (LOWER(E.name)||'. .

'||LOWER(SUBSTRING(D.name, 0, 6))||'@tcs.in') https://platform.stratascratch.com/coding/9992-


find-artists-that-have-been-on-spotify-the-most-
AS Email, E.name number-of-times?code_type=1
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; bedrooms?code_type=1

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-nationality?code_type=1
jack.sales@tcs.in Jack Sales .

lily.sales@tcs.in Lily Sales


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

https://platform.stratascratch.com/coding/9915-
GROUP BY AND AGGREGATION FUNCTIONS highest-cost-orders?code_type=1
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 https://platform.stratascratch.com/coding/1004
9-reviews-of-categories?code_type=1
SELECT D.name, COUNT(1) AS emp, .

MIN(E. salary) AS Min,


MAX(E. salary) AS Max, https://platform.stratascratch.com/coding/9991-
AVG(E. salary) AS Avg, top-ranked-songs?code_type=1
SUM(E. 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_type=1
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_type=1
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 SELECT dept, 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/1007
SCALAR SUB QUERY 7-income-by-title-and-gender?code_type=1
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-department?code_type=1
FROM employee
WHERE salary > ( https://platform.stratascratch.com/coding/9814-
SELECT AVG(salary) counting-instances-in-text?code_type=1
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=1 FROM employee E2
WHERE E2.dept = E1.dept
. );
https://platform.stratascratch.com/coding/1035
3-workers-with-the-highest-salaries?code_type=1 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 * financial-sector-of-the-entire-world-along-with-
its-continent?code_type=1
FROM department
WHERE did NOT IN (
SELECT DISTINCT(dept) https://platform.stratascratch.com/coding/1006
0-top-cool-votes?code_type=1
FROM employee .

WHERE dept IS NOT NULL


); https://platform.stratascratch.com/coding/1030
0-premium-vs-freemium?code_type=1
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 query 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=1
SELECT brand, SUM(price) AS Total_Sales .

FROM sales .

https://platform.stratascratch.com/coding/9905-
GROUP BY brand) sales highest-target-under-manager?code_type=1
JOIN (
SELECT AVG(Total_Sales) AS SALES https://platform.stratascratch.com/coding/1035
FROM ( 2-users-by-avg-session-time?code_type=1
SELECT brand, SUM(price) AS Total_Sales .

FROM sales https://platform.stratascratch.com/coding/1028


GROUP BY brand) X 5-acceptance-rate-by-date?code_type=1
) AVG_SALES .

ON SALES.Total_Sales > AVG_SALES.Sales;


https://platform.stratascratch.com/coding/1028
brand Total_Sales SALES 4-popularity-percentage?code_type=1
.
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=1
[WITH (CTE), SELECT, FROM, WHERE, HAVING] .

Why do we write same query twice let’s use "with" clause? WINDOW /ANALYTIC/ 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
Step 3: Find brand where TSPB > ASPAB 1. can create partitions using by grouping then
2. apply any window function to each of those partitions.
WITH Total_Sales (brand, TSPB) AS
ROW NUMBER
(SELECT S.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_NUMBER() OVER() AS Roll,
AVG_SALES (ASPAB) AS
ROW_NUMBER() 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 1
102 Sam D1 2 2
JOIN AVG_SALES AV
103 Alicia D2 3 1
ON TS. TSPB > AV.ASPAB;
104 Alex D2 4 2
brand TSPB ASPAB 105 Robbi D2 5 3
Apple 6160.0 4326.666666666666 106 Jack D3 6 1
108 Lily D3 7 2
ADVANTAGES OF USING WITH CLAUSE 107 Tom None 8 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 ARE ROW_NUMBER() 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) X
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 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 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
RANK() OVER(ORDER BY salary DESC) AS RNK, Alex D2 20000 30000 20000 LOW SAME
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 Sam D1 40000 2 2
https://platform.stratascratch.com/coding/1031
103 Alicia D2 30000 3 3 9-monthly-percentage-difference?code_type=1
104 Alex D2 20000 4 4
105 Robbi D2 20000 5 4
106 Jack D3 8000 6 5 FIRST_VALUE and LAST_VALUE
107 Tom None 5000 7 6 Query to display the most & least expensive product
108 Lily D3 5000 7 6 under each category (corresponding to each record)
FIRST_VALUE extracts first record of the partition.
LAST_VALUE extracts last record of the partition.
https://platform.stratascratch.com/coding/9680- SELECT category, name, price,
most-profitable-companies?code_type=1
. 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=1
LAST_VALUE(name)
OVER(PARTITION BY category
.

ORDER BY price DESC) AS Cheap


.

https://platform.stratascratch.com/coding/1004
6-top-5-states-with-5-star- FROM sales;
businesses?code_type=1
category name price Expensive Cheap

.
Laptop XPS 15 2300 XPS 15 XPS 15
https://platform.stratascratch.com/coding/514- Laptop MacBook Pro 2000 XPS 15 XPS 13
marketing-campaign-success- Laptop XPS 13 2000 XPS 15 XPS 13
advanced?code_type=1 Laptop MacBook Air 1200 XPS 15 MacBook Air
Phone iPhone 13 1300 iPhone 13 iPhone 13
LAG and LEAD Phone Galaxy Note 1200 iPhone 13 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 S21 1100 iPhone 13 Galaxy S21
LAG extracts previous record. Tablet ipad 7th gen 560 ipad 7th gen ipad 7th gen
LEAD extracts 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
LAG(salary) OVER(ORDER BY eid) AS P_SAL, is b/c of default frame clause SQL is using. What is frame?
LEAD(salary) OVER(ORDER BY eid) AS N_SAL
FROM employee E) FRAME CLAUSE
SELECT *, Fetch least expensive product of each category
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, name,
FIRST_VALUE(name) OVER(PARTITION BY category CASE WHEN X.BUCKETS = 1 THEN 'EXPENSIVE'
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 Samsung Galaxy Note 20 EXPENSIVE
Phone Samsung Galaxy S21 1100 Apple iPhone 12 MIDRANGE
Tablet Samsung Galaxy Tab A7 220 Samsung Galaxy S21 CHEAP
.

https://platform.stratascratch.com/coding/9917- CUME_DIST / CUMMULATIVE DISTRIBUTION /


average-salaries?code_type=1 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_DIST()
 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 S21 1100 Galaxy S21 Galaxy S21
Laptop Apple MacBook Pro 13 30%
NTH_VALUE Laptop Dell XPS 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
expensive is "iPhone 13" when compared to all products
FROM (
SELECT category, brand, name, Perc
SELECT *,
FROM (
NTH_VALUE(name, 2)
SELECT *,
OVER(PARTITION BY category
PERCENT_RANK()
ORDER BY price DESC
OVER(ORDER BY price) AS PER_RANK,
RANGE BETWEEN UNBOUNDED PRECEDING
ROUND(PERCENT_RANK()
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 Samsung Galaxy 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/blog/interview-
questions/sql-interview-questions
It segregate records of the partition into N no. of buckets

You might also like