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

SQL NOTES

Databases are organized collections of data that serve as digital repositories for storing and managing structured information, allowing for efficient data retrieval and manipulation. They come in various types, including relational databases that use tables and SQL, and NoSQL databases designed for unstructured data. Understanding database characteristics, such as data integrity and security, is essential for effective data management across different industries.

Uploaded by

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

SQL NOTES

Databases are organized collections of data that serve as digital repositories for storing and managing structured information, allowing for efficient data retrieval and manipulation. They come in various types, including relational databases that use tables and SQL, and NoSQL databases designed for unstructured data. Understanding database characteristics, such as data integrity and security, is essential for effective data management across different industries.

Uploaded by

zephyriaarts
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 141

Introductio

n to
Databases
What are Databases NOTES
• We’re swamped by information every second
of every day. Sometimes this information is
not useful and we forget about it. But if the
information is useful, we remember it, or we
could say we store it — in our brains.
• This same idea applies to data and databases.
Think of databases as the storage units for
important information. We can use a database
to store things like user information, customer
orders, blog post text, comments, etc… These
items are all important for us to keep track of
to access later and potentially update.
What are Databases NOTES
• While we would want some users to interact with
our database, we might not want everyone to have
the same permissions. This means depending on
who the user is, they would use the database
differently. Imagine if we had a form that took in
user comments and stored them in a database.
• We want regular users to be able to add to the
database, but we certainly don’t want them to edit
any existing comments. However, we could grant
permission to administrators, aka admins, to
access old comments and update them if needed.
• Later on, we could even use the information from
the database and display it on our site. Going back
to our comments example, we could display user
comments like seen on review sites.
What are Databases NOTES

A database is an organized
collection of data, typically
stored and accessed
electronically from a
computer system. It serves
as a digital repository for
storing and managing
structured information.
Types of Databases (Traditional) NOTES
Relational Databases:
• Organize data into tables with rows and columns.
• Use structured query language (SQL) for data
manipulation.
• Example: MySQL, PostgreSQL, Oracle Database.

NoSQL Databases:
• Designed for handling unstructured, semi-structured,
or polymorphic data.
• Examples: MongoDB (document-oriented), Cassandra
(column-family), Redis (key-value store).
Example Tables for Relational Databases NOTES
Relationship:

Relation: The
Customers table
and the Orders
table are related
through the
CustomerID column.

Type: This is a one-


to-many
relationship, where
each customer can
place multiple
orders, but each
order belongs to
only one customer.
Importance of Databases NOTES
• Business Applications: Databases are crucial for
businesses to store, retrieve, and manage data
efficiently.

Examples:
• Retail: Storing customer information, sales
transactions.
• Banking: Managing accounts, transactions, and
financial records.
• Healthcare: Patient records, medical history.
• Online Services: User profiles, transactions.
Example Table: Business Applications of Databases NOTES
• Each example table
Retail Banking illustrates how databases
organize data for specific
business needs.
• For instance, in Retail,
the Customers table
stores customer
information, and the
Orders table tracks
customer orders.
Healthcar Online
• Similarly, in Healthcare,
e Services the Patients table stores
patient demographics,
while the MedicalRecords
table records patient
visits, diagnoses, and
prescriptions.
• These tables
demonstrate how
databases facilitate
efficient data storage,
retrieval, and
management across
various industries.
Characteristics of Databases NOTES
Characteris • Data Management:
Description Example Additional Notes Utilizes techniques like
tic
indexing and
Efficient storage using compression.
E-commerce platform
Data Store large volumes of indexing and data
storing millions of • Concurrency Control:
Management data efficiently. compression
product listings. Uses locking and isolation
techniques.
levels to manage
Uses locking simultaneous access.
Manage multiple users Banking system
mechanisms and
Concurrency accessing the allowing thousands of • Data Integrity:
transaction isolation
Control database users to access Maintained through
levels to prevent data
simultaneously. accounts. constraints and validation
conflicts.
rules.
Uses constraints (e.g.,
Ensure accuracy and Healthcare database • Scalability: Achieved
Data primary keys, foreign
consistency of stored ensuring patient through horizontal or
Integrity keys) to maintain data
data. records are correct. vertical scaling
accuracy.
strategies.
Achieved through
horizontal scaling • Security: Implements
Ability to handle Social media platform robust measures for
(adding more servers)
Scalability growing amounts of scaling to support authentication,
or vertical scaling
data and users. millions of users. authorization, and
(upgrading existing
servers). encryption.

Uses authentication,
Implement access Government database
authorization, and
Security controls to protect securing classified
encryption techniques
sensitive information. documents.
to safeguard data.
Real-World Example: Chaayos Operations NOTES
Scenario: Chaayos uses a relational database to These tables illustrate
how Chaayos can
manage customer orders, inventory, and employee organize and manage
information. customer information,
orders, and inventory
using a relational
Example: Tables include: database.
• Customers: Stores customer details such as name,
contact information. This structure allows
• Orders: Records orders placed by customers, for efficient data
including items and quantities. retrieval,
manipulation, and
• Inventory: Tracks stock levels of tea blends, snacks, analysis using SQL
and other menu items. queries. Adjustments
can be made based on
specific requirements
or additional fields
needed for
comprehensive
database
management.
Example Tables for Chaayos Operations NOTES
• Customers Table: Stores
details of Chaayos
customers, including their
unique customer_id,
name, contact_number,
and email.
• Orders Table: Records
each customer's order
with order_id linked to
the customer_id from the
Customers table. It
includes order details
such as order_date,
item_name, quantity, and
total_amount.
• Inventory Table: Tracks
stock levels of various
menu items at Chaayos.
Each item has a unique
item_id, item_name,
category (e.g., Tea,
Snack), and
quantity_in_stock.
Key
Takeaway
s
Key Takeaways NOTES
A database is essential for organizing and
managing structured data.

