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

MY SQL

The document provides an overview of MySQL, covering key concepts such as data, databases, DBMS, and RDBMS, along with the Structured Query Language (SQL) used for managing relational databases. It details various SQL commands categorized into DDL, DML, DQL, DCL, and TCL, explaining their functions and providing syntax examples for creating, modifying, and querying databases. Additionally, it highlights MySQL's features, including its open-source nature and compatibility with multiple programming languages.

Uploaded by

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

MY SQL

The document provides an overview of MySQL, covering key concepts such as data, databases, DBMS, and RDBMS, along with the Structured Query Language (SQL) used for managing relational databases. It details various SQL commands categorized into DDL, DML, DQL, DCL, and TCL, explaining their functions and providing syntax examples for creating, modifying, and querying databases. Additionally, it highlights MySQL's features, including its open-source nature and compatibility with multiple programming languages.

Uploaded by

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

MYSQL

What is Data?
Data is statically raw and unprocessed information.

What is a Database?
A database is a collection of data that is organized, which is also called structured data. It can be
accessed or stored in a computer system that can stored in a tabular form .

What is called DBMS?


A database is a collection of data that is organized, which is also called structured data. It can be
accessed or stored in a computer system. It can be managed through a Database Management
System (DBMS), a software used to manage data. Database refers to related data in a structured
form.

What is called RDBMS?


 RDBMS stands for Relational Database Management Systems. A database is an organized
collection of data stored in a computer system and usually controlled by a database management
system (DBMS). The data in common databases is modeled in tables, making querying and
processing efficient.
 RDBMS stands for Relational Database Management Systems. It is a program that allows us to
create, delete, and update a relational database.
 A Relational Database is a database system that stores and retrieves data in a tabular format
organized in the form of rows and columns.
 It is a smaller subset of DBMS which was designed by E.F Codd in the 1970s. The major
DBMSs like SQL, My-SQL, and ORACLE are all based on the principles of relational DBMS.

SQL
 SQL stands for Structured Query Language.
 It is a database language used for storing, manipulating and accessing data stored in RDBMS.
 It is a standard query language for RDBMS like MySQL, SQL server, etc.
 SQL was developed by Donald D. Chamberlin, Donald C. Messerly, Raymond F. Boyce at IBM in
1970.
 It was initially called as SEQUEL (Structured English Query Language).
 In 1986, ANSI (American National Standard Institute) adopted SQL as a standard language for
RDBMS.
 SQL is a very simple, reliable and easy to learn language for RDBMS.
Characteristics of SQL
 SQL is a very simple, reliable and easy to learn language for RDBMS.
 It is specially used to perform various operations in relational database.
 It can perform various operations like create, insert, update, delete and access data a database.
 It provides high speed data access from a database.
 It provides easy and efficient facility for the manipulation of database.

MySQL
 MySQL is a most popular RDBMS based on SQL.
 It is a freely downloaded software.
 MySQL was introduced by a named, MySQL AB in 1994.
 It was developed by David Axmark, Allam Larsson, Michael Widenius.

PAGE NO:-1
 It was first released on 23rd may 1995 for personal users based on ISAM (Indexed Sequential Access
Method).
 It was acquired by Sun Micro System in 2008. • It uses SQL statements for creating, manipulating,
updating and accessing database.
 In MySQL data can be stored in the form of tables and runs virtually on cross platform like LINUX,
UNIX, WINDOWS, etc.

Features of MySQL
 It is a free open source software available freely for download.
 It provides fast, easy and reliable method of use.
 It can run on a server.
 It is used for both small and large applications.
 MySQL uses SQL commands for operation.
 It runs on cross platform.
 It works with different programming languages like C, C++, Java, Python, etc.

SQL COMMANDS AND ITS CLASSIFICATION


 SQL commands can be used not only for searching the database but also to perform various other
functions like create tables, insert data to tables, modify data, drop the table, etc.
 SQL commands are classified into following types:-
1. DDL (Data Definition Language) commands
2. DML (Data Manipulation Language) commands
3. DQL/DRL (Data Query Language)/ (Data Retrieval Language) commands
4. DCL (Data Control Language) commands
5. TCL (Transmission Control Language) commands

DDL
 DDL stands for Data Definition Language.
 It is a sub-language of SQL.
 It is used to define the structure of the tables and other objects in a database (index, view, etc.).
 It allows a user to create, modify, remove database objects like table.
The structure of database objects can be modified by using following DDL commands:
i. CREATE
ii. ALTER
iii. DROP
iv. TRUNCATE
v. RENAME

1. CREATE command
 This command is used to create database as well as database objects (table) with the specified
name.
 Syntax for creating database: -
MySQL> CREATE DATABASE <database name>;

Example for creating database: -


MySQL> CREATE DATABASE COLLEGE;
 Syntax for creating table: -

PAGE NO:-2
 A table is used to organize data in the form of rows and columns and used for both storing
and displaying records in the structure format. It is similar to worksheets in the spreadsheet
application. A table creation command requires three things:
 Name of the table
 Names of fields
 Definitions for each field
 MySQL allows us to create a table into the database by using the CREATE TABLE command.
 syntax: - create table <table name>
(
<column name 1><data type 1> (size),
<column name 2><data type 2> (size),
<column name 3><data type 3> (size),
<column name N><data type N> (size)
);
 Example: - create table science1
(
sl_no int (5),
name char (20),
roll_num varchar (15),
address text,
dob date
);

2. ALTER TABLE command


 ALTER TABLE command is used to modify or alter the structure of an existing table.
 It allows a user to add/drop a column, modify the data type of a column, rename a column
or a table.
 Add column in an existing table
 MySQL allows the ALTER TABLE ADD COLUMN command to add a new column to
an existing table
 Syntax: - alter table <table name> add column name (data type) (value);
 Example: - alter table science add aadhar_card char (20);

