SQL NOTES
SQL NOTES
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.
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.
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
Primar
table.
• Must be unique and cannot contain
NULL values.
• Typically created using a single
Foreig
tables.
• References the primary key of
another table.
• Helps maintain data consistency and
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.
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.
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.
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.
Clause Description
This clause is used to specify the columns that you want to retrieve
SELECT
from the database 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.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
.
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.
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