0% found this document useful (0 votes)
3 views

MY_SQL

Uploaded by

Jay Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MY_SQL

Uploaded by

Jay Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

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.

Here are some key features and aspects of MySQL:

1.Relational Database: MySQL is a relational database system, which means it


organizes data into tables with rows and columns. These tables can have
relationships with one another, making it easier to manage and query data
.
2 Open Source: MySQL is open-source software, which means it is free to use and
can be modified by anyone according to the terms of the open-source license. This
has contributed to its widespread adoption.

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.

7Community and Enterprise Editions: MySQL offers both a community edition


(free) and an enterprise edition (commercially supported). The enterprise edition
includes additional features and support options

8Replication and High Availability: MySQL provides features for database


replication and high availability configurations, allowing for data redundancy and
failover mechanisms.

9Security: MySQL offers various security features, including user authentication,


encryption, and access control, to protect your data.

10Performance Optimization: Developers and administrators can fine-tune


MySQL for optimal performance using configuration settings, indexing strategies,
and query optimization techniques.
DATABASE

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

CUS ID BILL NO. PRODUCT NAME


QTY DICOUNT PROFIT CUSTOMER NAME PHONE NUMBER
2 1123 9999999 1 20 100 RADHEY 9999999
1 123564 9999999 5 30 50 SHYAM 9999999
4 231656 9999999 6 40 40 KRISHEN 9999999
3 156456 9999999 7 60 60 HARI 9999999
…..
JOINS

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

4 HARI 99999 B4 MONITOR 1 21


7 MURLI 99999 NULL NULL NULL NULL
3 KRISHNA 99999 NULL NULL NULL NULL
RIGHT 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
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

1 RADHEY 999 B3 KEYBOARD 11 212


4 HARI 99999 B4 MONITOR 1 21

5 NULL NULL B6 GAME CONSOLE


11 321
FULL 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

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

2 SHYAM 99999 B2 MOUSE 2 12


1 RADHEY 999 B3 KEYBOARD 11 212

4 HARI 99999 B4 MONITOR 1 21


5 NULL NULL B6 GAME CONSOLE11 321
3 KRISHNA 99999 NULL NULL NULL NULL
7 MURLI 99999 NULL NULL NULL NULL
CONSTRAINT

In MySQL, a constraint is a rule or condition that is applied to a


table's data to maintain data integrity and ensure that data follows
certain restrictions or requirements. Constraints help enforce
rules and relationships between the data in a database. There are
several types of constraints in MySQL, including:

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

• CREATE TABLE employees (


• employee_id INT PRIMARY KEY,
• first_name VARCHAR(50) DEFAULT 'John',
• last_name VARCHAR(50) DEFAULT 'Doe'
• );

• INDEX

• CREATE TABLE products (

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

• CREATE TABLE orders (


• order_id INT PRIMARY KEY AUTO_INCREMENT,
• product_id INT,
• quantity INT
• );

• ENUM

• CREATE TABLE colors (


• color_id INT PRIMARY KEY,
• name ENUM('Red', 'Green', 'Blue', 'Yellow')
• );
FUNCTIONS

• 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:**

• - **SUM():** Calculates the sum of numeric values in a column.

• - **COUNT():** Counts the number of rows or non-null values in a column.

• - **AVG():** Computes the average of numeric values in a column.

• - **MIN():** Retrieves the minimum value from a column.

• - **MAX():** Retrieves the maximum value from a column.


FUNCTIONS

• 3. **Date and Time Functions:**



• - **NOW():** Returns the current date and time.

• - **DATE_ADD():** Adds a specified time interval to a date.

• - **DATE_SUB():** Subtracts a specified time interval from a date.

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.

• - **SUBSTRING():** Extracts a portion of a string.

• - **TRIM():** Removes leading and trailing spaces from a string.

• - **CHAR_LENGTH():** Returns the character length of a string.

• - **LOCATE():** Finds the position of a substring in a string.

• 5. **Control Flow Functions:**

• - **IF():** Returns one value if a condition is true and another if it's


false.

• - **CASE**: Performs conditional processing in SQL queries.

• - **COALESCE():** Returns the first non-null value from a list of


expressions.
FUNCTIONS

• 6. **Data Type Conversion Functions:**


• - **CAST():** Converts an expression to a specified data type.
• - **CONVERT():** Converts an expression to a specified data type.

• 7. **User-Defined Functions (UDFs):**


• - MySQL allows you to create your own custom functions using the

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:

SELECT CalculateRectangleArea(5.5, 3.0); -- This will return 16.50

Make sure you have the necessary privileges to create functions,


and be cautious when writing functions as they can affect the
behavior of your database. Test your functions thoroughly before
using them in production environments.
TRIGGER

• In MySQL, triggers are database objects that are automatically


executed in response to specified events or conditions occurring in a
table. Triggers are typically used to enforce data integrity, automate
repetitive tasks, or log changes to a table. MySQL supports both
`BEFORE` and `AFTER` triggers, and they can be defined for `INSERT`,
`UPDATE`, and `DELETE` operations. Here's an overview of how to
create and use triggers in MySQL:

• **Basic Syntax for Creating a Trigger:**

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:**

• 1. **BEFORE Triggers:** These triggers are executed before the


triggering event (e.g., BEFORE INSERT, BEFORE UPDATE, BEFORE
DELETE). They are often used to validate data or modify values
before the action occurs.

• 2. **AFTER Triggers:** These triggers are executed after the


triggering event (e.g., AFTER INSERT, AFTER UPDATE, AFTER DELETE).
They are commonly used for logging or auditing changes.
PARTITIONS OF SQL

SQL

DDL DML

M Y
CREATE
DESELECT

C O
U N
ALTER INSERT

DROP UPDATE

RENAME DELETE
CREATE

• CREATE DATABASE DATABASE_NAME ;

• CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE CONSTRAINT


,…….);

