Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views36 pages

MySQL Notes by SHUMAILA

The document provides a comprehensive guide on installing MySQL and using MySQL Workbench, detailing steps for both Windows/macOS and Linux (Ubuntu) installations. It explains key concepts such as databases, DBMS, and data types, along with SQL commands for creating, modifying, and querying tables. Additionally, it covers constraints, functions, and best practices for managing data within MySQL.

Uploaded by

cchauhansahab719
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

MySQL Notes by SHUMAILA

The document provides a comprehensive guide on installing MySQL and using MySQL Workbench, detailing steps for both Windows/macOS and Linux (Ubuntu) installations. It explains key concepts such as databases, DBMS, and data types, along with SQL commands for creating, modifying, and querying tables. Additionally, it covers constraints, functions, and best practices for managing data within MySQL.

Uploaded by

cchauhansahab719
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Installing MySQL

What is MySQL workbench?


MySQL Workbench is a visual tool for database architects, developers, and DBAs. It
provides data modeling, SQL development, and comprehensive administration
tools for server configuration, user administration, backup, and much more.

What is a Database Management System (DBMS)?


A Database Management System (DBMS) is software that interacts with end users,
applications, and the database itself to capture and analyze data. It allows for the
creation, retrieval, updating, and management of data in databases. If you know
one DBMS, you can easily transition to another, as they share similar concepts and
functionalities.

Windows / macOS Installation


1. Download from: https://dev.mysql.com/downloads/installer/
2. Run the installer and choose Developer Default.
3. Set a root password when prompted.
4. Install MySQL Workbench (optional but helpful GUI).

Linux (Ubuntu) Installation


Follow these steps to install MySQL and create a user:
Step 1: Update Package Index Step 5: Test Login

sudo apt update mysql -u harry -p

Enter the password: password

Step 2: Install MySQL Server Make sure to replace 'password' with a secure password of your choice in
production environments.
sudo apt install mysql-server

Step 3: Secure the Installation

sudo mysql_secure_installation

Choose your options (yes to most).

Step 4: Create a User 'harry'@'localhost'

Log into MySQL:

sudo mysql

Run the following SQL commands:

CREATE USER 'harry'@'localhost' IDENTIFIED BY 'password';


GRANT ALL PRIVILEGES ON *.* TO 'harry'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

EXIT;
Step 2: Create a Table
Getting Started with MySQL Now we’ll create a simple users table:

CREATE TABLE users (


What is a Database? id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,


A database is a container that stores related data in an organized way. In MySQL, a email VARCHAR(100) UNIQUE NOT NULL,
database holds one or more tables. gender ENUM('Male', 'Female', 'Other'),

date_of_birth DATE,
Think of it like:
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

• Folder analogy: );

• A database is like a folder.


This table will store basic user info.
• Each table is a file inside that folder.
• The rows in the table are like the content inside each file.

• Excel analogy:
Step 3: Drop the Database
• A database is like an Excel workbook.
You can delete the entire database (and all its tables) using:
• Each table is a separate sheet inside that workbook.
• Each row in the table is like a row in Excel.
DROP DATABASE startersql;

Be careful — this will delete everything in that database.

Step 1: Create a Database

CREATE DATABASE startersql; Data Types Explained


• INT : Integer type, used for whole numbers.
After creating the database, either: • VARCHAR(100) : Variable-length string, up to 100 characters.
• Right-click it in MySQL Workbench and select “Set as Default Schema”, or • ENUM : A string object with a value chosen from a list of permitted values. eg.
• Use this SQL command: gender ENUM('Male', 'Female', 'Other')
• DATE : Stores date values. eg date_of_birth DATE
USE startersql;
• TIMESTAMP : Stores date and time, automatically set to the current timestamp
when a row is created.
• BOOLEAN : Stores TRUE or FALSE values, often used for flags like is_active .

Working with Tables in MySQL


• DECIMAL(10, 2) : Stores exact numeric data
values, useful for financial data. The first number Selecting Data from a Table
is the total number of digits, and the second is the
number of digits after the decimal point. Select All Columns

SELECT * FROM users;


Constraints Explained
• AUTO_INCREMENT : Automatically generates a unique number for each row. This fetches every column and every row from the users table.
• PRIMARY KEY : Uniquely identifies each row in the table.
• NOT NULL : Ensures a column cannot have a NULL value. Select Specific Columns
• UNIQUE : Ensures all values in a column are different.
SELECT name, email FROM users;
• DEFAULT : Sets a default value for a column if no value is provided. eg.
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP , is_active BOOLEAN
This only fetches the name and email columns from all rows.
DEFAULT TRUE

Renaming a Table
To rename an existing table:

RENAME TABLE users TO customers;

To rename it back:

RENAME TABLE customers TO users;


Altering a Table
You can use ALTER TABLE to modify an existing table.

Inserting Data into MySQL Tables


Add a Column
To add data into a table, we use the INSERT INTO statement.
ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT TRUE;

Drop a Column Insert Without Specifying Column Names (Full Row


ALTER TABLE users DROP COLUMN is_active;
Insert)
This method requires you to provide values for all columns in order, except
columns with default values or AUTO_INCREMENT .
Modify a Column Type

