MySQL Fast Track
Course
By OLIR Learning
Christopher Jeberson
Founder & Director of Olir
IT Experience 1
13 years of experience in IT field working with
TCS
2 Clients
Microsoft
Nokia
Roles 3 Verizon
Corporate Trainer Rogers
Technical Program Manager
Lead & Tech Lead
4 Skills
Developer & Tester SQL Developer & Administrator, Java, C# &
Python
Power BI, MS Business Intelligence & Azure
Unix (Shell & Awk scripting)
HTML, CSS, Bootstrap & AngularJs
Contact: 86676 04148 | Email: [email protected] | Selaiyur, Tambaram, Chennai
What is a Database?
Database Types of Databases SQL
A database is an organized Relational Databases (RDBMS) Structured Query Language,
collection of data, typically used to interact with databases.
Structured data stored in
stored and accessed
tables with relationships Perform tasks like retrieving,
electronically.
between them. Example: updating, deleting, and
MySQL, PostgreSQL manipulating data.
Non-Relational Databases SQL is the standard language
(NoSQL) for relational databases.
Data stored in non-tabular
formats such as documents,
key-value pairs, or graphs.
Example: MongoDB,
Cassandra.
What is MySQL?
1 MySQL
A widely-used, open-source Relational Database Management
System (RDBMS).
2 Supports SQL
Used in web applications, analytics, e-commerce, and more.
3 Where MySQL is Used
Web applications (Facebook, Twitter), e-commerce platforms
(Shopify), data analytics platforms, content management systems
(WordPress).
CRUD Operations
Create
Add new data to the database.
Read
Retrieve data from the database.
Update
Modify existing data in the database.
Delete
Remove data from the database.
Database Overview: classicmodels
Business Context: This database models a vehicle business that sells products and manages orders,
employees, customers, and payments.
Tables
Customers Orders Orderdetails Payments
Customer information. Customer orders. Product details in each Customer payment
order. tracking.
Products Productline Employee Office
Individual product Categories of products. Employee details. Company offices.
details.
Reading Data (SWALO)
SELECT WHERE Aggregate Functions
The SELECT statement retrieves The WHERE clause filters the data Aggregate functions perform
data from a database. based on specific conditions. calculations on groups of data.
LIMIT ORDER BY
The LIMIT clause restricts the The ORDER BY clause sorts the data
number of rows returned. in ascending or descending order.
SELECT Statement
Used to retrieve data from one or more tables.
Select all columns Select specific columns Using Aliases
SELECT * FROM products; SELECT productName, SELECT productName AS
productDescription FROM Product, productDescription AS
products; Description FROM products;
Using Distinct
SELECT DISTINCT productLine FROM products;
practice
Select all columns from the customers table.
1
Select the productName and buyPrice from the products table.
2
3 Use aliases to rename columns while selecting product names and prices.
Select distinct productName values from the products table.
4
Select all employees with their first and last names combined.
5
SQL Operations
Arithmetic Operations
Comparison Operations
Logical Operations
String Operations
Date and Time Operations
Aggregation Operations
NULL Operation
Other Operations
Arithmetic Operation
Perform mathematical calculations on numeric data.
Add Substract Multiply
SELECT buyPrice + 10 FROM SELECT buyPrice - 5 FROM SELECT buyPrice * 2 FROM
products; products; products;
Divide Modulus
SELECT buyPrice / 2 FROM products; SELECT buyPrice % 2 FROM products;
Comparison Operation
Used to compare values
Equal Not Equal Greater Than
SELECT * FROM products SELECT * FROM products SELECT * FROM products
WHERE buyPrice = 50; WHERE buyPrice != 50; WHERE buyPrice > 100;
BETWEEN IN
SELECT * FROM products SELECT * FROM products
WHERE buyPrice BETWEEN 50 AND 100; WHERE buyPrice IN (50, 100, 150);
Logical Operation
Combine conditions in a query using logical operators.
AND OR NOT
SELECT * FROM products SELECT * FROM products SELECT * FROM products
WHERE buyPrice > 50 AND WHERE buyPrice > 100 OR WHERE NOT productLine =
productLine = 'Motorcycles'; productLine = 'Classic Cars'; 'Motorcycles';
String Operation
Manipulate and work with text data.
Uppercase Concatenation Substring
SELECT UPPER(productName) SELECT CONCAT(firstName, ' ', SELECT
FROM products; lastName) AS FullName FROM SUBSTRING(productName, 1, 5)
employees; FROM products;
LIKE
SELECT productName FROM products WHERE productName LIKE 'S%';
Date and Time Operations
Work with date and time data in SQL.
Current Date Extract Year Date Difference
SELECT CURDATE(); SELECT YEAR(orderDate) FROM SELECT DATEDIFF(shippedDate,
orders; orderDate) FROM orders;
Add Days
SELECT orderDate + INTERVAL 10 DAY FROM orders;
Aggregate Operations
Perform calculations on multiple rows of data and return a single value.
COUNT SUM AVG
SELECT COUNT(*) AS SELECT SUM(buyPrice) AS SELECT AVG(buyPrice) AS
TotalProducts FROM products; TotalPrice FROM products; AveragePrice FROM products;
MAX MIN
SELECT MAX(buyPrice) AS MaxPrice FROM SELECT MIN(buyPrice) AS MinPrice FROM products;
products;
NULL Operations
Functions to handle NULL values in SQL.
IS NULL IS NOT NULL COALESCE
SELECT * FROM products SELECT * FROM products SELECT COALESCE(buyPrice, 0)
WHERE buyPrice IS NULL; WHERE buyPrice IS NOT NULL; AS FinalPrice FROM products;
Other Operations
Additional SQL functions to perform specific tasks.
CAST IF
SELECT CAST(buyPrice AS DECIMAL(10,2)) FROM SELECT IF(buyPrice > 100, 'Expensive', 'Affordable')
products; AS PriceCategory FROM products;
CASE
SELECT CASE WHEN buyPrice > 100 THEN 'Expensive' ELSE 'Affordable' END AS PriceCategory FROM products;
practice
1 Add 100 to the amount for all payments.
Retrieve customers with a creditLimit between 20000 and 50000.
2
Select all products where buyPrice is greater than 100 and quantityInStock is more than 50.
3
Extract the first 5 characters from each productName.
4
Concatenate the contact first names and contact last names of all customers into a single column
5
called "Contact Fullname."
Calculate the number of days between orderDate and shippedDate for all orders.
6
Count the total number of products in the Motorcycles product line.
7
Replace State with NULL values with city value.
8
Convert amount to a decimal value with no decimal places.
9
10 Categorize Order as 'High Volume' if Ordered quantity is greater than 100, and 'Low Volume'
otherwise from orderDetails
Aggregation
The GROUP BY clause in SQL is used to group rows that have the same values
COUNT (Single Column) COUNT (Multiple Column)
SELECT productLine, COUNT(*) AS productCount SELECT productLine, productVendor, COUNT(*) AS
FROM products GROUP BY productLine; productCount FROM products GROUP BY
productLine, productVendor;
SUM
SELECT productLine, SUM(buyPrice) AS totalValue FROM products GROUP BY productLine;
Aggregation - Filtering
The HAVING clause is used to filter data after it has been grouped.
HAVING
SELECT orderNumber, COUNT(*) AS orderCount
FROM orderdetails
GROUP BY orderNumber
HAVING COUNT(*) > 10;
Combining “GROUP BY” with other clauses
COMBINE
SELECT orderNumber, COUNT(*) AS orderCount
FROM orderdetails
WHERE quantityOrdered > 10
GROUP BY orderNumber
Limit
Controls the number of rows returned by a SELECT query.
LIMIT
SELECT productName, buyPrice
FROM products
LIMIT 5;
“LIMIT” with offset
Skips a specific number of rows before starting to return the rows.
OFFSET
SELECT productName, buyPrice
FROM products
LIMIT 5, 5;
practice
Calculate the total number of products in the Motorcycles product line.
1
Find the maximum buyPrice of all products in the Classic Cars product line.
2
Select 2nd costliest based on buyPrice from products.
3
4 Select all products and sort them by buyPrice in descending order.
Retrieve all products and sort them first by productLine in ascending order, then by buyPrice in
5
descending order.
Order By
Sorts the result set of a query by one or more columns.
Ascending (Default) Descending
SELECT productName, buyPrice SELECT productName, buyPrice
FROM products FROM products
ORDER BY buyPrice; ORDER BY buyPrice DESC;
Sorting Multiple Rows
SELECT productName, productLine, buyPrice
FROM products
ORDER BY productLine ASC, buyPrice DESC;
Combining ORDER, OFFSET & LIMIT
The order of execution is ORDER —> OFFSET —> LIMIT
SELECT productName, buyPrice
FROM products
ORDER BY buyPrice DESC
LIMIT 5, 5;
Joins
INNER LEFT RIGHT
An INNER JOIN returns only the A LEFT JOIN returns all rows from A RIGHT JOIN is the opposite of a
rows where there is a match in both the left table, and the matched LEFT JOIN. It returns all rows from
tables. rows from the right table. If no the right table, and the matched
match is found, NULL values are rows from the left table. If no match
returned for the columns of the is found, NULL values are returned
right table. for the columns of the left table.
FULL CROSS JOIN WITH ALIAS
A FULL JOIN returns all rows when A CROSS JOIN returns the Cartesian Using table aliases can make your
there is a match in either the left or product of both tables, meaning queries easier to read, especially
right table. If there’s no match, every row from the first table is when working with long table
NULL values are returned for the combined with every row from the names or multiple tables.
columns of the missing table. second table.
However, MySQL doesn’t directly
support FULL JOIN. You can achieve
this by combining LEFT JOIN and
RIGHT JOIN with a UNION.
MULTIPLE JOINS
You can join more than two tables
by chaining multiple JOIN clauses.
Each additional table is joined in the
same manner as the first two.
Join
Inner Left
SELECT orders.orderNumber, orders.orderDate, SELECT customers.customerName,
customers.customerName orders.orderNumber
FROM orders FROM customers
INNER JOIN customers LEFT JOIN orders
ON orders.customerNumber = ON customers.customerNumber =
customers.customerNumber; orders.customerNumber;
Right Full
SELECT orders.orderNumber, SELECT customers.customerName,
customers.customerName orders.orderNumber
FROM orders FROM customers
RIGHT JOIN customers LEFT JOIN orders ON customers.customerNumber =
orders.customerNumber
ON orders.customerNumber =
customers.customerNumber; UNION
SELECT customers.customerName,
orders.orderNumber
FROM orders
RIGHT JOIN customers ON orders.customerNumber
= customers.customerNumber;
Cross Join with Alias
SELECT customers.customerName, SELECT c.customerName, o.orderNumber
products.productName
FROM customers AS c
FROM customers
INNER JOIN orders AS o
CROSS JOIN products;
ON c.customerNumber = o.customerNumber;
Multiple Joins
SELECT orders.orderNumber, customers.customerName, employees.firstName, employees.lastName
FROM orders
INNER JOIN customers ON orders.customerNumber = customers.customerNumber
INNER JOIN employees ON customers.salesRepEmployeeNumber = employees.employeeNumber;
practice
Retrieve the customerName and orderNumber for all customers who have placed orders.
1
2 Select employeeNumber and customerName for all customers handled by a specific sales
representative (use salesRepEmployeeNumber to join employees and customers).
3 Select all customers and their orderNumbers, including customers who have not placed any orders.
Retrieve a list of all employees and the offices they are assigned to, even if an employee doesn't have
4
an assigned office.
List all orders and the customers who placed them, including orders that do not have an associated
5
customer (hypothetical).
Select all offices and their associated employees, including offices that currently have no employees.
6
Retrieve all customers and orders, ensuring that customers without orders and orders without
7
customers are both included.
Update
INSERT UPDATE
Inserting new row of data Modify existing data
Insert
Used to add new rows of data into a table
Single Row All Columns
INSERT INTO students (studentID, firstName, INSERT INTO students
lastName, age)
VALUES (2, 'Jane', 'Doe', 22);
VALUES (1, 'John', 'Doe', 20);
Multiple Rows From Another Table
INSERT INTO students (studentID, firstName, INSERT INTO students_archive (studentID,
lastName, age) firstName, lastName, age)
VALUES SELECT studentID, firstName, lastName, age
(3, 'Alice', 'Smith', 19), FROM students
(4, 'Bob', 'Brown', 21), WHERE age > 21;
(5, 'Charlie', 'White', 23);
Update
Used to modify existing records in a table.
Single Column Multiple Column
UPDATE products UPDATE products
SET buyPrice = 55.00 SET buyPrice = 50.00, MSRP = 100.00
WHERE productCode = 'S10_1678'; WHERE productCode = 'S10_1949';
Updating Multiple Rows Update all Rows
UPDATE products UPDATE products
SET buyPrice = buyPrice * 1.10 SET quantityInStock = 100;
WHERE productLine = 'Motorcycles';
Updating based on another table
UPDATE customers
JOIN employees ON customers.salesRepEmployeeNumber = employees.employeeNumber
SET customers.salesRepEmployeeNumber = employees.employeeNumber
WHERE employees.jobTitle = 'Sales Rep';
Remove Data/Object
DELETE TRUNCATE DROP
Used to delete data from specific Used to delete all the data from the Used to permanently delete an
rows from a table. table entire database, table, column, or
other database object.
Delete
Specific Row All Row
DELETE FROM orders DELETE FROM products;
WHERE customerNumber = 103;
Using Join
DELETE orders
FROM orders
INNER JOIN customers ON orders.customerNumber = customers.customerNumber
WHERE customers.salesRepEmployeeNumber = 1504;
Truncate
Delete table
TRUNCATE TABLE customers;
Drop
Table Database
DROP TABLE employees; DROP DATABASE sales_db;
Column View
ALTER TABLE productlines DROP VIEW customer_orders_view;
DROP COLUMN description;
Index Trigger
DROP INDEX idx_customer_name ON customers; DROP TRIGGER order_after_insert;
Create
DATABASE TABLE VIEW
Collection SQL Objects Unit with rows and columns A view is a virtual table based on
the result set of a SQL query.
STORED PROCEDURE TRIGGER
A stored procedure is a set of SQL A trigger is a set of SQL statements
statements that can be stored in that automatically executes
the database and executed ("triggers") when a specific event
repeatedly. occurs in a table, such as INSERT,
UPDATE, or DELETE.
Create
Database View
CREATE DATABASE school_db; CREATE VIEW adult_students AS
SELECT studentID, firstName, lastName
FROM students
WHERE age > 18;
SELECT * FROM adult_students;
Stored Procedure Trigger
CREATE PROCEDURE GetStudentsByAge (IN CREATE TRIGGER student_insert_trigger
min_age INT)
AFTER INSERT ON students
BEGIN
FOR EACH ROW
SELECT studentID, firstName, lastName
BEGIN
FROM students
INSERT INTO student_log (studentID, action)
WHERE age > min_age;
VALUES (NEW.studentID, 'INSERTED');
END;
END;
Data Types
1 Numeric 2 String
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT, CHAR, VARCHAR, TEXT, MEDIUMTEXT, LONGTEXT
DECIMAL, FLOAT, DOUBLE
3 Datetime 4 BINARY
DATE, TIME, DATETIME, TIMESTAMP BLOB, MEDIUMBLOB, LONGBLOB
5 Other
BOOLEAN
TABLE CREATION
CREATE TABLE students (
studentID INT,
name VARCHAR(100),
age INT
);
Constraints
1 PRIMARY KEY 2 FOREIGN KEY
Uniquely identifies each row in the table Establishes a link between two tables.
3 NOT NULL 4 UNIQUE
Ensures that a column cannot have NULL values. Ensures that all values in a column are unique.
5 CHECK
Ensures that all values in a column satisfy a specific condition.
TABLE CREATION WITH CONSTRAINTS
CREATE TABLE students (
studentID INT PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50)
);
CREATE TABLE enrollments (
enrollmentID INT PRIMARY KEY,
studentID INT,
courseID INT,
FOREIGN KEY (studentID) REFERENCES students(studentID)
);
Cascading
Actions to be taken when a referenced row in the parent table is updated or deleted.
1 ON DELETE CASCADE 2 ON UPDATE CASCADE
When a row in the parent table is deleted, the When the primary key in the parent table is
corresponding rows in the child table are also updated, the corresponding foreign key in the
deleted. child table is automatically updated.
3 ON DELETE SET NULL 4 ON DELETE RESTRICT
When a row in the parent table is deleted, the Prevents the deletion of a row in the parent table
foreign key in the child table is set to NULL. if there are matching rows in the child table.
TABLE CREATION WITH CONSTRAINTS
CREATE TABLE employees (
employeeID INT AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(50),
lastName VARCHAR(50)
);
CREATE TABLE departments (
departmentID INT AUTO_INCREMENT PRIMARY KEY,
departmentName VARCHAR(100),
employeeID INT,
FOREIGN KEY (employeeID) REFERENCES employees(employeeID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Thank You
Thank you for attending this MySQL Fast Track Course. I hope you enjoyed the sessions and learned valuable skills.
Feel free to reach out if you have any questions or require further assistance. I am happy to support you on your
MySQL journey.
Mobile: 86676 04148
Email: [email protected]