alter table science add aadhar_card char (20);

PAGE NO:-3
 Add multiple column in an existing table
 Syntax: - alter table <table name> add column name (data type) (value) , add column
name (data type) (value);
 Example: - alter table science add city char (20), add aadhar_card char (12);

alter table science add city char (20), add aadhar_card char (12);

 Delete a particular single column in existing table


 Sometimes, we want to remove single or multiple columns from the table. MySQL allows
the ALTER TABLE DROP COLUMN statement to delete the column from the table.
Syntax: - alter table <table name> drop column name;
Example: - alter table science drop aadhar_card;

PAGE NO:-4
alter table science drop aadhar_card;

 delete multiple column in existing table


Syntax: - alter table <table name> drop column name, drop column name;
Example: - alter table science drop aadhar_card , drop city;

alter table science drop aadhar_card, drop city;

PAGE NO:-5
 how to CHANGE/RENAME COLUMN NAME in MySQL
Syntax: - alter table <table name> change old column name new column name
(datatype)(value);
Example: - alter table science change dob date_of_birth date;

alter table science change dob date_of_birth date;

 How to MODIFY/CHANGE COLUMN DATA TYPE


Syntax: - alter table <table name> modify existing column (new datatype) (value);
Example: - alter table science modify city varchar (20);

PAGE NO:-6
alter table science modify city varchar (20);

 How to modify multiple column data type


 Syntax: - alter table <table name> modify existing column (new datatype) (value), modify
existing column (new datatype) (value);
 Example: - alter table science modify city char (20) , modify Aadhar_card varchar (15);

alter table science modify city char (20) , modify Aadhar_card varchar(15);

PAGE NO:-7
 How to change/Rename table name of existing table
 Alter table <existing table name> RENAME TO <new table name>;
 alter table science rename to G1;

3. DROP command
 Delete a particular database from existing database list from mysql
 We can delete a database using DROP DATABSE command
 syntax: - drop database <database name>;
 Example: - drop database science;

 Delete a particular table existing in a database


 MYSQL uses a Drop Table statement to delete the existing table. This statement removes the
complete data of a table along with the whole structure or definition permanently from the database
 syntax: - drop table <table name>;
 Example: - drop table science2;

PAGE NO:-8
(science2 table already exist in uniitech database)
 Use drop command

4.TRUNCATE command
 This command is used to remove all the records from a table
 Syntax: - TRUNCATE TABLE <table name>;
 Example: - TRUNCATE TABLE SCIENCE;
5. RENAME command
 This command is used to rename database objects(table)
 Syntax: - RENAME TABLE <table name> TO <new table name>;
 RENAME TABLE science1 To science2;

DML
 DML stands for Data Manipulation Language
 DML is a sub-language of SQL.
 The DML commands are used to access and manipulate data stored in an existing database.
 It is used to insert data into database table, update data of a database table and delete data from a
database table.
 Various types of DML commands are: -
(i) INSERT
(ii) UPDATE
(iii) DELETE
(iv) LOCK TABLE

PAGE NO:-9
1) INSERT command
 data insert in existing table
 The rows are added to relations(table) using INSERT command of SQL.
 Syntax: - insert into <table name> (column 1, column 2, -----------column n)
values (data1, data 2, -------------- data n);

insert into science (name, roll_num, address, date_of_birth, mark)


-> values('ramesh_behera','is23-013','nayagarh','1996-05-27',68.28),
-> ('bhagawan mahanty','is23-014','nayagarh','1996-02-21','84.23');

(ii) UPDATE command


 This command is used to update an existing value of a field or more than one field.
 It uses WHERE clause to put condition.
 Syntax: - UPDATE <table name>SET <col_name> = value WHERE<condition>;

PAGE NO:-10
 Multiple data update/change using update command
 Syntax: - UPDATE <table name>SET <col_name> = value,<col_name> = value WHERE
<condition>;
 update science set name ='sureshnayak' ,roll_num
='is23012',address='boudh',date_of_birth='1995-06-12'where mark=23.05;

PAGE NO:-11
(iii)DELETE command: -
 This command is used to delete records from a table.
 This command is used to delete one record or multiple record at a time.
 It uses WHERE clause to put condition.
 Syntax: - DELETE FROM <table name>WHERE <condition>;

PAGE NO:-12
DQL
 DQL stands for Data Query Language.
 It is also known as DRL (Data Retrieval Language).
 DQL is the sub-language of SQL.
 It is used to access data stored in a database table.
 It uses several clauses (WHERE, LIKE, IN, BETWEEN, DISTINCT, GROUP BY, ORDER BY) to
access records with certain condition.
 It has only one command: -
(i) SELECT

(i) SELECT command: -


 This command is used to access data from the database table.
 It uses several clauses (WHERE, LIKE, IN, BETWEEN, DISTINCT, GROUP BY, ORDER BY)
to access records with certain condition.
 Syntax: - SELECT <col name> FROM <table name>;
 Example: - select * from science;

 display particular columns in a table


 Syntax: - select column name, column name from table_name;
 Example: - select name, address from science;

 display particular rows in existing table


 Syntax: - select * from table_name where column name = (values);
 Example: - select * from science where name='radhikabehera';

PAGE NO:-13
 display particular rows in existing table
 Syntax: - select column name, column name from table_name where column name =
(values);
 Example: - select name, address from science where name='radhikabehera';

 using Between command

 Syntax: - select * from table_name where column name between (values 1) and (values 2);
 Example: - select * from science where mark between 70.00 and 100.00;

SELECT DISTINCT command


 This command is used to display the records of a table with distinct values.
 This command will display only one instance of the duplicate values.
 Syntax: - SELECT DISTINCT <col_name> FROM <table_name>;
 Example: -SELECT DISTINCT ROLL FROM STUDENT;