ALTER TABLE users MODIFY COLUMN name VARCHAR(150); INSERT INTO users VALUES
(1, 'Alice', '[email protected]', 'Female', '1995-05-14', DEFAULT);

Not recommended if your table structure might change (e.g., new columns
added later).
Move a Column to the First Position
To move a column (e.g., email ) to the first position:

Insert by Specifying Column Names (Best Practice)


ALTER TABLE users MODIFY COLUMN email VARCHAR(100) FIRST;

This method is safer and more readable. You only insert into specific columns.

To move a column after another column (e.g., move after ):


gender name
INSERT INTO users (name, email, gender, date_of_birth) VALUES

('Bob', '[email protected]', 'Male', '1990-11-23');


ALTER TABLE users MODIFY COLUMN gender ENUM('Male', 'Female', 'Other') AFTER name;

or for multiple rows:

INSERT INTO users (name, email, gender, date_of_birth) VALUES


('Bob', '[email protected]', 'Male', '1990-11-23'),

('Charlie', '[email protected]', 'Other', '1988-02-17');


The remaining columns like
id (which is AUTO_INCREMENT ) and created_at
(which has a default) are automatically handled by MySQL.

Querying Data in MySQL using SELECT


Insert Multiple Rows at Once
The SELECT statement is used to query data from a table.

INSERT INTO users (name, email, gender, date_of_birth) VALUES

('Charlie', '[email protected]', 'Other', '1988-02-17'),

('David', '[email protected]', 'Male', '2000-08-09'),


Basic Syntax
('Eva', '[email protected]', 'Female', '1993-12-30');

SELECT column1, column2 FROM table_name;


This is more efficient than inserting rows one by one.

To select all columns:

SELECT * FROM users;

Filtering Rows with WHERE

Equal To

SELECT * FROM users WHERE gender = 'Male';

Not Equal To

SELECT * FROM users WHERE gender != 'Female';

-- or

SELECT * FROM users WHERE gender <> 'Female';


Greater Than / Less Than IN
SELECT * FROM users WHERE date_of_birth < '1995-01-01';
SELECT * FROM users WHERE gender IN ('Male', 'Other');
SELECT * FROM users WHERE id > 10;

Greater Than or Equal / Less Than or Equal

SELECT * FROM users WHERE id >= 5;


LIKE (Pattern Matching)
SELECT * FROM users WHERE id <= 20;
SELECT * FROM users WHERE name LIKE 'A%'; -- Starts with A

SELECT * FROM users WHERE name LIKE '%a'; -- Ends with a

SELECT * FROM users WHERE name LIKE '%li%'; -- Contains 'li'

Working with NULL

IS NULL
AND / OR
SELECT * FROM users WHERE date_of_birth IS NULL;

SELECT * FROM users WHERE gender = 'Female' AND date_of_birth > '1990-01-01';

IS NOT NULL SELECT * FROM users WHERE gender = 'Male' OR gender = 'Other';

SELECT * FROM users WHERE date_of_birth IS NOT NULL;

ORDER BY
BETWEEN SELECT * FROM users ORDER BY date_of_birth ASC;

SELECT * FROM users ORDER BY name DESC;


SELECT * FROM users WHERE date_of_birth BETWEEN '1990-01-01' AND '2000-12-31';

LIMIT

SELECT * FROM users LIMIT 5; -- Top 5 rows


SELECT * FROM users LIMIT 10 OFFSET 5; -- Skip first 5 rows, then get next 10

SELECT * FROM users LIMIT 5, 10; -- Get 10 rows starting from the 6th row (Same as
above)

SELECT * FROM users ORDER BY created_at DESC LIMIT 10;

UPDATE - Modifying Existing Data


Quick Quiz
The UPDATE statement is used to change values in one or more rows.
What does the following queries do?

SELECT * FROM users WHERE salary > 60000 ORDER BY created_at DESC LIMIT 5; Basic Syntax

UPDATE table_name
SELECT * FROM users ORDER BY salary DESC;
SET column1 = value1, column2 = value2

WHERE condition;
SELECT * FROM users WHERE salary BETWEEN 50000 AND 70000;

Example: Update One Column

UPDATE users
SET name = 'Alicia'

WHERE id = 1;

This changes the name of the user with id = 1 to “Alicia”.

Example: Update Multiple Columns

UPDATE users

SET name = 'Robert', email = '[email protected]'


WHERE id = 2;

Without WHERE Clause (Warning)

UPDATE users
SET gender = 'Other';
This updates every row in the table. Be very careful when omitting the WHERE 4. Set the gender of user Ishaan to Other .
clause.
UPDATE users
SET gender = 'Other'

WHERE name = 'Ishaan';

Quick Quiz: Practice Your UPDATE Skills

Try answering or running these queries based on your users table.


5. Reset salary of all users to ₹50,000 (Careful - affects all rows).
1. Update the salary of user with id = 5 to ₹70,000.
UPDATE users

SET salary = 50000;


UPDATE users

SET salary = 70000

WHERE id = 5; Note: This query will overwrite salary for every user. Use with caution!

2. Change the name of the user with email [email protected]


to Aisha Khan .

UPDATE users
SET name = 'Aisha Khan'

WHERE email = '[email protected]';

3. Increase salary by ₹10,000 for all users whose salary is less


than ₹60,000.

UPDATE users

SET salary = salary + 10000


