MySQL Database Management Overview
MySQL Database Management Overview
A database is an organized collection of data that is stored and managed in a structured way to
allow efficient access, manipulation, and management of that data.
It typically stores data in tables, rows, and columns, making it easier to retrieve, modify, and
analyze. Databases are used in various applications, ranging from business operations to
scientific research, web development, and more.
Database Management Systems (DBMS)
A Database Management System (DBMS) is software that provides an interface to interact
with the database. It handles the storage, retrieval, and updating of data, ensuring that it is done
efficiently and securely. DBMSs can be used for relational or non-relational databases and
provide features such as:
• Data Integrity: Ensures accuracy and consistency.
• The data is structured and typically follows a schema with defined relationships between
tables.
• Relational databases use Structured Query Language (SQL) for managing and querying
the data.
• They can use different data models like key-value pairs, document-based storage, graph
databases, and column-family stores.
• NoSQL databases can scale horizontally, making them well-suited for handling large
volumes of data, distributed environments, and high-velocity operations.
Data
Examples:
Introduction to SQL:
• SQL (Structured Query Language) is a standardized programming language used to
manage and manipulate relational databases.
• It allows users to create, read, update, and delete data (often referred to as CRUD
operations) within databases. SQL is widely used in various database management
systems (DBMS) like MySQL, PostgreSQL, Oracle, SQL Server, and SQLite.
What is MySQL?
MySQL is an open-source, relational database management system (RDBMS) that uses
Structured Query Language (SQL) to manage and manipulate data. It is one of the most popular
database systems used in web applications, known for its speed, reliability, and ease of use.
MySQL is commonly used in conjunction with programming languages such as PHP, Java, and
Python to build dynamic websites and applications.
Key characteristics of MySQL:
• Relational Database: Data is stored in tables with predefined relationships between them.
• Open-Source: It is free to use and has an active community contributing to its development.
• High Performance:
• MySQL is optimized for high-speed data access and is suitable for applications that
require fast query execution.
• Scalability:
• MySQL can handle large databases and supports horizontal scaling (replication) for
distributing data across multiple servers.
• Security:
• MySQL provides strong security features, including user authentication, encryption, and
data access controls.
• Indexing:
• It supports various types of indexes to optimize query performance.
• Multi-Threaded:
• MySQL uses multi-threading for handling multiple queries simultaneously, enhancing
performance in multi-user environments.
• Cross-Platform:
• It runs on different platforms such as Linux, Windows, macOS, and others.
• DML (Data Manipulation Language): Commands used to manipulate data in tables. Example:
SELECT, INSERT, UPDATE, DELETE.
• DCL (Data Control Language): Commands for controlling access to data. Example: GRANT,
REVOKE.
• TCL (Transaction Control Language): Commands used to manage transactions in the database.
Example: COMMIT, ROLLBACK.
SQL Syntax and Conventions
SQL syntax follows specific rules and conventions:
• SQL Keywords: Keywords (such as SELECT, INSERT, UPDATE) are generally written in
uppercase to make the commands more readable. However, SQL is case-insensitive, so SELECT,
select, or SeLeCt all work the same.
• Semicolon (;): The semicolon is used to terminate a SQL statement. While some databases might
automatically detect the end of a statement, it's good practice to use it explicitly.
• Strings: Text values (strings) should be enclosed in single quotes ('), e.g., 'Hello'.
Creating and Managing Databases
In SQL, you can create, modify, and delete databases. Below are the key SQL commands used
for managing databases:
CREATE DATABASE
The CREATE DATABASE command is used to create a new database.
Syntax:
CREATE DATABASE database_name;
Example:
USE company;
This will set the company database as the active database, so any queries or operations you perform will be
executed within the company database.
Additional SQL Commands for Managing Databases
DROP DATABASE
The DROP DATABASE command deletes a database and all of its data (tables, views, etc.).
Syntax:
DROP DATABASE database_name;
Example:
• VARCHAR: A variable-length string (more efficient than CHAR when data length varies).
• Example: VARCHAR(50) stores up to 50 characters, but only uses the required space.
• INT: Integer data type for whole numbers. We can also use
(Tinyint,smallint,mediumint,bigint).
• Example: INT can store values like -2147483648 to 2147483647.
• ENUM : ENUM is a string data type in MySQL that allows you to define a column with a fixed
set of allowed values.
Example :
• BOOLEAN: Used for storing true or false values (some databases may use TINYINT for
this).
• Example: BOOLEAN can store TRUE or FALSE.
• TEXT: Used for large amounts of text data (larger than VARCHAR). We can also use
(Tinytext , mediumtext,longtext).
• Example: TEXT can store long descriptions or paragraphs.
• BLOB: Used for storing binary large objects, such as images, videos, or files.
• Example: BLOB can store raw binary data.
Syntax:
CREATE TABLE table_name (
column_name1 data_type [constraints],
column_name2 data_type [constraints],
...
);
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE,
salary DECIMAL(10, 2)
);
2. DESCRIBE Table
The DESCRIBE (or EXPLAIN) command provides information about the structure of a table, such
as the column names, data types, and constraints.
Syntax:
DESCRIBE table_name;
Example:
DESCRIBE employees;
This command will return the table structure for the employees table, showing the column names, data
types, and any constraints (such as PRIMARY KEY).
Example:
INSERT INTO employees (employee_id, first_name, last_name, hire_date, salary)
VALUES (1, 'John', 'Doe', '2025-01-01', 55000.00);
This inserts a new row into the employees table with values for the columns employee_id, first_name,
last_name, hire_date, and salary.
Alternatively, if you're inserting into all columns (in the same order as defined), you can omit the
column names:
INSERT INTO employees
VALUES (2, 'Jane', 'Smith', '2025-02-01', 60000.00);
This will retrieve the first_name, last_name, and salary columns from the employees table.
Possible Mistakes
Mistake 1
The number of values that we're inserting must match with the number of column names that are
specified in the query.
Mistake 2
SQL
1
Error: nosuchtable: players_information
Mistake 3
While inserting data, be careful with the datatypes of the input values. Input value datatype
should be same as the column datatype.
• condition: The condition that the data must meet to be included in the result.
Example 1: Select records based on a condition
SELECT *
FROM employees
WHERE department = 'Sales';
This will return only the rows where the salary is greater than 55000.
Update Clause:
The UPDATE clause in SQL is used to modify existing records in a table. You can use it to update
one or more columns in the records that meet a specific condition defined by the WHERE clause.
If you don't use a WHERE clause, all the records in the table will be updated.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• table_name: The name of the table where you want to update data.
• value1, value2, ...: The new values for the respective columns.
• WHERE condition: Specifies the condition that must be met for the rows to be updated. Without
the WHERE clause, all rows in the table will be updated.
Example 1: Simple Update
UPDATE employees
SET salary = 60000
WHERE employee_id = 101;
This query updates the salary of the employee with employee_id 101 to 60,000.
Example 2: Updating Multiple Columns
UPDATE employees
SET salary = 70000, department = 'Marketing'
WHERE employee_id = 102;
This query updates both the salary and department of the employee with employee_id 102.
Example 3: Update Based on Multiple Conditions
UPDATE employees
SET salary = 80000
WHERE department = 'Sales' AND hire_date > '2020-01-01';
This query updates the salary of employees in the "Sales" department who were hired after
January 1, 2020.
This query will set the department to 'HR' for every record in the employees table (since no WHERE
condition is provided).
This query updates the department of the employee with employee_id 101 to the value retrieved
from the departments table based on the department_id of 1.
Example 6: Update with Arithmetic Operations
You can perform arithmetic operations in the SET clause to update values.
UPDATE employees
SET salary = salary + 5000
WHERE department = 'Sales';
This query increases the salary by 5,000 for all employees in the "Sales" department.
Important Notes:
• Always use a WHERE clause unless you intend to update every row in the table.
• If you forget the WHERE clause, all rows will be updated, which can cause data loss or
unintended changes.
Rollback Cannot be
Can be Rollback Cannot be Rollback
Support Rollback
Removes table
Data Removes selected
and data Removes all rows
Removal rows
completely
Slower, as each row is Instant removal, Faster than DELETE
Efficiency
processed individually affecting schema but slower than DROP
Does not fire
Triggers Fires triggers Does not fire triggers
triggers
Delete Clause:
The DELETE clause in SQL is used to remove records from a table. You can delete specific rows
that meet certain conditions using the WHERE clause, or delete all rows from the table if no
WHERE condition is provided.
Syntax:
• table_name: The name of the table from which you want to delete records.
• condition: A condition that specifies which records to delete. If you omit the WHERE clause, all
records in the table will be deleted.
Important Notes:
• WHERE Clause: If you use the WHERE clause, only the rows that meet the specified condition
will be deleted.
• Without WHERE Clause: If you omit the WHERE clause, all rows in the table will be deleted.
However, the table structure remains intact (i.e., the table itself is not deleted).
• Cannot Undo: The DELETE operation is permanent, so be careful when executing it. Once the
data is deleted, it's gone unless you have a backup or transaction to roll back.
Example 1: Delete Specific Record
DELETE FROM employees
WHERE employee_id = 101;
This query deletes the record of the employee with employee_id 101 from the employees table.
Example 2: Delete Multiple Records
This query deletes all records of employees who belong to the "Sales" department.
Example 3: Delete All Records (Without WHERE Clause)
This query deletes all records from the employees table, but the table structure (columns, indexes,
etc.) remains intact. Be cautious, as this action is irreversible unless you have a backup.
Example 4: Delete Using a Subquery
You can use a subquery to delete records based on data from another table.
DELETE FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE department_name =
'Marketing');
This query deletes all employees who are part of the "Marketing" department by using a subquery to find
the matching department_id.
Truncate Command
the TRUNCATE command is used to delete all rows from a table quickly. Unlike the DELETE command,
TRUNCATE does not generate individual row deletions; instead, it removes all data in the table by
deallocating the data pages associated with the table. It is a fast and efficient way to clear out all data
from a table, but with some important differences compared to DELETE.
Syntax:
TRUNCATE TABLE table_name;
• table_name: The name of the table from which you want to remove all rows.
Key Characteristics of TRUNCATE:
• Faster than DELETE: Since TRUNCATE does not log individual row deletions, it is
generally faster than DELETE when clearing large tables.
• Resets AUTO_INCREMENT: In MySQL, TRUNCATE resets the AUTO_INCREMENT
counter for the table, meaning that any new rows inserted will start with the first auto-
increment value (e.g., 1).
• Cannot Be Rolled Back (in some cases): In MySQL, TRUNCATE is treated like a DDL
(Data Definition Language) operation, not a DML (Data Manipulation Language)
operation. This means that in certain scenarios (like when not wrapped in a transaction),
you cannot roll back the action. However, if you use TRUNCATE inside a transaction in
InnoDB (and the transaction hasn't been committed), it can be rolled back.
• Does Not Fire Triggers: Unlike DELETE, which might trigger BEFORE DELETE and
AFTER DELETE triggers (if they are defined), TRUNCATE does not fire triggers in MySQL.
• Table Structure Remains: Unlike DROP, which removes the table entirely, TRUNCATE
only removes the data. The structure of the table, including columns, constraints, and
indexes, remains unchanged.
• No WHERE Clause: TRUNCATE removes all rows from the table. You cannot specify a
condition or filter like you can with DELETE. If you need to delete specific rows, use
DELETE with a WHERE clause.
Example 1: Basic TRUNCATE Usage
TRUNCATE TABLE employees;
This query will remove all rows from the employees table, but the table structure will remain
intact, and any auto-increment counter will be reset.
DROP COMMAND
he DROP command is used to remove database objects like tables, databases, or indexes
permanently. When you use the DROP command, the object (such as a table) and all its data are
completely removed, and this action cannot be undone unless you have a backup.
Common Uses of the DROP Command
• DROP TABLE: Removes a table and all its data, indexes, and associated constraints.
• DROP DATABASE: Removes a database and all the tables contained in it.
This query will completely remove the employees table from the database, including all rows,
structure (columns), constraints, and indexes.
• DROP DATABASE
ALTER STATEMENT:
the ALTER statement is used to modify the structure of an existing database object, such as a
table. It allows you to add, delete, or modify columns, change a table’s name, or even rename or
modify constraints like indexes or primary keys.
Syntax:
• operation: The type of modification you want to make (e.g., adding, deleting, or modifying
columns).
Common Operations with ALTER TABLE
• Add a New Column
• Drop a Column
This query adds a new column called email of type VARCHAR(255) to the employees table.
2. Modify an Existing Column
You can change the properties of an existing column, such as its data type or default value, using
the MODIFY COLUMN clause.
Syntax:
Example:
ALTER TABLE employees
MODIFY COLUMN salary DECIMAL(10, 2);
3. Rename a Column or Table
You can rename a column or a table using the RENAME COLUMN or RENAME TO clause.
Rename a Column:
This query renames the email column to email_address in the employees table.
Rename a Table:
Example:
ALTER TABLE employees
DROP COLUMN email_address;
This query deletes the email_address column from the employees table.
Like operators
The LIKE operator in MySQL is a powerful tool used in WHERE clauses to search
for patterns within strings. Here's a breakdown of its key features:
Purpose:
• It enables you to perform pattern matching, allowing you to find data that
resembles a specific format rather than requiring an exact match.
• This is particularly useful when you need to search for:
• Names starting with a certain letter.
• Words containing a specific substring.
• Data that adheres to a particular structure.
Wildcards:
The LIKE operator works in conjunction with wildcard characters:
• % (Percent sign):
• Represents zero or more characters.
• Example: LIKE 'a%' matches any string that starts with "a". LIKE '%xyz%'
matches any string that contains "xyz".
• _ (Underscore):
• Represents a single character.
• Example: LIKE 'a_c' matches strings like "abc", "adc", etc.
Syntax:
The basic syntax is:
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
Examples:
• Search for names starting with "J":
SELECT * FROM employees
WHERE name LIKE 'J%';
This will return all records where the name ends with "n", like "John", "Brian", etc.
• Search for names containing "an":
SELECT * FROM employees
WHERE name LIKE '%an%';
This will return all records where the name contains "an", like "James", "Amanda", etc.
• Search for names with exactly 4 characters and starting with "J":
SELECT * FROM employees
WHERE name LIKE 'J___';
This will return names that start with "J" and have exactly 3 more characters, like "John",
"Jack", etc.
• Search for names with "a" in the second position:
SELECT * FROM employees
WHERE name LIKE '_a%';
• This will return records where the second letter of the name is "a", like "James", "Carlos",
etc.
Combining % and _:
You can combine both wildcards to create more complex patterns.
• Match names starting with "J" and having exactly 4 characters:
SELECT * FROM employees
WHERE name LIKE 'J__%';
This will match names like "John", "Jack", "Joe", etc., starting with "J" and having at
least 3 characters.
Examples of wildcard combinations:
• Match names with exactly 3 characters, with "a" as the second character:
SELECT * FROM employees
WHERE name LIKE '_a_';
This will match names like "Jay", "Max", etc., where the second character is "a" and the
name is 3 characters long.
Important Notes:
• By default, the LIKE operator is case-insensitive in MySQL, but this
behavior may vary depending on the collation of the column or database. To
perform case-sensitive searches, you can use the BINARY keyword:
SELECT * FROM employees
WHERE BINARY name LIKE 'J%';
This will match names starting with a capital "J" but not lowercase "j".
• Wildcards only work with the LIKE operator. If you need more advanced
pattern matching (like regular expressions), you can use the REGEXP operator
in MySQL.
Summary:
• % matches zero or more characters.
These wildcards, combined with the LIKE operator, provide powerful pattern
matching capabilities in MySQL queries.
Constraints in SQL.
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data entered ,
then the data is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table
level
This enforces a field to always contain a value, which means that you cannot insert a new record, or
update a record without adding a value to this field.
CREATE TABLE users (
);
UNIQUE CONSTRAINTS:
The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and
PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE [Link], you can have many
UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
);
Primary keys must contain UNIQUE values, and cannot contain NULL values.
name VARCHAR(100)
);
The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CHECK CONSTARINTS:
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column which
will satisfy a specified condition.
);
DEFAULT CONSTARINTS:
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
id INT,
);
Here’s a detailed overview of String functions, Date and Time functions, Numeric functions,
Control flow functions, Mathematical operators, and Regular expressions in MySQL
queries:
1. String Functions in MySQL
• CONCAT(): Concatenates two or more strings.
SELECT CONCAT('Hello', ' ', 'World');
-- Output: Hello World
• LENGTH(): Returns the length of a string (in bytes).
SELECT LENGTH('Hello');
-- Output: 5
• SUBSTRING(): Extracts a portion of a string.
SELECT SUBSTRING('Hello World', 7, 5);
-- Output: World
• UPPER(): Converts a string to uppercase.
UPDATE custom
SET name = UPPER(name);
SELECT UPPER('hello');
-- Output: HELLO
• LOWER(): Converts a string to lowercase.
SELECT LOWER('HELLO');
-- Output: hello
• TRIM(): Removes leading and trailing spaces from a string.
SELECT TRIM(' Hello ');
-- Output: Hello
• REPLACE(): Replaces all occurrences of a substring within a string.
SELECT REPLACE('Hello World', 'World', 'Everyone');
-- Output: Hello Everyone
• LEFT(): Returns the left part of a string with a specified number of characters.
SELECT LEFT('Hello', 3);
-- Output: Hel
• RIGHT(): Returns the right part of a string with a specified number of characters.
SELECT RIGHT('Hello', 3);
-- Output: llo
2. Date and Time Functions in MySQL
• NOW(): Returns the current date and time.
SELECT NOW();
-- Output: 2025-03-05 [Link]
• CURDATE(): Returns the current date.
SELECT CURDATE();
-- Output: 2025-03-05
• CURTIME(): Returns the current time.
SELECT CURTIME();
-- Output: [Link]
• DATE_FORMAT(): Formats a date value according to a specified format.
SELECT DATE_FORMAT('2025-03-05', '%M %d, %Y');
-- Output: March 05, 2025
• DATE_ADD(): Adds a time interval to a date.
SELECT DATE_ADD('2025-03-05', INTERVAL 7 DAY);
-- Output: 2025-03-12
• DATE_SUB(): Subtracts a time interval from a date.
SELECT DATE_SUB('2025-03-05', INTERVAL 7 DAY);
-- Output: 2025-02-26
• YEAR(), MONTH(), DAY(): Extracts the year, month, or day from a date.
SELECT YEAR('2025-03-05');
-- Output: 2025
• DATEDIFF(): Returns the difference in days between two dates.
SELECT DATEDIFF('2025-03-12', '2025-03-05');
-- Output: 7
3. Numeric Functions in MySQL
• ROUND(): Rounds a number to a specified number of decimal places.
SELECT ROUND(123.4567, 2);
-- Output: 123.46
• FLOOR(): Returns the largest integer value less than or equal to a number.
SELECT FLOOR(123.456);
-- Output: 123
• CEIL() or CEILING(): Returns the smallest integer value greater than or equal to a
number.
SELECT CEIL(123.456);
-- Output: 124
• ABS(): Returns the absolute value of a number.
SELECT ABS(-123.45);
-- Output: 123.45
• MOD(): Returns the remainder of a number divided by another number.
SELECT MOD(10, 3);
-- Output: 1
5. Mathematical Operators and Expressions
• +, -, *, /: Standard mathematical operators for addition, subtraction, multiplication, and
division.
SELECT 5 + 3, 10 - 2, 4 * 2, 8 / 2;
-- Output: 8, 8, 8, 4
• MOD(): Returns the remainder of a division (modulo operator).
SELECT MOD(10, 3);
-- Output: 1
• POWER(): Returns the value of a number raised to a power.
SELECT POWER(2, 3);
-- Output: 8
• SQRT(): Returns the square root of a number.
SELECT SQRT(9);
-- Output: 3
• LOG(): Returns the natural logarithm of a number.
SELECT LOG(100);
-- Output: 4.605170
AGGREGATION FUNCTIONS
In MySQL, aggregation refers to the process of combining multiple rows of data into a single
result based on some criteria. This is typically done using aggregate functions in combination
with the GROUP BY clause. Common aggregate functions include:
• COUNT(): Counts the number of rows or non-NULL values.
• SUM(): Sums the values of a column.
• AVG(): Calculates the average of a numeric column.
• MIN(): Returns the minimum value from a column.
• MAX(): Returns the maximum value from a column.
Basic Syntax of Aggregation
Here’s a basic structure of using aggregate functions:
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
Example Queries:
1. COUNT()
To count the number of rows in a table:
SELECT COUNT(*) FROM employees;
To count the number of employees in each department:
SELECT department_id, COUNT(*) AS num_employees
FROM employees
GROUP BY department_id;
2. SUM()
To calculate the total salary of all employees:
SELECT SUM(salary) FROM employees;
To calculate the total salary for each department:
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;
3. AVG()
To calculate the average salary of employees:
SELECT AVG(salary) FROM employees;
To calculate the average salary per department:
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;
5. HAVING Clause
You can also use the HAVING clause to filter results after aggregation. The WHERE clause
filters rows before aggregation, while HAVING filters after aggregation.
For example, to find departments with a total salary greater than $100,000:
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
HAVING SUM(salary) > 100000;
Combining Aggregate Functions
You can combine multiple aggregate functions in a single query:
SELECT department_id,
COUNT(*) AS num_employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees
GROUP BY department_id;
In SQL, GROUP BY and HAVING are often used together to aggregate data and filter it based
on certain conditions. Let me break down each of them for you:
GROUP BY
• Purpose: The GROUP BY clause is used to group rows that have the same values in
specified columns into summary rows, like "total" or "average". It is often used in
combination with aggregate functions (e.g., COUNT(), SUM(), AVG(), MAX(), MIN()).
• How it works: When you use GROUP BY, SQL will organize the data into groups based
on the column(s) you specify. Each group can then be summarized using aggregate
functions.
Example of GROUP BY:
SELECT dept, SUM(salary)
FROM employees
GROUP BY dept;
This will give you the total salary for each department.
HAVING
• Purpose: The HAVING clause is used to filter groups that are created by the GROUP BY
clause. It is similar to the WHERE clause, but WHERE filters rows before grouping,
while HAVING filters groups after aggregation.
• How it works: You can use HAVING to apply conditions to aggregated data (like the
result of SUM, AVG, etc.).
Example of HAVING:
SELECT dept, SUM(salary)
FROM employees
GROUP BY dept
HAVING SUM(salary) > 30000;
This will give you the total salary for each department, but only for departments where the total
salary is greater than 30,000.
Key Points to Remember:
• GROUP BY is used to create groups of rows based on one or more columns.
• HAVING is used to filter those groups based on aggregate functions (e.g., SUM(),
AVG()), whereas WHERE is used to filter rows before grouping.
Full Example with Both GROUP BY and HAVING:
SELECT dept, COUNT(*), SUM(salary)
FROM employees
GROUP BY dept
HAVING SUM(salary) > 50000;
This will count the number of employees and calculate the total salary for each department. It
will only return departments where the total salary exceeds 50,000.
• Explanation: This query first filters employees with a salary greater than 100,000 using
the WHERE clause. Then it groups those filtered employees by department (GROUP BY
dept) and counts how many employees in each department have a salary greater than
100,000. It then filters the results to only include departments with more than one such
employee using the HAVING clause.
Example 6: Finding the department with the lowest average salary
To find the department with the lowest average salary:
SELECT dept, AVG(salary) AS average_salary
FROM employees
GROUP BY dept
ORDER BY average_salary ASC
LIMIT 1;
• Explanation: This query calculates the average salary for each department, sorts the
departments by average salary in ascending order (ORDER BY average_salary ASC),
and limits the result to the department with the lowest average salary using LIMIT 1.
Example 7: Departments with a salary greater than the total salary of all departments
combined
This query finds departments where the total salary is greater than half of the total salary of all
departments combined.
SELECT dept, SUM(salary) AS total_salary
FROM employees
GROUP BY dept
HAVING SUM(salary) > (SELECT SUM(salary) / 2 FROM employees);
3. Find departments with both the highest and lowest salaries greater than 30,000
JOINS
In MySQL, joins are used to combine rows from two or more tables based on a related column
between them. Here’s a detailed overview of the different types of joins you can use in MySQL:
1. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example:
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
INDEXES
Think of a table in MySQL like a book and its data as the content. Without an index, if you want
to find specific information, you have to read through the entire book (scan the whole table). An
index is like the index at the back of a book – it provides a shortcut, allowing MySQL to quickly
locate the rows that match your search criteria without scanning the entire table.
Why Use Indexes?
* Speed up SELECT queries: This is the primary reason. Indexes drastically reduce the time it
takes to retrieve data.
* Improve WHERE clause performance: When you filter data using WHERE clauses, indexes
help MySQL quickly identify the relevant rows.
* Optimize JOIN operations: Indexes on the join columns can significantly speed up how
MySQL combines data from multiple tables.
* Enforce UNIQUE constraints: Unique indexes ensure that all values in a column are distinct.
* Speed up ORDER BY and GROUP BY in some cases: If the index matches the sorting or
grouping order, MySQL can use the index to avoid extra sorting steps.
VIEWS
In MySQL, a view is a virtual table that is based on the result of a SELECT query. It
doesn't store data physically, but rather, it provides a way to encapsulate a query
and present it as a table. You can use views to simplify complex queries, reuse SQL
code, and encapsulate logic.
Basic Syntax to Create a View:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE VIEW active_employees AS
SELECT employee_id, first_name, last_name, hire_date
FROM employees
WHERE status = 'active';
n this example, active_employees is a view that displays the employee_id, first_name, last_name, and
hire_date of all employees who have a status of 'active'.
Querying a View:
Once the view is created, you can query it just like a regular table:
SELECT * FROM active_employees;
Altering a View:
You can modify the structure of an existing view with the CREATE OR REPLACE VIEW statement:
CREATE OR REPLACE VIEW active_employees AS
SELECT employee_id, first_name, last_name, hire_date, department
FROM employees
WHERE status = 'active';
Dropping a View:
If you no longer need a view, you can remove it using the DROP VIEW statement:
DROP VIEW active_employees;
note :-
views:-
create :-
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
display:-
SHOW FULL TABLES WHERE
Table_type = 'VIEW';
drop :-
DROP VIEW view_name;
SET OPERATIONS
In MySQL, set operators are used to combine the results of multiple queries. The most common
set operators are:
• UNION
• UNION ALL
Each set operator works with the result sets of multiple SELECT queries. Let’s go through them in
detail with examples:
1. UNION
The UNION operator combines the results of two or more SELECT statements into a
single result set. It removes duplicate rows by default.
Syntax:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Example: Assuming we have two tables, employees_2022 and employees_2023, with the
same structure:
Table: employees_2022
id name
1 Alice
2 Bob
Table: employees_2023
id name
2 Bob
3 Charlie
Query:
SELECT name FROM employees_2022
UNION
SELECT name FROM employees_2023;
Result:
name
Alice
Bob
Charlie
2. UNION ALL
The UNION ALL operator also combines the results of two or more SELECT statements
but includes all duplicates.
Syntax:
SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;
Example: Using the same tables as above:
Query:
SELECT name FROM employees_2022
UNION ALL
SELECT name FROM employees_2023;
Result:
name
Alice
Bob
Bob
Charlie
3. INTERSECT
MySQL does not support the INTERSECT operator directly. However, you can achieve
the same result using a subquery.
Example: To find names that exist in both employees_2022 and employees_2023:
Query:
SELECT name FROM employees_2022
WHERE name IN (SELECT name FROM employees_2023);
Result:
name
Bob
4. EXCEPT
MySQL does not support the EXCEPT operator directly either. You can achieve similar
functionality using a LEFT JOIN or NOT IN.
Example: To find names in employees_2022 that are not in employees_2023:
Query:
SELECT name FROM employees_2022
WHERE name NOT IN (SELECT name FROM employees_2023);
Result:
name
Alice
Summary of Set Operations
• UNION: Combines results from multiple queries and removes duplicates.
• UNION ALL: Combines results from multiple queries and includes duplicates.
• INTERSECT: Not directly supported, but can be simulated using INNER
JOIN or EXISTS.
• EXCEPT: Not directly supported, but can be simulated using LEFT JOIN or NOT IN.
SUBQUERIES
Subqueries in MySQL
• A SQL subquery is a query inside another query.
• The outer query in which the inner query is inserted is the main query.
• We can include a subquery into the SELECT, FROM, JOIN, WHERE or HAVING
clause.
• We can also use subqueries when updating the database (i.e. in INSERT, UPDATE, and
DELETE statements).
• ORDER BY command cannot be used in a subquery.
Types of Subquery
• Scalar subqueries (Single-row)
• Multiple row subqueries (Multi-row)
Scalar Subquery
• A scalar subquery is a subquery that returns a single value.
• Mostly Aggregate Functions (COUNT, MIN, MAX, SUM, AVG) used in scalar subquery.
• Scalar subquery can also be a query with expression which returns single value as
[Link] is typically used in a context where a single value is expected, such as in the
SELECT clause or a comparison operation (WHERE or HAVING Clause).
Syntax :-
Select column
from table
where column operator ( sub query);
example :-
SELECT name
FROM employee
WHERE salary <(SELECT AVG(salary) FROM employee);
Multi-row Subquery
• It is a type of subquery in SQL that returns multiple rows of data.
• Multi-row subqueries can return multiple rows that can be used as a set of values for
comparison, filtering, or other operations in the outer query.
Syntax:-
Select columns
from table
where column in/not in /any/all ( sub query);
example :-
SELECT name, department
FROM employee
WHERE department IN (SELECT department FROM employee GROUP BY
department HAVING COUNT(*) > 2 );
ANY Operator
• The ANY operator is used in combination with comparison operators to compare a value
with a set of values returned by a subquery.(Multiple-row subquery)
• It returns true if the comparison holds true for at least one value in the set.
Syntax :-
Select columns
from table
where column any ( select column from table);
example :-
SELECT *
FROM employee
WHERE salary = ANY ( SELECT salary FROM employee WHERE department = 'HR');
ALL Operator
• The ALL operator is used in combination with comparison operators to compare a value
with a set of values returned by a subquery.(Multiple-row subquery)
• It returns true if the comparison holds true for all values in the set.
SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL (Subquery);
Example :-
SELECT *
FROM employee
WHERE salary > ALL ( SELECT salary FROM employee WHERE department =
'Accounts ' );
Transaction Management
• Transaction Management in MySQL refers to controlling a set of SQL operations so that they
either complete entirely (commit) or not at all (rollback), ensuring data integrity and
consistency.
• It’s crucial for applications where multiple operations need to be treated as a single unit of work
—like bank transfers, bookings, etc.
What is Transaction?
• All modification is successful when the transaction is committed.
• All modifications are undone when the transaction is rollback.
ACID properties :-
Atomicity
• Atomicity ensures that the entire transaction is treated as a single unit of work.
• Atomicity simply means that all queries in a transaction must succeed for the transaction
to succeed.
• If one query fails, the entire transaction fails.
Consistency
• Consistency ensures that the database remains in a valid state before and after the
transaction.
Isolation
• Isolation ensures that the execution of a transaction is independent of other transactions
running concurrently.
Durability
• Durability ensures that once a transaction is committed, its effects are permanent and
survive system failures.
START TRANSACTION
• This command marks the beginning of a transaction.
• All the subsequent SQL statements/queries within the same session will be considered
part of the same transaction until it is either committed or rolled back.
SYNTAX:
START TRANSACTION;
or
BEGIN TRANSACTION;
COMMIT
• This command is used to permanently save the changes made during the current
transaction.
• Once a transaction is committed, its changes are made permanent and cannot be rolled
back
SYNTAX:-
COMMIT
ROLLBACK
• This command is used to undo the changes made during the current transaction.
• It rolls back the transaction to its starting point, discarding any modifications made within
the transaction.
SYNTAX:-
ROLLBACK
SAVEPOINT
• This command allows you to set a point within a transaction to which you can later roll
back.
• It is useful when you want to undo part of a transaction without rolling back the entire
transaction.
SYNTAX:
SAVEPOINT savepoint_name ;
ROLLBACK TO
• After setting a savepoint, you can roll back to it using
SYNTAX:
ROLLBACK TO savepoint_name ;
Example :-
START TRANSACTION;
INSERT INTO emp (id, name, salary, department, dob) VALUES (111, 'Joe', 50000, 'HR', '1990-
01-01');
SAVEPOINT sp_after_insert;
UPDATE emp SET salary = 60000 WHERE id = 106;
SAVEPOINT sp_after_update;
DELETE FROM emp WHERE id = 102;
ROLLBACK TO sp_after_update;
--check emp table
ROLLBACK TO sp_after_insert;
--check emp table
IMAGE
• In MySQL, you can insert images (or any binary files) into a table using a BLOB
(Binary Large Object) data type. To do this, you can use the LOAD_FILE() function to
read a file (like an image) from the file system and store its binary content into the
database.
NORMALIZATION
Normalization:-
Normalization is a process used in database design to minimize redundancy and dependency
by organizing fields and tables of a database. The goal is to ensure that data is logically stored
and reduces the chances of data anomalies (update, delete, and insert anomalies). Let's break
• It is in 1NF.
• All non-key attributes are fully functionally dependent on the primary key (no partial
dependencies).
c. Third Normal Form (3NF)
A table is in 3NF if:
• It is in 2NF.
non-prime attributes).
Denormalization
Denormalization is the process of combining tables to optimize read performance at the cost
denormalization improves query performance by reducing the need for complex joins.