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

MYSQL NOTES

The document provides an overview of frontend and backend web development, detailing the roles of each and the languages used. It explains various types of databases, including DBMS and RDBMS, along with their characteristics, advantages, and limitations. Additionally, it covers SQL operations, data types, and the importance of databases in data management.

Uploaded by

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

MYSQL NOTES

The document provides an overview of frontend and backend web development, detailing the roles of each and the languages used. It explains various types of databases, including DBMS and RDBMS, along with their characteristics, advantages, and limitations. Additionally, it covers SQL operations, data types, and the importance of databases in data management.

Uploaded by

lokeshsamboji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

MYSQL NOTezS

—-------------------

Frontend:

-------------------

1. The part of a website that the user interacts with directly is


called frontend.

2. In frontend it is also refered as client side of the application.

3. It includes everything that users experience directly.

4. Html,css,js,bootstrap are the languages used for front end


development

Backend

-----------------

1. Backend is the server side of the web site

2. It stores and arranges the data and also make sure every thing on the
client side of the website works fine

3. In backend there are some languages java,python,php,c,c++.net……


etc

API:

---------

It means application programming interface. Which is the collection of


communication protocols used by various programs to communicate
between them.

Data

------------

Data is a piece of information that can be translated into form for efficient
moment is called for data.

Database:

-----------------

It is a collection of data. That is organized which is also called structured


data

It can be stored in a computer system.

It can manage through database management system.

In a database data is organized into tables consits of rows and columns.

Types of databases

----------------------------------

DBMS
----------------

DBMS stands for Database Management System. It is a software system that


enables users to define, create, maintain, and control access to a database. The
primary purpose of a DBMS is to provide an environment that is both convenient
and efficient for users to retrieve and store information in databases.

RDBMS

---------------

RDBMS stands for Relational Database Management System. It is a type of database


management system that organizes data into tables, which consist of rows and
columns. Each row represents a record or tuple, and each column represents a field
or attribute of that record.

Key characteristics of RDBMS include:

1. Tabular Structure: Data is organized into tables (relations) where each


table has a unique name and consists of rows (tuples) and columns
(attributes).

2. Structured Query Language (SQL): RDBMS uses SQL as its standard


language for querying and manipulating data. SQL allows users to perform
operations such as retrieving, inserting, updating, and deleting data.

3. Data Integrity: RDBMS enforces rules (constraints) to ensure data


integrity, including primary key constraints (uniquely identifies each
record), foreign key constraints (maintains referential integrity between
tables), and other constraints like NOT NULL and CHECK constraints.

4. Relationships: RDBMS supports relationships between tables through


foreign keys, which establish connections between related data in
different tables. Common relationship types include one-to-one, one-to-
many, and many-to-many.

5. Normalization: RDBMS supports normalization techniques to reduce data


redundancy and improve data integrity. Normalization involves organizing
data into tables in such a way that minimizes redundancy and
dependency.
6. Transactions: RDBMS supports ACID properties (Atomicity, Consistency,
Isolation, Durability) for transactions. Transactions are units of work that
are executed reliably and atomically (all-or-nothing principle), ensuring
data consistency and reliability.

Examples of popular RDBMS include Oracle Database, MySQL, Microsoft SQL Server,
PostgreSQL, and SQLite. RDBMSs are widely used in various applications and
industries where structured and relational data management is essential for
efficient data storage, retrieval, and manipulation.

NoSQL DBMS

--------------------

It is suitable for unstrucred and semi-structred data.

Ex: MongoDB (document store), Apache Cassandra (column-family store)

Object oriented Database

----------------------------------

It stores data in the form of objects.

Ex: db4o

4) graph dbms:

-------------------------

It optimize for storing graph data.

Ex: Neo4j (graph database), arango DB.


5) In Memory DBMS:

-----------------------------------

It stores the data primarly in the computers main memory(RAM).

Ex: Redis, SAP HANA.

6) Distributed DBMS

------------------------

It splits the data multiple servers or multiple locations.

Ex:

----

Google cloud spanner

Amazon Aurora.

7) Columnar Databases:

---------------------------------------

It sores the data in cloumns rather than rows.

Ex: Amazon Redshift, Apache HBase, Google Bigtable.


Time Series DBMS

----------------------------

It optimize for handlling time stamped data such as financial market data.

Ex: Influx DB, Open TSDB

XML DBMS

