0% found this document useful (0 votes)
19 views

SQL Leetcode

Uploaded by

Ratnesh Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

SQL Leetcode

Uploaded by

Ratnesh Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Page 1 of 6

Create table Person (personId int, firstName varchar(255), lastName varchar(255));


Create table Address1 (addressId int, personId int, city varchar(255), state varchar(255));
insert into Person (personId, lastName, firstName) values ('1', 'Wang', 'Allen');
insert into Person (personId, lastName, firstName) values ('2', 'Alice', 'Bob');
insert into Address1 (addressId, personId, city, state) values ('1', '2', 'New York City', 'New York');
insert into Address1 (addressId, personId, city, state) values ('2', '3', 'Leetcode', 'California');
/*
Write an SQL query to report the first name, last name, city, and state of each person in the Person
table. If the address of a personId is not present in the Address table, report null instead.
Return the result table in any order.
The query result format is in the following example.
Person table:
+----------+----------+-----------+
| personId | lastName | firstName |
+----------+----------+-----------+
| 1 | Wang | Allen |
| 2 | Alice | Bob |
+----------+----------+-----------+
Address table:
+-----------+----------+---------------+------------+
| addressId | personId | city | state |
+-----------+----------+---------------+------------+
| 1 | 2 | New York City | New York |
| 2 | 3 | Leetcode | California |
+-----------+----------+---------------+------------+
Output:
+-----------+----------+---------------+----------+
| firstName | lastName | city | state |
+-----------+----------+---------------+----------+
| Allen | Wang | Null | Null |
| Bob | Alice | New York City | New York |
+-----------+----------+---------------+----------+
Explanation:
There is no address in the address table for the personId = 1 so we return null in their city and
state.addressId = 1 contains information about the address of personId = 2.
*/
select firstName,lastName,a.city,a.state from Person p
left join Address a on p.personID=a.personID;
--****************************************************************************************************
Create table Products (product_id int, low_fats varchar(2), recyclable varchar(2));
insert into Products (product_id, low_fats, recyclable) values ('0', 'Y', 'N');
insert into Products (product_id, low_fats, recyclable) values ('1', 'Y', 'Y');
insert into Products (product_id, low_fats, recyclable) values ('2', 'N', 'Y');
insert into Products (product_id, low_fats, recyclable) values ('3', 'Y', 'Y');
insert into Products (product_id, low_fats, recyclable) values ('4', 'N', 'N');
/*
Write an SQL query to find the ids of products that are both low fat and recyclable.
Return the result table in any order.
The query result format is in the following example.
Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Output:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: Only products 1 and 3 are both low fat and recyclable.
*/
select product_id from Products
where 'Y' in low_fats and 'Y' in recyclable;

