0% found this document useful (0 votes)
14 views31 pages

SQL Guidebook 2025-26 - Nucleus

The SQL Guidebook, published by Nucleus, covers SQL concepts from basics to advanced levels, including over 30 practice queries. Aimed at enhancing students' analytics skills, it serves as an educational resource for personal use and is not for commercial distribution. The guidebook is supported by contributions from various interns and faculty members, emphasizing collaborative learning and mentorship in the field of database management.

Uploaded by

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

SQL Guidebook 2025-26 - Nucleus

The SQL Guidebook, published by Nucleus, covers SQL concepts from basics to advanced levels, including over 30 practice queries. Aimed at enhancing students' analytics skills, it serves as an educational resource for personal use and is not for commercial distribution. The guidebook is supported by contributions from various interns and faculty members, emphasizing collaborative learning and mentorship in the field of database management.

Uploaded by

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

SQL

GUIDEBOOK
Basics to Advanced |
3 Domains | 30+ Practice Queries

Edition 2025-26
ISSUE DETAILS AND COPYRIGHT
© 2025 by Nucleus — The Analytics Society, Shaheed Sukhdev College of Business Studies
All Rights Reserved.

This guidebook is licensed for personal use and is meant for educational purposes only.

No part of this publication may be reproduced or transmitted in any form or by any means electronic, recording, photocopy, or any information storage and retrieval system or
otherwise without prior written permission of the team. For permission requests, write to Nucleus at [email protected]

This guidebook is not to be sold or used by any means for monetary gains.

© Nucleus SSCBS 2025-26 1Ⅱ


ACKNOWLEDGEMENTS
Before starting out, we’d like to take this moment to thank our mentors, our seniors, our teachers – and all those who helped shape this guidebook into a reality.
Following our culture at Nucleus – where learning is meant to be fun and accessible to everyone in the simplest manner possible – the idea for this guidebook took root, and
here we finally are.

We’re deeply thankful to past members of Nucleus – whose unwavering support and commitment inspired us to simplify SQL concepts for beginners. This guidebook reflects
the spirit of collaborative learning – we hope it serves as a practical and lasting companion for anyone starting their SQL journey and encourage a deeper appreciation of
database management.

Aryan Goyal Vanshika Jain


President, 2025-26 Vice President, 2025-26
Nucleus – The Analytics Society Nucleus – The Analytics Society
Shaheed Sukhdev College of Business Studies Shaheed Sukhdev College of Business Studies
Strategy Intern – Edelman India Research Intern – ICF International

Here are the amazing brains behind this creation:


Co-Authored by Atibha Jaiswal (Intern at EY-Parthenon), Avishi Sood (Intern at Rebel Foods), Gautam Nayak (Intern at Sleepy Owl), Kavy Rastogi (Intern at Bain Capability
Network), Kush Agarwal (Intern at JSW), Maghav Dev Mittal (Intern at Bain Capability Network), Priyanshu Kumar (Intern at Redcliffe Labs), Samriddhi Chandran (Intern at HDFC
Bank), Snehal Srivastava (Intern at VRB Capital), Vansh Khari (Intern at Bain Capability Network)

And a heartfelt thanks to our guide, mentors in short beloved & learned seniors:
Aman Bhandari (Houlihan Lokey), Anish Agarwal (Bain Capability Network), Krishang Baldi (YCP Auctus), Jatin Singh (Bain Capability Network), Moksh Ahuja (Nation with NaMo),
Muskan Goyal (Big Bang A.I.), Nancy Garg, Nikhil Jain (D.E. Shaw India), Radhika Singh, Sneha Jindal (Alvarez & Marsal), Uday Arora (Alvarez & Marsal), Vanshika Bhattad (Trinity
Life Sciences), Yash Agarwal (L.E.K. Consulting)

On a final note, ALL THE BEST, we hope this guide makes learning SQL easier and more fun for you. Good luck!