-----------------

It handles xml data.

Ex: Basex.

Distributed database management system

-----------------------------------------------------------

A distributed database refers to a database system in which data is stored and


managed across multiple physical or logical locations. Unlike a centralized database
where all data is stored on a single system, a distributed database distributes data
across different sites connected by a network. Each site in a distributed database
may be a separate computer system, server, or even a data center.

Key characteristics and concepts of distributed databases include:

1. Distribution Transparency: Users and applications accessing the


distributed database may not be aware of the distribution of data. The
database management system (DBMS) handles the complexity of
distributing and coordinating data access transparently.
2. Location Transparency: Applications can access data without needing to
know the physical location of data. This transparency is managed by the
DBMS, which handles data access and distribution based on queries and
operations.

3. Replication: Distributed databases may replicate data copies across


multiple sites for redundancy, fault tolerance, and improved performance.
Replication ensures that data remains available even if one site fails.

4. Concurrency Control: Managing concurrent access to distributed data is


crucial to maintain data consistency and integrity. Distributed DBMSs
employ techniques such as distributed locking, timestamp ordering, and
two-phase commit protocols to ensure transactions are executed correctly
across multiple sites.

5. Scalability: Distributed databases can scale horizontally by adding more


nodes or sites to handle increasing data volumes or user demands. This
scalability is essential for handling large-scale applications and distributed
systems.

6. Data Fragmentation: Data in a distributed database may be fragmented or


partitioned across different sites based on various criteria such as data
ranges, functions, or access patterns. Fragmentation helps optimize data
storage and access efficiency.

7. Network Independence: Distributed databases are designed to function


independently of the underlying network infrastructure. They can operate
over different types of networks (LANs, WANs, or even the Internet) while
ensuring data consistency and performance.

8. Global Transactions: Supporting global transactions that span multiple


sites is a critical feature of distributed databases. This involves
coordinating distributed transactions to ensure atomicity, consistency,
isolation, and durability (ACID properties) across all participating sites.

Examples of distributed databases include Google's Bigtable, Amazon DynamoDB,


Apache Cassandra, and some implementations of cloud databases that span
multiple data centers globally.

In summary, distributed databases provide flexibility, scalability, and resilience by


distributing data across multiple locations, enabling efficient management of large-
scale data and supporting distributed applications and systems.
A cloud management database (CMD) typically refers to a specialized database
system used by cloud service providers (CSPs) to manage and store information
related to their cloud infrastructure and services. This database plays a crucial role
in enabling the CSP to efficiently manage and operate their cloud platform, ensuring
scalability, reliability, and performance.

The main differences between DBMS and RDBMS are given below:

No DBMS RDBMS
.
1) DBMS applications store RDBMS applications store data in a
data as file. tabular form.

2) In DBMS, data is generally In RDBMS, the tables have an identifier


stored in either a called primary key and the data values
hierarchical form or a are stored in the form of tables.
navigational form.

3) Normalization is not Normalization is present in RDBMS.


present in DBMS.

4) DBMS does not apply any RDBMS defines the integrity constraint
security with regards to for the purpose of ACID (Atomocity,
data manipulation. Consistency, Isolation and Durability)
property.

5) DBMS uses file system to in RDBMS, data values are stored in


store data, so there will be the form of tables, so a relationship
no relation between the between these data values will be
tables. stored in the form of a table as well.
6) DBMS has to provide some RDBMS system supports a tabular
uniform methods to access structure of the data and a relationship
the stored information. between them to access the stored
information.

7) DBMS does not support RDBMS supports distributed database.


distributed database.

8) DBMS is meant to be for RDBMS is designed to handle large


small organization and amount of data. it supports multiple
deal with small data. it users.
supports single user.

9) Examples of DBMS are file Example of RDBMS are mysql, postgre,


systems, xml etc. sql server, oracle etc.

Storage Areas

As the Part of our Applications, we required to store our Data like


Customers Information, Billing Information, Calls Information etc..

To store this Data, we required Storage Areas. There are 2 types of Storage
Areas.

1) Temporary Storage Areas


2) Permanent Storage Areas

Temporary Storage Areas:


These are the Memory Areas where Data will be stored temporarily.
Eg: All JVM Memory Areas (like Heap Area,
Method Area, Stack Area etc). Once JVM
shutdown all these Memory Areas will be cleared
automatically.

