Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
103 changes: 47 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,59 +1,50 @@
# Leetcode SQL Questions & Solutions <br/>

![alt text](https://github.com/cM2908/leetcode-sql/blob/main/LeetCode.png)

#### Repository Contains :<br/>

(1) All Leetcode SQL Question Solutions <br/>
(2) PostgreSQL Dump File (leetcodedb.sql)<br/>

#### Problem statements of all questions including leetcode premium questions :<br/>

(1) https://leetcode.ca <br/>
(2) https://lifewithdata.com/sql <br/>
(3) https://www.jiakaobo.com/leetcode <br/>

#### How to Import dump file using command line terminal?<br/>

(1) Open terminal & open psql utility
```
user@my-machine:~$ psql
```
(2) Create Database (To import the dump file, database should be created priorly)<br/>
```
postgres=# CREATE DATABASE sample_db;
```
(3) Quit the psql promt
```
postgres=# \q
```
(4) From terminal, Load dump file into the newly created database using below command
```
user@my-machine:~$ pg_restore --host "127.0.0.1" --port "5432" --username "postgres" --dbname "sample_db" --verbose "leetcodedb.sql"
```
Replace your configurations(host,port,username) in pg_restore command<br/>

#### How to Import dump file using PgAdmin tool?<br/><br/>

(1) Open PgAdmin & Create Database
```
Servers -> Databases -> Create -> Database.. (Create Database dialog will get opened)
```
(2) Restore Dump File<br/>
```
Right Click on newly created Database & select Restore option from menu (Restore dialog will get opened)
```
Just Browse the dump file and keep other options as it is.

#### Notes : <br/>

(1) Do not just copy-paste and run the content of dump file into either "psql promt in terminal" or "query tool of pgadmin".<br/>
(Because dump file contains COPY commands not INSERTS,So doing such will cause errors.)<br/>
(2) Table names are suffixed with question number.<br/>
(3) New solutions will get added as I solve them.<br/>

#### Checkout my another repository which cantains Miscellaneous SQL Questions & Solutions : <br/>
# LeetCode SQL Questions and Solutions

![LeetCode SQL](https://github.com/cM2908/leetcode-sql/blob/main/LeetCode.png)

This repository contains LeetCode SQL solutions organized by difficulty and documented as Markdown files.

## Repository Structure

- `easy/`
- `medium/`
- `hard/`

Each solution file is named with the LeetCode question number and title, for example:

- `easy/1050. Actors and Directors Who Cooperated At Least Three Times.md`
- `medium/176. Second Highest Salary.md`
- `hard/262. Trips and Users.md`

## What Each Solution Includes

Each Markdown solution document typically contains:

- the LeetCode problem link
- the problem description
- table schema details
- sample input and expected output
- the SQL solution
- a short breakdown of the query logic

## Problem Statement References

Problem statements, including premium questions, can be referenced from:

1. https://leetcode.ca
2. https://lifewithdata.com/sql
3. https://www.jiakaobo.com/leetcode

## Notes

1. Table names in the SQL queries are suffixed with the question number.
2. The repository is now documentation-oriented, so solutions are stored as `.md` files instead of standalone `.sql` files.
3. New solutions can be added in the same Markdown format as more problems are covered.

## Other Resources

Miscellaneous SQL repository:
https://github.com/cM2908/misc-sql

#### Checkout my Blogs on interesting SQL topics : <br/>
SQL blog:
http://chintan-sql.blogspot.com
Binary file removed dump_file/leetcodedb.sql
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Question 1050: Actors and Directors Who Cooperated At Least Three Times

**LeetCode URL:** https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/

## Description

Write a solution to find all the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times. Return the result table in any order. The result format is in the following example.

## Table Schema Structure

```sql
Create table If Not Exists ActorDirector (actor_id int, director_id int, timestamp int);
```

## Sample Input Data

```sql
insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '0');
insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '1');
insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '2');
insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '2', '3');
insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '2', '4');
insert into ActorDirector (actor_id, director_id, timestamp) values ('2', '1', '5');
insert into ActorDirector (actor_id, director_id, timestamp) values ('2', '1', '6');
```

## Expected Output Data

```text
+-------------+-------------+
| actor_id | director_id |
+-------------+-------------+
| 1 | 1 |
+-------------+-------------+
```

## SQL Solution

```sql
SELECT actor_id,director_id
FROM actor_director_1050
GROUP BY actor_id,director_id
HAVING COUNT(1)>=3;
```

## Solution Breakdown

### Goal

The query builds the final result columns `actor_id`, `director_id` from `actor_director`.

### Result Grain

One row per unique key in `GROUP BY actor_id,director_id`.

### Step-by-Step Logic

1. Aggregate rows with COUNT grouped by actor_id,director_id.
2. Project final output columns: `actor_id`, `director_id`.
3. Filter aggregated groups in `HAVING`: COUNT(1)>=3.

### Why This Works

Grouping keys define the reporting grain; aggregate functions then summarize values at exactly that grain. `HAVING` ensures only groups that satisfy business thresholds survive. The final projection exposes only the columns required by the result contract.

### Performance Notes

Primary cost drivers are sorting/grouping. Indexes on join/filter/group keys typically provide the biggest speedup.

### Common Pitfalls

- Every non-aggregated selected column must belong to the grouping grain.

This file was deleted.

73 changes: 73 additions & 0 deletions easy/1068. Product Sales Analysis I.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Question 1068: Product Sales Analysis I

**LeetCode URL:** https://leetcode.com/problems/product-sales-analysis-i/

## Description

Write a solution to report the product_name, year, and price for each sale_id in the Sales table. Return the resulting table in any order. The result format is in the following example.

## Table Schema Structure

```sql
Create table If Not Exists Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table If Not Exists Product (product_id int, product_name varchar(10));
```

## Sample Input Data

```sql
insert into Sales (sale_id, product_id, year, quantity, price) values ('1', '100', '2008', '10', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('2', '100', '2009', '12', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('7', '200', '2011', '15', '9000');
insert into Product (product_id, product_name) values ('100', 'Nokia');
insert into Product (product_id, product_name) values ('200', 'Apple');
insert into Product (product_id, product_name) values ('300', 'Samsung');
```

## Expected Output Data

```text
+--------------+-------+-------+
| product_name | year | price |
+--------------+-------+-------+
| Nokia | 2008 | 5000 |
| Nokia | 2009 | 5000 |
| Apple | 2011 | 9000 |
+--------------+-------+-------+
```

## SQL Solution

```sql
SELECT p.product_name,s.year,s.price
FROM sales_1068 s
JOIN product_1068 p ON s.product_id = p.product_id;
```

## Solution Breakdown

### Goal

The query builds the final result columns `product_name`, `year`, `price` from `sales`, `product`.

### Result Grain

Row grain follows the post-filter join output.

### Step-by-Step Logic

1. Combine datasets using JOIN. Join predicates control row matching and prevent accidental cartesian growth.
2. Project final output columns: `product_name`, `year`, `price`.

### Why This Works

Join conditions align related entities so each output row is built from the correct source records. The final projection exposes only the columns required by the result contract.

### Performance Notes

Primary cost drivers are join operations. Indexes on join/filter/group keys typically provide the biggest speedup.

### Common Pitfalls

- Verify join keys and cardinality; wrong joins can duplicate or drop rows silently.

3 changes: 0 additions & 3 deletions easy/1068. Product Sales Analysis I.sql

This file was deleted.

72 changes: 72 additions & 0 deletions easy/1069. Product Sales Analysis II.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Question 1069: Product Sales Analysis II

**LeetCode URL:** https://leetcode.com/problems/product-sales-analysis-ii/

## Description

The query result format is in the following example: Sales table: +---------+------------+------+----------+-------+ | sale_id | product_id | year | quantity | price | +---------+------------+------+----------+-------+ | 1 | 100 | 2008 | 10 | 5000 | | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ Product table: +------------+--------------+ | product_id | product_name | +------------+--------------+ | 100 | Nokia | | 200 | Apple | | 300 | Samsung | +------------+--------------+ Result table: +--------------+----------------+ | product_id | total_quantity | +--------------+----------------+ | 100 | 22 | | 200 | 15 | +--------------+----------------+ Difficulty: Easy Lock: Prime Company: Amazon Problem Solution 1069-Product-Sales-Analysis-II All Problems: Link to All Problems All contents and pictures on this website come from the Internet and are updated regularly every week.

## Table Schema Structure

```sql
Create table If Not Exists Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table If Not Exists Product (product_id int, product_name varchar(10));
```

## Sample Input Data

```sql
insert into Sales (sale_id, product_id, year, quantity, price) values ('1', '100', '2008', '10', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('2', '100', '2009', '12', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('7', '200', '2011', '15', '9000');
insert into Product (product_id, product_name) values ('100', 'Nokia');
insert into Product (product_id, product_name) values ('200', 'Apple');
insert into Product (product_id, product_name) values ('300', 'Samsung');
```

## Expected Output Data

```text
+--------------+----------------+
| product_id | total_quantity |
+--------------+----------------+
| 100 | 22 |
| 200 | 15 |
+--------------+----------------+
```

## SQL Solution

```sql
SELECT product_id,SUM(quantity) AS total_quantity
FROM sales_1068
GROUP BY product_id;
```

## Solution Breakdown

### Goal

The query builds the final result columns `product_id`, `total_quantity` from `sales`.

### Result Grain

One row per unique key in `GROUP BY product_id`.

### Step-by-Step Logic

1. Aggregate rows with SUM grouped by product_id.
2. Project final output columns: `product_id`, `total_quantity`.

### Why This Works

Grouping keys define the reporting grain; aggregate functions then summarize values at exactly that grain. The final projection exposes only the columns required by the result contract.

### Performance Notes

Primary cost drivers are sorting/grouping. Indexes on join/filter/group keys typically provide the biggest speedup.

### Common Pitfalls

- Every non-aggregated selected column must belong to the grouping grain.

3 changes: 0 additions & 3 deletions easy/1069. Product Sales Analysis II.sql

This file was deleted.

Loading