© Nucleus SSCBS 2025-26 Ⅲ


ABOUT NUCLEUS

01
Nucleus-The Analytics Society of SSCBS is one of
the most exclusive and prestigious society in the
whole of Delhi University

02 nucleus ki
We focus on enhancing the skill set of the
students in the field of analytics by providing
them with requisite training in various industry group photo
standard applications encompassing MS-Excel,
Power BI, Python, R, Tableau among various
others

03
The society also shares an excellent longstanding
relationship with the corporate sector

04
We have collaborated with firms in context of
taking up live projects, conducting speaker
sessions both within the private and public sector
domains

© Nucleus SSCBS 2025-26 Ⅳ


OUR INITIATIVES

Knowledge Sharing Sessions

The Analytics Conclave

Live Projects and


Guidebooks

© Nucleus SSCBS 2025-26 V


TEACHERS-IN-CHARGE

Dr. Amrina Kausar Dr. Mona Verma Dr. Rishi Rajan Sahay Dr. Satish Kumar Goel
(Associate Professor) (Associate Professor) (Associate Professor) (Assistant Professor)

We extend our heartfelt gratitude to our Teachers-in-Charge — Dr. Amrina Kausar, Dr. Mona Verma, Dr. Rishi Rajan Sahay, and Dr. Satish Kumar Goel — whose unwavering
support and insightful guidance were instrumental in the creation of this SQL Guidebook. Their dedication, patience, and expertise have been a constant source of inspiration
throughout our journey. With their encouragement, we were able to pursue our goals with confidence and clarity.

The mentorship they provided has not only shaped our understanding but has also helped us grow as learners and as a team. Their commitment to fostering a culture of
initiative, learning, and academic excellence has made a lasting impact on our experience at Nucleus.

We remain deeply grateful for the time and effort they invested in our growth. Their belief in the power of student-led learning continues to motivate us to keep pushing
boundaries and striving for better. This guidebook stands as a reflection of their continued encouragement and the values they instilled in us. We thank them sincerely for
being the guiding force behind every step of the way.

© Nucleus SSCBS 2025-26 VI


TABLE OF CONTENTS
S. No. Particulars Page No. S. No. Particulars Page No.

Basics of SQL 11 Drop & Truncate Statement 15

1 Introduction to Databases 2 12 Delete Statement 16

2 Relational Databases & SQL Servers 3 13 Update Statement 17

3 Database schema 4 14 Alter Statement 18

4 Relationships 5 15 Case Statement 19

5 About SQL 7 Clauses


6 Elements, Uses & Benefits of SQL 8 16 Introduction 21

Statements 17 Select Statement 22

7 Introduction to SQL Statements 10 18 Group By Statement 23

9 Create Statement 12 19 Order By Statement 24

10 Use & Insert Statement 13 20 Limit Statement 25

© Nucleus SSCBS 2025-26 VIII


TABLE OF CONTENTS
S. No. Particulars Page No. S. No. Particulars Page No.

Operators Aggregate Functions


21 Introduction 27 26 SUM() & COUNT() 39

22 All & Between Operator 29 27 Other Functions 40

23 In & Any/Some Operator 30 Joins


24 Like Operator 31 28 Introduction to SQL Joins 42

25 And & Or Operator 32 29 Inner Join 43

26 Exists Operator 33 30 Left Join 44

Sub Queries 31 Right Join 45

27 Introduction 35 32 Full Join 46

28 Single & Multi Row Queries 36 33 Cross & Self Join 47

29 Temporary Tables in SQL 37 34 Union Join 49

© Nucleus SSCBS 2025-26 IX


TABLE OF CONTENTS
S. No. Particulars Page No. S. No. Particulars Page No.

Case Studies 41 Capacity Analysis 80

A Finance 42 Resource Allocation 85

35 Data Dictionary & Schema Diag. 52 C Retail

