SQL Simplified For All 1716213668
SQL Simplified For All 1716213668
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
.
https://platform.stratascratch.com/
Revoke multiple privilege coding/1000 3-lyft-driver-wages?
REVOKE INSERT, UPDATE ON Users TO code_type=1
'Test';
.
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
SET
Fetch employees from Management & involve on
projects
SELECT name
FROM employee .
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
https://platform.stratascratch.com/coding/
9891- customer-details?code_type=1
CROSS JOIN
Give 500 bonus for all employees
CREATE “Advance” TABLE
bonus
500
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
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
.
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
.
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
https://platform.stratascratch.com/
coding/1031 9-monthly-percentage-
difference?code_type=1
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.
https://platform.stratascratch.com/coding/
9917- average-salaries?code_type=1
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