WHERE salary < 60000;
This removes the table structure and all data permanently.

DELETE - Removing Data from a Table Best Practices


The DELETE statement removes rows from a table. • Always use unless you’re intentionally updating/deleting everything.
WHERE
WHERE
• Consider running a
SELECT with the same clause first to confirm what
Basic Syntax will be affected:

SELECT * FROM users WHERE id = 3;


DELETE FROM table_name

WHERE condition;
• Always back up important data before performing destructive operations.

Example: Delete One Row Quick Quiz: Practice Your DELETE Skills

DELETE FROM users


what will happen if you run these queries?

WHERE id = 3;
DELETE FROM users

WHERE salary < 50000;

Delete Multiple Rows


DELETE FROM users
WHERE salary IS NULL;
DELETE FROM users

WHERE gender = 'Other';

Delete All Rows (but keep table structure)

DELETE FROM users;

Drop the Entire Table (use with caution)

DROP TABLE users;


Example:

CREATE TABLE users (

id INT PRIMARY KEY,


MySQL Constraints name VARCHAR(100) NOT NULL

);
Constraints in MySQL are rules applied to table columns to ensure the accuracy,
validity, and integrity of the data.
Change an existing column to NOT NULL:

ALTER TABLE users


1. UNIQUE Constraint MODIFY COLUMN name VARCHAR(100) NOT NULL;

Ensures that all values in a column are different.


Make a column nullable again:
Example (during table creation):
ALTER TABLE users

CREATE TABLE users ( MODIFY COLUMN name VARCHAR(100) NULL;

id INT PRIMARY KEY,


email VARCHAR(100) UNIQUE

);

3. CHECK Constraint
Add UNIQUE using ALTER TABLE :
Ensures that values in a column satisfy a specific condition.

ALTER TABLE users

ADD CONSTRAINT unique_email UNIQUE (email); Example: Allow only dates of birth after Jan 1, 2000

ALTER TABLE users


ADD CONSTRAINT chk_dob CHECK (date_of_birth > '2000-01-01');

2. NOT NULL Constraint Naming the constraint ( chk_dob ) helps if you want to drop it later.

Ensures that a column cannot contain NULL values.

4. DEFAULT Constraint

Sets a default value for a column if none is provided during insert.


Example: Example:

CREATE TABLE users ( CREATE TABLE users (

id INT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,

is_active BOOLEAN DEFAULT TRUE name VARCHAR(100)

); );

Each new row gets the next available integer value in id .


Add DEFAULT using ALTER TABLE :

ALTER TABLE users

ALTER COLUMN is_active SET DEFAULT TRUE;


Summary Table

Constraint Purpose

UNIQUE Prevents duplicate values


5. PRIMARY KEY Constraint
NOT NULL Ensures value is not NULL
Uniquely identifies each row. Must be NOT NULL and UNIQUE.
CHECK Restricts values using a condition

Example: DEFAULT Sets a default value

PRIMARY KEY Uniquely identifies each row


CREATE TABLE users (
id INT PRIMARY KEY,
AUTO_INCREMENT Automatically generates unique numbers
name VARCHAR(100)

);

Add later with ALTER TABLE :

ALTER TABLE users


ADD PRIMARY KEY (id);

6. AUTO_INCREMENT

Used with PRIMARY KEY to automatically assign the next number.


SUM()

Calculate total salary payout:

SQL Functions (MySQL) SELECT SUM(salary) AS total_payroll FROM users;

SQL functions help you analyze, transform, or summarize data in your tables.

We’ll use the users table which includes:


AVG()
• id , name , email , gender , date_of_birth , salary , created_at
Find average salary:

SELECT AVG(salary) AS avg_salary FROM users;

1. Aggregate Functions
These return a single value from a set of rows.

Grouping with GROUP BY


COUNT()
Average salary by gender:
Count total number of users:

SELECT gender, AVG(salary) AS avg_salary


SELECT COUNT(*) FROM users; FROM users

GROUP BY gender;

Count users who are Female:

SELECT COUNT(*) FROM users WHERE gender = 'Female';

2. String Functions

LENGTH()
MIN() and MAX()
Length of user names:
Get the minimum and maximum salary:

SELECT name, LENGTH(name) AS name_length FROM users;


SELECT MIN(salary) AS min_salary, MAX(salary) AS max_salary FROM users;
LOWER() and UPPER() DATEDIFF()

Convert names to lowercase or uppercase: Find number of days between today and birthdate:

SELECT name, LOWER(name) AS lowercase_name FROM users; SELECT name, DATEDIFF(CURDATE(), date_of_birth) AS days_lived FROM users;

SELECT name, UPPER(name) AS uppercase_name FROM users;

TIMESTAMPDIFF()
CONCAT()
Calculate age in years:
Combine name and email:
SELECT name, TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS age FROM users;

SELECT CONCAT(name, ' <', email, '>') AS user_contact FROM users;

4. Mathematical Functions
3. Date Functions
ROUND() , FLOOR() , CEIL()
NOW()
SELECT salary,
Current date and time: ROUND(salary) AS rounded,

FLOOR(salary) AS floored,

SELECT NOW(); CEIL(salary) AS ceiled

FROM users;

YEAR() , MONTH() , DAY()