36 Revenue Analysis 53 43 Data Dictionary & Schema Diagram 96

37 Expenditure Profiling 60 44 Market Trend Analysis 97

38 Fraud Detection 67 45 Market Segmentation 102

39 Customer Lifetime Value 70 46 Inventory Management 107

47 Inventory Optimisation 112


B Healthcare
39 Data Dictionary & Schema Diag. 74 Additional Resources

40 Staff Performance 75 49 Resources , Top SQL Interview Tips 117

© Nucleus SSCBS 2025-26 X


INTRODUCTION

© Nucleus SSCBS 2025-26 1


Basics of SQL | Overview

INTRODUCTION TO DATABASES
WHAT IS A DATABASE?
A database is an organized collection of data that is stored and accessed electronically. Databases are designed
to manage large amounts of information by allowing users to input, retrieve, and manage data efficiently.

IMPORTANCE OF DATABASE:
Efficient data management: Helps organize and maintain large volumes of data
Quick data retrieval: Allows for fast access and manipulation of data
Data integrity: Ensures accuracy and consistency of data over its lifecycle

TYPES OF DATABASES:

Stores data in tables with rows and columns MySQL


RELATIONAL / SQL PostgreSQL
DATABASE Ensures data integrity through atomicity, consistency, Oracle Database
isolation, and durability Microsoft SQL Server
DATABASES

Designed for unstructured data; supports document, key-value, MongoDB


graph, and column-family storage models Cassandra
NoSQL DATABASE Redis
Easily scales horizontally to handle large volumes of data
Couchbase

Optimized for storing and querying time-stamped or time-series InfluxDB


TIME-SERIES DATABASE data TimescaleDB
Commonly used for IoT, financial data, and real-time analytics Prometheus

© Nucleus SSCBS 2025-26 2


Basics of SQL | Overview

RELATIONAL DATABASES & SQL SERVERS


WHAT IS A RELATIONAL DATABASE?
Relational databases store data in tables that are related to each other through foreign keys. Each table consists of rows and RELATIONAL DATABASE
columns, where each column represents a data attribute and each row represents a record.

EXAMPLES AND USE CASES:


MySQL: Widely used for web applications
PostgreSQL: Known for its robustness and support for complex queries
Oracle Database: Oracle Database is commonly used in large enterprises for its scalability and performance
Microsoft SQL Server: Often used in enterprise environments with strong integration with Microsoft products

WHAT IS SQL SERVER?


SQL Server is a relational database management system (RDBMS) developed by Microsoft, which allows users to store,
manage, and access data within a structured format using Structured Query Language (SQL) commands.

DATABASE SERVERS

SQL SERVERS
DATABASE
CLIENT

© Nucleus SSCBS 2025-26 3


Basics of SQL | Overview

DATABASE SCHEMA
WHAT IS A DATABASE SCHEMA?
A schema is a blueprint of a database, outlining how data is organized and interrelated. It defines tables, fields, relationships, and other elements. A visual representation of
this schema is called a schema diagram, showing tables, columns, data types, keys, and relationships.

PRIMARY KEYS AND FOREIGN KEYS


Primary Key: A unique identifier for each record in a CATEGORY
table. It ensures that each record can be uniquely
category_id int
identified. For example, pet_id in ‘PET’ table and
PET category_name varchar
breed_id in ‘BREED’ table are examples of primary
keys. pet_id int
name varchar
Foreign Key: A field (or a collection of fields) in one BREED
category_id int
table that uniquely identifies a row of another table.
breed_id int breed_id int
It creates a link between the tables. For example,
age int breed_name varchar
category_id, breed_id, location_id in ‘PET’ table are
examples of foreign keys. location_id int category_id int
image_url varchar

LOCATION

This concept of primary and foreign keys will location_id int


be later explored in detail when we’ll talk location_name varchar
about different types of joins in SQL

© Nucleus SSCBS 2025-26 4