• 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

• ALTER TABLE TABLE_NAME RENAME TO NEW_TABLE_NAME ;

• ALTER TABLE TABLE_NAME RENAME COLUMN COLUMN_NAME TO


NEW_COLUMN_NAME ;

• ALTER TABLE TABLE_NAME ADD COLUMN COLUMN_NAME

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

• DROP TABLE table_name;

• DROP DATABASE database_name;

• DROP INDEX index_name ON table_name;

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;

• DROP CONSTRAINT CONSTRAINT_NAME ;


RENAME

• RENAME TABLE current_table_name TO new_table_name;

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

• SELECT * FROM TABLE_NAME ;

• SELECT COLUMN_NAME FROM TABLE_NAME ;

SELECT COLUMN_NAME FROM TABLE_NAME WHERE CONDITION;

SELECT COLUMN_NAME FROM TABLE_NAME WHERE NOT


CONDITION;

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 ;

SELECT AGG_FUNC(COLUMN_NAME) FROM TBALE_NAME GROUP BY


COLUMN_NAME_FOR_GROUPING;

• SE;ECT COLUMN_NAME FROM TABLE_NAME ORDER BY


COLUMN_FOR_ORDERING ASC/DESC LIMIT 1/2/3/4…….;

• SELECT AGG_FUNC(COLUMN_NAME) FROM TABLE_NAME WHERE


CONDITION GROUP BY COLUMN_NAME HAVING CONDITION ;
INSERT

• INSERT INTO employees (first_name, last_name, salary)


• VALUES ('John', 'Doe', 50000);

• INSERT INTO table_name


• VALUES (value1, value2, value3, ...);

• INSERT INTO new_table (column1, column2, column3)

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

1. **Atomicity:** One of the fundamental properties of transactions is atomicity. This


means that all the SQL statements within a transaction are executed as a single,
indivisible unit. If any part of the transaction fails (e.g., due to an error or exception),
the entire transaction is rolled back, and no changes are applied to the database. If all
statements succeed, the transaction is committed, making all changes permanent.

2. **Consistency:** Transactions ensure that the database transitions from one


consistent state to another. The database remains in a valid state before and after the
execution of a transaction. This ensures that data integrity constraints and rules are

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.

5. **Transaction Control Statements:** As mentioned earlier, MySQL provides


transaction control statements that allow you to initiate transactions (`BEGIN` or
`START TRANSACTION`), commit transactions (`COMMIT`), and roll back transactions
(`ROLLBACK`). You can also set transaction-specific options using `SET TRANSACTION`.

6. **Savepoints:** Savepoints are markers within a transaction that allow you to


define points to which you can roll back in case of an error or to undo a portion of a
transaction without affecting the entire transaction. Savepoints are created using
`SAVEPOINT`, and you can roll back to a savepoint using `ROLLBACK TO SAVEPOINT`.

7. **Implicit vs. Explicit Transactions:** In MySQL, transactions can be either implicit


or explicit. Implicit transactions are automatically started and committed for each SQL
statement. Explicit transactions are started and managed using the transaction control
statements. Explicit transactions offer more control and are commonly used for
complex operation
MODES OF TRANSACTIONS

AUTOCOMMIT TRANSACTION : THIS IS THE DEFAULT


TRANSACTION FOR THE SQL SERVER . SUCCESSFUL
TRANSACTIONS WILL BE SETTLED AND FAILED WILL BE
ROLLED BACK

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

COMMIT :SAVE THE CHANGES