Permanent Storage Areas:


Also known as
Persistent Storage
Areas. Here we can
store Data
permanently.
Eg: File Systems, Databases, Data warehouses, Big Data Technologies etc

File Systems:

File Systems can be provided by Local operating System.

File Systems are best suitable to store very less Amount of Information.

Limitations:

1) We cannot store huge Amount of Information.


2) There is no Query Language support and hence operations will
become very complex.
3) There is no Security for Data.
4) There is no Mechanism to prevent duplicate Data.
Hence there may be a chance of Data Inconsistency
Problems.

To overcome the above Problems of File Systems, we should go for


Databases.

Databases:

1) We can store Huge Amount of Information in the Databases.


2) Query Language Support is available for every Database
and hence we can perform Database Operations very easily.
3) To access Data present in the Database, compulsory
username and pwd must be required. Hence Data is
secured.
4) Inside Database Data will be stored in the form of Tables.
While developing Database Table Schemas, Database
Admin follow various Normalization Techniques and can
implement various Constraints like Unique Key Constrains,
Primary Key Constraints etc which prevent Data
Duplication. Hence there is no chance of Data
Inconsistency Problems.

Limitations of Databases:

1) Database cannot hold very Huge Amount of Information like


Terabytes of Data.
2) Database can provide support only for Structured Data
(Tabular Data OR Relational Data) and cannot provide
support for Semi Structured Data (like XML Files) and
Unstructured Data (like Video Files, Audio Files, Images etc)

To overcome this Problems we should go for more


Advanced Storage Areas like Big Data Technologies, Data
warehouses etc..

Why we use database?

-------------------------------------

1. Data retrival

2. Data security.

3. Data recovery

4. Data manage

5. Data organization
6. Concurrency control

SQL (Structured Quey language)

It is designed for managing and manipulating relational databases.

It is a standard language for interacting with RDBMS.

Sql operations

-----------------------

1. Select

2. Insert

3. Update

4. Delete

5. Create

6. Alter

7. Drop

8. Truncate
SQL is A case sensitive.

In sql the keywords are Written in Upper Case for better readabilty.

Semicolon are used terminate sql statements

SQL IDENTIFIERS:-

Identifier:- the user defined name

Ex: variable-name, object -name,table-name,alias-name, coloumn-name.

Maximum length---- 30 chars

Allowed chars---A-Z/a-z/0-9/$,_,#.

Identifiers are not case sensitive.

First character must be an alphabet

Keywords are not allowed.

MySQL Commands

In MySQL the commands are used to perform various actions related to


databases.
CREATE DATABASE MyDataBase;

SHOW DATABASES;

Use MyDataBase;

DROP DATABASE MyDataBase;

EXIT;

QUIT;

In the above program description for each and every line

-----------------------------------------------------------------------------------------

This command creates a new database named MyDataBase;

This coomand shows existed databases in mysql server;

This command is used to switch to the specified database.

This command is used to deletes the specified database perminently.

This command is used to exit the mysql command line interface.

It is similar to nexit

Introduction to TABLE’s

---------------------------------------------------------------------------
Table is a fundmental structure and used to organize and stores data.

It is a 2-D structure composed of rows and columns.

Each row in a table represents a record. While each column represents a


specific attributes.

Cell:

------

The intrersection of a rows and columns it contains a single data value.

Primary key:

--------------------

It is a unique identifier for each record in the table.

Table name:

--------------------------

Each table is given a unique name with in the database.

Data Types

-----------------------

Data Types define the kind of data that can be stored in a column.
The type of values are fixed or variable

1.Numeric datatypes

--------------------------------------

These data types includes exact numeric data types.

For example, integer,float,bits.

Integral data types(5):

Minimum
Storage Minimum Value Value Maximum Maximum
Type (Bytes) Signed Unsigned Value Signed Value Unsigned

TINYINT 1 -128 0 127 255

SMALLINT 2 -32768 0 32767 65535

MEDIUMIN
T 3 -8388608 0 8388607 16777215

INT 4 -2147483648 0 2147483647 4294967295

63 63 64
BIGINT 8 -2 0 2 -1 2 -1

Float(m,d):-

-----------------
It is a floating point number that cannot be unsigned

It defines the display length(m) and the number of decimals(d).

Ex: float(10,2) which means 10 is the total number of digits including


decimals where 2 is the number of decimals

Ex: 12345678.90;