CLAUSES

© Nucleus SSCBS 2025-26 20


Basics of SQL | Clauses in SQL

INTRODUCTION
In MySQL, clauses are components of SQL statements that define conditions, constraints, or modifications on the data being queried or manipulated. They help refine, filter,
group, or sort results within a database operation.

SELECT Clause OUTPUT


The SELECT statement in SQL is used to fetch or retrieve data from a database.
ID Name Age AddressID
SELECTING ALL ROWS AND COLUMNS 1 Amit 30 1
Example: 2 Priya 25 1
SQL STATEMENT 3 Rahul 35 2

SELECT * FROM employees; 4 Sita 28 3


5 Vijay 22 3
The SELECT clause is followed by FROM clause 6 Anita 33 5
The asterisk (*) means ‘all columns’
7 Ravi 29 6
The table name is specified in the FROM clause

Name Age
SELECTING SPECIFIC COLUMNS
Amit 30
SQL STATEMENT
Priya 25
SELECT NAME, AGE FROM employees; Rahul 35
Sita 28
To select specific columns, instead of an asterisk (*), we enter a list of Vijay 22
columns in the SELECT statement
Anita 33
Each column name is separated from the others by a comma and the
columns are displayed in the order listed Ravi 29

© Nucleus SSCBS 2025-26 21


Basics of SQL | Clauses in SQL

WHERE
SELECT DISTINCT Clause OUTPUT
The SELECT DISTINCT statement is used to return only distinct (different) values. AddressID
Example: 1
SQL STATEMENT 2
3
SELECT DISTINCT AddressID FROM employees;
5
6
WHERE Clause
The WHERE clause is used to filter records in a database. It extracts records that
satisfy a specific condition. ID Name Age AddressID
E. xample: 1 Amit 30 1
SQL STATEMENT 3 Rahul 35 2
4 Sita 28 3
SELECT * FROM employees WHERE Age>25;
6 Anita 33 5
Operator Meaning 7 Ravi 29 6
Numeric values should not be enclosed
= Equal to
in quotes whereas SQL requires text
<> or != Not Equal to values to be enclosed in single quotes
(‘’). Double quotes (“”) are not allowed!
< Less than
<= Less than or equal to The WHERE clause follows the
> Greater than FROM clause
WHERE clause is also used in
>= Greater than or equal to
UPDATE, DELETE etc!

© Nucleus SSCBS 2025-26 22


Basics of SQL | Clauses in SQL

GROUP BY & HAVING


GROUP BY Clause OUTPUT
The GROUP BY clause is used to aggregate data by one or more columns.
It also allows you to perform aggregate functions such as COUNT, SUM, AVG,
MIN, and MAX on each group. AddressID Count
1 2
Example:
2 1
SQL STATEMENT
3 2
SELECT AddressID, COUNT(*) AS Count FROM employees GROUP BY AddressID; 5 1
6 1
Note: “Aliases” in lieu of table names are used in SQL using “AS”.

HAVING Clause
The HAVING clause filters records that are grouped by the GROUP BY clause.
It is similar to the WHERE clause, but HAVING is used after grouping the records.
Example:

SQL STATEMENT
AddressID Count
SELECT AddressID, COUNT(*) AS Count
FROM employees 1 2
GROUP BY AddressID 3 2
HAVING COUNT(*) > 1;

© Nucleus SSCBS 2025-26 23


JOINS

© Nucleus SSCBS 2025-26 40


Basics of SQL | Joins in SQL

INTRODUCTION
What is a SQL Join?
A SQL join is a clause used to combine rows from two or more tables in a database based on a related column (typically a primary key in one table and a foreign key in another)
between them. It allows for the retrieval of related data stored in multiple tables by matching columns that are specified in the join condition.

IMPORTANCE OF JOINS IN SQL