MOD()
Extract parts of date_of_birth :
Find even or odd user IDs:
SELECT name, YEAR(date_of_birth) AS birth_year FROM users;

SELECT id, MOD(id, 2) AS remainder FROM users;


5. Conditional Functions

IF()
MySQL Transactions and AutoCommit
SELECT name, gender,
IF(gender = 'Female', 'Yes', 'No') AS is_female By default, MySQL operates in AutoCommit mode. This means that every SQL
FROM users; statement is treated as a transaction and is committed automatically. However, for
more control over when changes are saved, you can turn AutoCommit off and
manage transactions manually.

Summary Table
1. Disabling AutoCommit
Function Purpose
When AutoCommit is off, you can explicitly control when to commit or rollback
COUNT() Count rows changes.

SUM() Total of a column


To disable AutoCommit:
AVG() Average of values
SET autocommit = 0;
MIN() / MAX() Lowest / highest value

LENGTH() String length


This turns off AutoCommit, meaning that changes you make won’t be saved to the
CONCAT() Merge strings database unless you explicitly tell MySQL to commit them.

YEAR() / DATEDIFF() Date breakdown / age Important: Until you execute a COMMIT , your changes are not permanent.

ROUND() Rounding numbers

IF() Conditional logic


2. COMMIT — Save Changes to the Database
Once you’ve made changes and you’re confident that everything is correct, you can
use the COMMIT command to save those changes.

To commit a transaction:

COMMIT;
This saves all the changes made since the last COMMIT or ROLLBACK . After this
ROLLBACK;
point, the changes become permanent.

3. ROLLBACK — Revert Changes to the Last Safe Point 4. Enabling AutoCommit Again
If you make an error or decide you don’t want to save your changes, you can
If you want to turn AutoCommit back on (so that every statement is automatically
rollback the transaction to its previous state.
committed), you can do so with:

To rollback a transaction: SET autocommit = 1;

ROLLBACK;

This undoes all changes since the last COMMIT or ROLLBACK .


Best Practices

• Use COMMIT when you want to make changes permanent.


Example Workflow • Use ROLLBACK to discard changes if something goes wrong.

Here’s a simple example of using COMMIT and ROLLBACK in a transaction: • Consider disabling AutoCommit when performing complex updates to avoid
saving partial or incorrect data.
1. Turn off AutoCommit:

SET autocommit = 0;

2. Make some changes (e.g., updating a salary):

UPDATE users SET salary = 80000 WHERE id = 5;

3. Decide whether to commit or rollback:

1. If you’re happy with the changes, run:

COMMIT;

2. If you’re not happy and want to revert the changes, run:


Feature PRIMARY KEY UNIQUE

Must be
Yes Yes
unique
Understanding PRIMARY KEY in MySQL
Allows NULL Yes (one or more NULLs
No
A PRIMARY KEY is a constraint in SQL that uniquely identifies each row in a table. values allowed)

It is one of the most important concepts in database design. How many


Only one per table Can have multiple
allowed

Required by Recommended, often


Optional
What is a Primary Key? table required

Dropping Cannot be easily dropped Can be dropped anytime


• A PRIMARY KEY :

• Must be unique
• Cannot be NULL
• Is used to identify rows in a table Example with UNIQUE
• Can be a single column or a combination of columns
CREATE TABLE users (
• Each table can have only one primary key
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
Example: name VARCHAR(100)
);
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) In this example:


);
• id is the unique identifier for each row.
• email must be unique, but is not the primary key.

How Is PRIMARY KEY Different from UNIQUE ?


Can I Drop a PRIMARY KEY?
At first glance,
PRIMARY KEY and UNIQUE might seem similar since both prevent
duplicate values. But there are important differences: Yes, but it is more restricted than dropping a UNIQUE constraint.

ALTER TABLE users DROP PRIMARY KEY;


This may fail if the primary key is being used elsewhere (like in a foreign key
or auto_increment column).

To drop a UNIQUE constraint:


Foreign Keys in MySQL
ALTER TABLE users DROP INDEX email;
A foreign key is a column that creates a link between two tables. It ensures that
the value in one table must match a value in another table.

Auto Increment This is used to maintain data integrity between related data.

In MySQL, a
PRIMARY KEY is often used with the AUTO_INCREMENT attribute to
automatically generate unique values for new rows.
Why Use Foreign Keys?
CREATE TABLE users ( Imagine this scenario:
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) You have a users table. Now you want to store each user’s address. Instead of
); putting address columns inside the users table, you create a separate
addresses table, and link it to users using a foreign key.

This means that every time you insert a new row, MySQL will automatically assign a
unique value to the id column. You can change the starting value of
AUTO_INCREMENT using:
Creating a Table with a Foreign Key
ALTER TABLE users AUTO_INCREMENT = 1000;
Let’s create an addresses table where each address belongs to a user.

CREATE TABLE addresses (

id INT AUTO_INCREMENT PRIMARY KEY,

Key Takeaways user_id INT,

street VARCHAR(255),

• Use PRIMARY KEY for the main identifier of a row. city VARCHAR(100),

state VARCHAR(100),
• Use UNIQUE for enforcing non-duplicate values in other columns (like email
pincode VARCHAR(10),
or phone).
FOREIGN KEY (user_id) REFERENCES users(id)
• You can have only one primary key, but you can have many unique );
constraints.
Explanation: Adding ON DELETE Action
• user_id is a foreign key.
By default, if you delete a user that has related addresses, MySQL will throw an
• It references the error. You can control this behavior with ON DELETE .
id column in the table.
users
• This ensures that every address must be linked to a valid user.
Example with ON DELETE CASCADE :