Different types of databases cater to varying


data storage and retrieval needs.

Understanding database characteristics helps


ensure efficient data management and
integrity.
Relational
Database
Concepts
Tables, Rows, and Columns NOTES
Definition
• Tables: Structured as a collection of related
data entries organized in rows and columns.
• Rows: Individual records or data entries within
a table.
• Columns: Represents a specific attribute or
field within a table.
Colum
ns
Tabl
Row e
s
Primary Keys and Foreign Keys NOTES
Primary Key:
• Definition: A column (or combination of
columns) that uniquely identifies each row in a
table.
• Example: In a Customers table, the
CustomerID column could serve as the
primary key.

Foreign Key:
• Definition: A column (or set of columns) in one
table that references a primary key in another
table.
• Example: In an Orders table, the CustomerID
column is a foreign key referencing the
Example: Primary Keys and Foreign Keys NOTES
Primary Key
(CustomerID):
• Each row in the
Customers table has a
unique CustomerID,
which serves as the
primary key.
• It uniquely identifies
each customer record.

Foreign Key
(CustomerID in Orders
table):
• In the Orders table, the
CustomerID column is a
foreign key that
references the
CustomerID column in
the Customers table.
• This relationship links
each order to the
corresponding customer
who placed it.
Primary Keys and Foreign Keys NOTES
.
Aspect Primary Key Foreign Key Primary Key: Used to
uniquely identify each
A column (or combination of A column (or set of columns) in
Definition columns) that uniquely identifies one table that references a record (row) in a table.
each row in a table. primary key in another table. It ensures that no two
Establishes relationships between rows have the same
Ensures each row has a unique
Purpose
identifier.
tables by referencing the primary values in the primary
key of another table. key column(s).
In an Orders table, the CustomerID
In a Customers table, the
column is a foreign key referencing
Example CustomerID column could serve as Foreign Key: Used to
the CustomerID column in the
the primary key. establish relationships
Customers table.
Uniquene References a unique value in between tables. It
Unique within the table. points to the primary
ss another table.
Must match the data type of the
key of another table to
Constrain Must be unique and cannot
referenced primary key and ensure referential
ts contain NULL values. integrity, typically
maintain referential integrity.
enforcing constraints
such as CASCADE or
RESTRICT actions on
updates or deletions.
Things to Keep in Mind When Working with Keys NOTES

• Uniquely identifies each row in a

Primar
table.
• Must be unique and cannot contain
NULL values.
• Typically created using a single

y Key column (e.g., CustomerID).


• Enables efficient data retrieval and
ensures data integrity.

• Establishes relationships between

Foreig
tables.
• References the primary key of
another table.
• Helps maintain data consistency and

n Key enforce referential integrity.


• Must match the data type and values
of the referenced primary key.
Golden Rules for Keys NOTES

Uniqueness
• Ensure each primary
key value is unique
within its table.

Performance
• Index keys Integrity
appropriately to • Foreign keys should
optimize query reference existing
performance, primary key values
especially for to maintain data
frequently accessed integrity.
columns.

Naming
• Use descriptive and Consistency
meaningful names • Keep data
for keys to enhance consistent across
readability (e.g., related tables to
CustomerID for avoid orphan
primary key in records.
Customers table).
Relationship Between Tables NOTES
• One-to-One: Each record in Table A Example:One-
to-Many: A
relates to exactly one record in Table B. single customer
• One-to-Many: Each record in Table A can place
can relate to multiple records in Table B. multiple orders
• Many-to-Many: Records in Table A can (Customers to
Orders
relate to multiple records in Table B, and relationship).
vice versa.
Relationship Between Tables: One-to-One NOTES
• In a one-to-one relationship, a record in table B
belongs to only one record in table A. And a record in
Table A belongs to only one record in Table B.

• For example, in the relationship between people and


driver’s license numbers, a person can have only one
driver’s license number, and a driver’s license
number belongs to only person.
Relationship Between Tables: One-to-Many NOTES
• In a one-to-many relationship, a record in table A can
potentially belong to several records in table B. Think
about the relationship between orders and items - an
order can contain many items, but an item belongs to
a single order.
• In this case, the orders table is the one side and the
items table is the many side.
Relationship Between Tables: Many-to-Many NOTES
• In a many-to-many relationship, a record in table B
can potentially belong to several records in table A.
And vice versa, a record in table A can potentially
belong to several records in Ttable B.
• Think about the relationship between products and
categories: a product can belong to many categories,
and a category can contain many products.
Setting
up DB
Brower
What is DB Browser NOTES
• DB Browser is a visual tool used to organize
commands sent to SQLite. With databases, it’s easy to
lose track of commands that have been run.
• DB Browser lets you see exactly the sequence of
commands you are executing before you run them.
• DB Browser will also allow you to see the column
structure for the tables within the database you’re
working with, so inserting data or other manipulation
of data is more manageable and doesn’t require
performing queries every time you need to remember
the structure of your data.
Installing DB Brower NOTES
Link:
https://sqlitebro
wser.org/dl/