Data Normalization: In a well-designed database, data is normalized to reduce redundancy and dependency. This involves splitting data into related tables. Joins allow you
to retrieve normalized data from these separate tables and present it as if it were in a single table.
Data Integration: Joins enable the integration of data from multiple tables, making it possible to perform comprehensive queries that combine related information. This is
essential for generating meaningful insights and reports.
Flexibility: Joins provide flexibility in querying data. They allow you to construct complex queries that can retrieve, filter, and manipulate data from various tables based on
different conditions.
Efficiency: Using joins, you can retrieve related data in a single query rather than performing multiple separate queries and combining the results programmatically. This is
often more efficient and can lead to better performance, especially with large datasets.

TYPES OF JOINS IN SQL

Inner Join Left Join Right Join Full Join Cross Join Self Join

© Nucleus SSCBS 2025-26 41


Basics of SQL | Joins in SQL

INNER JOIN
What is an Inner Join?
An INNER JOIN in SQL is a type of join that retrieves only the rows from both tables that have matching values in the specified columns. If there is no match between
the tables, the rows are not included in the result set.

SQL SYNTAX

SELECT column1, column2, ...


FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

Foreign Key Primary Key

ID Name Age Address ID Address ID Country


1 Amit 30 1 1 INDIA
ID Name Age Address ID Address ID Country
2 Priya 25 1 2 USA
1 Amit 30 1 1 INDIA
3 Rahul 35 2 4 AUSTRALIA
2 Priya 25 1 1 INDIA
4 Sita 28 3 6 FRANCE
3 Rahul 35 2 2 USA
5 Vijay 22 3 7 NEPAL
7 Ravi 29 6 6 FRANCE
6 Anita 33 5 8 UK
7 Ravi 29 6 9 SPAIN

© Nucleus SSCBS 2025-26 42


Basics of SQL | Joins in SQL

LEFT (OUTER) JOIN


What is a Left Join?
A LEFT JOIN (or LEFT OUTER JOIN) in SQL is used to combine rows from two or more tables, based on a related column between them. It returns all rows from the
left table and the matched rows from the right table. If no match is found, NULL values are returned for columns from the right table.

SQL SYNTAX

SELECT column1, column2, ...


FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;

ID Name Age Address ID Address ID Country ID Name Age Address ID Address ID Country
1 Amit 30 1 1 INDIA 1 Amit 30 1 1 INDIA
2 Priya 25 1 2 USA 2 Priya 25 1 1 INDIA
3 Rahul 35 2 4 AUSTRALIA 3 Rahul 35 2 2 USA
4 Sita 28 3 6 FRANCE 4 Sita 28 3 NULL NULL
5 Vijay 22 3 7 NEPAL 5 Vijay 22 3 NULL NULL
6 Anita 33 5 8 UK 6 Anita 33 5 NULL NULL
7 Ravi 29 6 9 SPAIN 7 Ravi 29 6 6 FRANCE

© Nucleus SSCBS 2025-26 43


Basics of SQL | Joins in SQL

RIGHT (OUTER) JOIN


What is a Right Join?
A RIGHT JOIN (or RIGHT OUTER JOIN) in SQL is used to combine rows from two or more tables based on a related column between them. It returns all rows from the
right table and the matched rows from the left table. If no match is found, NULL values are returned for columns from the left table.

SQL SYNTAX

SELECT column1, column2, ...


FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;

ID Name Age Address ID Address ID Country ID Name Age Address ID Address ID Country
1 Amit 30 1 1 INDIA 1 Amit 30 1 1 INDIA
2 Priya 25 1 2 USA 2 Priya 25 1 1 INDIA
3 Rahul 35 2 4 AUSTRALIA 3 Rahul 35 2 2 USA
4 Sita 28 3 6 FRANCE NULL NULL NULL NULL 4 AUSTRALIA
5 Vijay 22 3 7 NEPAL 7 Ravi 29 6 6 FRANCE
6 Anita 33 5 8 UK NULL NULL NULL NULL 7 NEPAL
7 Ravi 29 6 9 SPAIN NULL NULL NULL NULL 8 UK
NULL NULL NULL NULL 9 SPAIN