If you want addresses to be automatically deleted when the user is deleted:


Dropping a Foreign Key
CREATE TABLE addresses (
To drop a foreign key, you need to know its constraint name. MySQL auto- id INT AUTO_INCREMENT PRIMARY KEY,
generates it if you don’t specify one, or you can name it yourself: user_id INT,

street VARCHAR(255),

CREATE TABLE addresses ( city VARCHAR(100),

id INT AUTO_INCREMENT PRIMARY KEY, state VARCHAR(100),

user_id INT, pincode VARCHAR(10),

CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

); );

To drop it: Or alter it later:

ALTER TABLE addresses ALTER TABLE addresses

DROP FOREIGN KEY fk_user; ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE
CASCADE;

Adding a Foreign Key Later (Using ALTER)


Other ON DELETE Options
Suppose the foreign key was not defined during table creation. You can add it
later using ALTER TABLE : ON DELETE
Behavior
Option

ALTER TABLE addresses CASCADE Deletes all related rows in child table
ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id);
SET NULL Sets the foreign key to NULL in the child table

RESTRICT Prevents deletion of parent if child exists (default)


Summary
• Foreign keys connect tables and enforce valid references. SQL JOINs in MySQL
• You can create them inline or with ALTER TABLE .
In SQL, JOINs are used to combine rows from two or more tables based on related
• You can drop them by name.
columns — usually a foreign key in one table referencing a primary key in another.
• Use ON DELETE to control what happens when the parent row is deleted.
We’ll use the following two tables:

users table

id name

1 Aarav

2 Sneha

3 Raj

addresses table

id user_id city

1 1 Mumbai

2 2 Kolkata

3 4 Delhi

Note: user_id is a foreign key that references users.id .

1. INNER JOIN
Returns only the matching rows from both tables.
Output:
SELECT users.name, addresses.city
FROM users name city
INNER JOIN addresses ON users.id = addresses.user_id;
Aarav Mumbai

Sneha Kolkata
Output:
Raj NULL
name city
Raj is shown even though he doesn’t have an address.
Aarav Mumbai

Sneha Kolkata
Visual Representation:
Raj is excluded because there is no matching address. Delhi is excluded
users addresses
because its user_id (4) is not in users .
| 1 | | 1 |

Visual Representation: | 2 | | 2 |
| 3 | | |

users addresses => all users + matched addresses (or NULL)

| 1 | | 1 |

| 2 | | 2 |
| | | |

=> only matching pairs


3. RIGHT JOIN
Returns all rows from the right table ( addresses ), and matching rows from the
left table ( users ). If no match is found, NULLs are returned.

2. LEFT JOIN SELECT users.name, addresses.city

FROM users
Returns all rows from the left table ( users ), and matching rows from the right
RIGHT JOIN addresses ON users.id = addresses.user_id;
table ( addresses ). If no match is found, NULLs are returned.

SELECT users.name, addresses.city Output:


FROM users

LEFT JOIN addresses ON users.id = addresses.user_id;


name city

Aarav Mumbai

Sneha Kolkata
name city

NULL Delhi

Delhi is shown even though it points to a user_id that doesn’t exist. SQL UNION and UNION ALL
Visual Representation: The UNION operator in SQL is used to combine the result sets of two or more

SELECT statements. It removes duplicates by default.


users addresses

If you want to include all rows including duplicates, use .


UNION ALL
| 1 | | 1 |

| 2 | | 2 |
| | | 4 |

=> all addresses + matched users (or NULL)


Example Scenario
You already have a users table for active users. Now, we’ll create an
admin_users table to store users who are administrators or have special roles. We

Summary Table will then combine the names from both tables using UNION .

JOIN Type Description

INNER JOIN Only matching rows from both tables Step 1: Create the admin_users Table
LEFT JOIN All rows from left table + matching from right
CREATE TABLE admin_users (
RIGHT JOIN All rows from right table + matching from left
id INT PRIMARY KEY,
name VARCHAR(100),

email VARCHAR(100),
gender ENUM('Male', 'Female', 'Other'),
date_of_birth DATE,

salary INT
);
Step 2: Insert Sample Data into admin_users SELECT name, salary FROM users
UNION

INSERT INTO admin_users (id, name, email, gender, date_of_birth, salary) VALUES SELECT name, salary FROM admin_users;

(101, 'Anil Kumar', '[email protected]', 'Male', '1985-04-12', 60000),

(102, 'Pooja Sharma', '[email protected]', 'Female', '1992-09-20', 58000),


(103, 'Rakesh Yadav', '[email protected]', 'Male', '1989-11-05', 54000),
(104, 'Fatima Begum', '[email protected]', 'Female', '1990-06-30', 62000);
Adding separate roles

SELECT name, 'User' AS role FROM users

UNION
Step 3: Use UNION to Combine Data SELECT name, 'Admin' AS role FROM admin_users;

Let’s combine the active and admin user names.

SELECT name FROM users