After following the


installation process,
open up the software
and you will
presented with an
interface for opening
or creating a new
database.
Using DB Browser to Create a New Table NOTES
Steps: Link:
1. Creating a new database with DB Browser will open a File https://sqlitebro
dialog box, where you can set where the SQLite database will
live in your file structure.
wser.org/dl/
2. After creating a db, you will be presented with an interface for
creating a table. Add a name for the table at the top, and then
add and remove fields in the Fields window.
3. Each field has a free-text name, a dropdown for its type, and
four checkboxes for not-null, primary key, autoincrement,
and unique attributes, as well as other parameters.
4. You will see the SQL query that DB Browser executes to create
this table update as you add information to this table. Update
these and press “OK”.
5. You will see the Database Structure tab of DB Browser refresh
with the updated information.
6. Note that no changes have been made to any database file yet,
and queries are only executed by DB Browser when the “Write
Changes” button is pressed. Press the “Write Changes”
button and create your table.
Adding Data to a SQLite Table Using DB Browser NOTES
Steps: Link:
1. Switch from the Database Structure tab to https://sqlitebro
wser.org/dl/
the Browse Data tab.
2. You can add a row to the table with the New
Record button. Click it and update the
columns in the viewport as you would a
spreadsheet.
3. Remember that no data will be inserted into
the SQLite database until the “Write
Changes” button is pressed.
4. Press that button and you will have
successfully added a row to your table.
Running SQL
Commands in
DB Brower
Opening a database file NOTES
Steps:
1. In order to open a database file, click “Open
Database” (or find it under the ‘File’ menu).
2. Find the .sqlite file of your database and
open it.
3. From there, you can see the database
schema in the “Database Structure” or
manually inspect the tables in the “Browse
Data” tab.
Opening a database file NOTES
Writing SQL queries NOTES
DB Browser
supports
writing SQL
queries directly
under the
“Execute SQL”
tab.
SQL
101
Introduction to SQL NOTES
SQL (Structured Query Language) may be an
effective language utilized to communicate with
databases. It is used to make, adjust and
oversee information stored in relational
databases.
It can be used to query, insert, upgrade ,
and erase records from the database, as well
as create and adjust the structure of the
database itself . It could be a very versatile
dialect and can be utilized to perform complex
queries and control huge amounts of
information.
SQL is the foremost commonly utilized
language for databases and is utilized in a wide
assortment of program applications.
What is SQL? NOTES
SQL, or Structured Query Language, is a
powerful tool used in managing and analyzing
data within databases. Imagine you're
managing a chain of cafes, and your goal is to
understand customer preferences and
purchasing habits. SQL allows you to query your
database to extract valuable insights.
What is SQL? NOTES
In this scenario, let's say you want to analyze
customer orders from the past year to
determine popular menu items and customer
spending habits. Using SQL, you can create a
query that retrieves a list of customers who
made purchases, what items they ordered, and
the total amount spent on each item.
What is SQL? NOTES
You start by setting up a database as a digital
repository for storing information. Within this
database, you create tables to store data about
your menu items, such as item names, prices,
and categories. Each time a customer places an
order, the details including the customer's
name, ordered items, quantities, and total
amount spent are stored in another table.
What is SQL? NOTES
By querying this database with SQL commands,
you can:
• Retrieve a list of customers who made
purchases within the last year.
• Determine which menu items were ordered
the most.
• Calculate the total amount spent by each
customer and the number of items they
purchased.
• SQL commands allow you to manage and
manipulate this data effectively, helping you
derive insights to improve menu offerings,
understand customer preferences, and
optimize business operations.
SQL
Database
Basics
SQL Database Basics NOTES
SQL databases are relational databases that use Structured Query
Language (SQL) for managing information. SQL is a programming
language ‍utilized for interacting with the data stored in a relational
database. It permits clients to create ✏️, Update , erase ❌, and
retrieve information from the database ️.
SQL databases to use SQL commands to control and query data . SQL
databases are divided into tables and fields . Each table is composed
of rows and columns, and each column is composed of areas . Each
field is constrained to a specific data type , such as text , integer , or
date .
The foremost common SQL commands are SELECT , Insert , Update ,
and Delete ❌. SELECT is utilized to recover data from the database,
Insert is utilized to add new data to the database, Update is utilized to
modify existing information, and Erase is utilized to expel information
from the database.

SQL databases are utilized for data storage in numerous applications,


