MY_SQL
MY_SQL
M Y
WHAT IS SQL
DE
O
WHY IT IS USED
C
WHERE IT IS USED
N
WHEN IT IS USED
U
HOW IT IS USED
MySQL is an open-source relational database management system (RDBMS) that
is widely used for storing, managing, and retrieving data. It is a popular choice for
web applications and is often used in conjunction with scripting languages like PHP
to create dynamic websites.
Y
3Scalability: MySQL can handle both small-scale and large-scale applications. It
offers various storage engines, such as InnoDB and MyISAM, that cater to different
M
scalability and performance requirements.
DE
4Cross-Platform: MySQL is available on various operating systems, including
O
Windows, Linux, macOS, and more. This cross-platform compatibility makes it
C
accessible to a wide range of users.
N
5Multi-User Support: MySQL supports multiple users and concurrent connections,
U
making it suitable for applications with high levels of concurrent activity.
6SQL Support: MySQL uses Structured Query Language (SQL) for defining,
querying, and managing data. It supports standard SQL syntax with some
extensions and variations.
A database is a structured collection of data organized and stored in a way that allows for efficient
retrieval, management, and manipulation of that data. Databases are used to store and manage
information in various applications, ranging from simple personal record-keeping systems to
complex enterprise-level systems. Here are some key characteristics and concepts related to
databases:
1.Structured Data: Databases store data in a structured format, often using tables, rows, and
columns. Each row represents a record, while each column represents a specific attribute or field
of the data
.
2Data Integrity: Databases typically enforce data integrity constraints to ensure that the data is
Y
accurate and consistent. This includes enforcing rules like unique keys, primary keys, foreign keys,
M
and data type constraints.
E
3Querying: Users and applications can retrieve and manipulate data from a database using
D
queries written in a database query language, such as SQL (Structured Query Language). SQL
O
allows for various operations like selecting, inserting, updating, and deleting data.
C
4.Relational Databases: Relational databases, like MySQL, PostgreSQL, and Microsoft SQL
N
Server, are a common type of database that organizes data into tables with defined relationships
U
between them. These databases are widely used for a wide range of applications.
5NoSQL Databases: NoSQL databases, such as MongoDB and Cassandra, are designed to
handle unstructured or semi-structured data and can be a better choice for certain types of
applications, such as those requiring high scalability or flexibility.
6Database Management System (DBMS): A DBMS is software that manages the database. It
provides tools for creating, updating, and querying data while handling low-level tasks like data
storage and retrieval
7.Normalization: The process of database normalization involves organizing data to reduce data
redundancy and improve data integrity. It typically results in a series of related tables with minimal
data duplication.
8.Indexes: Databases use indexes to optimize data retrieval. Indexes are data structures that
provide quick access to specific rows in a table based on the values of one or more columns.
9.Transactions: Databases support transactions, which are sequences of one or more SQL
statements treated as a single unit of work. Transactions ensure data consistency and integrity by
allowing operations to be either completed in their entirety or rolled back in case of failure.
10.Security and Access Control: Databases have security mechanisms to control who can
access and manipulate the data. This includes user authentication, authorization, and auditing
features.
DATABASE
KEY VALUE
Y
DOCUMENT
M
DBMS
DE
O
WIDE
N C COLUMN
U
DATABASE
GRAPH
TABLE
RDBMS
REALTION
Data flow
M Y
DE
C O
UN
• RDBMS stands for Relational Database
Management System. It is a type of
database management system that
organizes data into structured tables with
Y
rows and columns, and it enforces
M
relationships between these tables to
E
ensure data integrity. Here are some key
D
characteristics and concepts associated
O
with RDBMS
N C
U A DBMS, or Database Management
System, is software that manages and
facilitates the efficient storage,
retrieval, organization, and
manipulation of data within a
database. Its primary purpose is to
provide a structured and organized
way to store and access data.
DBMS
KEY VALUE
DATABASE
M Y
DE
C O
UN
DBMS
DOCUMENT
DATABASE
M Y
DE
C O
UN
DBMS
WIDE
COLUMN
M Y
DE
C O
UN
DBMS
GRAPH
DATABASE
M Y
DE
C O
UN
RDBMS
TABLE NO. 1
CUSTOMER ID CUSTOMER NAME PHONE NUMBER
1 RADHEY 9999999
PRIMARY KEY 2 SHYAM 9999999
3 KRISHEN 9999999
ASE 4 HARI 9999999
…..
M Y
DE
TABLE NO. 2
O
CUS ID BILL NO. PRODUCT NAME QTY DICOUNT PROFIT
2 1123 9999999 1 20 100
C
FOREIGN KEY 1 123564 9999999 5 30 50
N
4 231656 9999999 6 40 40
U
3 156456 9999999 7 60 60
…..
COMPLETE
M Y
DE
C O
UN
INNER JOIN
TABLE NO. 1
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER
1 RADHEY 999
2 SHYAM 99999
3 KRISHNA 99999
4 HARI 99999
7 MURLI 99999
M Y
DE
O
TABLE NO. 2
C
CUSTOMER ID BILL NUMBER ITEM NAME QTY PRICE
N
1 B1 LAPTOP 1 123
U
2 B2 MOUSE 2 12
1 B3 KEYBOARD 11 212
4 B4 MONITOR 1 21
5 B6 GAME CONSOLE 11 321
COMBINE TABLE
ID CUSTOMER NAME
CONTACT NUMBER BILL NUMBER ITEM NAME QTY PRICE
1 RADHEY 999 B1 LAPTOP 1 123
2 SHYAM 99999 B2 MOUSE 2 12
1 RADHEY 999 B3 KEYBOARD 11 212
4 HARI 99999 B4 MONITOR 1 21
LEFT OUTER JOIN
TABLE NO. 1
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER
1 RADHEY 999
2 SHYAM 99999
3 KRISHNA 99999
4 HARI 99999
7 MURLI 99999
M Y
DE
TABLE NO. 2
O
CUSTOMER ID BILL NUMBER ITEM NAME QTY PRICE
C
1 B1 LAPTOP 1 123
2 B2 MOUSE 2 12
N
1 B3 KEYBOARD 11 212
U
4 B4 MONITOR 1 21
5 B6 GAME CONSOLE 11 321
COMBINE TABLE
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER BILL NUMBER ITEM NAME QTY PRICE
1 RADHEY 999 B1 LAPTOP 1 123
2 SHYAM 99999 B2 MOUSE 2 12
1 RADHEY 999 B3 KEYBOARD 11 212
TABLE NO. 1
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER
1 RADHEY 999
2 SHYAM 99999
3 KRISHNA 99999
4 HARI 99999
7 MURLI 99999
M Y
COMBINE TABLE
E
BILL NUMBER ITEM NAME QTY PRICE
D
B1 LAPTOP 1 123
TABLE NO. 2
O
B2 MOUSE 2 12
CUSTOMER ID BILL NUMBER ITEM NAME QTY PRICE
C
B3 KEYBOARD 111 B1212 LAPTOP 1 123
N
B4 MONITOR 12 B2 21 MOUSE 2 12
U
1 B3 KEYBOARD 11 212
4 B4 MONITOR 1 21
5 B6 GAME CONSOLE
11 321
COMBINE TABLE
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER BILL NUMBER ITEM NAME QTY PRICE
1 RADHEY 999 B1 LAPTOP 1 123
2 SHYAM 99999 B2 MOUSE 2 12
TABLE NO. 1
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER
1 RADHEY 999
2 SHYAM 99999
3 KRISHNA 99999
4 HARI 99999
7 MURLI 99999
M Y
DE
TABLE NO. 2
O
CUSTOMER ID BILL NUMBER ITEM NAME QTY PRICE
C
1 B1 LAPTOP 1 123
N
2 B2 MOUSE 2 12
U
1 B3 KEYBOARD 11 212
4 B4 MONITOR 1 21
5 B6 GAME CONSOLE
11 321
COMBINE TABLE
CUSTOMER ID CUSTOMER NAME CONTACT NUMBER BILL NUMBER ITEM NAME QTY PRICE
1 RADHEY 999 B1 LAPTOP 1 123
TYPES OF CONSTRAINTS
M Y
•PRIMARY KEY
DE
C
•UNIQUE
O
U N•FOREIGN KEY
•CHECK
•NOT NULL
•DEFAULT
•INDEX
•AUTO_INCREMENT (or Identity)
•ENUM
•UNIQUE INDEX
SYNTAX
• PRIMARY KEY
• CREATE TABLE employees (
• employee_id INT PRIMARY KEY,
• first_name VARCHAR(50),
• last_name VARCHAR(50)
• );
• UNIQUE
• CREATE TABLE products (
• product_id INT,
• product_name VARCHAR(50) UNIQUE,
Y
• price DECIMAL(10, 2)
M
• );
DE
• FOREIGN KEY
O
CREATE TABLE orders (
C
order_id INT PRIMARY KEY,
N
product_id INT,
U
quantity INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
CHECK
CREATE TABLE students (
student_id INT PRIMARY KEY,
age INT CHECK (age >= 18),
grade CHAR(1) CHECK (grade IN ('A', 'B', 'C', 'D', 'F'))
);
NOT NULL
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL
);
SYNTAX
DEFAULT
• INDEX
M Y
E
• product_id INT PRIMARY KEY,
D
• product_name VARCHAR(50),
C O
• price DECIMAL(10, 2),
N
• INDEX idx_product_name (product_name)
U
• );
• AUTO INCRIMENT
• ENUM
• 1. Scalar Functions:
•
• - **Math Functions:** Functions for mathematical calculations, such as
`ABS()`, `ROUND()`, `CEIL()`, `FLOOR()`.
•
• - **String Functions:** Functions for working with text data, including
`CONCAT()`, `LENGTH()`, `UPPER()`, `LOWER()`.
Y
• - **Date and Time Functions:** Functions for handling date and time
M
values, like `NOW()`, `DATE_FORMAT()`, `TIMESTAMPDIFF()`.
DE
O
• - **Conversion Functions:** Functions for converting data types, like
C
`CAST()`, `CONVERT()`.
N
.
U
• - **Control Flow Functions:** Functions for conditional processing, such as
`IF()`, `CASE`.
• 2. **Aggregate Functions:**
M Y
• - **DATEDIFF():** Calculates the number of days between two dates.
DE
• - **DATE_FORMAT():** Formats date and time values as strings.
C O
• 4. **String Functions:**
N
•
U
- **CONCAT():** Combines two or more strings.
Y
`CREATE FUNCTION` statement. These are known as User-Defined
Functions (UDFs).
E M
D
• SELECT CONCAT(first_name, ' ', last_name) AS full_name,
O
• DATE_FORMAT(birth_date, '%Y-%m-%d') AS
C
formatted_birth_date,
N
• IF(salary > 50000, 'High', 'Low') AS salary_status
U
• FROM employees;
FUNCTIONS
DELIMITER //
CREATE FUNCTION CalculateRectangleArea(length DECIMAL(10, 2),
width DECIMAL(10, 2))
RETURNS DECIMAL(10, 2)
Y
BEGIN
M
DECLARE area DECIMAL(10, 2);
E
SET area = length * width;
D
RETURN area;
O
END //
C
DELIMITER ;
U N
After creating the function, you can use it in SQL queries like any
other function:
M Y
DE
O
•CREATE TRIGGER trigger_name
C
• {BEFORE | AFTER} {INSERT | UPDATE |
U
DELETE}
N
• ON table_name
• FOR EACH ROW
• BEGIN
• -- Trigger body: Write the actions to be
performed here
• END;
TRIGGER
• EXAMPLE:
• DELIMITER //
• CREATE TRIGGER SetCreationTimestamp
• BEFORE INSERT
• ON employees
• FOR EACH ROW
Y
• BEGIN
M
• SET NEW.created_at = NOW();
E
• END;
D
• //
O
• DELIMITER ;
N C
U
In this example, the trigger `SetCreationTimestamp` is executed
before inserting a new record into the `employees` table. It sets the
`created_at` column to the current timestamp using the `NOW()`
function.
**Types of Triggers:**
SQL
DDL DML
M Y
CREATE
DESELECT
C O
U N
ALTER INSERT
DROP UPDATE
RENAME DELETE
CREATE
• DELIMITER //
• CREATE FUNCTION CalculateRectangleArea(length DECIMAL(10, 2), width
DECIMAL(10, 2))
Y
• RETURNS DECIMAL(10, 2)
M
• BEGIN
E
• DECLARE area DECIMAL(10, 2);
D
• SET area = length * width;
O
• RETURN area;
N C
• END //
U
• DELIMITER ;
• DELIMITER //
• CREATE TRIGGER SetCreationTimestamp
• BEFORE INSERT
• ON employees
• FOR EACH ROW
• BEGIN
• SET NEW.created_at = NOW();
• END;
• //
• DELIMITER ;
ALTER
Y
DATA_TYPE CONSTRAINT;
E M
• ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME
D
new_data_type;
C O
ALTER TABLE TABLE_NAME ADD CONTRAINT
N
CONSTRAINT_NAME(COLUMN_NAME );
U
ALTER TABLE table_name
ADD FOREIGN KEY (column_name)
REFERENCES referenced_table(referenced_column);
DROP
Y
• DROP PROCEDURE procedure_name;
E M
• DROP FUNCTION function_name;
O
• DROP TRIGGER trigger_name;
D
N C
• DROP VIEW view_name;
U
• DROP USER username;
Y
• RENAME TABLE employees TO staff;
E M
D
• .RENAME TABLE old_db.old_table TO new_db.new_table;
C O
• RENAME TABLE old_table1 TO new_table1, old_table2 TO
N
new_table2, ...;
U
SELECT
M Y
E
SELECT COLUMN_NAME FROM TABLE_NAME WHERE LIKE A%A;
O D
SELECT COLUMN_NAME FROM TABLE_NAME WHERE CONDITION
C
AND CONDITION ;
U N
SELECT COLUMN_NAME FROM TABLE_NAME WHERE CONDITION OR
CONDITION ;
M Y
E
• SELECT columnA, columnB, columnC
D
• FROM source_table
C O
• WHERE some_condition;
U N
UPDATE
•UPDATE table_name
•SET column1 = value1, column2 = value2, ...
•WHERE condition;
DELETE
M Y
D E
C O
N
•DELETE FROM
U condition;
•WHERE
table_name
PROPERTIES OF
TRANSACTIONS IN SQL
Y
not violated.
E M
3. **Isolation:** Isolation defines the degree to which one transaction is isolated from
D
the effects of other concurrent transactions. MySQL uses isolation levels to control
O
this behavior. Common isolation levels include READ UNCOMMITTED, READ
COMMITTED, REPEATABLE READ, and SERIALIZABLE. These levels determine how locks
C
are acquired and released during transactions, affecting concurrency and consistency.
U N
4. **Durability:** Once a transaction is committed, its changes are permanent and
will survive system failures (such as power outages or crashes). This property is
essential for maintaining data durability.
Y
IMPLICIT TRANSACTION : THIS MODE ENABLES SQL
M
SERVER TO START IMPLICIT TRANSACTION FOR EVERY
DE
DML STATEMENT BUT WE NEED TO COMMIT OR ROLL
O
BACK THE COMMAND AT THE END OF TRANSACTION
N C
U
EXPLICIT TRANSACTION : EXPLICIT TRANSACTION
PROVIDES TO DEFINE A TRANSACTION EXACTLY WITH
THE STARTING AND ENDING POINTS OF THE
TRANSACTION
TRANSACTION CONTROLL
Y
TRANSACTION IN WHICH TO ROLL BACK
E M
D
SET:PLACES A NAME ON A TRANSACTION
C O
COMMIT AND ROLL BACK IS ALWAYS USED WITH
N
TRANSACTIONS
U
STORED PROCEDURES
M Y
E
BEGIN
D
-- SQL statements go here
C O
END;
U N
- `procedure_name`: This is the name of the stored procedure.
- `parameter_list`: This is an optional list of input and output
parameters that the procedure can accept.
Inside the `BEGIN` and `END` block, you can include one or more
SQL statements to perform a specific task or operation. You can use
control structures, conditionals, loops, and error handling within the
procedure to create complex logic.
• In MySQL, `UNION` and `UNION ALL` are used to combine the result sets of
two or more `SELECT` statements into a single result set. However, they differ
in how they handle duplicate rows:
• 1. `UNION`:
Y
• - The `UNION` operator combines the result sets of multiple `SELECT`
E M
statements and returns a distinct set of rows in the final result.
O D
• Example:
N C
• SELECT column1, column2 FROM table1
• UNION
U
• SELECT column1, column2 FROM table2;
•
• If there are duplicate rows between `table1` and `table2`, `UNION` will return
only one instance of each duplicate row.
UNION ALL
• 2. **UNION ALL:**
• - The `UNION ALL` operator is used to combine the result sets of
multiple SELECT queries, but it retains all rows, including duplicates.
Y
• - Unlike `UNION`, `UNION ALL` does not remove duplicate rows. If
M
there are duplicates in the result sets, they will appear in the final
E
result.
• Example:
O D
N C
• SELECT column1 FROM table1
U
• UNION ALL
• SELECT column1 FROM table2;
• If there are duplicate rows in the result sets from `table1` and
`table2`, they will all be included in the final result.
• 1. **Syntax:**
• The basic syntax of the `TRUNCATE` statement is as follows:
Y
• TRUNCATE TABLE table_name;
E M
• `table_name` is the name of the table from which you want to remove
D
all rows.
O
• 2. **Behavior and Considerations:**
C
• - `TRUNCATE` is a data removal operation, and it does not generate
N
any log entries for individual row deletions, which makes it faster than
U
`DELETE` for removing all data from a table.
• - `TRUNCATE` is typically faster than `DELETE` because it deallocates
the data pages used by the table and resets the auto-increment
counters (if any). However, it does not provide the same level of control
and logging as `DELETE`.
• - `TRUNCATE` is also more efficient in terms of system resources
because it uses fewer resources compared to `DELETE` when clearing a
large table.
• 4. **Additional Notes:**
• - The `TRUNCATE` statement is an efficient way to remove all data
from a table, but it does not provide the ability to selectively delete
specific rows based on conditions. If you need to delete specific rows,
you should use the `DELETE` statement instead.
• - After using `TRUNCATE`, the table structure and indexes remain
intact. The table is effectively empty with reset auto-increment values.
To install MySQL Workbench along with the MySQL Server on a Windows operating system, you can follow these
steps:
4. **Select Products:**
Y
- In the "Select Products and Features" step, you can choose the components you want to install. Make sure to
select "MySQL Server" and "MySQL Workbench" by checking the boxes next to them.
E M
5. **Select Version:**
- Choose the version of MySQL Server and MySQL Workbench you want to install. The installer usually
D
recommends the latest version, which is a good choice for most users.
O
6. **Installation Path:**
C
- Specify the installation path for MySQL Server and MySQL Workbench. You can use the default paths or choose
N
custom directories.
U
7. **Configure Server:**
- In the "Type and Networking" step, you can configure the MySQL Server. You can leave most of the settings at
their default values for a basic installation.
- Set a root password for MySQL. Make sure to remember this password, as it will be needed to access the MySQL
Server.
8. **Start Installation:**
- Click the "Execute" button to start the installation process. The installer will download and install the selected
components.
9. **Complete Installation:**
- Once the installation is complete, you will see a summary screen. Ensure that MySQL Server and MySQL
Workbench are marked as "Installed." You can also click the "Next" button to configure additional settings if
needed.
That's it! You have now successfully installed MySQL Workbench along with the MySQL Server on your Windows
operating system. You can use MySQL Workbench to manage your MySQL databases and perform various
database-related tasks.
LINK TO INSTALL
https://dev.mysql.com/downloads/installer/
M Y
DE
C O
U N
M Y
DE
C O
UN
Y
- SQL databases are relational and structured, while NoSQL databases
M
are non-relational and unstructured. SQL databases use tables, and
DE
NoSQL databases use collections/documents.
C O
3. **What is a primary key in a database table?**
N
- A primary key is a unique identifier for each record in a database
U
table. It ensures that each row is unique and provides a way to
reference that row.
Y
based on a condition.
E M
D
• 8. **What is a subquery in SQL?**
O
• - A subquery is a query nested inside another query. It can
C
be used to retrieve data that will be used in the main query.
U N
• 9. **What is an index in a database, and why is it
important?**
• - An index is a data structure that improves the speed of
data retrieval operations on a database table. It's important
because it allows the database to quickly find and retrieve
data.
Y
underlying tables.
E M
• 13. **What is the difference between a stored procedure
D
and a function in SQL?**
O
• - A stored procedure is used to perform an action, and it
C
may or may not return a value. A function, on the other
N
hand, always returns a value.
U
• 14. **What is SQL injection, and how can it be
prevented?**
• - SQL injection is a security vulnerability where an
attacker can manipulate SQL queries. It can be prevented by
using parameterized queries or prepared statements.