--*************************************************************************************************
Create table Customer1 (id int, name varchar(25), referee_id int);
insert into Customer1 (id, name, referee_id) values ('1', 'Will',NULL);
insert into Customer1 (id, name, referee_id) values ('2', 'Jane', NULL);
insert into Customer1 (id, name, referee_id) values ('3', 'Alex', '2');
insert into Customer1 (id, name, referee_id) values ('4', 'Bill', NULL);
insert into Customer1 (id, name, referee_id) values ('5', 'Zack', '1');
insert into Customer1 (id, name, referee_id) values ('6', 'Mark', '2');
/*
Write an SQL query to report the names of the customer that are not referred by
the customer with id = 2.Return the result table in any order.The query result format is in the
following example.
Customer table:
+----+------+------------+
| id | name | referee_id |
+----+------+------------+
| 1 | Will | null |
| 2 | Jane | null |
| 3 | Alex | 2 |
| 4 | Bill | null |
| 5 | Zack | 1 |
| 6 | Mark | 2 |
+----+------+------------+
Output:
+------+
| name |
+------+
| Will |

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23
Page 2 of 6

| Jane |
| Bill |
| Zack |
+------+
*/
select * from Customer1;
select name from Customer1 where referee_id !=2 or referee_id is null;
select name from Customer1 where id not in (select id from Customer1 where referee_id=2);
select name from Customer1 where name not in (select name from Customer1 where referee_id=2);
--select name from Customer1 where referee_id not in (select referee_id from Customer1 where referee_id=2);
--will give only zack,hence change to id column as it has no null values.
--****************************************************************************************************************
Create table Customers2 (id int, name varchar(255));
Create table Orders2 (id int, customerId int);
insert into Customers2 (id, name) values ('1', 'Joe');
insert into Customers2 (id, name) values ('2', 'Henry');
insert into Customers2 (id, name) values ('3', 'Sam');
insert into Customers2 (id, name) values ('4', 'Max');
insert into Orders2 (id, customerId) values ('1', '3');
insert into Orders2 (id, customerId) values ('2', '1');
/*
Write an SQL query to report all customers who never order anything.
Return the result table in any order.
The query result format is in the following example.
Customers table:
+----+-------+
| id | name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
Output:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
*/
select * from Customers2;
select * from Orders2;
--customers who oredered food
select c.id,c.name,o.id,o.customerId from Customers2 c
join Orders2 o on c.id=o.customerId;
--customers who ordered food display only name now
select c.name from Customers2 c
join Orders2 o on c.id=o.customerId;
--method1
--customers who didnt ordered food display only name
select c.name as Customers from Customers2 c
where c.name not in (select c.name from Customers2 c
join Orders2 o on c.id=o.customerId);
--method 2
select c.name as Customers from Customers2 c
where c.id not in (select customerid from orders2);
--********************************************************************************************************************
Create table Employees4 (employee_id int, name varchar(30), salary int);
insert into Employees4 (employee_id, name, salary) values ('2', 'Meir', '3000');
insert into Employees4 (employee_id, name, salary) values ('3', 'Michael', '3800');
insert into Employees4 (employee_id, name, salary) values ('7', 'Addilyn', '7400');
insert into Employees4 (employee_id, name, salary) values ('8', 'Juan', '6100');
insert into Employees4 (employee_id, name, salary) values ('9', 'Kannon', '7700');
/*
Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID
of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0
otherwise.Return the result table ordered by employee_id.The query result format is in the following example.
Employees table:
+-------------+---------+--------+
| employee_id | name | salary |
+-------------+---------+--------+
| 2 | Meir | 3000 |
| 3 | Michael | 3800 |
| 7 | Addilyn | 7400 |
| 8 | Juan | 6100 |
| 9 | Kannon | 7700 |
+-------------+---------+--------+
Output:
+-------------+-------+
| employee_id | bonus |
+-------------+-------+
| 2 | 0 |
| 3 | 0 |
| 7 | 7400 |
| 8 | 0 |
| 9 | 7700 |
+-------------+-------+
Explanation:
The employees with IDs 2 and 8 get 0 bonus because they have an even employee_id.
The employee with ID 3 gets 0 bonus because their name starts with 'M'.
The rest of the employees get a 100% bonus.
*/

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23
Page 3 of 6

select employee_id,case when mod(employee_id,2)!=0 and name not like('M%') then salary
else 0
end as Bonus
from Employees4
order by employee_id;

select employee_id ,salary as bonus from Employees4