It takes 24 places and requires 2 bytes of storage.

Double(m,d):- in this data type it takes 53 places as a decimal decision. And


it requires 8 bytes of storage.

It cannot be unsigned.

Bit(m):-it is used to store the bit values into the table column.

Here m defines number of bits per value that has a range of 1 to 64.

Bool

-----------

It is used only for the true and false condition.

It is considerd numeric value 1 as true. And 0 as false.

Character/String Data Types:


Data Type Memory Range Description
Size

CHAR(n) n* n Fixed-length character string


Number of characters where n specifies the column
characters length in characters. Padded with
spaces as necessary.

VARCHAR(n) L + 1 or 2 1 to n Variable-length character string


bytes characters with a maximum length of n
overhead characters. Uses space for actual
data plus 1 or 2 bytes for
overhead.

TEXT L + 1 or 2 Up to Variable-length character string


bytes 65,535 with a maximum length of 65,535
overhead bytes characters. Used for longer
strings that exceed VARCHAR's
maximum length.

TINYTEXT L + 1 or 2 Up to 255 Variable-length character string


bytes bytes with a maximum length of 255
overhead characters. Suitable for small text
fields.

MEDIUMTEXT L + 1 or 2 Up to Variable-length character string


bytes 16,777,21 with a maximum length of
overhead 5 bytes 16,777,215 characters. Used for
medium-sized text fields.

LONGTEXT L + 1 or 2 Up to 4 GB Variable-length character string


bytes with a maximum length of 4 GB
overhead characters. Used for large text
fields.

Binary Data Types:

Data Type Memory Range Description


Size

BINARY(n) n bytes n Fixed-length binary string where n


bytes specifies the column length in bytes.
Padded with zeros as necessary.
VARBINARY(n) L + 1 or 2 1 to n Variable-length binary string with a
bytes bytes maximum length of n bytes. Uses
overhead space for actual data plus 1 or 2
bytes for overhead.

Date data types

------------------

Data Type Format Range

Description
DATE 'YYYY-MM-DD' '1000-01-01' Stores date
to '9999-12- values
31 without any
time
component.
TIME 'HH:MM' '-838:59:59' Stores time
to '838:59:59' values
without any
date
component.
DATETIME 'YYYY-MM-DD '1000-01-01 Stores both
HH:MM' 00:00:00' to date and time
'9999-12-31 values.
23:59:59'
TIMESTAMP 'YYYY-MM-DD '1970-01-01 Stores date
HH:MM' 00:00:01' UTC and time
to '2038-01- values and is
19 03:14:07' generally
UTC used for
recording
timestamps of
when a row
was inserted
or updated.
YEAR YYYY 1901 to 2155 Stores a year
(four-digit value.
format)

DDL (Data Definition Language)

----------------------------------------------

1. Create:- this command is used to create new database, tables, create


other database objects

2. Drop: existing database object or table.

3. Alter: it is used to modify the structure of an existing database object.

4. Truncate: it used to delete all rows from a table.

DML: (Data Manipulation Language)

----------------------------------------------------

1. Insert:- this command is used to add new records to a table.

2. Update:- this command is used to modify the existing records in a


table.

3. Delete:- this command is used to remove records from a table based


on specific condition

4. Lock:- it can be used to control acsses to a resource, ensuring that


only one transaction. Can access it at time preventing conflicts.
DCL (Data Control Language):-

----------------------------------------------

1. grant:- this command is used to gives specific permisions to a user in


a data abse.

This permisiion might be include the abilty to select or delete


data as well

As create or drop tables.

2. Revoke:- the revoke command is used to take away previously


granted permisions

Froma user.

TCL(Transaction Control Language)

------------------------------------------------------

1. Commit:- this command is used to perminently save the changes


made during the

Current transaction.

Once transaction is commited. Its changes become permanent


and visible

To other transactions.

2. Rollback:- if an error occurs or if the transaction needs to be canceld


for any reason

Rollback is issued to revert the database.


In simple it is used to and do the changes made during the
current

Transactions

3. Savepoint:- it is used to set a point with in a transaction who


which you can later

Rollback.

DQL(Data Query Language)

—-----------------------------

1. Select:- this commnad is used to retive data from one or more tables
in a database

Day-3:

-----------

-- Show existing databases (assuming you're already connected to your


MySQL server)

SHOW DATABASES;