including websites , program applications , and versatile applications .
They are moreover used for making reports and analyzing
information
Common SQL Commands NOTES
• SELECT: used to select data from a database
• UPDATE: It is used to update existing records in a table
• DELETE: It is used to delete records from a table
• INSERT INTO: used to insert new records into a table
• CREATE TABLE: It is used to create a new table
• ALTER TABLE: It is used to modify an existing table
• DROP TABLE: It is used to delete a table
• JOIN: It combines rows from two or more tables based on a
common column.
• WHERE: used to specify criteria to limit the results of a query
• ORDER BY: used to sort the results of a query in ascending or
descending order
Applicati
on of SQL
SQL Database Basics NOTES
1.SQL is used to store and manipulate data in databases. It
Data Storage is the standard language used to access and modify data in
relational databases.

1.SQL is used to define data structures and modify the


Data existing database structures. It is the language used to
create and modify tables, indexes, views, and other
Definition database objects.

1.SQL is used to query data from a database. Queries can be


Data Retrieval used to retrieve and filter data from one or more tables.

Data 1.SQL updates, adds, and erases data in a database. It can


be utilized to modify existing information, insert new
Manipulation records, and delete undesirable records.

1.SQL is utilized to control access to the database. It is


Data Security utilized to set up client accounts, grant and deny benefits,
and set up security arrangements.

1.SQL is utilized to analyze information put away in a


Data Analysis database. It can be utilized to perform calculations,
produce reports, and make visualizations.
Advantag
es of SQL
Advantages of SQL NOTES
No programming • SQL does not require a large number of coding lines for managing the SQL provides various
database systems. We can easily access and maintain the database by using advantages which
needed simple SQL syntactical rules. These simple rules make the SQL user-friendly.
make it more popular
in the field of data
High-Speed • A large amount of data is accessed quickly and efficiently from the database
by using SQL queries. Insertion, deletion, and updation operations on data
science. It is a perfect
Query Processing are also performed in less time. query language which
allows data
professionals and
Standardized • SQL follows the long-established standards of ISO and ANSI, which offer a
users to communicate
uniform platform across the globe to all its users.
Language with the database.
• The structured query language can be easily used in desktop computers,
Portability laptops, tablets, and even smartphones. It can also be used with other
applications according to the user's requirements.

Interactive • We can easily learn and understand the SQL language. We can also use this
language for communicating with the database because it is a simple query
language. This language is also used for receiving the answers to complex
language queries in a few seconds.

More than one • The SQL language also helps in making the multiple views of the database
structure for the different database users.
Data View
Key
Takeaway
s
Key Takeaways NOTES
SQL (Structured Query Language) is a declarative language
that manages and manipulates data in a relational database.
SQL enables users to query, update, insert, and delete data.

SQL can create, alter, and drop tables, indexes, constraints,


and triggers.
SQL supports various data types, such as numeric, string,
date, and binary.
SQL can be used to join multiple tables to query data from
them.
SQL is used to create stored procedures and functions for
database automation.
SQL is an open-source language, which means it is platform-
independent and can be used on any database platform.
Popular SQL
Databases
and
Platforms
Popular SQL Databases and Platforms NOTES
1. MySQL: MySQL is an open-source relational database
management system (RDBMS) that's broadly utilized in web
application advancement.
2. PostgreSQL: PostgreSQL is an object-relational database
management system (ORDBMS) that's profoundly extensible and
strong.
3. Microsoft SQL Server: Microsoft SQL Server is an enterprise-level
RDBMS stage used by numerous expansive organizations.
4. Oracle Database: Oracle Database is an enterprise-level RDBMS
stage utilized by numerous expansive organizations.
5. MongoDB: MongoDB could be a NoSQL database platform
prevalent in present-day web applications.
6. Amazon Aurora: Amazon Aurora could be a social database
engine created by Amazon Web Services (AWS).
7. IBM DB2: IBM DB2 may be an RDBMS stage utilized by
organizations of all sizes.
8. SAP HANA: SAP HANA is an in-memory database stage utilized by
numerous organizations for real-time analytics and decision-
making.
SQL
Applications
in Real-World
Situations
SQL Applications in Real-World Situations NOTES

Online Banking
• Monetary institutions utilize SQL to track client exchanges and account
information. Usually fundamental for giving securely online managing an
account administrations.
Retail Management
• Stores depend on SQL to oversee stock, track client orders, and analyze
deal patterns.
Healthcare Records
• Clinics utilize SQL to store and access sensitive patient data such as
medical histories, analyses, and medicines.

Airline Reservation Frameworks


• Aircrafts utilize SQL to store flight plans, estimating information, and
customer data.
Weather Forecasting:
• Meteorologists utilize SQL to store and analyze chronicled information to
make more exact expectations.
Reasons
why SQL is
widely used
Reasons why SQL is widely used NOTES
Data • SQL allows users to efficiently manage large amounts of data. This
includes tasks such as creating, modifying, and deleting data stored in
Management a database.

• SQL enables users to retrieve data from a database quickly and


Data Retrieval efficiently. This makes it a valuable tool for data analysis and decision-
making.

• SQL provides built-in security features such as user authentication,


Data Security encryption, and access control. This helps to ensure that data is kept
secure and protected from unauthorized access.

Data • SQL ensures that data in a database remains consistent, even when
multiple users are accessing it simultaneously. This is important for
Consistency maintaining data integrity and avoiding data inconsistencies.

• SQL is highly scalable and can handle large amounts of data. This
Data Scalability makes it a valuable tool for organizations that need to manage and
analyze vast amounts of data.