PAGE NO:-14
DCL
 DCL stands for Data Control Language.
 DCL is of SQL. a sub-language
 It is used to provide permission to the database user to control database access and manipulation of
data stored in that database.
 There are mainly two types of DCL commands:
(i) GRANT
(ii) REVOKE
(i) GRANT command
 This command is used to give user's access privileges to database.

(ii) REVOKE command


 This command is used to withdraw access privileges given with the GRANT command

TCL
 TCL stands for Transaction Control Language
 TCL is a sub-language of SQL.
 It is used to manage and control all the database transactions.
 TCL commands are used to control the changes made by DML commands.
 If the transactions are successful, then these transactions save permanently by Using COMMIT
command.
 If the transactions are unsuccessful due to some error, then these transactions can be cancelled by
using ROLLBACK command.
 Various types of TCL commands are:
(1) START TRANSACTION
(ii) COMMIT
(iii) ROLLBACK
(iv) SAVEPOINT
(v) SET TRANSACTION

(i) START TRANSACTION command


 By default, MySQL runs with AUTOCOMMIT mode enabled. This means that as soon as we
execute a statement, the changes made by the statement save permanently in the disk
 So, the changes made by the statement cannot be rolled back.
 To disable AUTOCOMMIT mode, we use the START TRANSACTION statement.
 START TRANSACTION command is used to commit the current transaction and start a new
transaction.
 Syntax: -START TRANSACTION;
 Example: -SELECT * FROM STUDENT;

(ii) COMMIT command


 This command is used to save the changes made by a transaction permanently.
 When a transaction is completed successfully, then a COMMIT command is issued.
 A COMMIT command saves the changes made by a transaction permanently and end the current
transaction.
 A committed transaction cannot be rolled back.
 Syntax: -COMMIT;
OR,
COMMIT WORK;

PAGE NO:-15
 Example: -SELECT * FROM STUDENT;

(iii) ROLLBACK command


 When a transaction is being executed, it may be executed successfully or unsuccessfully.
 If the transaction is being executed unsuccessfully, then the entire transaction is reverted
(cancelled) using the ROLLBACK statement.
 The ROLLBACK statement cancels the entire transaction and back to the beginning after the last
commit.
 A committed transaction cannot be rolled back.
 Syntax: -ROLLBACK;
OR,
ROLLBACK WORK;
 Example: -SELECT * FROM STUDENT;

(iv) SAVEPOINT command


 This command is used as a marker point in a transaction.
 It is used for semi committing a transaction.
 Since, the ROLLBACK statement cancels the entire transaction and back to the beginning after last
commit.
 So that, to rollback a transaction up to a certain point from bottom to top SAVEPOINT statement is
used.
 Syntax: -SAVEPOINT VALUE;
 example: -SAVEPOINT A;
 To remove SAVEPOINT from a transaction, RELEASE SAVEPOINT command is executed.
 Syntax: - RELEASE SAVEPOINT VALUE;
 example: -RELEASE SAVEPOINT Α;

(v) SET TRANSACTION command


 This command is used to specify properties for the current transaction.
 For example, we can specify a transaction to be read only or read write.
 Syntax: -START TRANSACTION [ READ ONLY | READ WRITE);
USE command
 After creating a database, we need to open it for use.
 USEcommand is used to open a database and allowed to perform SQL operations that database.
 Syntax: -USE <database_name>;
 Example: - Use uniitech;

DESC command/Describing all the details of existing table


 DESCRIBE means to show the information in detail. Since we have tables in MySQL, so we will
use the DESCRIBE command to show the structure of our table, such as column names,
constraints on column names, etc. The DESC command is a short form of the DESCRIBE
command. Both DESCRIBE and DESC command are equivalent and case sensitive.
 syntax: - desc <table name>;
 example: - desc science;

PAGE NO:-16
SHOW command
 SHOW command is used to display a list of existing databases on the server.
 It can also be used to display a list of existing tables in a database.
 syntax: - show databases;

DATA TYPES IN MYSQL


 A data type is a format that specifies the nature of the data to be stored in a field of the table.
 It represents what kind of value or data a field can store.
 For example: int, float, decimal, char, etc.

 Types of data type:


1. Numeric data type
2. String data type
3. Date and time data type
1. Numeric data type
 The data type which is used to store integer value as well as fractional value is called as numeric
data type.
 Different types of numeric data type are:
(i) TINYINT:
 It is used to store integer value ranges from -27 to 27-1 or 0 to 255.
 It reserves 1 byte of memory space.
(ii) SMALLINT:
 It is used to store integer value ranges from -215 to 215-1.
 It reserves 2 bytes of memory space.
(iii) MEDIUMINT:
 It is used to store integer value ranges from -223 to 223-1.
 It reserves 3 bytes of memory space.
(iv) INT:
 It is used to store integer value ranges from -231 to 231-1.
 It reserves 4 bytes of memory space.
(v) BIGINT:
 It is used to store integer value ranges from -263 to 263-1.

PAGE NO:-17
 It reserves & bytes of memory space.
(vi) FLOAT
 It is used to store fractional value
 It is used to store single precision floating point number up to 24 decimal places.
 It reserves 4 bytes of memory space.
(vii) DOUBLE:
 It is used to store fractional value.
 It is used to store double precision floating point number up to 53 decimal places.
 It reserves 8 bytes of memory space.
(viii) DECIMAL:
 It is used to store unpacked floating-point number.
 It reserves 5 to 17 bytes of memory space.
2. String data type
 The data type which is used to store string value is called as string data type.
 A string is a set of characters written within single quote.
Types of string data type:
(i) CHAR (size):
 It is used to store string value of fixed length.
 It can hold maximum 255 (28-1) no. of characters.
 It uses static memory allocation.
 It is 50% faster than VARCHAR.