-- Create a new database called CODEGNAN

CREATE DATABASE CODEGNAN;

-- Switch to the newly created database


USE CODEGNAN;

Create

-- Create a table named EMPLOYEES within the CODEGNAN database

CREATE TABLE EMPLOYEES (

EMP_ID CHAR(5),

FNAME VARCHAR(50),

LNAME VARCHAR(50),

AGE INT,

DOJ DATE,

ADDRESS TINYTEXT,

DEPT VARCHAR(20)

);

-- Show tables in the current database (CODEGNAN)

SHOW TABLES;

-- Describe the structure of the EMPLOYEES table


DESC EMPLOYEES;

-- Alternatively, show columns information for the EMPLOYEES table

SHOW COLUMNS FROM EMPLOYEES;

ALTER

-- Modify the FNAME column in the EMPLOYEES table to VARCHAR(30)

ALTER TABLE EMPLOYEES MODIFY FNAME VARCHAR(30);

-- Show columns information for the EMPLOYEES table to verify changes

SHOW COLUMNS FROM EMPLOYEES;

-- Add a new column named LOCATION of type TINYTEXT to the EMPLOYEES


table

ALTER TABLE EMPLOYEES ADD LOCATION TINYTEXT;

-- Show columns information for the EMPLOYEES table to verify changes

SHOW COLUMNS FROM EMPLOYEES;

-- Add a new column named PFID of type INT after the ADDRESS column
ALTER TABLE EMPLOYEES ADD PFID INT AFTER ADDRESS;

-- Show columns information for the EMPLOYEES table to verify changes

SHOW COLUMNS FROM EMPLOYEES--;

Rename

-- Rename the FNAME column to FIRSTNAME in the EMPLOYEES table

ALTER TABLE EMPLOYEES CHANGE FNAME FIRSTNAME VARCHAR(30);

-- Show columns information for the EMPLOYEES table to verify changes

SHOW COLUMNS FROM EMPLOYEES;

-- Rename the LNAME column to LASTNAME and change its data type to
VARCHAR(60)

ALTER TABLE EMPLOYEES CHANGE COLUMN LNAME LASTNAME VARCHAR(60);

-- Describe the structure of the EMPLOYEES table to verify changes

DESC EMPLOYEES;

drop
-- Drop the PFID column from the EMPLOYEES table

ALTER TABLE EMPLOYEES DROP COLUMN PFID;

-- Describe the structure of the EMPLOYEES table to verify changes

DESC EMPLOYEES;

-- Drop the LOCATION column from the EMPLOYEES table

ALTER TABLE EMPLOYEES DROP COLUMN LOCATION;

-- Describe the structure of the EMPLOYEES table to verify changes

DESC EMPLOYEES;

-- Rename the EMPLOYEES table to CODEGNAN_EMP

ALTER TABLE EMPLOYEES RENAME TO CODEGNAN_EMP;

-- Show tables in the current database to verify the table name change

SHOW TABLES;
Insert

-- Method 1: Insert values explicitly into all columns

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE,


DOJ, ADDRESS, DEPT)

VALUES

('E001', 'John', 'Doe', 30, '2023-01-15', '123 Main St', 'IT'),

('E002', 'Jane', 'Smith', 28, '2023-02-20', '456 Elm St', 'HR');

-- Method 2: Insert values into specific columns (not all columns need to be
specified)

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE)

VALUES

('E003', 'Michael', 'Johnson', 35),

('E004', 'Emily', 'Brown', 32);


SELECT*FROM CODEGNAN_EMP;

-- Method 3: Insert values using SELECT statement from another table or


query

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, DOJ,


ADDRESS, DEPT)

SELECT 'E005', 'William', 'Taylor', 40, '2023-05-15', '567 Cedar St', 'Sales'
UNION ALL

SELECT 'E006', 'Sophia', 'Martinez', 25, '2023-06-20', '321 Birch St',


'Operations';

SELECT*FROM CODEGNAN_EMP;

-- Method 4: Insert values using SET syntax (useful for updating existing rows
or inserting multiple rows)

INSERT INTO CODEGNAN_EMP SET EMP_ID = 'E007', FIRSTNAME = 'Daniel',


LASTNAME = 'Garcia', AGE = 33, DOJ = '2023-07-10', ADDRESS = '234 Oak
St', DEPT = 'IT';