• SQL is a standardized language, which means that it is compatible


Standardization with many different database management systems. This makes it
easy to transfer data between different systems.

• SQL enables users to perform complex data analysis tasks such as


Data Analysis grouping, filtering, and sorting data. This makes it a valuable tool for
business intelligence and data analytics
Key
Takeaway
s
Key Takeaways NOTES
SQL (Structured Query Language) is a powerful language
for creating, managing, and manipulating database data.

SQL is used for a variety of tasks, including data retrieval,


analysis, and reporting.

SQL is versatile, efficient, and relatively easy to learn.

SQL can be used to create and modify database structures


and to insert, update, and delete data from databases.

SQL is essential for data professionals and web developers


to build and maintain databases and for querying and
transform data.
SQL
Syntax
SQL Syntax (The Way SQL Commands are Structured) NOTES
Following are some most important points When you want to
do some operations
about the SQL syntax which are to remember: on the data in the
• You can write the keywords of SQL in both database, then you
must have to write
uppercase and lowercase, but writing the SQL the query in the
keywords in uppercase improves the predefined syntax of
readability of the SQL query. SQL.
• SQL statements or syntax are dependent on
The syntax of the
text lines. We can place a single SQL structured query
statement on one or multiple text lines. language is a unique
set of rules and
• You can perform most of the action in a guidelines, which is
database with SQL statements. not case-sensitive.
Its Syntax is defined
• SQL syntax depends on relational algebra and and maintained by
tuple relational calculus. the ISO and ANSI
standards.
SQL Syntax (The Way SQL Commands are Structured) NOTES
Following are some most important points Relational algebra
influences SQL
about the SQL syntax which are to remember: commands like SELECT,
JOIN, and PROJECT,
• You can write the keywords of SQL in both uppercase and which manipulate data
lowercase, but writing the SQL keywords in uppercase improves by specifying what to
the readability of the SQL query. retrieve or modify from
tables.
• SQL statements or syntax are dependent on text lines. We can
place a single SQL statement on one or multiple text lines.
• You can perform most of the action in a database with SQL Tuple relational calculus
statements. influences the condition-
based filtering in SQL
• SQL syntax depends on relational algebra (using WHERE clause),
where you specify
and tuple relational calculus. conditions that must be
met for rows (tuples) to
be included in the result
set.
SQL Syntax (The Way SQL Commands are Structured) NOTES
In practice when you write SQL queries: In summary, SQL syntax
is designed based on
relational algebra and
1. You use SELECT to specify which columns tuple relational calculus
(attributes) you want to retrieve, influenced principles, providing a
structured way to
by relational algebra's projection operation. interact with and
manipulate relational
2. You use WHERE to specify conditions that databases effectively.
rows (tuples) must meet to be included in
the result set, influenced by tuple relational
calculus.
3. JOIN operations combine data from multiple
tables based on common columns, reflecting
relational algebra's join operations.
SQL
Statement
s
SQL Statements NOTES
SQL statements tell the database what
operation you want to perform on the
structured data and what information you would
like to access from the database.

The statements of SQL are very simple


and easy to use and understand. They are
like plain English but with a particular
syntax.
Basic
Exercises
SQL Clauses covered in Basic Exercises NOTES
Clauses Covered in the upcoming exercises:
SELECT
FROM
WHERE
AS
ORDER BY
GROUP BY
LIMIT
DISTINCT
COUNT
SUM
AVG
ROUND
Exercise 1: Problem NOTES

1.Write a SQL query to


retrieve all columns
from a table named
OrdersCompact.
Exercise 1: Solution NOTES
Select * FROM OrdersCompact

Clause Description

This clause is used to specify the columns that you want to retrieve
SELECT
from the database table.

The asterisk (*) is a wildcard character that means "all columns". It


*
tells the database to return all columns in the specified table.

FROM This clause specifies the table from which to retrieve the data.

This is the name of the table from which the data is being selected.
OrdersCompact It should contain the order information in a compact format (as
implied by the name).
Exercise 1: Solution - Detailed Explanation NOTES
Detailed Explanation The query will
SELECT: This clause is used to specify the columns that fetch the
you want to retrieve from the table. In this query, the CustomerName,
asterisk (*) wildcard is used, which means all columns Market, and
will be retrieved. Segment columns
from the
*: The asterisk (*) is a wildcard character used in SQL to
OrdersCompact
select all columns from the specified table. Instead of
table. It will
listing each column individually, the asterisk tells the
display the data
database to include every column available in the table
from these
in the result set.
specific columns
FROM: This clause is used to specify the table from which for all rows in the
the data should be retrieved. It follows the SELECT OrdersCompact
clause and indicates the source of the data. table.
OrdersCompact: This is the name of the table from which
you are selecting the data. The query will look into this
table and retrieve all columns for every row in the table.
Why Use SELECT * NOTES
Using SELECT * is useful in scenarios where you
need to quickly retrieve all data from a table,
such as for debugging purposes or when you
need a complete view of the data without
filtering or specifying columns.
Potential Drawbacks NOTES
• Performance: Retrieving all columns can be Best Practice:
inefficient if the table has a large number of columns While SELECT * is
or rows. It may result in higher memory usage and convenient, it is
slower query performance. generally better to
specify only the
• Unnecessary Data: You might retrieve more data columns you need.
than needed, which can lead to unnecessary data This approach
transfer and processing. improves
performance, reduces
• Schema Changes: If the table schema changes (e.g., data transfer, and
columns are added or removed), the query results can makes the query
change unexpectedly, potentially leading to issues in results more
applications relying on the query. predictable and easier
to manage.
Exercise 2: Problem NOTES