where mod(employee_id,2)!= 0 and name not like 'M%'
union
select employee_id,0 as bonus from Employees4
where mod(employee_id,2)=0 or name like 'M%'
order by employee_id;
--**********************************************************************************************************************
Create table Salary3 (id int, name varchar(100), sex char(1), salary int);
insert into Salary3 (id, name, sex, salary) values ('1', 'A', 'm', '2500');
insert into Salary3 (id, name, sex, salary) values ('2', 'B', 'f', '1500');
insert into Salary3 (id, name, sex, salary) values ('3', 'C', 'm', '5500');
insert into Salary3 (id, name, sex, salary) values ('4', 'D', 'f', '500');
/*
Write an SQL query to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a
single update statement and no intermediate temporary tables.Note that you must write a single update statement,
do not write any select statement for this problem.The query result format is in the following example.
Example 1:
Salary table:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | m | 2500 |
| 2 | B | f | 1500 |
| 3 | C | m | 5500 |
| 4 | D | f | 500 |
+----+------+-----+--------+
Output:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | f | 2500 |
| 2 | B | m | 1500 |
| 3 | C | f | 5500 |
| 4 | D | m | 500 |
+----+------+-----+--------+
Explanation:
(1, A) and (3, C) were changed from 'm' to 'f'.
(2, B) and (4, D) were changed from 'f' to 'm'.
*/
--method1
UPDATE salary3 s
SET sex =
CASE
WHEN sex='m' THEN 'f'
WHEN sex='f' THEN 'm'
END;
select * from salary3;
--method2
update salary3 set sex=decode(sex,'m','f','f','m');
select * from salary3;
--********************************************************************************************************
Create table Person1 (Id int, Email varchar(255));
insert into Person1 (id, email) values ('1', 'john@example.com');
insert into Person1 (id, email) values ('2', 'bob@example.com');
insert into Person1 (id, email) values ('3', 'john@example.com');
/*
Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id.
Note that you are supposed to write a DELETE statement and not a SELECT one.
After running your script, the answer shown is the Person table. The driver will first compile and run your piece of code
and then show the Person table. The final order of the Person table does not matter.
Person table:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Output:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.
*/
--method 1 error
delete from (select p.*,rownum() over(order by id) as rn from Person1 p)
where rn>1;
--method 2 error
with temptable_cte as (select p.*,rownum() over(order by id) as rn from Person1 p)
delete from temptable_cte where rn>1;
--method 3
delete from Person1 p
where p.id NOT IN (with temptable_cte as (select min(id) from Person1 group by email) select * from temptable_cte);
select * from Person1;
--method 4
delete from Person1 where id not in (select min(id) from Person1 group by email);
--method 5
delete from Person1
where id in (SELECT P1.id
FROM Person1 P1 JOIN Person1 P2
ON(P1.id > P2.id AND P1.email = P2.email) );

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23
Page 4 of 6

--*********************************************************************************************************************
Create table Users (user_id int, name varchar(40));
insert into Users (user_id, name) values ('1', 'aLice');
insert into Users (user_id, name) values ('2', 'bOB');
/*
Write an SQL query to fix the names so that only the first character is uppercase and the rest are lowercase.
Return the result table ordered by user_id.
The query result format is in the following example.
Users table:
+---------+-------+
| user_id | name |
+---------+-------+
| 1 | aLice |
| 2 | bOB |
+---------+-------+
Output:
+---------+-------+
| user_id | name |
+---------+-------+
| 1 | Alice |
| 2 | Bob |
+---------+-------+
*/
select user_id,upper( substr(name,1,1) ) || lower( substr(name,2) ) as name from Users;
select user_id,INITCAP(name) as name from Users;