SELECT*FROM CODEGNAN_EMP;
-- Method 5: Insert multiple rows in a single INSERT statement

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, DOJ,


ADDRESS, DEPT)

VALUES

('E008', 'Emma', 'White', 29, '2023-08-15', '567 Maple St', 'HR'),

('E009', 'Oliver', 'Lee', 31, '2023-09-20', '789 Elm St', 'Finance');

SELECT*FROM CODEGNAN_EMP;

DELETE

------------

-- Delete the record where EMP_ID is 'E001'

DELETE FROM CODEGNAN_EMP WHERE EMP_ID = 'E001';

-- Select all records from CODEGNAN_EMP table

SELECT * FROM CODEGNAN_EMP;

-- Delete records where AGE is greater than 30

DELETE FROM CODEGNAN_EMP WHERE AGE > 30;AP


-- Select all records from CODEGNAN_EMP table after first deletion

SELECT * FROM CODEGNAN_EMP;

-- Delete all records from CODEGNAN_EMP table

DELETE FROM CODEGNAN_EMP;

-- Select all records from CODEGNAN_EMP table after second deletion

SELECT * FROM CODEGNAN_EMP;

UPDATE

-------------

-- Update the ADDRESS for EMP_ID 'E001'

UPDATE CODEGNAN_EMP

SET ADDRESS = '567 Cedar St'

WHERE EMP_ID = 'E001';

-- Select all records from CODEGNAN_EMP table after update


SELECT * FROM CODEGNAN_EMP;

LOCK

---------

-- Set transaction isolation level to READ COMMITTED

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

-- Start a new transaction

START TRANSACTION;--

-- Select the record for EMP_ID 'E001' and lock it for update

SELECT * FROM CODEGNAN_EMP WHERE EMP_ID = 'E001' FOR UPDATE;

-- At this point, the record with EMP_ID 'E001' is locked for update within this
transaction.

-- Other transactions will be blocked from updating this record until the
current transaction is committed or rolled back.

-- Update the AGE column for EMP_ID 'E001'

UPDATE CODEGNAN_EMP SET AGE = 31 WHERE EMP_ID = 'E001';


-- Commit the transaction to apply changes

COMMIT;

ROLLBACK

-------------

-- Start a new transaction

START TRANSACTION;

-- Attempt to update the AGE column (example update that might fail)

UPDATE CODEGNAN_EMP SET AGE = 32 WHERE EMP_ID = 'E001';

-- Simulate an error that prevents the update from completing

-- For example, an error might occur due to a constraint violation or data


validation failure.

-- Select all records from CODEGNAN_EMP to observe the state before


rollback

SELECT * FROM CODEGNAN_EMP;


-- Rollback the transaction to undo changes

ROLLBACK;

-- Select all records from CODEGNAN_EMP after rollback to verify changes


were undone

SELECT * FROM CODEGNAN_EMP;

EXAMPLE2

--------------

-- Start a new transaction

START TRANSACTION;

-- Update the ADDRESS column for EMP_ID 'E002'

UPDATE CODEGNAN_EMP SET ADDRESS = '789 Elm St' WHERE EMP_ID =


'E002';

-- Select all records from CODEGNAN_EMP to observe changes after first


update
SELECT * FROM CODEGNAN_EMP;

-- Update the DEPT column for EMP_ID 'E002'

UPDATE CODEGNAN_EMP SET DEPT = 'Finance' WHERE EMP_ID = 'E002';

-- Select all records from CODEGNAN_EMP to observe changes after second


update

SELECT * FROM CODEGNAN_EMP;

-- Rollback the transaction to undo changes

ROLLBACK;

-- Select all records from CODEGNAN_EMP to verify changes were rolled back

SELECT * FROM CODEGNAN_EMP WHERE EMP_ID = 'E002';

SAVEPOINT

--------------

-- Start a new transaction

START TRANSACTION;
-- Update the AGE column for EMP_ID 'E001'

UPDATE CODEGNAN_EMP SET AGE = 32 WHERE EMP_ID = 'E001';

-- Set a SAVEPOINT named 'update_savepoint'

SAVEPOINT update_savepoint;

-- Update the ADDRESS column for EMP_ID 'E001'

UPDATE CODEGNAN_EMP SET ADDRESS = '456 Main St' WHERE EMP_ID =


'E001';

-- Select all records to observe changes

SELECT * FROM CODEGNAN_EMP;