(ii) VARCHAR (size):
 It is used to store string value of variable length.
 It can hold maximum 65,535 (216-1) no. of characters.
 It uses dynamic memory allocation.
 It is slower than CHAR
(iii) TINYTEXT:
 It can hold a maximum of 28-1 characters in a string.
(iv) TEXT:
 It can hold a maximum of 216-1 characters in a string.
(v) MEDIUMTEXT:
 It can hold a maximum of 224-1 characters in a string.
(vi) LONGTEXT:
 It can hold a maximum of 232-1 characters in a string

3. Date and time data type


 The data type which is used to store date and time value in YYYY-MM-DD HH:MM:SS format is
called as date and time data type.
 Types of date and time data type:
(i) DATE ( ):
 It is used to store date values into a field in YYYY-MM-DD format.
(ii) TIME ( ):
 It is used to store time values into a field in HH:MM:SS format.
(iii) DATETIME ( ):
 It is used to store both date and time values in YYYY-MM-DD HH:MM: SS format.
(iv) TIMESTAMP ( ):
 It is used to store both date and time values in YYYYMMDDHHMMSS format.
(v) YEAR ():
 It is used to store year values in 2-digit format (YY) or in 4-digit format (YYYY).

PAGE NO:-18
OPERATORS IN MYSQL
 Operators are special symbols or keywords used to perform different operations on columns of a
table to produce some result.
 Different types of operators used in MySQL are:
(i) Arithmetic operators:
 These operators are used to perform arithmetic operations like addition, subtraction, multiplication,
division and remainder.
 Arithmetic operators can be used through SELECT command.
OPERATOR
Addition
Subtraction
Multiplication
 Syntax: - SELECT <expression><arithmetic operator><expression> [FROM <table name>]
(WHERE <condition>]:
 Example:- SELECT name,mark + 20 from science1;

i) Comparison operators/ Relational operators


 These operators are used to compare two or more values of a table.
 If the comparison is false, then the result is zero (0) and if the comparison is true, then the result is
non-zero.
 These operators are also called as relational operators.
OPERATOR DESCRIPTION
= Equal to
> Greater than
< Less than
>= Greater than equal to
<= Less than equal to
< > or != Not equal to
 Syntax: - mysql> SELECT <column name> FROM <table name>WHERE <expression>
<comparison operator> <expression>;

PAGE NO:-19
 Example : -

(iii) Logical operators


 These operators are used to perform logical operations on a table.
OPERATOR DESCRIPTION
AND Logical AND
OR Logical OR
NOT Logical NOT

 Syntax: - SELECT <column_name> FROM <table_name> WHERE <expression> <logical


operator><expression>;
 Example:

PAGE NO:-20
(iv) BETWEEN operator

 The BETWEEN operator/clause is used to show a range of values of the specified column,
including the lower and the upper values.
 Syntax: -SELECT <column name> FROM <table name> WHERE <column name> BETWEEN
<value> AND <value2>;

(v) IN operator
 The IN operator/clause is used to checks a value within a List (set of values separated by commas).
 If the value is matched, then it will return the matching rows.
 Syntax: - SELECT <column name> FROM <table name>WHERE <column name> IN <(valuel,
value2,)>

PAGE NO:-21
(VI) LIKE operator
 The LIKE operator/clause is used to search data, by matching some pattern.
 It is used for pattern matching of string data using wildcard characters % and Percent sign (%) used
to match any sequence of characters.
 Underscore ( ) used to match a single character.
 Syntax -SELECT <column name> FROM <table name> WHERE <column name? LIKE
<pattern>;

PRIMARY KEY
 The primary key of a table is a column or a group of columns that uniquely identifies a row/ record
of a table. Therefore, no two rows of a table can have the same primary key value.
 primary key add in table creation

MySQL> use uniitech;


Database changed
MySQL> create table arts
-> (
-> name char (20),
-> roll_num varchar (15) PRIMARY KEY,
-> address text,
-> dob date
-> );

 multiple primary key use at the time of create table

CREATE TABLE Result


(
CHSE_Roll CHAR(9),
Name VARCHAR(36),
Pass_Yr DATE,
Mark DECIMAL (4,2),
PRIMARY KEY (CHSE_Roll, Pass_Yr));

PAGE NO:-22
 How to insert primary key in existing table
Step: -1 first remove primary key from existing table
Syntax: - alter table (table name) drop primary key;
Example: - alter table Result drop primary key;

Step: -2 Then change NULL status ‘YES’


Syntax: - alter table (table name) modify column name data type null;
Example: - alter table result modify CHSE_Roll char (9) null;

PAGE NO:-23
Step: -3 Next add multiple primary key in existing table
Syntax: - alter table result add primary key (column name 1, column 2, -----------, column N);
Example: - alter table result add primary key (CHSE_Roll, Mark);

Tables data can be display in ascending order


 To Display a List of all the address in the alphabetical ascending order
 Syntax: - select * from table_name order by column name;
 Example: - select * from science order by address;

select * from science order by address;

Table’s data can be display in descending order


 To Display a List of all the address in the alphabetical ascending order
Syntax: - select * from table_name order by column name desc;

PAGE NO:-24
Example: - select * from science order by address desc;

select * from science order by address desc;

How to display NULL status “NO”. if a column have a NULL value status show NO .then we
understand that without insert the value we cannot execute

PAGE NO:-25
Find NULL value in particular column

NULL means a value that is unavailable, unassigned, unknown or inapplicable. NULL is not the same as
Zero or a space or any other character. In a table NULL is searched by using IS NULL keyword
To handle such situation MySQL provides three operators

 IS NULL: operator returns true if column value is NULL.


Syntax: - SELECT * FROM table name WHERE column name IS NULL;
Example: - SELECT * FROM Student WHERE Name IS NULL;
 IS NOT NULL: operator returns true if column value is not NULL.NOT NULL values in a table
