Module 1: Database & Table Basics
1. Introduction to MySQL & RDBMS Concepts
Theory
RDBMS (Relational Database Management System)
o Stores data in tables (rows and columns).
o Maintains relationships between tables using keys.
o Examples: MySQL, PostgreSQL, Oracle, SQL Server.
MySQL
o An open-source RDBMS that uses SQL (Structured Query
Language) to manage data.
o Based on client-server architecture.
o Ensures ACID compliance for data reliability.
Key Features
o Multi-user access
o Data integrity and security
o High performance and scalability
2. Databases, Tables, Rows, and Columns
Theory
Term Description
Database Collection of related tables.
Table Structured collection of data (rows +
columns).
Row (Record) A single data entry (tuple).
Column (Field) Defines data attributes (e.g., name,
age).
Syntax & Practical
-- Create a database
CREATE DATABASE company_db;
-- Use the created database
USE company_db;
-- Create a table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
department VARCHAR(30),
salary DECIMAL(10,2)
);
-- Show all databases
SHOW DATABASES;
-- Show tables in the current database
SHOW TABLES;
-- Describe table structure
DESCRIBE employees;
3. DDL Commands (Data Definition Language)
Theory
DDL commands are used to define or modify the structure of database
objects.
Major commands:
CREATE, ALTER, DROP.
Syntax & Practical
CREATE DATABASE
CREATE DATABASE school;
DROP DATABASE
DROP DATABASE school;
CREATE TABLE
CREATE TABLE students (
student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
grade CHAR(2)
);
ALTER TABLE
-- Add a column
ALTER TABLE students ADD email VARCHAR(100);
-- Modify column type
ALTER TABLE students MODIFY age SMALLINT;
-- Rename a column
ALTER TABLE students CHANGE grade class VARCHAR(5);
-- Drop a column
ALTER TABLE students DROP COLUMN email;
DROP TABLE
DROP TABLE students;
4. Data Types in MySQL
Theory
Category Data Type Description Example
Numeric INT, BIGINT, Integer & fixed- 10, 999999,
DECIMAL(p,s) point numbers 12.50
String/Text CHAR(n), Fixed or variable- 'Rohit', 'Analyst'
VARCHAR(n) length strings
Date/Time DATE, DATETIME, Date & time '2025-10-11',
TIME values '2025-10-11
[Link]'
Boolean BOOLEAN True/False (1/0) TRUE, FALSE
Practical
CREATE TABLE sample_types (
id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR(50),
join_date DATE,
salary DECIMAL(8,2),
is_active BOOLEAN
);
5. Constraints
Theory
Constraints ensure data integrity and enforce rules on columns.
Constraint Description Example
PRIMARY KEY Uniquely identifies each emp_id INT PRIMARY
row KEY
AUTO_INCREMENT Auto-generates emp_id INT
sequential numbers AUTO_INCREMENT
UNIQUE Ensures all values are email VARCHAR(50)
unique UNIQUE
NOT NULL Disallows NULL values name VARCHAR(30)
NOT NULL
FOREIGN KEY Links to another table FOREIGN KEY (dept_id)
REFERENCES
departments(dept_id)
COMPOSITE KEY Combines multiple PRIMARY KEY
columns as a key (student_id, subject_id)
Practical
CREATE TABLE departments (
dept_id INT PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(50) UNIQUE NOT NULL
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR(50) NOT NULL,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
6. Relationships in Databases
Theory
Type Definition Example
One-to-One (1:1) One record in Table A Employee ↔ Employee
↔ One record in Table Details
B
One-to-Many (1:N) One record in Table A Department ↔
↔ Many in Table B Employees
Many-to-Many (M:N) Many in Table A ↔ Students ↔ Courses
Many in Table B
Practical
One-to-Many Example
CREATE TABLE departments (
dept_id INT PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(50)
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
Many-to-Many Example
CREATE TABLE students (
student_id INT PRIMARY KEY AUTO_INCREMENT,
student_name VARCHAR(50)
);
CREATE TABLE courses (
course_id INT PRIMARY KEY AUTO_INCREMENT,
course_name VARCHAR(50)
);
CREATE TABLE student_course (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
Module 2: Basic Queries & Aggregations
1. SELECT Statements
Theory
The SELECT statement is used to retrieve data from one or more tables.
You can select specific columns or use * to select all columns.
Syntax
SELECT column1, column2, ...
FROM table_name;
-- Select all columns
SELECT * FROM table_name;
Practical
-- Retrieve all employee records
SELECT * FROM employees;
-- Retrieve specific columns
SELECT emp_name, department FROM employees;
-- Rename columns using AS
SELECT emp_name AS Employee, salary AS Salary FROM employees;
2. DISTINCT Keyword
Theory
Used to remove duplicate records from query results.
Works on one or more columns.
Syntax
SELECT DISTINCT column_name FROM table_name;
Practical
-- Get unique department names
SELECT DISTINCT department FROM employees;
-- Get unique combinations of department and salary
SELECT DISTINCT department, salary FROM employees;
3. Filtering Data (WHERE Clause)
Theory
The WHERE clause filters records based on conditions.
Conditions use comparison (=, !=, <, >, <=, >=) and logical (AND, OR,
NOT) operators.
Syntax
SELECT column1, column2
FROM table_name
WHERE condition;
Practical
-- Employees in 'IT' department
SELECT * FROM employees WHERE department = 'IT';
-- Employees with salary > 50000
SELECT emp_name, salary FROM employees WHERE salary > 50000;
-- Multiple conditions
SELECT * FROM employees
WHERE department = 'Finance' AND salary >= 40000;
4. BETWEEN Operator
Theory
The BETWEEN operator filters results within a range (inclusive of both
ends).
Syntax
SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Practical
-- Employees with salary between 30k and 50k
SELECT emp_name, salary FROM employees
WHERE salary BETWEEN 30000 AND 50000;
5. LIKE Operator
Theory
The LIKE operator is used for pattern matching in string columns.
Wildcards:
o % → any sequence of characters
o _ → exactly one character
Syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern';
Practical
-- Names starting with 'R'
SELECT emp_name FROM employees WHERE emp_name LIKE 'R%';
-- Names ending with 'a'
SELECT emp_name FROM employees WHERE emp_name LIKE '%a';
-- Names with 'oh' anywhere
SELECT emp_name FROM employees WHERE emp_name LIKE '%oh%';
6. IN Operator
Theory
The IN operator is used to match a column against multiple possible
values.
Easier and cleaner than using multiple OR conditions.
Syntax
SELECT column_name
FROM table_name
WHERE column_name IN (value1, value2, value3);
Practical
-- Employees from specific departments
SELECT emp_name, department
FROM employees
WHERE department IN ('Finance', 'HR', 'IT');
7. IS NULL / IS NOT NULL
Theory
IS NULL is used to check missing or undefined values.
Use IS NOT NULL to find records where a value exists.
Syntax
SELECT column_name
FROM table_name
WHERE column_name IS NULL;
SELECT column_name
FROM table_name
WHERE column_name IS NOT NULL;
Practical
-- Employees without assigned department
SELECT emp_name FROM employees WHERE department IS NULL;
-- Employees with salary info
SELECT emp_name, salary FROM employees WHERE salary IS NOT NULL;
8. Sorting Results (ORDER BY)
Theory
The ORDER BY clause sorts query results ascending (ASC) or descending
(DESC).
Default order is ASC.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;
Practical
-- Sort employees by salary (low → high)
SELECT emp_name, salary FROM employees ORDER BY salary ASC;
-- Sort by department (A→Z) and then salary (high→low)
SELECT emp_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
9. Limiting Results (LIMIT & OFFSET)
Theory
Used to restrict the number of rows returned.
Commonly used in pagination.
OFFSET specifies how many rows to skip before starting to return rows.
Syntax
SELECT column_name
FROM table_name
LIMIT number OFFSET offset_value;
Practical
-- Get first 5 employees
SELECT * FROM employees LIMIT 5;
-- Skip first 3 employees, then get next 5
SELECT * FROM employees LIMIT 5 OFFSET 3;
10. Aggregate Functions
Theory
Aggregate functions perform calculations on multiple rows and return a single
value.
Function Description Example
COUNT() Counts total rows COUNT(*)
SUM() Adds numeric values SUM(salary)
AVG() Calculates average value AVG(salary)
MIN() Returns smallest value MIN(salary)
MAX() Returns largest value MAX(salary)
Practical
-- Total number of employees
SELECT COUNT(*) AS total_employees FROM employees;
-- Average salary of employees
SELECT AVG(salary) AS avg_salary FROM employees;
-- Highest and lowest salary
SELECT MAX(salary) AS highest, MIN(salary) AS lowest FROM employees;
11. Grouping Data (GROUP BY)
Theory
GROUP BY groups rows that have the same values in specified columns.
Often used with aggregate functions to summarize data.
Syntax
SELECT column_name, AGG_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
Practical
-- Total employees per department
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
-- Average salary by department
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
12. Filtering Groups (HAVING Clause)
Theory
HAVING is similar to WHERE, but it filters aggregated/grouped results.
Used after GROUP BY.
Syntax
SELECT column_name, AGG_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Practical
-- Departments with more than 5 employees
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
-- Departments with avg salary > 40000
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 40000;
Module 3: Joins, Subqueries & Advanced Functions
1. JOINS (Combining Data from Multiple Tables)
Theory
Purpose:
Joins combine data from two or more tables based on a related column
(usually a key).
Each join type defines how unmatched rows are handled.
Join Type Description
INNER JOIN Returns rows that have matching
values in both tables.
LEFT JOIN Returns all rows from the left table +
matched rows from the right table.
RIGHT JOIN Returns all rows from the right table
+ matched rows from the left table.
FULL OUTER JOIN* Returns all rows when there’s a
match in one or both tables. (Not
directly supported in MySQL; can be
simulated using UNION of LEFT +
RIGHT JOIN.)
CROSS JOIN Returns the Cartesian product (all
combinations of both tables).
SELF JOIN A table joined with itself (useful for
hierarchical data).
Syntax
SELECT columns
FROM table1
JOIN_TYPE table2
ON [Link] = [Link];
Practical
INNER JOIN
SELECT e.emp_name, d.dept_name
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id;
LEFT JOIN
SELECT e.emp_name, d.dept_name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id;
RIGHT JOIN
SELECT e.emp_name, d.dept_name
FROM employees e
RIGHT JOIN departments d
ON e.dept_id = d.dept_id;
FULL OUTER JOIN (Simulated)
SELECT e.emp_name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id
UNION
SELECT e.emp_name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
CROSS JOIN
SELECT e.emp_name, d.dept_name
FROM employees e
CROSS JOIN departments d;
SELF JOIN
SELECT e1.emp_name AS Employee, e2.emp_name AS Manager
FROM employees e1
JOIN employees e2
ON e1.manager_id = e2.emp_id;
2. Subqueries (Nested Queries)
Theory
A Subquery is a query inside another query.
Used to filter, calculate, or compare results dynamically.
Can appear in SELECT, WHERE, or FROM clauses.
Type Usage
Single-row subquery Returns one value
Multi-row subquery Returns multiple values
Correlated subquery Refers to the outer query’s column
Syntax
SELECT column
FROM table
WHERE column OPERATOR (SELECT column FROM table WHERE condition);
Practical
Single-row Subquery
-- Employees with salary greater than average salary
SELECT emp_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Multi-row Subquery with IN
-- Employees in departments located in 'Mumbai'
SELECT emp_name
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE location = 'Mumbai'
);
Correlated Subquery
-- Employees earning more than department average
SELECT emp_name, salary, dept_id
FROM employees e
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE dept_id = e.dept_id
);
3. UNION and UNION ALL
Theory
Used to combine results from multiple queries (same number and type
of columns).
UNION → Removes duplicates.
UNION ALL → Keeps duplicates.
Syntax
SELECT column1, column2 FROM table1
UNION [ALL]
SELECT column1, column2 FROM table2;
Practical
-- Combine employees from two branches
SELECT emp_name, 'Branch A' AS branch FROM employees_a
UNION
SELECT emp_name, 'Branch B' AS branch FROM employees_b;
-- Include duplicates
SELECT emp_name, 'Branch A' AS branch FROM employees_a
UNION ALL
SELECT emp_name, 'Branch B' AS branch FROM employees_b;
4. Conditional Queries (CASE WHEN)
Theory
CASE provides if-else logic in SQL queries.
Evaluates conditions and returns a value when the condition is true.
Syntax
SELECT column,
CASE
WHEN condition THEN result1
WHEN condition THEN result2
ELSE default_result
END AS alias_name
FROM table;
Practical
-- Categorize employees based on salary
SELECT emp_name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary BETWEEN 50000 AND 79999 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
5. String & Date Functions
Theory
Function Category Description Example
CONCAT() String Combines two CONCAT(first_name, '
or more strings ', last_name)
SUBSTRING() String Extracts part of SUBSTRING('Rohit', 1,
a string 3) → 'Roh'
NOW() Date/Time Returns current NOW()
date and time
DATEDIFF() Date/Time Difference (in DATEDIFF('2025-10-
days) between 11','2025-10-01')
two dates
DATE_FORMAT() Date/Time Formats date DATE_FORMAT(NOW(),
as per pattern '%Y-%m-%d')
Practical
-- Combine first and last names
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
-- Extract first 3 letters of employee name
SELECT SUBSTRING(emp_name, 1, 3) AS short_name FROM employees;
-- Get current timestamp
SELECT NOW() AS current_time;
-- Calculate days since joining
SELECT emp_name, DATEDIFF(NOW(), join_date) AS days_since_joined FROM
employees;
-- Format joining date
SELECT emp_name, DATE_FORMAT(join_date, '%d-%M-%Y') AS formatted_date
FROM employees;
6. Window Functions
📘 Theory
Window Functions perform calculations across sets of rows related to
the current row.
Unlike GROUP BY, they don’t collapse rows.
Common in analytics for ranking, comparisons, and cumulative totals.
Function Purpose
ROW_NUMBER() Sequential numbering of rows
RANK() Ranking with gaps for ties
DENSE_RANK() Ranking without gaps
LEAD() Access next row’s value
LAG() Access previous row’s value
Syntax
SELECT column,
ROW_NUMBER() OVER (ORDER BY column) AS row_num
FROM table;
Practical
-- Rank employees by salary (highest to lowest)
SELECT emp_name, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
-- Show previous employee’s salary
SELECT emp_name, salary,
LAG(salary) OVER (ORDER BY salary DESC) AS prev_salary
FROM employees;
-- Add a row number to each record
SELECT emp_name, department,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC)
AS row_num
FROM employees;
7. Temporary Tables (for Analytics)
Theory
A Temporary Table stores intermediate results for complex analysis or
multi-step queries.
Exists only for the session that created it and is automatically deleted
when the session ends.
Syntax
CREATE TEMPORARY TABLE temp_table AS
SELECT columns
FROM existing_table
WHERE condition;
Practical
-- Create temporary table of high earners
CREATE TEMPORARY TABLE high_earners AS
SELECT emp_name, department, salary
FROM employees
WHERE salary > 80000;
-- Use it for further analysis
SELECT department, COUNT(*) AS total_high_earners
FROM high_earners
GROUP BY department;
Module 4: Data Manipulation, Transactions & Indexing
1. DML Commands
Definition:
DML (Data Manipulation Language) commands are used to insert, update, and
delete data within database tables.
Common Commands:
Command Description
INSERT INTO Adds new rows to a table
UPDATE Modifies existing data
DELETE Removes rows from a table
Syntax & Examples:
Insert Data
INSERT INTO employees (emp_id, name, department, salary)
VALUES (101, 'Rohit Jaiswal', 'Data', 50000);
Update Data
UPDATE employees
SET salary = 55000
WHERE emp_id = 101;
Delete Data
DELETE FROM employees
WHERE emp_id = 101;
2. Transactions
Definition:
A transaction is a group of SQL operations executed as a single unit. It ensures
ACID properties — Atomicity, Consistency, Isolation, Durability.
Common Commands
Command Description
START TRANSACTION Begins a new transaction
COMMIT Saves all changes
ROLLBACK Reverts changes made during the
transaction
Syntax & Example:
START TRANSACTION;
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 2;
COMMIT; -- or use ROLLBACK if something goes wrong
3. Handling NULL Values
Definition:
NULL represents missing or unknown data.
Key Checks
-- Find rows with NULL values
SELECT * FROM employees WHERE manager_id IS NULL;
-- Replace NULL with a default value
SELECT IFNULL(manager_id, 'No Manager') AS manager FROM employees;
4. Keys & Relationships
Definition:
Keys ensure uniqueness and establish relationships between tables.
Key Type Purpose
Primary Key Uniquely identifies each record
Foreign Key Links data between two tables
Unique Key Ensures all values are unique but
allows NULLs
Composite Key Combines two or more columns for
unique identification
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
product_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
5. Indexing
Definition:
An index improves query performance by allowing faster data retrieval, but
slightly increases storage and slows down DML operations.
Common Types
Index Type Description
CREATE INDEX Creates a non-unique index
CREATE UNIQUE INDEX Ensures values are unique
Syntax & Examples:
-- Create Index
CREATE INDEX idx_department ON employees(department);
-- Create Unique Index
CREATE UNIQUE INDEX idx_email ON employees(email);
-- Drop Index
DROP INDEX idx_department ON employees;
When to Use:
Columns used in WHERE, JOIN, or ORDER BY clauses frequently.
Avoid indexing columns with many duplicate values.
6. Performance Considerations
Index selective columns (highly unique values).
Avoid too many indexes on frequently updated tables.
Use EXPLAIN to analyze query performance.
Regularly monitor index fragmentation.
Module 5: Views, Procedures, Triggers & Analytics Queries
1. Views
Theory
A View is a virtual table based on a SELECT query.
Simplifies complex queries and restricts access to specific columns.
Does not store data physically.
Syntax
-- Create a view
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
-- Drop a view
DROP VIEW view_name;
Practical
-- View of employees in IT department
CREATE VIEW it_employees AS
SELECT emp_name, salary, department
FROM employees
WHERE department = 'IT';
-- Query the view
SELECT * FROM it_employees;
-- Drop the view
DROP VIEW it_employees;
2. Stored Procedures & Functions
Theory
Stored Procedure: Predefined SQL statements executed with CALL. Can
include input/output parameters.
Function: Returns a single value, can be used in queries.
Syntax
Procedure:
CREATE PROCEDURE procedure_name (IN param1 datatype, OUT param2
datatype)
BEGIN
-- SQL statements
END;
-- Call procedure
CALL procedure_name(param1, @param2);
Function:
CREATE FUNCTION function_name(param datatype)
RETURNS datatype
BEGIN
-- SQL statements
RETURN value;
END;
-- Use function
SELECT function_name(column) FROM table;
Practical
-- Procedure to increase salary by 10%
CREATE PROCEDURE raise_salary(IN dept VARCHAR(50))
BEGIN
UPDATE employees SET salary = salary * 1.1 WHERE department = dept;
END;
CALL raise_salary('IT');
-- Function to calculate bonus (10% of salary)
CREATE FUNCTION calc_bonus(salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
BEGIN
RETURN salary * 0.1;
END;
SELECT emp_name, calc_bonus(salary) AS bonus FROM employees;
3. Triggers
Theory
Triggers automatically execute before or after an INSERT, UPDATE, or
DELETE.
Useful for audit logs, validations, or automatic updates.
Syntax
CREATE TRIGGER trigger_name
BEFORE|AFTER INSERT|UPDATE|DELETE
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END;
Practical
-- Trigger to log salary changes
CREATE TRIGGER before_salary_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_log(emp_id, old_salary, new_salary, change_date)
VALUES (OLD.emp_id, [Link], [Link], NOW());
END;
4. Transactions & Isolation Levels
Theory
Transactions: Group SQL operations executed as one unit.
Isolation Levels: Control visibility of uncommitted changes to other
transactions.
Isolation Level Description
READ UNCOMMITTED Dirty reads allowed
READ COMMITTED No dirty reads
REPEATABLE READ No non-repeatable reads
SERIALIZABLE Highest isolation, prevents all
anomalies
Practical
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 2;
COMMIT;
5. Performance Optimization
Theory
Optimize queries using indexes, EXPLAIN, and efficient SQL design.
Avoid unnecessary subqueries or full table scans.
Syntax
EXPLAIN SELECT * FROM employees WHERE department = 'IT';
CREATE INDEX idx_department ON employees(department);
6. Backup & Restore
Theory
Backup ensures data safety; restore recovers lost data.
mysqldump is commonly used in MySQL.
Practical
-- Backup database
mysqldump -u root -p company_db > company_backup.sql
-- Restore database
mysql -u root -p company_db < company_backup.sql
7. User Management
Theory
Control database access using GRANT and REVOKE.
Define privileges for security.
Syntax
-- Grant privileges
GRANT SELECT, INSERT, UPDATE ON company_db.* TO 'user1'@'localhost'
IDENTIFIED BY 'password';
-- Revoke privileges
REVOKE INSERT, UPDATE ON company_db.* FROM 'user1'@'localhost';
8. JSON Handling
Theory
MySQL supports JSON data type for semi-structured data.
Functions allow extracting and aggregating JSON content.
Syntax
-- Extract JSON value
JSON_EXTRACT(json_column, '$.key');
-- Aggregate JSON array
JSON_ARRAYAGG(column_name);
Practical
SELECT JSON_EXTRACT(employee_data, '$.[Link]') AS city FROM
employees;
SELECT JSON_ARRAYAGG(emp_name) AS employee_list FROM employees
WHERE department = 'IT';
9. Advanced Analytics Queries
Theory
Used for business intelligence & reporting.
Includes rolling sums, rankings, percentiles, trends.
Examples
-- Rolling sum of salaries
SELECT emp_id, salary,
SUM(salary) OVER (ORDER BY emp_id ROWS BETWEEN 2 PRECEDING AND
CURRENT ROW) AS rolling_sum
FROM employees;
-- Rank employees by salary
SELECT emp_name, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
-- Percentile example
SELECT emp_name, salary,
PERCENT_RANK() OVER (ORDER BY salary) AS percentile
FROM employees;
10. Cursors & Temporary Tables for Analytics
Theory
Cursors: Allow row-by-row processing of query results (used in complex
analytics or procedures).
Temporary Tables: Store intermediate results for multi-step
computations.
Syntax
-- Create temporary table
CREATE TEMPORARY TABLE temp_sales AS
SELECT * FROM sales WHERE month = 'Oct';
-- Cursor Example
DECLARE cur1 CURSOR FOR SELECT emp_id, salary FROM employees;
OPEN cur1;
FETCH cur1 INTO @emp_id, @salary;
CLOSE cur1;