Section outline
-
-
π― Course Goals
-
Understand relational databases and SQL fundamentals.
-
Write efficient queries to extract, filter, and analyze data.
-
Perform joins, subqueries, aggregations, and window functions.
-
Work with real-world databases for business use-cases.
-
Optimize queries, design schemas, and understand transactions.
-
Prepare for SQL interviews and certifications.
π Course Structure
Duration: 8β10 weeks (self-paced)
Format: Text lessons, Quizzes, exercises, projects, and case studies -
-
-
1. Definition of a Database
A database is an organized collection of data that can be stored, managed, and retrieved efficiently using a computer system.
Think of it as a digital filing cabinet:
-
A file cabinet stores documents β A database stores information.
-
A folder groups related documents β A table groups related records.
-
Each page in a folder has details β Each row in a table has information.
π In short:
-
Data = raw facts (e.g., "John", "Salary: 50,000").
-
Database = a structured way of storing these facts so they can be searched, updated, and analyzed efficiently.
Key Features of Databases:
-
Structured storage β Organized into tables, rows, and columns.
-
Efficient retrieval β Allows fast searching and filtering.
-
Data integrity β Ensures accuracy and consistency.
-
Security β Controls who can access or change the data.
-
Scalability β Handles growing amounts of data.
Example:
An Employee Database may have a table like this:Employee_ID Name Department Salary Hire_Date 101 John HR 50,000 2018-05-20 102 Alice IT 70,000 2019-01-15 103 Raj Finance 65,000 2020-03-01
2. Difference Between Relational (RDBMS) and Non-Relational (NoSQL) Databases
Databases are broadly categorized into two types:
A. Relational Databases (RDBMS)
-
Store data in tables (rows and columns).
-
Relationships are established between tables using primary keys and foreign keys.
-
Use SQL (Structured Query Language) for data retrieval and manipulation.
-
Ensure ACID properties (Atomicity, Consistency, Isolation, Durability) β reliable transactions.
Example:
-
Employees table and Departments table linked by Department_ID.
-
Query to find all employees in IT:
Pros:
β Structured & reliable
β Strong data integrity
β Great for complex queriesCons:
β Rigid schema β not flexible for rapidly changing data
β Scaling horizontally (across many servers) can be difficult
B. Non-Relational Databases (NoSQL)
-
Store data in flexible formats:
-
Document-based (JSON/XML) β MongoDB
-
Key-Value β Redis
-
Columnar β Cassandra
-
Graph-based β Neo4j
-
-
No fixed schema β data can change frequently.
-
Designed for big data and high scalability.
-
Prioritize speed and flexibility over strict consistency.
Example (Document Database β MongoDB):
Pros:
β Handles unstructured/semi-structured data
β Scales easily across servers
β High performance for read/write operationsCons:
β Weaker consistency in some models
β Not ideal for complex relational queries
β Quick Comparison:
Feature Relational (RDBMS) Non-Relational (NoSQL) Data Format Tables (rows & columns) Documents, Key-Value, Graph, Columns Schema Fixed, structured Flexible, dynamic Language SQL Varies (MongoQL, CQL, APIs) Best For Structured data, transactions Big Data, real-time apps Example Systems MySQL, PostgreSQL, Oracle MongoDB, Redis, Cassandra
3. Popular RDBMS
Letβs look at the most widely used relational databases:
πΉ MySQL
-
Open-source, widely used for web applications.
-
Powers platforms like WordPress, Facebook (early days).
-
Great for small to medium-sized projects.
πΉ PostgreSQL
-
Advanced, open-source RDBMS.
-
Supports complex queries, JSON data, full-text search.
-
Strong in analytics, geospatial data, data science use cases.
πΉ SQL Server (by Microsoft)
-
Enterprise-grade, widely used in corporate environments.
-
Deep integration with Microsoft ecosystem (Excel, Power BI, .NET).
-
Offers both on-premise and cloud (Azure SQL) options.
πΉ Oracle Database
-
Extremely powerful, secure, and feature-rich.
-
Used by large enterprises (banking, telecom, governments).
-
Strong in performance tuning and large-scale data handling.
πΉ SQLite
-
Lightweight, file-based database (no server required).
-
Often embedded in mobile apps, IoT devices, local tools.
-
Example: Your phoneβs contact list is stored in SQLite.
4. Use-Cases of Databases
Databases are everywhere. Here are some industry examples:
πΈ Banking & Finance
-
RDBMS is preferred for transactions (must be accurate & consistent).
-
Example: Storing customer accounts, tracking deposits/withdrawals.
-
Queries: Checking balance, fraud detection, loan history.
πΈ E-commerce
-
Hybrid use (RDBMS + NoSQL).
-
RDBMS β Orders, payments, inventory.
-
NoSQL β Product recommendations, user browsing history.
-
Example: Amazon β structured transactions + NoSQL for personalization.
πΈ Social Media
-
NoSQL dominant because of unstructured data (posts, likes, comments).
-
Example: Facebook uses Cassandra, Instagram uses PostgreSQL + NoSQL.
-
Graph Databases (Neo4j) for friend relationships.
πΈ Analytics & Big Data
-
NoSQL + RDBMS combo.
-
Example: Netflix uses Cassandra (NoSQL) for streaming data + MySQL for user accounts.
-
Data warehouses (Snowflake, BigQuery, Redshift) for reporting.
π― Summary
-
A database organizes and manages data for efficient use.
-
RDBMS = structured, reliable, SQL-based, great for transactions.
-
NoSQL = flexible, scalable, great for unstructured/big data.
-
Popular RDBMS: MySQL, PostgreSQL, SQL Server, Oracle, SQLite.
-
Real-world use-cases: banking (transactions), e-commerce (orders + recommendations), social media (user data), analytics (big data insights).
-
-
When learning SQL, the first step is to understand how data is organized inside a database.
The three most important building blocks are:-
Tables
-
Rows (Records)
-
Columns (Fields)
Letβs break these down with clear examples.
1. πΉ What is a Table?
-
A table is like a container for data.
-
Think of it as an Excel sheet inside a database.
-
Each table stores information about a specific type of data.
π Example: An Employees table stores details about employees.
It looks like a grid with rows and columns.Employees Table (Example):
EmployeeID Name Department Salary 101 John HR 50,000 102 Alice IT 70,000 103 David Finance 65,000 -
Table name: Employees
-
Rows = each employee record
-
Columns = employee details (ID, Name, etc.)
2. πΉ What is a Row (Record)?
-
A row is a single entry in the table.
-
It represents one instance of the data type stored in the table.
-
Each row contains all the column values for that record.
π Example:
So, the first row in the Employees table means:
-
There is an employee named John,
-
His ID is 101,
-
He works in HR,
-
His salary is 50,000.
3. πΉ What is a Column (Field)?
-
A column defines an attribute or property of the data.
-
Every row must have a value (or sometimes NULL) for each column.
π Example Columns in the Employees table:
-
EmployeeID β unique identifier
-
Name β employeeβs name
-
Department β department name
-
Salary β salary amount
Each column has a data type (e.g., INT, VARCHAR, DATE, etc.).
For example:-
EmployeeID
β Integer -
Name
β Text (VARCHAR) -
Salary
β Number/Decimal
4. π Putting It All Together
Letβs visualize:
-
Table = Excel file named Employees.xlsx
-
Column = Each Excel column β βNameβ, βSalaryβ, βDepartmentβ
-
Row = Each Excel row β βJohn, 101, HR, 50000β
So in SQL:
-
Table = container of data
-
Row = one record (employee, student, order, etc.)
-
Column = attribute/field of that record
5. π₯οΈ SQL Example
Letβs create the Employees table in SQL:
Insert some rows:
Retrieve data (see rows & columns):
β You now understand:
-
Tables = storage like Excel sheet
-
Rows = records (John, ID 101, etc.)
-
Columns = attributes (Name, Salary, DeptID)
π Understanding Tables, Rows, and Columns (with Real-Life Examples)
1. π¦ Use-Case: Online Shopping (E-Commerce)
Think about Amazon or Flipkart.
They need to store details about their products.Products Table Example:
ProductID ProductName Category Price Stock 201 iPhone 15 Mobile 80000 50 202 Samsung TV Electronics 60000 20 203 Nike Shoes Fashion 5000 100 -
Table:
Products
-
Rows: Each row is one product (iPhone, TV, Shoes).
-
Columns: ProductID, Name, Category, Price, Stock.
π SQL Example:
This will list all Mobiles and their prices.
2. π¦ Use-Case: Banking
A bank needs to track customers and their accounts.
Customers Table Example:
CustomerID Name AccountType Balance 301 Rahul Savings 15000.00 302 Priya Current 50000.00 303 Arjun Savings 32000.00 -
Table:
Customers
-
Rows: Each customer is a record.
-
Columns: ID, Name, Account Type, Balance.
π SQL Example:
This query shows all customers who have more than βΉ20,000.
3. π Use-Case: Education (School / College)
A school keeps records of students.
Students Table Example:
StudentID Name Class Marks 401 Neha 10 89 402 Karan 12 76 403 Meena 9 92 -
Table:
Students
-
Rows: Each student = one row.
-
Columns: StudentID, Name, Class, Marks.
π SQL Example:
This shows toppers scoring 90 or above.
4. π Use-Case: Ride Booking (Uber/Ola)
A ride-booking app must store trips.
Rides Table Example:
RideID CustomerName Pickup Drop Fare 501 Ankit Delhi Noida 350 502 Sonali Mumbai Pune 1200 503 Ramesh Bangalore Airport 600 -
Table:
Rides
-
Rows: Each ride = one row.
-
Columns: RideID, Customer, Pickup, Drop, Fare.
π SQL Example:
This lists all high-value rides.
5. π Putting All Use-Cases Together
-
E-Commerce (Products) β whatβs being sold.
-
Banking (Customers) β who owns accounts.
-
Education (Students) β who studies in school.
-
Ride Booking (Rides) β trips being tracked.
In all these cases:
-
Table = container of data
-
Row = one record
-
Column = attribute of that record
-
-
1. πΉ What is SQL?
-
SQL stands for Structured Query Language.
-
It is the standard language used to communicate with databases.
-
SQL helps you:
-
Create databases and tables
-
Insert, update, and delete data
-
Query (search/filter) data
-
Control access (permissions)
-
Manage transactions
-
π In simple words: SQL is the language of databases.
2. πΉ Why Learn SQL?
-
Every business stores data (e-commerce, banking, education, social media).
-
SQL is used to organize and retrieve this data.
-
If you can speak SQL, you can βtalk to databasesβ like MySQL, PostgreSQL, SQL Server, Oracle, and SQLite.
3. πΉ Categories of SQL Commands
SQL commands are grouped into five main categories:
π¦ A. DDL (Data Definition Language)
-
Deals with structure of database objects (like tables, schemas).
-
Used to create, modify, or delete tables and databases.
Common Commands:
-
CREATE
β create a new table or database. -
ALTER
β change structure (add/remove column). -
DROP
β delete a table or database.
Example:
π© B. DML (Data Manipulation Language)
-
Deals with data stored inside tables.
-
Used to insert, modify, or remove records.
Common Commands:
-
INSERT
β add data into a table. -
UPDATE
β modify existing data. -
DELETE
β remove data.
Example:
π¨ C. DCL (Data Control Language)
-
Deals with access rights and permissions.
-
Used to control who can access what in the database.
Common Commands:
-
GRANT
β give permission. -
REVOKE
β take back permission.
Example:
π₯ D. TCL (Transaction Control Language)
-
Deals with transactions (a group of SQL commands that run together).
-
Helps maintain data integrity.
Common Commands:
-
COMMIT
β save changes permanently. -
ROLLBACK
β undo changes. -
SAVEPOINT
β create a checkpoint to rollback partially.
Example:
π§ (Optional) DQL (Data Query Language)
-
Some books/websites treat SELECT as a separate category (DQL).
-
Used only for retrieving data.
Example:
4. π Summary Table
Category Full Form Purpose Examples DDL Data Definition Language Defines structure CREATE, ALTER, DROP DML Data Manipulation Language Manages data INSERT, UPDATE, DELETE DCL Data Control Language Controls access GRANT, REVOKE TCL Transaction Control Language Manages transactions COMMIT, ROLLBACK, SAVEPOINT DQL Data Query Language Retrieves data SELECT
β You now know:
-
What SQL is
-
Why it is important
-
The 4 (or 5) categories of SQL commands with examples
π Introduction to SQL (with Real-World Use-Cases)
1. πΉ Banking System Example
A bank needs to manage customers, accounts, and transactions. Letβs see how each SQL category fits in.
π¦ A. DDL in Banking (Creating Database Structure)
π When a bank creates new systems, they define tables.
π‘ Use-case:
-
Create
Accounts
,Transactions
,Loans
tables. -
Alter structure when rules change (e.g., add
IFSC_Code
). -
Drop test tables after migration.
π© B. DML in Banking (Managing Customer Data)
π Once the structure is ready, banks insert and update customer details.
π‘ Use-case:
-
Insert β New account opening.
-
Update β Deposit, withdrawal, or loan repayment.
-
Delete β Account closure.
π¨ C. DCL in Banking (Access Permissions)
π A bank must control who can view/change data.
π‘ Use-case:
-
Clerks β Can only view accounts.
-
Managers β Can view & update balances.
-
Auditors β Can only read data, not change it.
π₯ D. TCL in Banking (Transactions)
π Money transfers involve multiple steps. If any step fails, everything must be undone to maintain accuracy.
π‘ Use-case:
-
Ensure deposits and withdrawals happen together.
-
If system crashes midway β rollback.
-
Savepoints used for partial rollbacks in large transactions.
2. πΉ E-Commerce Example
Imagine Amazon or Flipkart.
-
DDL β Create tables:
Products
,Orders
,Customers
. -
DML β Insert new products, update stock after purchase, delete discontinued items.
-
DCL β Grant access to customer service team for
Orders
, revoke admin rights after employee exit. -
TCL β Ensure product stock reduces only if payment is successful.
Example:
3. πΉ University Example
For managing students and exams.
-
DDL β Create
Students
,Courses
,Results
tables. -
DML β Insert new student records, update exam marks, delete graduated students.
-
DCL β Grant professors access to marks, revoke access after semester ends.
-
TCL β Ensure all marks for one exam update together or rollback.
4. π Quick Summary (Use-Cases at a Glance)
Category Banking Example E-Commerce Example University Example DDL Create Accounts
tableCreate Products
tableCreate Students
tableDML Insert deposits, update balance Update stock, insert orders Insert marks, update results DCL Grant auditor read-only rights Grant CS team access Grant professor access TCL Transfer money safely Payment + stock update Exam results update
β Now you not only know theory + SQL commands, but also how banks, e-commerce, and universities actually use them.
-
-
MySQL is one of the most widely used open-source databases.
π₯οΈ Steps for Installation:
-
Download
-
Download MySQL Installer for your OS (Windows/Mac/Linux).
-
Install
-
Run the installer β Choose Server only or Full setup.
-
Select MySQL Server and MySQL Workbench (GUI tool).
-
-
Configuration
-
Set root password (admin password for database).
-
Optionally create a user account.
-
Choose default port β
3306
.
-
-
Test Connection
-
Open MySQL Workbench or command line.
-
Run:
-
Enter password β you are inside MySQL!
-
π Tools to use:
-
MySQL Workbench (GUI)
-
Command Line
-
-
PostgreSQL is a powerful open-source database, popular in enterprises.
π₯οΈ Steps for Installation:
-
Download
-
Go toPostgreSQL Downloads.
-
Choose installer (Windows / Mac / Linux).
-
-
Install
-
Run installer.
-
Install pgAdmin (GUI tool).
-
-
Configuration
-
Set password for postgres user (super admin).
-
Default port:
5432
.
-
-
Test Connection
-
Open pgAdmin.
-
Connect with user:
postgres
and your password. -
Run a test query:
-
π Tools to use:
-
pgAdmin (GUI)
-
psql (command line)
-
-
SQL Server is a Microsoft database used in enterprises.
π₯οΈ Steps for Installation:
-
Download
-
Go toSQL Server Downloads.
-
Download SQL Server Developer Edition (free).
-
-
Install
-
Run installer β Choose Basic or Custom installation.
-
Install SQL Server Management Studio (SSMS) separately fromSSMS Download.
-
-
Configuration
-
Choose Mixed Mode Authentication (SQL + Windows login).
-
Set
sa
password (admin). -
Default port:
1433
.
-
-
Test Connection
-
Open SSMS.
-
Login with:
-
Server:
localhost
-
User:
sa
-
Password: your password
-
-
π Tools to use:
-
SSMS (SQL Server Management Studio)
-
Azure Data Studio (alternative GUI)
-
-
SQLite is the simplest and lightweight database β great for beginners.
π₯οΈ Steps for Installation:
-
Download
-
Go toSQLite Downloads.
-
Download Precompiled Binaries for your OS.
-
-
Install
-
Extract files.
-
Add the folder path to system environment variables (for command line access).
-
-
Test Connection
-
Open terminal / command prompt.
-
Run:
-
This creates a new database file
test.db
.
-
-
Run a Query
π Tools to use:
-
Command line
sqlite3
-
DB Browser for SQLite (GUI)
-
-
-
-
1. πΉ What is SELECT?
-
The SELECT statement is used to retrieve data from a database table.
-
It is the most common SQL command and forms the foundation of querying.
π General Syntax:
-
SELECT
β specifies which columns to show. -
FROM
β tells SQL which table to get data from.
2. πΉ Selecting All Columns
If you want to get all the data from a table, use
*
(wildcard).π Example Table: Employees
EmployeeID Name Department Salary 101 John HR 50000 102 Alice IT 70000 103 David Finance 65000 π Result:
Shows all rows and columns of the Employees table.
3. πΉ Selecting Specific Columns
You can choose only the columns you want.
π Result:
Name Salary John 50000 Alice 70000 David 65000
4. πΉ Using WHERE Clause (Filtering Data)
The
WHERE
clause filters rows based on conditions.π Result:
Name Department Alice IT David Finance
5. πΉ Using Aliases (Renaming Columns)
Aliases help make results more readable.
π Result:
EmployeeName MonthlySalary John 50000 Alice 70000 David 65000
6. πΉ Removing Duplicate Results (DISTINCT)
The
DISTINCT
keyword removes duplicates.π Result:
Department HR IT Finance
7. πΉ Sorting Results (ORDER BY)
You can sort rows in ascending (ASC) or descending (DESC) order.
π Result:
Name Salary Alice 70000 David 65000 John 50000
8. πΉ Limiting Results (LIMIT / TOP)
-
In MySQL & PostgreSQL β
LIMIT
-
In SQL Server β
TOP
π Result:
Shows only the first 2 rows.
9. π Summary
Keyword Purpose Example SELECT *
All columns SELECT * FROM Employees;
SELECT col1, col2
Specific columns SELECT Name, Salary FROM Employees;
WHERE
Filter rows WHERE Salary > 60000;
AS
Rename column Name AS EmployeeName
DISTINCT
Remove duplicates SELECT DISTINCT Department;
ORDER BY
Sort results ORDER BY Salary DESC;
LIMIT / TOP
Restrict rows LIMIT 5
/TOP 5
β You now know how to:
-
Select all or specific columns
-
Filter results
-
Rename columns
-
Remove duplicates
-
Sort and limit results
-
-
1. πΉ What is WHERE?
-
The WHERE clause is used to filter rows based on specific conditions.
-
It tells SQL: βOnly show the rows that match this rule.β
π General Syntax:
2. πΉ Example Table (Employees)
EmployeeID Name Department Salary Age 101 John HR 50000 30 102 Alice IT 70000 28 103 David Finance 65000 40 104 Neha IT 80000 35 105 Ramesh HR 45000 25
3. πΉ Basic Filtering
Equality (=)
π Result:
Name Department Alice IT Neha IT
Greater Than (>)
π Result:
Name Salary Alice 70000 David 65000 Neha 80000
Less Than (<)
π Result:
Name Age Alice 28 Ramesh 25
4. πΉ Combining Conditions
AND (Both Conditions Must Be True)
π Result:
Name Salary Department Neha 80000 IT
OR (At Least One Condition Must Be True)
π Result:
Name Department John HR David Finance Ramesh HR
NOT (Exclude Results)
π Result:
Name Department Alice IT David Finance Neha IT
5. πΉ Special Filtering Operators
BETWEEN (Range)
π Result:
Name Salary John 50000 Alice 70000 David 65000 Ramesh 45000
IN (Multiple Values)
π Result:
Name Department Alice IT David Finance Neha IT
LIKE (Pattern Matching)
π Result:
Name Alice π Patterns:
-
A%
β starts with A -
%a
β ends with a -
%am%
β contains "am"
IS NULL / IS NOT NULL
π Finds employees with no department assigned.
6. π Summary
Operator Example Meaning =
Salary = 50000
Equal to >
/<
Age > 30
Greater / Less than AND
Dept = 'IT' AND Salary > 70000
Both must be true OR
Dept = 'HR' OR Dept = 'Finance'
At least one true NOT
NOT Dept = 'HR'
Excludes HR BETWEEN
Salary BETWEEN 40000 AND 60000
Within a range IN
Dept IN ('IT','Finance')
Matches multiple values LIKE
Name LIKE 'A%'
Pattern search IS NULL
Dept IS NULL
Missing values
β You now know how to filter data with WHERE using:
-
Basic operators (
=
,<
,>
) -
Logical operators (
AND
,OR
,NOT
) -
Special filters (
BETWEEN
,IN
,LIKE
,NULL
)
-
-