--**********************************************************************************************************
Create table Activities(sell_date varchar(20), product varchar(20));
insert into Activities(sell_date, product) values ('2020-05-30', 'Headphone');
insert into Activities(sell_date, product) values ('2020-06-01', 'Pencil');
insert into Activities(sell_date, product) values ('2020-06-02', 'Mask');
insert into Activities(sell_date, product) values ('2020-05-30', 'Basketball');
insert into Activities(sell_date, product) values ('2020-06-01', 'Bible');
insert into Activities(sell_date, product) values ('2020-06-02', 'Mask');
insert into Activities(sell_date, product) values ('2020-05-30', 'T-Shirt');
select * from Activities;
/*
Input:
Activities table:
+------------+------------+
| sell_date | product |
+------------+------------+
| 2020-05-30 | Headphone |
| 2020-06-01 | Pencil |
| 2020-06-02 | Mask |
| 2020-05-30 | Basketball |
| 2020-06-01 | Bible |
| 2020-06-02 | Mask |
| 2020-05-30 | T-Shirt |
+------------+------------+
Output:
+------------+----------+------------------------------+
| sell_date | num_sold | products |
+------------+----------+------------------------------+
| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2 | Bible,Pencil |
| 2020-06-02 | 1 | Mask |
+------------+----------+------------------------------+
Explanation:
For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by a comma.
For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by a comma.
For 2020-06-02, the Sold item is (Mask), we just return it.
*/
--first group by sell_dates and count them
select distinct sell_date,count(product) from Activities group by sell_date order by sell_date;
--2020-05-30 3 --it has all unique products here.
--2020-06-01 2 --it has all unique products here.
--2020-06-02 2 --it has 2 masks we dont want count as 2 we want count as 1.

--now how to display the products name in front of the count of '1' in front of 2020-06-02
select distinct sell_date,product from Activities;--distinct values are displayed here.
--count will done on this only ,apply group by on this subquery result only
select sell_date,count(product) as num_sold from (select distinct sell_date,product from Activities)
group by sell_date order by sell_date;
--2020-05-30 3
--2020-06-01 2
--2020-06-02 1 --here we have one only.

--now how to display products in front of them.


select sell_date,count(product) as num_sold,listagg(product,',') within group (order by product) as products
from (select distinct sell_date,product from Activities)
group by sell_date order by sell_date;

--syntax of listagg
--List Concatenation aggregates a column or expression by combining the valuesinto a single string for each group.
--A string to delimit each value (either blank or a comma when omitted) and the order of the valuesin the result can be
--specified.
SELECT ColumnA,LISTAGG(ColumnB, ',') WITHIN GROUP (ORDER BY ColumnB) AS ColumnBs
FROM TableName GROUP BY ColumnA;

--*********************************************************************************************************************
/*Write an SQL query to report the patient_id, patient_name and conditions of the patients who have Type I Diabetes.
Type I Diabetes always starts with DIAB1 prefix.
Return the result table in any order.
The query result format is in the following example.
Patients table:
+------------+--------------+--------------+
| patient_id | patient_name | conditions |
+------------+--------------+--------------+
| 1 | Daniel | YFEV COUGH |

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23
Page 5 of 6

| 2 | Alice | |
| 3 | Bob | DIAB100 MYOP |
| 4 | George | ACNE DIAB100 |
| 5 | Alain | DIAB201 |
+------------+--------------+--------------+
Output:
+------------+--------------+--------------+
| patient_id | patient_name | conditions |
+------------+--------------+--------------+
| 3 | Bob | DIAB100 MYOP |
| 4 | George | ACNE DIAB100 |
+------------+--------------+--------------+
Explanation: Bob and George both have a condition that starts with DIAB1. */
select * from Patients where regexp_like(conditions, '(\s+|^)DIAB1');
select * from Patients where conditions like 'DIAB1%' or conditions like '% DIAB1%';