-- Rollback to the SAVEPOINT 'update_savepoint'

ROLLBACK TO SAVEPOINT update_savepoint;

-- Select all records again to verify changes were rolled back

SELECT * FROM CODEGNAN_EMP WHERE EMP_ID = 'E001';


-- Commit the transaction

COMMIT;

MySQL OPERATORS

===================

My sql operators are used to perform operation on the data in a database.

These operations can be catgerized into several types.

1. Arithmetic operators

Symb Operator Description Example Query


ol

+ Addition Adds two numbers SELECT 10 + 5 AS


together. AdditionResult;<br>Result: 15

- Subtraction Subtracts the second SELECT 10 - 5 AS


number from the first SubtractionResult;<br>Result:
number. 5

* Multiplicati Multiplies two SELECT 10 * 5 AS


on numbers. MultiplicationResult;<br>Result
: 50

/ Division Divides the first SELECT 10 / 5 AS


number by the second DivisionResult;<br>Result: 2
number.

% Modulus Returns the remainder SELECT 10 % 3 AS


of the division of the ModulusResult;<br>Result: 1
first number by the
second number.
DIV Integer Divides the first SELECT 10 DIV 3 AS
Division number by the second IntegerDivisionResult;<br>Resu
number and returns lt: 3
the integer part of the
result.

^ Bitwise XOR Performs a bitwise SELECT 5 ^ 3 AS


XOR operation on two BitwiseXORResult;<br>Result:
numbers. 6

create database mydb;

use mydb;

CREATE TABLE orders (

order_id INT PRIMARY KEY,

customer_id INT,

order_date DATE,

total_amount DECIMAL(10, 2),

shipping_address VARCHAR(255),

payment_status VARCHAR(20),

delivery_status VARCHAR(20)

);
INSERT INTO orders (order_id, customer_id, order_date,
total_amount, shipping_address, payment_status, delivery_status)

VALUES

(1, 101, '2023-01-05', 150.00, '123 Main St, Anytown, USA',


'Paid', 'Shipped'),

(2, 102, '2023-01-10', 200.50, '456 Elm St, Smalltown, USA',


'Paid', 'Delivered'),

(3, 103, '2023-02-15', 75.25, '789 Oak St, Bigcity, USA', 'Pending',
'In Progress'),

(4, 104, '2023-03-20', 300.75, '101 Pine St, Hometown, USA',


'Paid', 'Delivered'),

(5, 105, '2023-04-25', 180.00, '202 Cedar St, Farawaytown, USA',


'Paid', 'Shipped');

select*from orders;

-- Increase `total_amount` by 50 for all orders

UPDATE orders SET total_amount = total_amount + 50;

-- Check updated `total_amount` for verification

SELECT * FROM orders;


-- Reduce `total_amount` by 10 for all orders

UPDATE orders SET total_amount = total_amount - 10;

-- Check updated `total_amount` for verification

SELECT * FROM orders;

-- Double the `total_amount` for order_id 1

UPDATE orders SET total_amount = total_amount * 2 WHERE


order_id = 1;

-- Check updated `total_amount` for order_id 1 for verification

SELECT * FROM orders WHERE order_id = 1;

-- Divide `total_amount` by 2 for order_id 2

UPDATE orders SET total_amount = total_amount / 2 WHERE


order_id = 2;

-- Check updated `total_amount` for order_id 2 for verification

SELECT * FROM orders WHERE order_id = 2;

-- Set total_amount to remainder of division by 100 for order_id 3

UPDATE orders
SET total_amount = total_amount % 100

WHERE order_id = 3;

Comparison operators

----------------------------------

Operator Descriptio Example


n
= Equal to WHERE
age = 30;
!= Not equal WHERE
to departmen
t_id <> 5;
> Greater WHERE
than salary >
50000;
>= Greater WHERE
than or age >=
equal to 18;
< Less than WHERE
price <
100;
<= Less than WHERE
or equal quantity
to <= 10;
<=> Null-safe WHERE
equal to name <=>
'John';
BETWEEN Between WHERE
... AND ... an age
inclusive BETWEEN
range 20 AND 30;
NOT Not WHERE
BETWEEN between price NOT
... AND ... an BETWEEN
inclusive 50 AND
range 100;
AND Logical WHERE
AND age >= 18
AND age
<= 30;

Examples

--------------

-- Equal to (=): Select orders where total_amount is equal to 200.50