can
be searched using IS NOT NULL.
Syntax: - SELECT * FROM table name WHERE column name IS NULL;
Example: - SELECT * FROM Employee WHERE Salary IS NOT NULL;
 <=>: operator compares values, which (unlike the = operator) is true even for two NULL values.

DATABASE TRANSACTION
 A small unit of logical work performed on database is known as transaction.
 A database transaction is any operation made on a database.
 A transaction is said to be done when it performs operations like INSERT, UPDATE, DELETE,
SELECT, etc.
 When a transaction is successful, then any changes made by the transaction in database are
permanent otherwise the database remains unchanged.

STATES OF A TRANSACTION
 Every transaction in a database goes through a series of logical steps, known as states of
transaction.

The following are the various states of a transaction:


1. Begin 2. Active
3. Partially committed 4. Failed
5. Committed
6. Aborted 7. End

1. Begin
 When a transaction is initialized, it enters to begin state.
 Example: - inserting an ATM card into ATM machine.

PAGE NO:-26
2. Active
 After starting a transaction it enters to active state, to get ready for the operation.
 Example: - entering pin in ATM machine to connect to the bank.
3. Partially committed
 When a transaction executes its final operation but it is not completed yet, then it enters to partially
committed state.
 When a partially committed transaction completed successfully, then it enters to committed state
and then the transaction ends.
 When a partially committed transaction is unsuccessful, then it enters to failed state.
4. Failed
 When a transaction is unsuccessful in partially committed state, then it enters to failed state.
 A transaction in active state may also enter to failed state when it is unable to proceed further.
 once a failed state transaction a recovery mechanism is required to recover the database.
 Example of some recovery mechanism are:-
(1) Forward recovery
(ii) Backward recovery, etc.
5. Committed
 When a transaction is successful in partially committed state, then it enters to committed state.
 A committed transaction changes database permanently.
 Once a transaction is committed it cannot be rolled back.
6. Aborted
 A transaction enters to aborted state when it is failed.
 If any abnormal condition arises during transaction, then it enters to aborted state.
 An unsuccessful transaction goes through aborted state to end state.3
 To recover a database from aborted state we must kill the transaction or restart the transaction.
7. End state
 A transaction enters to end state after the transaction is completed successfully or unsuccessfully.
 An end state transaction disconnects the client from the server.

ACID PROPERTIES OF TRANSACTION


 A transaction is a small unit of logical work performed on a database.
 A transaction in a database system must maintain accuracy, completeness and data integrity.
 Every transaction in database must satisfy the following four properties:
(i) A-Atomicity
(ii) C-Consistency
(iii) I-Isolation
(iv) D-Durability
Atomicity
 Atomicity property of a transaction ensures that all operations within a work unit are successfully
completed and the changes made by the transaction must be permanent.
 If the transaction is failed, then the database must be rolled back to previous state. Each transaction
must have atomic value.
Consistency
 The consistency property of the transaction ensures that a database must be consistent before and
after transaction.
 For example, suppose you have 10000 rupees in your bank account before transaction, after doing
transaction of 2000 rupees successfully, now you have 8000 rupees in your bank account. That
means your transaction is in consistent state.
Isolation

PAGE NO:-27
 The isolation property of transaction ensures that, transaction must be operated independently and
transparent to each other.
 In database, multiple transactions can be performed without interfering with each other.
Durability
 This property of transaction ensures that the effect of a successfully committed transaction persist
even if in system failure.

FUNCTIONS IN MYSQL
 MySQL uses several types of functions to perform some operation (e.g. manipulation. calculation,
etc) on data stored in database.
 There are two types of functions in MySQL:
1. Single Row functions
2. Multiple Row functions

1. Single Row functions


 Single row functions are used to perform operation on single value of a table to return a single
value as result.
 They can accept one or more arguments but return only one result per row.
 These functions are used with SELECT command to return the result.
 Various types of single row functions are:-
(1) String functions
(ii) Mathematical functions/Numeric functions
(iii) Date & time functions

(i) String functions


 String functions are used to perform operation on characters or string values. • These functions are
used to manipulate string value stored in a database table.
 they return either a character, a string or a numeric value as a result.

 Various types of string functions are


I. ASCII ( )
II. CHAR ( )
III. CONCAT ( )
IV. CONCAT( )
V. INSTR ( )
VI. LCASE ( ) /LOWER ( )
VII. UCASE ( ) / UPPER( )
VIII. LTRIM( )
IX. RTRIM ( )
X. TRIM ( )
XI. SUBSTR( )
XII. MID( )
XIII. REVERSE ( )
XIV. LEFT( )
XV. RIGHT( )

a) ASCII ( )
 ASCII stands for American Standard Code for Information Interchange .
A to Z-65 to 90 a to z -97 to 122.

PAGE NO:-28
 This function is used to return the ASCII value of the left most character of a string.
 Syntax -SELECT ASCII (string);
 Example: - SELECT ASCII(‘sid’);

 If it takes an empty string, then it returns zero. SELECT ASCII(' ');

 If it takes an NULL argument, then it returns NULL


Example : - SELECT ASCII (NULL);

b) CHAR ( )
 This function is used to return a string of characters by taking one or more ASCII values as
argument.

PAGE NO:-29
 Syntax: - SELECT CHAR (N1, N2, N3,……. Using ascii);
 Example - select char (115,105,100 using ascii);

c) CONCAT ( )
 This function is used to concatenate strings.
 Syntax: - SELECT CONCAT (strl, str2, ………);
 Example: -select concat('sidhartha','nayak');

d) CONCAT_WS ( )
 This function is used to concatenate strings with a specified separator
 Syntax: - SELECT CONCAT_WS (separator, stri, str2,…..);
 Example: - select CONCAT_WS(' _ ', 'sidhartha', 'nayak');