--**********************************************************************************************************************
Create table Employ1 (employee_id int, name varchar(30));
Create table Salaries1 (employee_id int, salary int);
insert into Employ1 (employee_id, name) values ('2', 'Crew');
insert into Employ1 (employee_id, name) values ('4', 'Haven');
insert into Employ1 (employee_id, name) values ('5', 'Kristian');
insert into Salaries1 (employee_id, salary) values ('5', '76071');
insert into Salaries1 (employee_id, salary) values ('1', '22517');
insert into Salaries1 (employee_id, salary) values ('4', '63539');
/*
Write an SQL query to report the IDs of all the employees with missing information. The information of an employee is
missing if:The employee's name is missing, orThe employee's salary is missing.Return the result table ordered by employee_id in ascending order.
The query result format is in the following example.
Employees table:
+-------------+----------+
| employee_id | name |
+-------------+----------+
| 2 | Crew |
| 4 | Haven |
| 5 | Kristian |
+-------------+----------+
Salaries table:
+-------------+--------+
| employee_id | salary |
+-------------+--------+
| 5 | 76071 |
| 1 | 22517 |
| 4 | 63539 |
+-------------+--------+
Output:
+-------------+
| employee_id |
+-------------+
| 1 |
| 2 |
+-------------+
Explanation:
Employees 1, 2, 4, and 5 are working at this company.The name of employee 1 is missing.The salary of employee 2 is missing.
*/
--by union and not in concept we did.
select employee_id from Employ1 where employee_id not in (select employee_id from Salaries1)
union
select employee_id from Salaries1 where employee_id not in (select employee_id from Employ1);

--by using joins concept.


select e.employee_id,e.name,s.salary from Employ1 e left join Salaries1 s on e.employee_id=s.employee_id;
select s.employee_id,e.name,s.salary from Employ1 e right join Salaries1 s on e.employee_id=s.employee_id;

select e.employee_id,e.name,s.salary from Employ1 e left join Salaries1 s on e.employee_id=s.employee_id


union
select s.employee_id,e.name,s.salary from Employ1 e right join Salaries1 s on e.employee_id=s.employee_id;
--s.employee_id is important here.

--now use this union statement as subquery


select A.employee_id from
(select e.employee_id,e.name,s.salary from Employ1 e left join Salaries1 s on e.employee_id=s.employee_id
union
select s.employee_id,e.name,s.salary from Employ1 e right join Salaries1 s on e.employee_id=s.employee_id) A
where A.name is NULL or A.salary is NULL
order by A.employee_id;

--select * from Employ1 full join Salaries1 on Employ1.employee_id= Salaries1.employee_id;

--********************************************************************************************************************
Create table Products2 (product_id int, store1 int, store2 int, store3 int);
insert into Products2 (product_id, store1, store2, store3) values ('0', '95', '100', '105');
insert into Products2 (product_id, store1, store2, store3) values ('1', '70', NULL, '80');
select * from Products2;
/*Write an SQL query to rearrange the Products table so that each row has (product_id, store, price).
If a product is not available in a store, do not include a row with that product_id and store combination in the result table.
Return the result table in any order.
Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0 | 95 | 100 | 105 |
| 1 | 70 | null | 80 |
+------------+--------+--------+--------+
Output:
+------------+--------+-------+
| product_id | store | price |
+------------+--------+-------+
| 0 | store1 | 95 |
| 0 | store2 | 100 |

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23
Page 6 of 6

| 0 | store3 | 105 |
| 1 | store1 | 70 |
| 1 | store3 | 80 |
+------------+--------+-------+
Explanation:
Product 0 is available in all three stores with prices 95, 100, and 105 respectively.
Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.*/
SELECT product_id, 'store1' AS store, store1 AS price FROM Products2 WHERE store1 IS NOT NULL;
SELECT product_id, 'store2' AS store, store2 AS price FROM Products2 WHERE store2 IS NOT NULL;
SELECT product_id, 'store3' AS store, store3 AS price FROM Products2 WHERE store3 IS NOT NULL;

SELECT product_id, 'store1' AS store, store1 AS price FROM Products2 WHERE store1 IS NOT NULL
union
SELECT product_id, 'store2' AS store, store2 AS price FROM Products2 WHERE store2 IS NOT NULL
union
SELECT product_id, 'store3' AS store, store3 AS price FROM Products2 WHERE store3 IS NOT NULL
order by product_id;

SELECT product_id,store,price FROM Products2


UNPIVOT(price FOR store in (store1,store2,store3));

file:///C:/Users/RATNESH/Downloads/Telegram%20Desktop/leetcodesbasic 12-Jan-23

You might also like