© Nucleus SSCBS 2025-26 44


Basics of SQL | Joins in SQL

FULL (OUTER) JOIN


What is a Full Join?
A FULL OUTER JOIN in SQL is used to combine rows from two or more tables based on a related column between them. It returns all rows when there is a match in
either table. If there is no match, the result set will include NULL values for columns from the table without a match.

SQL SYNTAX

SELECT column1, column2, ...


FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;

ID Name Age Address ID Address ID Country ID Name Age Address ID Address ID Country
1 Amit 30 1 1 INDIA 1 Amit 30 1 1 INDIA
2 Priya 25 1 1 INDIA
2 Priya 25 1 2 USA
3 Rahul 35 2 2 USA
3 Rahul 35 2 4 AUSTRALIA 4 Sita 28 3 NULL NULL
4 Sita 28 3 6 FRANCE 5 Vijay 22 3 NULL NULL
5 Vijay 22 3 7 NEPAL 6 Anita 33 5 NULL NULL
7 Ravi 29 6 6 FRANCE
6 Anita 33 5 8 UK
NULL NULL NULL NULL 4 AUSTRALIA
7 Ravi 29 6 9 SPAIN NULL NULL NULL NULL 7 NEPAL
NULL NULL NULL NULL 8 UK
NULL NULL NULL NULL 9 SPAIN

© Nucleus SSCBS 2025-26 45


CASE STUDIES

© Nucleus SSCBS 2025-26 49


Case Study | Retail

Data Dictionary & Schema Diagram


Data Dictionary Inventory Table
Column Description Store_ID Identifier of the store.
Store Table Product_ID Identifier of the product.
Store_ID Unique identifier for each store Stock_On_Hand Quantity of the product available in stock.
Store_Name Name of the store
Store_City City where the store is located
Database Schema Diagram
Store_Location Specific location/address of the store
Store_Open_Date Date when the store was opened
Product Table
Product_ID Unique identifier for each product
Product_Name Name of the product
Product_Category Category to which the product belongs
Product_Cost Cost price of the product
Product_Price Selling price of the product
Sales Table
Sale_ID Unique identifier for each sale transaction
Date Date of the sale transaction
Store_ID Identifier of the store where the sale occurred
Product_ID Identifier of the product sold
Units Number of units sold in the transaction Link to the Dataset: Click here for accessing the dataset

© Nucleus SSCBS 2025-26 95


Case Study | Retail

BUSINESS CONCEPT: MARKET TREND ANALYSIS


Market Trend Analytics involves using SQL queries to analyze and interpret data, identifying patterns and trends in market behavior over time.
This approach helps businesses track sales, customer behavior, and product demand, enabling them to uncover insights such as seasonal trends,
growth rates, and emerging preferences. These insights support data-driven decision-making and strategic planning.

Insights from trend analysis allow for precise and


Marketing Strategies impactful marketing strategies, targeting specific
product categories to better align with consumer
demand and preferences

COMMON USE CASES


Data on emerging trends guides R&D initiatives,
Product Development directing innovation efforts towards product
categories experiencing increased consumer
interest and potential market growth

Trend data informs strategic business decisions,


Strategic Planning shaping overall goals and optimizing resource
allocation to align with market demands and future
opportunities

© Nucleus SSCBS 2025-26 96


Case Study | Retail

ASSIGNMENT 1: PRODUCT ANALYSIS

Can you provide a list of the top 20 products based on total units sold? We need to identify our most
popular products to ensure we are prioritizing their availability and focusing our marketing efforts on these
items. This data is vital for optimizing our inventory management and promotional strategies.

SQL Query: Output:


SELECT
p.Product_ID,
p.Product_Name,
SUM(s.Units) AS Total_Units_Sold
FROM sales s
JOIN products p ON s.Product_ID = p.Product_ID
GROUP BY
p.Product_ID, p.Product_Name
ORDER BY
Total_Units_Sold DESC
LIMIT 20;

© Nucleus SSCBS 2025-26 97


Case Study | Retail

THINKING PROCESS GUIDE: ASSIGNMENT 1


Clause Usage Purpose

SELECT
p.Product_ID, We’re selecting each Product_ID and Product_Name, then summing up the total number of units
1 SELECT p.Product_Name, sold (Total_Units_Sold) for each product.
SUM(s.Units) AS Total_Units_Sold

2 FROM FROM sales AS s The data comes from the sales table, which contains details about the units sold.

JOIN products p ON s.Product_ID = We join the sales table with the products table (p) using the Product_ID, so we can retrieve the
3 JOIN p.Product_ID product names corresponding to each sale.

GROUP BY The results are grouped by Product_ID and Product_Name, allowing us to aggregate the total units
4 GROUP BY p.Product_ID, p.Product_Name sold for each product.

ORDER BY We sort the products by Total_Units_Sold in descending order, so the products with the highest
5 ORDER BY Total_Units_Sold DESC sales appear at the top.

6 LIMIT LIMIT 20; Finally, we limit the results to the top 20 products based on total units sold.

© Nucleus SSCBS 2025-26 98


Case Study | Retail

ASSIGNMENT 2: STORE PERFORMANCE

Can you provide the total sales in USD for each store over a specified time period? We need to assess which stores
are performing the best and identify those that may need improvement. This information is essential for guiding our
resource allocation and strategic planning efforts.

SQL Query: Output:


SELECT
s.Store_ID,
s.Store_Name,
SUM(sa.Units* p.Product_Price) AS Total_Sales_USD
FROM sales sa
JOIN stores s ON sa.Store_ID = s.Store_ID
JOIN products p ON sa.Product_ID = p.Product_ID
WHERE
sa.Date >= '2022-01-01' AND sa.Date <= '2022-03-31'
GROUP BY sa.Store_ID, s.Store_Name
ORDER BY Total_Sales_USD DESC;

© Nucleus SSCBS 2025-26 99


Case Study | Retail

THINKING PROCESS GUIDE: ASSIGNMENT 2


Clause Usage Purpose

SELECT
s.Store_ID, We’re selecting each Store_ID and Store_Name, then calculating the total sales in USD
1 SELECT s.Store_Name, (Total_Sales_USD) for each store by multiplying the number of units sold (sa.Units) by the product
SUM(sa.Units* p.Product_Price) AS price (p.Product_Price).
Total_Sales_USD

2 FROM FROM sales AS s The data comes from the sales table (sa), which contains details about the sales transactions.

JOIN stores s ON sa.Store_ID =


We join the sales table with the stores table (s) using the Store_ID, so we can retrieve the store
3 s.Store_ID
JOIN JOIN products p ON sa.Product_ID =
names associated with each sale. Another join is performed with the products table (p) using the
Product_ID to link the product details, including prices, to each sale.
p.Product_ID

WHERE
We filter the sales to include only those that occurred between January 1, 2022, and March
4 WHERE sa.Date >= '2022-01-01' AND sa.Date
31, 2022.
<= '2022-03-31'

GROUP BY The results are grouped by Store_ID and Store_Name, allowing us to calculate the total sales for
5 GROUP BY sa.Store_ID, s.Store_Name each store.

ORDER BY Finally, we sort the stores by Total_Sales_USD in descending order, so the stores with the highest
6 ORDER BY Total_Sales_USD DESC; sales appear at the top.

© Nucleus SSCBS 2025-26 100


ALL THE BEST!

For queries, feedback and


more unqiue insights

2025, Nucleus - The Analytics Society of SSCBS


All rights reserved

You might also like