1.Write a SQL query to


retrieve specific
columns (Customer
Name, Market,
Segment) from the
OrdersCompact table.
Exercise 2: Solution NOTES
Select [Customer Name], Market, Segment
FROM OrdersCompact;
SQL Clause Purpose Explanation

Specifies the columns to retrieve. In


Column
SELECT this case, CustomerName, Market,
Selection
and Segment.
CustomerNa
These are the specific columns you
me, Market, Columns
want to retrieve from the table.
Segment
Indicates the table from which to
FROM Table Selection
retrieve the data.

OrdersCompa The name of the table containing the


Table Name
ct data you want to query.
Exercise 2: Solution - Detailed Explanation NOTES
Detailed Explanation The query will
SELECT: This clause is used to specify the columns fetch the
that you want to retrieve from the table. In this query, CustomerName,
you are selecting three columns: CustomerName, Market, and
Market, and Segment. Segment columns
from the
CustomerName, Market, Segment: These are the OrdersCompact
columns listed after the SELECT keyword. They specify table. It will
which columns' data should be fetched in the result display the data
set. from these
FROM: This clause is used to specify the table from specific columns
which the data should be retrieved. It follows the for all rows in the
SELECT clause. OrdersCompact
table.
OrdersCompact: This is the name of the table from
which you are selecting the data. The query will look
into this table to find the CustomerName, Market, and
Segment columns and retrieve their data.
Exercise 3: Filtering Rows with WHERE Clause NOTES

1.Retrieve a list of
customers who have
sales amount greater
than 10000.
Exercise 3: Filtering Rows with WHERE Clause NOTES
Exercise 4: Filtering Rows with WHERE Clause NOTES

1.Sorting Results with


ORDER BY Clause
Get the list of customers and
sort them by Sales amount in
descending order.
Exercise 4: Filtering Rows with WHERE Clause NOTES
Exercise 5:Limiting the Number of Rows Returned with LIMIT Clause NOTES

1.Retrieve the first 5 orders from


the orders table.
Exercise 5:Limiting the Number of Rows Returned with LIMIT Clause NOTES
Exercise 6: Using DISTINCT to Remove Duplicates NOTES

1.Find all unique customer names


from the orders table.
Exercise 6: Using DISTINCT to Remove Duplicates NOTES
Exercise 7: Counting Rows with COUNT Function NOTES

1.Count the total number of


orders in the OrdersCompact
table.
Exercise 7: Counting Rows with COUNT Function NOTES