UNION Using Order By with UNION


SELECT name FROM admin_users;

SELECT name FROM users

This returns a single list of unique names from both tables. UNION

SELECT name FROM admin_users

ORDER BY name;

UNION ALL Example

If you want to keep duplicate names (if any), use UNION ALL .

Rules of UNION
SELECT name FROM users
UNION ALL 1. The number of columns and their data types must match in all SELECT
SELECT name FROM admin_users; statements.
2. UNION removes duplicates by default.
3. UNION ALL keeps duplicates.

Using More Than One Column

You can also select multiple columns as long as both SELECT queries return the
same number of columns with compatible types.
When to Use UNION

• When you have two similar tables (like current and archived data).
• When you need to combine filtered results (e.g., high-salary users from two Self JOIN in MySQL
sources).
• When performing cross-category reporting. A Self JOIN is a regular join, but the table is joined with itself.

This is useful when rows in the same table are related to each other. For example,
when users refer other users, and we store the ID of the person who referred them
Summary in the same users table.

Operator Behavior

UNION Combines results, removes duplicates Step 1: Add a referred_by_id Column


UNION ALL Combines results, keeps duplicates
We’ll extend the existing users table to include a column called referred_by_id ,
which holds the id of the user who referred them.

ALTER TABLE users

ADD COLUMN referred_by_id INT;

This column:

• Will be NULL for users who were not referred.


• Will contain the id of another user who referred them.

Step 2: Insert Referral Data (Optional)


Assuming id = 1 is the first user, and referred others:

UPDATE users SET referred_by_id = 1 WHERE id IN (2, 3); -- User 1 referred Users 2
and 3

UPDATE users SET referred_by_id = 2 WHERE id = 4; -- User 2 referred User 4


Step 3: Use a Self JOIN to Get Referrer Names • Use aliases like a and b to differentiate the two instances of the same table.

We want to get each user’s name along with the name of the person who referred
them.

SELECT

a.id,

a.name AS user_name,
b.name AS referred_by

FROM users a
INNER JOIN users b ON a.referred_by_id = b.id;

Explanation:
• a refers to the user being queried.
• b refers to the user who referred them.
• LEFT JOIN is used so that users with NULL in referred_by_id are also
included.

Sample Output:

id user_name referred_by

1 Aarav NULL

2 Sneha Aarav

3 Raj Aarav

4 Fatima Sneha

Summary
• Use Self JOIN when you need to join a table with itself.
• In referral-based relationships, store the referrer’s id in the same table.
Demonstrating That a View is Always Up-To-Date
Let’s see what happens when the underlying data changes.

MySQL Views
Step 1: View before update
A view in MySQL is a virtual table based on the result of a SELECT query. It does
SELECT * FROM high_salary_users;
not store data itself — it always reflects the current data in the base tables.

Views are useful when: Output:

• You want to simplify complex queries


id name salary
• You want to reuse logic
• You want to hide certain columns from users 2 Sneha 75000

• You want a “live snapshot” of filtered data 5 Fatima 80000

Step 2: Update a user’s salary


Creating a View
UPDATE users

Suppose we want a view that lists all users earning more than ₹70,000. SET salary = 72000
WHERE name = 'Raj';

CREATE VIEW high_salary_users AS

SELECT id, name, salary

FROM users
Step 3: Query the view again
WHERE salary > 70000;
SELECT * FROM high_salary_users;

New Output:

Querying the View id name salary

2 Sneha 75000
SELECT * FROM high_salary_users;

5 Fatima 80000

This will return all users from the users table where salary is above ₹70,000. 3 Raj 72000

Notice how Raj is now included in the view — without updating the view
itself. That’s because views always reflect live data from the original table.
Dropping a View
To remove a view: MySQL Indexes
DROP VIEW high_salary_users; Indexes in MySQL are used to speed up data retrieval. They work like the index of
a book — helping the database engine find rows faster, especially for searches,
filters, and joins.

Summary
Viewing Indexes on a Table
• Views act like saved SELECT queries
• Views are not duplicated data To see the indexes on a table, use:
• Changes to base tables are reflected automatically
SHOW INDEXES FROM users;
• Great for simplifying complex queries or creating filtered access

This shows all the indexes currently defined on the users table, including the
automatically created primary key index.

Creating a Single-Column Index

Suppose you’re frequently searching users by their email . You can speed this up

by indexing the email column.

CREATE INDEX idx_email ON users(email);

What this does:


• Creates an index named idx_email
• Improves performance of queries like:

SELECT * FROM users WHERE email = '[email protected]';


• But this may not use the index effectively:

Important Notes WHERE salary > 70000

• Indexes consume extra disk space


• Indexes slow down Because the first column in the index ( gender ) is missing in the filter.
INSERT , UPDATE , and DELETE operations slightly
(because the index must be updated)
• Use indexes only when needed (i.e., for columns used in WHERE , JOIN ,
ORDER BY ) Dropping an Index
To delete an index:

Creating a Multi-Column Index DROP INDEX idx_email ON users;

If you often query users using both gender and salary , a multi-column index is
more efficient than separate indexes.

CREATE INDEX idx_gender_salary ON users(gender, salary);


Summary

Feature Description

Usage Example: SHOW INDEXES View current indexes on a table