SELECT * FROM orders WHERE total_amount = 200.50;

-- Not equal to (!= or <>): Select orders where payment_status is not equal
to 'Paid'

SELECT * FROM orders WHERE payment_status != 'Paid';

-- Less than (<): Select orders where total_amount is less than 100

SELECT * FROM orders WHERE total_amount < 100;

-- Less than or equal to (<=): Select orders where total_amount is less than
or equal to 150.00

SELECT * FROM orders WHERE total_amount <= 150.00;

-- Greater than (>): Select orders where total_amount is greater than 300
SELECT * FROM orders WHERE total_amount > 300;

-- Greater than or equal to (>=): Select orders where total_amount is greater


than or equal to 180.00

SELECT * FROM orders WHERE total_amount >= 180.00;

-- Null-safe equal to (<=>): Select orders where customer_id is null-safe


equal to 101

SELECT * FROM orders WHERE customer_id <=> 101;

-- BETWEEN: Select orders where total_amount is between 100 and 200

SELECT * FROM orders WHERE total_amount BETWEEN 100 AND 200;

-- NOT BETWEEN: Select orders where total_amount is not between 150 and
250

SELECT * FROM orders WHERE total_amount NOT BETWEEN 150 AND 250;

-- AND operator: Select orders where total_amount is between 100 and 200
AND payment_status is 'Paid'

SELECT * FROM orders WHERE total_amount BETWEEN 100 AND 200 AND
payment_status = 'Paid';
In operators

---------------------

Operator Example

Description

IN (...) Checks if a value WHERE department_id


matches any value in IN (1, 2, 3);
a list

NOT IN (...) Checks if a value does WHERE product_id


not match any value in NOT IN (101, 102,
a list 103);

Examples

------------

-- IN: Select orders where payment_status is 'Paid' or 'Pending'

SELECT * FROM orders WHERE payment_status IN ('Paid', 'Pending');

-- NOT IN: Select orders where payment_status is not 'Paid' or 'Pending'

SELECT * FROM orders WHERE payment_status NOT IN ('Paid', 'Pending');

Null operators

--------------------------

Operator Example
Description

IS NULL Checks if a value is WHERE email IS NULL;


NULL

IS NOT NULL Checks if a value is not WHERE phone_number


NULL IS NOT NULL;

Examples

----------------

-- IS NULL: Select orders where shipping_address is null

SELECT * FROM orders WHERE shipping_address IS NULL;

-- IS NOT NULL: Select orders where shipping_address is not null

SELECT * FROM orders WHERE shipping_address IS NOT NULL;

Logical operators

------------------------

Symbol Operator Description example

AND Logical AND Returns TRUE if SELECT * FROM


both conditions employees
are TRUE. WHERE
Otherwise, department =
returns FALSE. 'Sales' AND
salary >
50000;

OR Logical OR Returns TRUE if at SELECT * FROM


least one of the employees
conditions is WHERE
TRUE. Otherwise, department =
returns FALSE. 'Sales' OR
department =
'Marketing';

NOT Logical NOT Returns TRUE if SELECT * FROM


the condition is employees
FALSE. Otherwise, WHERE NOT
returns FALSE. department =
'Sales';

XOR Logical XOR Returns TRUE if SELECT * FROM


exactly one of employees
the conditions is WHERE
TRUE. Otherwise, department =
returns FALSE. 'Sales' XOR
department =
'Marketing';

Examples

----------------------

-- AND operator: Select orders where total_amount is between 100 and 200
AND payment_status is 'Paid'

SELECT * FROM orders

WHERE total_amount BETWEEN 100 AND 200 AND payment_status = 'Paid';

-- OR operator: Select orders where total_amount is less than 100 OR


payment_status is 'Pending'

SELECT * FROM orders

WHERE total_amount < 100 OR payment_status = 'Pending';


-- NOT operator: Select orders where payment_status is NOT 'Paid'

SELECT * FROM orders

WHERE NOT payment_status = 'Paid';

-- Emulate XOR (exclusive OR): Select orders where (total_amount is less


than 100 XOR payment_status is 'Paid')

-- This is achieved using a combination of AND, OR, and NOT operators.

SELECT * FROM orders

WHERE (total_amount < 100 AND payment_status <> 'Paid')

xOR (total_amount >= 100 AND payment_status = 'Paid');

You might also like