(e) INSTR( )
 This function is used to return the first occurrence of a substring on a string.
 Syntax: - SELECT INSTR (string, substring);
 Example: - SELECT INSTR (SUNIL', 'NI');

(f) LOCATE( )
 This function is similar to INSTR() but, the order of arguments are reversed.
 This function is also used to return the first occurrence of a substring on a string

PAGE NO:-30
 Syntax: - SELECT LOCATE (substring, string):
 Example: - SELECT LOCATE ('NI', 'SUNIL');

(g) LCASE()/LOWER( )
 This function is used to convert all the characters of a string into lowercase letter.
 Syntax: - SELECT LCASE (string);
or,
SELECT LOWER (string):
 Example: - SELECT LCASE ('SUNIL');

 Example: - SELECT LOWER ('SUNIL');

(h) UCASE( )/UPPER ( )


 This function is used to convert all the characters of a string into uppercase letter.
 Syntax: - SELECT UCASE (string);
 Syntax: - SELECT UPPER (string);

 Example: - SELECT UCASE ('sunil');

PAGE NO:-31
 Example: - SELECT UPPER ('sunil');

(i) LENGTH ( )
 This function is used to return the length of a string, where space is also count as one character.
 Syntax: - SELECT LENGTH (string);
 Example: - SELECT LENGTH ('hello world');

(j) LTRIM ( )
 This function is used to remove blank spaces from the left side of a string.
 Syntax: - SELECT LTRIM (string);
 EXAMPLE : - SELECT LTRIM (' SUNIL');

(k) RTRIM ( )
 This function is used to remove blank spaces from the right side of a string
 Syntax: - SELECT RTRIM (string);
 EXAMPLE: - SELECT RTRIM ('SUNIL ');

(l) TRIM ()
 This function is used to remove blank spaces from both side of a string.
 Syntax: - SELECT TRIM (string);
 Example: - SELECT TRIM(' GFG ');

PAGE NO:-32
(m) SUBSTR ( )
 This function is used to return a substring from the current string, specified by start and end index.
 Syntax: - SELECT SUBSTRING (string, start index, end index);
 Example: -SELECT SUBSTRING ('SUNIL', 2,4);

(n) MID ( )
 This function is same as SUBSTR ( ).
 This function is also used to return a substring from the current string, specified by start and end
index.
 Syntax: - SELECT MID (string, start index, end index);
 Example: - SELECT MID ('SUNIL', 2,4);

(0) REVERSE()
 This function is used to return the reverse of a string.
 Syntax: - SELECT REVERSE (string);
 Example: - select reverse ('sidhartha');

(p) LEFT( )
 This function is used to return 'n' number of characters from the left side of a string.
 Syntax: SELECT LEFT (string, n);
 Example: - SELECT LEFT (SUNIL, 3);

PAGE NO:-33
(q) RIGHT( )
 This function is used to return 'n' number of characters from the right side of a string.
 Syntax: -SELECT RIGHT (string, n);
 Example: - SELECT RIGHT (SUNIL', 3);

Mathematical functions/Numeric functions


 These functions are used to perform mathematical operation on numeric values and return numeric
values as result.
 Various types of mathematical functions are:-
(a) POW()/POWER()
(b) ROUND(n, d)
(c) ROUND(n)
(d) TRUNCATE()
(e) ABS()

(a) POW ( )/POWER ( )


 This function is used to return the power of a number raised to another number.
 Syntax: - SELECT POW (x,y);
OR
SELECT POWER (X,Y);

 Example: - select pow (2,3);


Or
select power (2,3);

PAGE NO:-34
(b) ROUND(n, d)
 This function is used to return the round up value of a number up to 'd' decimal places.
 Syntax: - SELECT ROUND (n ,d);
 Example: - SELECT ROUND (4.726, 1);

 SELECT ROUND (4.752, 1);

c. ROUND(n)
 This function is used to return a nearest integer value of a floating-point number.
 Syntax: - SELECT ROUND (n):
 Example: - SELECT ROUND (4.726);

 SELECT ROUND (4.345);

PAGE NO:-35
(d) TRUNCATE( )
 It is a mathematical function that returns a number truncated to 'd' decimal places.
 If d=0, then no fractional part.
 If d = -ve, then 'd' digits left of the decimal point of the value 'n' becomes 0.
 If d= +ve, then it will display the result up to 'd' decimal by truncating the rest part.
 Syntax: - select truncate(n,d);
 Example :- select truncate (426.239,2);

PAGE NO:-36
(e) ABS( )
 This function is used to return the absolute value or positive value of a number.
 Syntax: - SELECT ABS (n);
 Example: - SELECT ABS (-10);

(iii) Date and time function


 The functions that are used to manipulate date and time values are called as date and time
functions.
 In MySQL default date and time format is: YYYY-MM-DD and HH:MM:SS
 Various date and time functions used in MySQL are:
(a) CURDATE()
(b) DATE()
(c) MONTH()
(d) DAYOFMONTH( )
(e) DAYOFWEEK()
(f) DAYOFYEAR( )
(g) NOW( )
(h) SYSDATE()
(i) DAYNAME()

PAGE NO:-37
(a) CURDATE( )
 This function is used to return the current date of a system in YYYY-MM-DD format.
 Syntax: - SELECT CURDATE();

(b) DATE
 This function is used to return the date from date or date & time expression
 Syntax: - SELECT DATE (expression);
 Example: - SELECT DATE (2020-04-23 10:30:07);

(c) MONTH ( )
 This function is used to return the number of months of the date argument,
 The range of month is from 0 to 12.
 Syntax: - SELECT MONTH (date);
 Example: -SELECT MONTH (‘2020-04-23’);

(d) DAYOFMONTH( )
 This function is used to return the day of the month of the date argument.
 Range of the day of the month is from 0 to 31.
 Syntax: - SELECT DAYOFMONTH (date);
 Example: - SELECT DAYOFMONTH ('2024-03-23');

(e) DAYOFWEEK( )
 This function is used to the day of the week of the date argument.
 Range of the days of a week is from 1 to 7. As 1 for Sunday, 2 for Monday and so on.

PAGE NO:-38
 Syntax: -SELECT DAYOFWEEK (date);
 Example: - SELECT DAYOFWEEK('2024-03-23');

(f) DAYOFYEAR( )
 This function is used to return the day of a year of the date argument.
 Its ranges is from 1 to 366.
 Syntax: - SELECT DAYOFYEAR (date);
 Example: - SELECT DAYOFYEAR ('2024-12-31');

(g) DAYNAME( )
 This function is used to return the day name of the date argument.
 Syntax: - SELECT DAYNAME (date);
 Example: - SELECT DAYNAME ('2020-04-23');

(h) NOW( )
 This function is used to return the current date and time in YYYY-MM-DD HH:MM:SS format,
when used as a string.
 This function is used to return the current date and time in YYYY-MM-DD- HH:MM:SS format,
when it is used as a decimal number.
 Syntax: - SELECT NOW();

PAGE NO:-39
(i) SYSDATE( )
 This function is used to return the same value as NOW().
 This function returns current date and time when the function executes Where as, NOW() returns a
constant time.
 Syntax: -SELECT SYSDATE();
 Example: -SELECT SYSDATE();

 SYSDATE() does not get pause but the NOW() get pause by using SLEEP(n) function.
 Example: - SELECT SYSDATE(), SLEEP (20), SYSDATE();

2. Multiple Row Functions

 Multiple row functions are used to perform operation on multiple rows of a table to return a single
value as result.
 These functions are also called as aggregate functions or group functions.
 By using these functions we can perform operation on multiple rows at a time.
 Various types of aggregate functions are:-

(a) MAX()
(b) MIN()
(c) SUM()
(d) AVG()
(e) COUNT(*)
(f) COUNT(DISTINCT)

(a) MAX( )
 This function is used to return the maximum value of the numeric expressions on a column.
 It is used with SELECT command.
 It takes one argument as column name.
 Syntax: - SELECT MAX(column name) FROM <table_name>;
 Example: - select * from science;

PAGE NO:-40
 select MAX(mark) from science;

(b) MIN()
 This function is used to return the minimum value of the numeric expressions on a column.
 It is used with SELECT command.
 It takes one argument as column name.
 Syntax: - SELECT MIN(column name) FROM <table name>;
 Example:- select * from science;

 SELECT MIN(MARK) FROM science;

PAGE NO:-41
(c) SUM( )
 This function is used to return the sum of values of the numeric expressions on a column.
 It is used with SELECT command.
 It takes one argument as column name.
 Syntax: - SELECT SUM (column name) FROM <table_name>:
 Example: - select * from science;

 select sum(mark) from science;

(d) AVG( )

 This function is used to return the average value of the numeric expressions on a column.
 It is used with SELECT command.
 It takes one argument as column name.
 Syntax: - SELECT AVG(column name) FROM <table _name>;
 Example: - select avg(mark) from science;

PAGE NO:-42
(e) COUNT (*)
 This function is used to count total number of rows or records satisfying certain condition in
WHERE clause.
 This function is used to count total number of not null values on a column.
 It is used with SELECT command.
 Syntax - SELECT COUNT(*) FROM <table name>;
 Example: -

 select count(*) from science;

(f) COUNT(DISTINCT)
 This function is used to count total number of distinct records or rows on a table.
 It eliminates duplicate values from counting total number of records of a table, according to
specified column.
 It is used with SELECT command.
 Syntax: - SELECT COUNT(DISTINCT column name) FROM <table_name>;
 Example: - SELECT COUNT(DISTINCT MARK) FROM science;
NOTE: All the aggregate functions do not take null values into consideration.

PAGE NO:-43
JOIN STRATEGY

 A join is a technique used to access and display data from multiple tables at a time by using
MySQL statement.
 It allows to display records from multiple tables by using different join strategies.
 Various types of join strategies are:-
1. Self join/Natural join
II. Equi join/Inner join
III. Cartesian product/Cross join

Self Join/Natural Join

 When a table joined to itself, then it is called self join.


 represents unitary relationship.
 Example:- SELECT *FROM employee NATURAL JOIN department;

Table-1: Department
Create Table department
(
DEPT_NAME Varchar(20),
MANAGER_NAME Varchar(255)
);

INSERT INTO department(DEPT_NAME,MANAGER_NAME) VALUES ( "IT", "ROHAN");


INSERT INTO department(DEPT_NAME,MANAGER_NAME) VALUES ( "SALES", "RAHUL");
INSERT INTO department(DEPT_NAME,MANAGER_NAME) VALUES ( "HR", "TANMAY");
INSERT INTO department(DEPT_NAME,MANAGER_NAME) VALUES ( "FINANCE", "ASHISH");
INSERT INTO department(DEPT_NAME,MANAGER_NAME) VALUES ("MARKETING",
"SAMAY");

PAGE NO:-44
Table-2: Employee
Create Table employee
(
EMP_ID int,
EMP_NAME Varchar(20),
DEPT_NAME Varchar(255)
);

INSERT INTO employee(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (1, "SUMIT", "HR");


INSERT INTO employee(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (2, "JOEL", "IT");
INSERT INTO employee(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (3, "BISWA",
"MARKETING");
INSERT INTO employee(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (4, "VAIBHAV", "IT");
INSERT INTO employee(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (5, "SAGAR","SALES");

PAGE NO:-45
SELECT *FROM employee NATURAL JOIN department;

II. Equi Join/Inner Join


 The join which is used to access data from two or more tables that must have a common field in
both, is called as equi join.
 Syntax: - SELECT <column name> FROM <tablel>, <table2> WHERE <tablel>.common field
relational operator><table2>.common_field;

PAGE NO:-46
III. CARTESIAN PRODUCT/CROSS JOIN

 A Cartesian product of two tables is a table obtained by pairing up each row of one table with each
row of another table.
 If a table has 'm' rows and another table has 'n' rows, then the Cartesian product of two table has
'm*n' rows.
 Syntax: - SELECT <tablel>.column_name, <table2>.column name FROM <table 1> CROSS JOIN

<table2>;
 Example: - SELECT * FROM CUSTOMER CROSS JOIN ORDERS;

PAGE NO:-47
PAGE NO:-48
UNION
 Union of two tables is the combination of records from those tables.
 Union operation combines two SELECT statements of two tables that have same number of
columns having same data type.
 Union does not display any duplicate rows unless ALL is specified with it.
 Syntax: - SELECT <column_name> FROM <tablel> UNION SELECT <column_name> FROM
<table2>;
EXAMPLE

CREATE TABLE Emp1


(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);

 INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)


-> VALUES (1, 'Shubham', 'India','23','738479734'),
-> (2, 'Aman ', 'Australia','21','436789555'),
-> (3, 'Naveen', 'Sri lanka','24','34873847'),
-> (4, 'Aditya', 'Austria','21','328440934'),
-> (5, 'Nishant', 'Spain','22','73248679');

 SELECT* FROM Emp1;

PAGE NO:-49
 CREATE TABLE Emp2
(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);

INSERT INTO Emp2 (EmpID, Name,Country, Age, mob)


VALUES (1, 'Tommy’, ‘England','23','738985734'),
(2, 'Allen’, ‘France','21','43678055'),
(3, 'Nancy', 'India','24','34873847'),
(4, 'Adi’, ‘Ireland','21','320254934'),
(5, 'Sandy', 'Spain','22','70248679');

SELECT * FROM Emp2;

PAGE NO:-50
 SELECT * FROM Emp1 UNION SELECT * from Emp2;

CLAUSES USED WITH SELECT COMMAND


 Some of the clauses used with SELECT command are
1. WHERE clause
2. ORDER BY clause
3. GROUP BY clause
4. HAVING clause
5. BETWEEN clause
6. IN clause
7. LIKE clause

1. WHERE clause
 This clause is used to provide certain condition on individual records of a table
 This clause is used with SELECT command, UPDATE command, DELETE command to provide
some condition.
 Syntax of WHERE clause used with SELECT command:
 SELECT <column name> FROM <table name> WHERE <condition>;
 Syntax of WHERE clause used with UPDATE command
 UPDATE <table name> SET <column name>= value WHERE <condition>;
 Syntax of WHERE clause used with DELETE command:
 DELETE FROM <table name> WHERE <condition>;

2. ORDER BY clause
 This clause is used to arrange the records in ascending or descending order.
 By default, this clause arranges the records in ascending order.
 It is used with SELECT command.

PAGE NO:-51
 Syntax: - select * from table_name order by column name;
 Example: - select * from science order by address;

select * from science order by address;

Table’s data can be display in descending order


 To Display a List of all the address in the alphabetical ascending order
Syntax: - select * from table_name order by column name desc;
Example: - select * from science order by address desc;

PAGE NO:-52
select * from science order by address desc;

GROUP BY clause
 This clause is used to divide the records into groups according to the value of a specified column.
 This clause is used with SELECT command
 Syntax: -SELECT <column_name>, group_function FROM <table name> [WHERE <condition>]
GROUP BY <column_name>;
 Example: - select address, count(*) from science group by address;

4. HAVING clause

PAGE NO:-53
 This clause is used with GROUP BY clause to put some condition on individual groups. not on
individual records,
 This clause is used with SELECT command
 Syntax: - SELECT <column name>, group function FROM <table name> GROUP BY <column
name> HAVING <condition>;
 Example: -
CREATE TABLE Employee1
(
Employee Id int,
Name varchar(20),
Gender varchar(20),
Salary int,
Department varchar(20),
Experience varchar(20)
);

INSERT INTO Employee1 (EmployeeId, Name, Gender, Salary, Department, Experience)


-> VALUES (5, 'Priya Sharma', 'Female', 45000, 'IT', '2 years'),
-> (6, 'Rahul Patel', 'Male', 65000, 'Sales', '5 years'),
-> (7, 'Nisha Gupta', 'Female', 55000, 'Marketing', '4 years'),
-> (8, 'Vikram Singh', 'Male', 75000, 'Finance', '7 years'),
-> (9, 'Aarti Desai', 'Female', 50000, 'IT', '3 years');

 SELECT Department, sum(Salary) as Salary FROM employee1 GROUP BY department;

PAGE NO:-54
5. BETWEEN clause
 The BETWEEN clause is used to show a range of values of the specified column, including the
lower and the upper values.
 Syntax :- SELECT <column name> FROM <table name> WHERE <column name> BETWEEN
<value> AND <value 2>;
 Example: - select name , Department from Employee1 where Salary between 40000 AND 60000;

(i) IN clause
 The IN clause is used to checks a value within a List (set of values separated by commas)
 If the value is matched, then it will return the matching rows.
 Syntax: - SELECT <column name> FROM <table name> WHERE <column name> IN <(valuel,
value2-----value N);
 Example:
(ii) LIKE clause
 The LIKE clause is used to search data, by matching some pattern.
 It is used for pattern matching of string data using wildcard characters % and Percent sign (%)
used to match any sequence of characters.
 Underscore( ) used to match a single character.
 Syntax:-SELECT <column name> FROM <table name> WHERE <column name> LIKE
<pattern>;

PAGE NO:-55

You might also like