SELECT * FROM users CREATE INDEX Create single or multi-column indexes


WHERE gender = 'Female' AND salary > 70000;
DROP INDEX Remove an index

This query can take advantage of the combined index on gender and salary . Use when Query performance on large tables is a concern

Avoid on Columns that are rarely queried or always unique

Index Order Matters


For a multi-column index on (gender, salary) :

• This works efficiently:

WHERE gender = 'Female' AND salary > 70000


• The outer query selects all users with a salary greater than that average.

Subqueries in MySQL Subquery with IN


A subquery is a query nested inside another query. Subqueries are useful for Now let’s say we want to find users who have been referred by someone who earns
breaking down complex problems into smaller parts. more than ₹75,000.

They can be used in:


SELECT id, name, referred_by_id
• SELECT statements FROM users

• WHERE clauses WHERE referred_by_id IN (


SELECT id FROM users WHERE salary > 75000
• FROM clauses
);

Explanation:
Example Scenario: Salary Comparison
• The inner query: SELECT id FROM users WHERE salary > 75000 returns a list
Suppose we want to find all users who earn more than the average salary of all of user IDs (referrers) who earn more than ₹75,000.
users. • The outer query selects users whose referred_by_id is in that list.

Scalar Subquery Example


Other Places Subqueries Are Used
This subquery returns a single value — the average salary — and we compare each
You can also use subqueries:
user’s salary against it.
• Inside SELECT columns (called scalar subqueries)
SELECT id, name, salary
• In the FROM clause to create derived tables
FROM users

WHERE salary > (


Example in :
SELECT AVG(salary) FROM users SELECT
);
SELECT name, salary,

(SELECT AVG(salary) FROM users) AS average_salary

FROM users;
Explanation:
• The inner query: SELECT AVG(salary) FROM users returns the average salary.
This shows each user’s salary along with the overall average.
Summary

Subquery Type Use Case GROUP BY and HAVING in MySQL


Scalar Subquery Returns one value (e.g. AVG, MAX) The GROUP BY clause is used to group rows that have the same values in

Subquery with IN Returns multiple values specified columns. It is typically used with aggregate functions like COUNT , SUM ,
AVG , MIN , or MAX .
Subquery in SELECT Shows related calculated value
The HAVING clause is used to filter groups after aggregation — similar to how
Subquery in FROM Acts as a virtual table
WHERE filters individual rows.

Subqueries are powerful tools when filtering based on computed or dynamic


conditions.

Example Table: users

Assume this is your users table:

id name gender salary referred_by_id

1 Aarav Male 80000 NULL

2 Sneha Female 75000 1

3 Raj Male 72000 1

4 Fatima Female 85000 2

5 Priya Female 70000 NULL

GROUP BY Example: Average Salary by Gender

SELECT gender, AVG(salary) AS average_salary

FROM users

GROUP BY gender;
Explanation: Why not WHERE ?
• This groups users by gender. • WHERE is used before grouping.
• Then calculates the average salary for each group. • HAVING is used after groups are formed — it’s the only way to filter

aggregated values.

GROUP BY with COUNT


Find how many users were referred by each user:
Another Example: Groups with More Than 1 Referral

SELECT referred_by_id, COUNT(*) AS total_referred


SELECT referred_by_id, COUNT(*) AS total_referred
FROM users
FROM users
WHERE referred_by_id IS NOT NULL
WHERE referred_by_id IS NOT NULL
GROUP BY referred_by_id
GROUP BY referred_by_id;
HAVING COUNT(*) > 1;

Output:

referred_by_id total_referred
Summary
1 2

2 1 Can use
Clause Purpose
aggregates?

WHERE Filters rows before grouping No

HAVING Clause: Filtering Groups GROUP


Groups rows based on column values N/A
BY
Let’s say we only want to show genders where the average salary is greater than
HAVING Filters groups after aggregation Yes
₹75,000.

Use
SELECT gender, AVG(salary) AS avg_salary GROUP BY to organize data, and HAVING to filter those groups based on
FROM users aggregate conditions.
GROUP BY gender
HAVING AVG(salary) > 75000;

ROLLUP
To get subtotals and grand totals, you can use ROLLUP :
SELECT gender, COUNT(*) AS total_users
FROM users

GROUP BY gender WITH ROLLUP;

Stored Procedures in MySQL


Explanation: A stored procedure is a saved SQL block that can be executed later. It’s useful
when you want to encapsulate logic that can be reused multiple times — like
• This will give you a count of users by gender, along with a grand total for all
queries, updates, or conditional operations.
users.

Why Change the Delimiter?


By default, MySQL uses ; to end SQL statements.