ROLL BACK:ROLL BACK THE CHANGES

SAVEPOINT:CREATE POINTS WITHIN GROUPS OF

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

In MySQL, the `CREATE PROCEDURE` statement is used to define and


create a stored procedure. A stored procedure is a precompiled
collection of one or more SQL statements that can be executed as a
single unit. These procedures are typically used to encapsulate a
series of SQL statements into a reusable and modular unit.

Here is the basic syntax for creating a stored procedure in MySQL:

CREATE PROCEDURE procedure_name ([parameter_list])

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.

Stored procedures are a powerful tool in MySQL for encapsulating


business logic, promoting code reusability, and improving database
performance and security. They are often used in database systems
to modularize complex tasks and provide a structured way to
interact with the database.
UNION

• 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.

• In summary, you would use `UNION` when you want to eliminate


duplicate rows and get a distinct set of results, while you would use
`UNION ALL` when you want to keep all rows, including duplicates, in
the combined result. Your choice between `UNION` and `UNION ALL`
will depend on the specific requirements of your query and whether
you want to include or exclude duplicate rows in the final output.
TRUNCATE

• In MySQL, the `TRUNCATE` statement is used to quickly delete all rows


from a table, effectively removing all the data in the table. It is a DDL
(Data Definition Language) statement and operates much faster than the
`DELETE` statement, which removes rows one by one. Here are the key
points to know about the `TRUNCATE` statement:

• 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.

• 3. **Constraints and Considerations:**


• - You must have the `TRUNCATE` privilege on the table to use the
`TRUNCATE` statement.
• - You cannot use `TRUNCATE` on tables that are referenced by foreign
keys from other tables. To use `TRUNCATE`, you would typically need to
drop the foreign key constraints first.

• 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:

1. **Download MySQL Installer:**


- Visit the official MySQL website to download the MySQL Installer for Windows. You can find it at
https://dev.mysql.com/downloads/installer/.
- On the download page, you'll find two versions: MySQL Installer for Windows (32-bit) and MySQL Installer for
Windows (64-bit). Choose the appropriate version based on your system's architecture (most modern systems are
64-bit).

2. **Run the Installer:**


- Once the installer is downloaded, run the executable file (e.g., "mysql-installer-community-8.x.xx.xxx.msi") to
launch the MySQL Installer.

3. **Choose Installation Type:**


- In the MySQL Installer, you'll be presented with several installation types. Select "Custom" to have more control
over the components you want to install, including the MySQL Server and MySQL Workbench.

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.

10. **Launch MySQL Workbench:**


- After installation, you can launch MySQL Workbench from the Start Menu or by searching for "MySQL
Workbench" in the Windows search bar.

11. **Connect to MySQL Server:**


- Open MySQL Workbench and connect to the MySQL Server using the root username and the password you set
during the installation.

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

DOWNLOAD AS PER SYSTEM BIT


M Y
DE
C O
UN

CLICK HERE TO DOWNLOAD


SOME INTERVIEW
QUESTIONS

1. **What is SQL, and what is it used for?**


- SQL stands for Structured Query Language, and it is used for
managing and querying relational databases.

2. **Explain the difference between SQL and NoSQL databases.**

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.

4. **Explain the purpose of the `SELECT` statement in SQL.**


- The `SELECT` statement is used to retrieve data from a database. It
allows you to specify which columns to retrieve and filter data using
various conditions.

5. **What is the difference between `INNER JOIN` and `LEFT JOIN` in


SQL?**
- `INNER JOIN` returns only the matching rows from both tables, while
`LEFT JOIN` returns all rows from the left table and the matching rows
from the right table.
• 6. **What is the `WHERE` clause in SQL used for?**
• - The `WHERE` clause is used to filter rows from a table
based on a specified condition.

• 7. **Explain the difference between `GROUP BY` and


`HAVING` clauses in SQL.**
• - `GROUP BY` is used to group rows based on a specified
column, and `HAVING` is used to filter the grouped results

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.

• 10. **Explain the ACID properties in the context of database


transactions.**
• - ACID stands for Atomicity, Consistency, Isolation, and
Durability. It is a set of properties that guarantee reliable
processing of database transactions.
• 11. **What is normalization in the context of database
design?**
• - Normalization is the process of organizing data in a
database to reduce data redundancy and improve data
integrity.

• 12. **Explain the concept of a view in SQL.**


• - A view is a virtual table that is based on the result of a
SQL statement. It provides an abstraction layer over the

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.

• 15. **Explain the difference between the `UNION` and


`UNION ALL` operators in SQL.**
• - `UNION` returns distinct rows from multiple SELECT
statements, while `UNION ALL` returns all rows, including
duplicates.

You might also like