.
Filtering Data: NOTES
1. Write a SQL query to retrieve all Customer
Names from the OrdersCompact table who
are from a specific city (e.g., Delhi).
Filtering Data: NOTES
Filtering Data: NOTES
1. Write a SQL query to retrieve all customers
from the OrdersCompact who ordered after a
specific date (e.g., ‘31-12-2021').
Filtering Data: NOTES
Filtering Data: NOTES
Sorting Data NOTES
1. Write a SQL query to retrieve all Customers
from the OrdersCompact and Order Date
Column as well.

Order the results by their OrderDate in


descending order.
Sorting Data NOTES
Sorting Data NOTES
1. Write a SQL query to retrieve all Customers
from the OrdersCompact table and order the
results alphabetically by their name.
Sorting Data NOTES
Aggregate Functions NOTES
1. Write a SQL query to calculate the total
number of customers in the OrdersCompact
table.
Aggregate Functions NOTES
Aggregate Functions NOTES
1. Write a SQL query to calculate the average
Sales of Customers in the OrdersCompact
table.
Aggregate Functions NOTES
Additional Exercises NOTES
1. Write a SQL query to retrieve the top 5
customers from the OrdersCompact table.
Additional Exercises NOTES
Additional Exercises NOTES
1. Write a SQL query to retrieve Customers who
have purchased within the last year.
Additional Exercises NOTES
Introductio
n to Set
Operations
Overview NOTES
Set operations in SQL allow you to combine the
results of two or more queries into a single
result set. These operations are particularly
useful when you want to work with multiple
datasets that are related in some way but are
not directly joined by a common column or key.
The most commonly used set operations are
UNION, UNION ALL, INTERSECT, and EXCEPT (or
MINUS in some SQL dialects).
UNION NOTES
UNION ALL NOTES
INTERSECT NOTES
EXCEPT NOTES
Key Points to Remember: NOTES
Column Compatibility: Set operations require that
the result sets being combined have the same
number of columns, and corresponding columns
must have compatible data types.
Order of Operations: When multiple set operations
are used in a single query, they are executed in a
specific order. INTERSECT is performed first,
followed by UNION and EXCEPT. However, you can
use parentheses to control the order of operations.
Performance Considerations: Set operations,
particularly UNION and INTERSECT, can be
resource-intensive as they may involve sorting and
comparing large datasets. Consider using UNION
ALL when duplicates are acceptable to improve
performance.
When to Use Set Operations: NOTES
Combining Data from Multiple Sources: When
you have data spread across different tables
or queries that need to be combined into a
single result set.
Filtering and Comparison: When you need to
find differences or commonalities between
datasets, such as identifying new, lost, or
returning customers in a campaign analysis.
Simplifying Complex Queries: Sometimes, set
operations can simplify queries by breaking
them down into smaller, more manageable
parts.
Set Operations Diagram Explaination NOTES
Understanding IN and NOT IN in SQL NOTES
The IN and NOT IN clauses in SQL are powerful
tools for filtering data based on a list of values
or the result of a subquery. They allow you to
specify a set of values or a subquery that you
want to match against, making it easier to
retrieve or exclude specific records from your
result set.
Campaign
Data Case
Study
Background NOTES
Chaayos recently launched a marketing
campaign aimed at increasing customer
retention and acquiring new customers. The
campaign ran for one month, and now the
marketing team wants to analyze its impact.
Data Available NOTES
You have two tables:
Customers_Before: Contains customer names
who were active before the campaign.
Column: CustName (e.g., Aaron, Justin, Craig,
Katherine)

Customers_After: Contains customer names


who were active after the campaign.
Column: CustName (e.g., Justin, Craig, Rick, Jim)
Tasks NOTES
Your task is to analyze the impact of the campaign by
answering the following questions:
All Customers:
Question: Who were all the customers associated
with Chaayos across both periods (before and after the
campaign)?
Combine the two datasets to create a comprehensive
list of all unique customers who were active at any
point.

New Customers:
Question: Which customers became active only after
the campaign?
Identify the new customers who were not present
before the campaign but became active afterward.
Tasks NOTES
Your task is to analyze the impact of the campaign
by answering the following questions:
Lost Customers:
Question: Which customers were active before the
campaign but are no longer active?
Determine which customers stopped being active
after the campaign.

Returning Customers:
Question: Which customers were active both
before and after the campaign?
Identify the loyal customers who continued to
engage with Chaayos before and after the
campaign.
Instructions NOTES
Instructions:Using SQL, write queries to answer
the questions above. You can use either set
operations (UNION, IN, NOT IN) and join
operations (LEFT JOIN, INNER JOIN).
Set
Operations -
Problem
Statements
Finding All Customers NOTES
Problem Statement:
Retrieve a list of all customer names who were
either in the Customers_Before or
Customers_After table.
Finding All Customers: Solution NOTES
-- Select all unique customer names from
Customers_Before
SELECT DISTINCT CustName
FROM Customers_Before

-- UNION combines the results from the two queries


and removes duplicates
UNION

-- Select all unique customer names from


Customers_After
SELECT DISTINCT CustName
FROM Customers_After;
Finding All Customers: Explaination NOTES
• SELECT DISTINCT CustName FROM Customers_Before:
Retrieves all unique customer names from the
Customers_Before table.

• UNION: Combines the results from the first and second


query, ensuring that any duplicate customer names
that appear in both tables are only shown once.

• SELECT DISTINCT CustName FROM Customers_After:


Retrieves all unique customer names from the
Customers_After table.
Finding New Customers NOTES
Problem Statement:
Identify customer names that appear in the
Customers_After table but not in the
Customers_Before table. These are considered
"new" customers.
Finding New Customers: Solution NOTES
-- Select customer names from Customers_After
that are not in Customers_Before
SELECT CustName
FROM Customers_After
WHERE CustName NOT IN (
-- Subquery to select all customer names
from Customers_Before
SELECT CustName
FROM Customers_Before
);
Finding New Customers: Explaination NOTES
• SELECT CustName FROM Customers_After: Retrieves
all customer names from the Customers_After table.

• WHERE CustName NOT IN (...): Filters out any


customer names that are also found in the
Customers_Before table.

• SELECT CustName FROM Customers_Before: This


subquery retrieves all customer names from the
Customers_Before table. The NOT IN condition ensures
that only customer names not found in this subquery
are returned, identifying customers who are new.
Finding Lost Customers NOTES
Problem Statement:
Identify customer names that were in the
Customers_Before table but do not appear in
the Customers_After table. These are
considered "lost" customers.
Finding Lost Customers: Solution NOTES
-- Select customer names from
Customers_Before that are not in
Customers_After
SELECT CustName
FROM Customers_Before
WHERE CustName NOT IN (
-- Subquery to select all customer names
from Customers_After
SELECT CustName
FROM Customers_After
);
Finding Lost Customers: Explaination NOTES
• SELECT CustName FROM Customers_Before: Retrieves
all customer names from the Customers_Before table.

• WHERE CustName NOT IN (...): Filters out any


customer names that are also found in the
Customers_After table.

• SELECT CustName FROM Customers_After: This


subquery retrieves all customer names from the
Customers_After table. The NOT IN condition ensures
that only customer names not found in this subquery
are returned, identifying customers who were lost
after the campaign.
Finding Returning Customers NOTES
Problem Statement:
Identify customer names that appear in both
the Customers_Before and Customers_After
tables. These are considered "returning"
customers.
Finding Returning Customers: Solution NOTES
-- Select customer names from Customers_After
that are also in Customers_Before
SELECT CustName
FROM Customers_After
WHERE CustName IN (
-- Subquery to select all customer names
from Customers_Before
SELECT CustName
FROM Customers_Before
);
Finding Returning Customers: Explaination NOTES
• SELECT CustName FROM Customers_After: Retrieves
all customer names from the Customers_After table.

• WHERE CustName IN (...): Filters the results to include


only customer names that are also found in the
Customers_Before table.

• SELECT CustName FROM Customers_Before: This


subquery retrieves all customer names from the
Customers_Before table. The IN condition ensures that
only customer names that exist in both tables are
returned, identifying returning customers.
Joins -
Problem
Statements
Finding All Customers NOTES
Problem Statement:
Retrieve a list of all customer names who were
either in the Customers_Before or
Customers_After table.
Finding All Customers: Solution NOTES
-- Select all customer names from Customers_Before
SELECT b.CustName
FROM Customers_Before b
-- Perform a LEFT JOIN with Customers_After to include all customers from
Customers_Before
LEFT JOIN Customers_After a
ON b.CustName = a.CustName

UNION

-- Select all customer names from Customers_After who are not in


Customers_Before
SELECT a.CustName
FROM Customers_After a
-- Perform a LEFT JOIN with Customers_Before to find customers only in
Customers_After
LEFT JOIN Customers_Before b
ON a.CustName = b.CustName
-- Filter to include only those customers who are not present in Customers_Before
WHERE b.CustName IS NULL;
Finding All Customers: Explaination NOTES
• First Part (Lines 2-6):
• SELECT b.CustName FROM Customers_Before b: Retrieves all
customer names from the Customers_Before table.
• LEFT JOIN Customers_After a ON b.CustName = a.CustName: Performs
a LEFT JOIN to combine the Customers_Before table with the
Customers_After table. It returns all customers from Customers_Before
and matches them with any customers in Customers_After.
• UNION: Combines the result of the first and second queries while
removing duplicates.
• Second Part (Lines 8-14):
• SELECT a.CustName FROM Customers_After a: Retrieves all
customer names from the Customers_After table.
• LEFT JOIN Customers_Before b ON a.CustName =
b.CustName: Performs a LEFT JOIN to find customers from
Customers_After who do not have a match in
Customers_Before.
• WHERE b.CustName IS NULL: Filters the result to include only
customers who are not present in Customers_Before,
effectively identifying new customers.
Finding New Customers NOTES
Problem Statement:
Identify customer names that appear in the
Customers_After table but not in the
Customers_Before table. These are considered
"new" customers.
Finding New Customers: Solution NOTES
-- Select customer names from Customers_After
that are not in Customers_Before
SELECT CustName
FROM Customers_After
WHERE CustName NOT IN (
-- Subquery to select all customer names
from Customers_Before
SELECT CustName
FROM Customers_Before
);
Finding New Customers: Explaination NOTES
• SELECT CustName FROM Customers_After: Retrieves
all customer names from the Customers_After table.

• WHERE CustName NOT IN (...): Filters out any


customer names that are also found in the
Customers_Before table.

• SELECT CustName FROM Customers_Before: This


subquery retrieves all customer names from the
Customers_Before table. The NOT IN condition ensures
that only customer names not found in this subquery
are returned, identifying customers who are new.
Finding Lost Customers NOTES
Problem Statement:
Identify customer names that were in the
Customers_Before table but do not appear in
the Customers_After table. These are
considered "lost" customers.
Finding Lost Customers: Solution NOTES
-- Select customer names from
Customers_Before that are not in
Customers_After
SELECT CustName
FROM Customers_Before
WHERE CustName NOT IN (
-- Subquery to select all customer names
from Customers_After
SELECT CustName
FROM Customers_After
);
Finding Lost Customers: Explaination NOTES
• SELECT CustName FROM Customers_Before: Retrieves
all customer names from the Customers_Before table.

• WHERE CustName NOT IN (...): Filters out any


customer names that are also found in the
Customers_After table.

• SELECT CustName FROM Customers_After: This


subquery retrieves all customer names from the
Customers_After table. The NOT IN condition ensures
that only customer names not found in this subquery
are returned, identifying customers who were lost
after the campaign.
Finding Returning Customers NOTES
Problem Statement:
Identify customer names that appear in both
the Customers_Before and Customers_After
tables. These are considered "returning"
customers.
Finding Returning Customers: Solution NOTES
-- Select customer names from Customers_After
that are also in Customers_Before
SELECT CustName
FROM Customers_After
WHERE CustName IN (
-- Subquery to select all customer names
from Customers_Before
SELECT CustName
FROM Customers_Before
);
Finding Returning Customers: Explaination NOTES
• SELECT CustName FROM Customers_After: Retrieves
all customer names from the Customers_After table.

• WHERE CustName IN (...): Filters the results to include


only customer names that are also found in the
Customers_Before table.

• SELECT CustName FROM Customers_Before: This


subquery retrieves all customer names from the
Customers_Before table. The IN condition ensures that
only customer names that exist in both tables are
returned, identifying returning customers.

You might also like