But when defining stored procedures, we use ; inside the procedure as well. This
can confuse MySQL. To avoid this, we temporarily change the delimiter (e.g. to
$$ or // ) while creating the procedure.

Syntax for Creating a Stored Procedure

DELIMITER $$

CREATE PROCEDURE procedure_name()


BEGIN

-- SQL statements go here


END$$

DELIMITER ;

After the procedure is created, we reset the delimiter back to .


;
Creating a Procedure with Input Parameters Notes
Let’s say you want to create a stored procedure that inserts a new user into the • Input parameters are declared using the IN keyword.
users table. • Stored procedures are stored in the database and can be reused.

Example:

DELIMITER $$ Viewing Stored Procedures

CREATE PROCEDURE AddUser(


SHOW PROCEDURE STATUS WHERE Db = 'startersql';
IN p_name VARCHAR(100),

IN p_email VARCHAR(100),
IN p_gender ENUM('Male', 'Female', 'Other'),

IN p_dob DATE,

IN p_salary INT
Dropping a Stored Procedure
)

BEGIN
INSERT INTO users (name, email, gender, date_of_birth, salary) DROP PROCEDURE IF EXISTS AddUser;

VALUES (p_name, p_email, p_gender, p_dob, p_salary);

END$$

DELIMITER ;
Summary
This creates a procedure named AddUser that accepts five input parameters.
Command Purpose

DELIMITER $$ Temporarily change statement delimiter

CREATE PROCEDURE Defines a new stored procedure


Calling the Procedure
CALL procedure_name(...) Executes a stored procedure
You can call the procedure using:
DROP PROCEDURE Removes an existing procedure

CALL AddUser('Kiran Sharma', '[email protected]', 'Female', '1994-06-15', 72000);

This will insert the new user into the users table.
Step 1: Create the Log Table
Triggers in MySQL CREATE TABLE user_log (

id INT AUTO_INCREMENT PRIMARY KEY,


A trigger is a special kind of stored program that is automatically executed
user_id INT,
(triggered) when a specific event occurs in a table — such as INSERT , UPDATE , or
name VARCHAR(100),
DELETE . created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);
Triggers are commonly used for:

• Logging changes
• Enforcing additional business rules
• Automatically updating related data Step 2: Create the Trigger
We now define a trigger that runs after a new user is added.

Basic Trigger Structure DELIMITER $$

CREATE TRIGGER trigger_name CREATE TRIGGER after_user_insert

AFTER INSERT ON table_name AFTER INSERT ON users

FOR EACH ROW FOR EACH ROW

BEGIN BEGIN

-- statements to execute INSERT INTO user_log (user_id, name)

END; VALUES (NEW.id, NEW.name);

END$$

Triggers can be fired: DELIMITER ;

• BEFORE or AFTER an event


• On INSERT , UPDATE , or DELETE
Explanation:
• AFTER INSERT means the trigger fires after the user is inserted.


NEW refers to the new row being added to the table.
Scenario: Log Every New User Insertion users
• We insert the new user’s ID and name into the table.
user_log
Suppose we want to log every time a new user is inserted into the users table.
We’ll create a separate table called user_log to store log entries.
Step 3: Test the Trigger

CALL AddUser('Ritika Jain', '[email protected]', 'Female', '1996-03-12', 74000);

More on MySQL
Now check the user_log table:
This section covers some essential MySQL features and operators that help you
write more powerful and flexible queries.
SELECT * FROM user_log;

You should see Ritika’s info automatically logged.


1. Logical Operators
Logical operators are used to combine multiple conditions in a WHERE clause.
Dropping a Trigger
Operator Description Example
If you need to remove a trigger:
salary > 50000 AND gender =
AND All conditions must be true
'Male'
DROP TRIGGER IF EXISTS after_user_insert;

At least one condition is gender = 'Male' OR gender =


OR
true 'Other'

NOT Reverses a condition NOT gender = 'Female'


Summary

Trigger Component Description

BEFORE / AFTER When the trigger runs 2. Add a Column to an Existing Table
INSERT / UPDATE / Use ALTER TABLE to add a column:
What kind of action triggers it
DELETE

ALTER TABLE users


NEW.column Refers to the new row (for INSERT , UPDATE )
ADD COLUMN city VARCHAR(100);

OLD.column Refers to the old row (for UPDATE , DELETE )

FOR EACH ROW Executes for each affected row This adds a new column named city to the users table.
3. Wildcard Operators SELECT DISTINCT gender FROM users;

Wildcards are used with the LIKE operator for pattern matching in text.
Returns a list of unique gender values from the users table.
Wildcard Description Example

Matches any
% WHERE name LIKE 'A%' (starts with A)
sequence
6. TRUNCATE Keyword
Matches a single WHERE name LIKE '_a%' (second letter
_
character TRUNCATE removes all rows from a table, but keeps the table structure.
is ‘a’)

TRUNCATE TABLE users;

4. LIMIT with OFFSET • Faster than DELETE FROM users


• Cannot be rolled back (unless in a transaction-safe environment)
LIMIT is used to limit the number of rows returned. OFFSET skips a number of
rows before starting to return rows.

SELECT * FROM users


7. CHANGE vs MODIFY Column
ORDER BY id
Both
LIMIT 5 OFFSET 10; CHANGE and MODIFY are used to alter existing columns in a table, but they
work slightly differently.
This skips the first 10 rows and returns the next 5.
CHANGE: Rename and change datatype
Alternative syntax:

ALTER TABLE users


SELECT * FROM users CHANGE COLUMN city location VARCHAR(150);
ORDER BY id

LIMIT 10, 5;
This renames city to location and changes its type.

This also skips 10 and returns 5 (syntax: LIMIT offset, count ).


MODIFY: Only change datatype

ALTER TABLE users


MODIFY COLUMN salary BIGINT;
5. DISTINCT Keyword

DISTINCT is used to return only unique values. This changes only the datatype of salary .

You might also like