*** MYSQL Notes ***
Index
Sr no Date Topics Page
No
1 18/12/2024 MYSQL INTRODUCTION 2
2 Data Types 4
3 Operators 8
4 19/12/2024 Sublanguages 12
5 Constraints 18
6 Clauses 26
7 23/12/2024 Joins 25
8 Normalization 28
9 24/12/2024 Subqueries 29
10 Mysql Object 33 To
37
Tables,Views,Sequences,Synonyms,Index xMaterialzied views
11 26/12/2024 Stored Procedures 38
12 Functions 40
13 Cursors 44
14 Triggers 45
1|Page
❖ Data
1.Data is a collection of raw facts(numbers,digits,symbols....)
2.Data never gives meaningful statements.
❖ Information
1.Information is used to processing the data.
2.Information gives meaningful statements.
❖ Database
1.Database is a one type of software.
2.The purpose of Database is to store interrelated data permanently.
3.Database store the data in the form of tables.
4.Table is a collection of rows and columns.
5.Rows are records and columns are fields.
6.By using SQL we can communicate with Database and perform operations by using queries.
7.There are 2 types of datatypes.They are
1.OLTP(ONLINE TRANSACTION PROCESSING)
to store day to day transactional data
Ex: Banking transactions
➢ Retail sales data
➢ Inventory management systems
2.OLAP(ONLINE ANALTICAL PROCESSING)
to store historical data
Ex: Data warehouses
➢ Business intelligence systems
➢ Sales trend analysis
2|Page
❖ MySQL
1.Mysql is a database/rdbms product.
2.The purpose of MySQL is to store interrelated data permanently.
❖ DBMS
1.DBMS stands for database management system.
2.DBMS is a one type of software.
3.The purpose of DBMS is to create the data and manage the data.
❖ RDBMS
1.RDBMS stands for relational database management system.
2.RDBMS is the enhanced version of DBMS.
❖ ORDBMS
1.ORDBMS stands for object relational database management system.
2.ORDBMS is a combination of oops and RDBMS.
Difference between DBMS and RDBMS
SNO KEY DBMS RDBMS
1. Definition DBMS stands for database RDBMS stand for Relatinal databse management
management system system
2. Data storage Data is stored as file Data is stored as tables
3. Data access In DBMS each data elements are In RDBMS multiple data elements are
to be accessed individually. to be accessed at same time
4. Relationship There is no relationship between Data is present in multiple tables which can be
3|Page
data in DBMS related to each other
5. Normalization Normalization cannot be achieved Normalization can be achieved
6. Data quantity DBMS deals with small quantity of data RDBMS deals with large quantity of data
7. Data Redundancy Data Redundancy is common in DBMS Data Redundancy can be reduced using keys
and
indexes in RDBMS
8. User DBMS supports single user at a time RDBMS supports multiple users at a time
**************************************************************************************************
❖ Datatypes
1.Datatypes determines what type of value we can store.
2.There are 3 types of datatypes.They are
➢ Numeric Types
➢ Date & Time Types
➢ String Types
1.Numeric Types
Numeric Types are divided into 2 types.They are
➢ Integer Types
➢ Floating-point types
1.Integer Types
Integer Types stores both positive and negative values without decimal.
Ex
sal int(200)
300
4|Page
2.Floating-point Types
Floating-point Types stores both positive and negative values with decimal and without decimal.
p =======> precision ====> Total number of digits
s =======> scale ========> Number of digits after decimal
Examples
sal decimal(7,2)
50000.00
sal float(6,3)
999.129======>999.129
sal double(6,3)
999.129======>999.129
sal float(6,3)
999.0009======>999.001
sal decimal(6,3)
999.0009======>error
**************************************************************************************************
Integer Types
Type length Minimum value Maximum value Minimum size Maximum size in Bytes
TINYINT 1 -128 127 0 255
SMALLINT 2 -32768 32767 0 65535
MEDIUMINT 3 -8388608 8388607 0 16777215
INT 4 -2147483648 2147483647 0 4294967295
5|Page
BIGINT 8 -9223372036854775808 9223372036854775807 0 18446744073709551615
Floating-point Types
Type Length (Bytes) Minimum Value Maximum Value
--------------------------------------------------------------------------------------------------- ------------------------------------------
FLOAT 4 -3.402823466 × 10³⁸ 3.402823466 × 10³⁸
DOUBLE 8 -1.7976931348623157 × 10³⁰⁸ 1.7976931348623157 × 10³⁰⁸
**************************************************************************************************
DATE AND TIME TYPES
DATE AND TIME TYPES is used to store date and time.
TYPES DESCRIPTION DISPLAY FORMAT RANGE
DATE use when you need only date information YYYY-MM-DD '1000-01-01' TO '9999-12-31'
TIME use when you need only time information HH:MM:SS -838:59:59 TO 838:59:59
DATETIME use when you need values containing both YYYY-MM-DD HH:MM:SS '1000-01-01 00:00:00' TO
date and time information 9999-12-31 23:59:59
TIMESTAMP values are converted from the current zone YYYY-MM-DD HH:MM:SS '1970-01-01 00:00:01' UTC
to utc while storing and converted back from TO
utc to the current time zone when retrived '2038-01-19 03:14:07' UTC
(automatically updated when a row is modified)
Universal Coordinated Time
**************************************************************************************************
6|Page
3.STRING TYPES
STRING TYPES is used to store multiple characters enclosed with single or double quotes.
TYPES DESCRIPTION RANGE
CHAR CHAR recommended to use fixed length data 255 characters
VARCHAR VARCHAR recommended to use variable length 65,535 characters data.
BLOB Large Binary Data(videos,images,Audios..) 65,535 bytes(Binary Large Object)
ENUM List of possible values 65,535 Distinct values
SET List of possible values 65,535 values
Examples
Gender char(1)
name varchar(30)
Bhavadeesh
OPTION ENUM('one,'two','three')
OPTION SET('one,'two','three')
Note:current version of MySQL is 8.x
**************************************************************************************************
7|Page
❖ MYSQL INSTALLATION
1.go to google and type mysql===>go to downloads after clicking first link===>mysql community downloads==>mysql
installer for windows==>click on second link download (303.1 mb)==>
click on no thanks just start my downloads===>open the downloaded file ==>wait for the app to get install==>select
custom==>next
2.mysql servers==>mysql server==>mysql server 8.0==>mysql server 8.0.38x64==>drag to be installed
3.applications==>mysql workbench==>mysql workbench 8.0==>mysql workbench 8.0.37x64==>drag to be installed
4.mysql shell==>mysql shell==>mysql shell 8.0==>mysql shell 8.0.38x64==>drag to be
installed===========>next====>execute==>next==>next==>next==>set
password==>next==>execute==>finish==>next==>finish
**************************************************************************************************
❖ Operators
1.operator is a symbol.
2.The purpose of operator is to perform operations.
3.They are 5 types of operators.They are
1.Arithmetic operators(+,-,*,/,%)
2.Relational operators(>,<,>=,<=,=,<>)
3.Logical operators(AND,OR,NOT)
4.Special operators(IN,NOT IN,IS NULL,IS NOT NULL,BETWEEN,NOT BETWEEN,LIKE,ANY,ALL,EXISTS)
5.Set operators(union,union all,intersect,minus)
1.Arithmetic operators(+,-,*,/,%)
Arithmetic operators are used to perform operations like addition,subtraction,multiplication and division.
Addition =======> select 5+3; ===========> 8
Substraction ====> select 5-3; ===========> 2
Multiplication ==> select 5*3; ===========> 15
Divison =========> select 20/2; ==========> 10.0000
Modulo Divison ==> select 20%2; ==========> 0
8|Page
2.Relational operators(>,<,>=,<=,=,<>)
Relational operators are used to compare 2 values and returns either true(1) or false(0).
Examples
select 5>3;==========>1
select 5<3;==========>0
select 5>=5;=========>1
select 5<=5;=========>1
select 5=5;==========>1
select 5=3;==========>0
select 5<>3;==========>1
select 5>0;===========>1
3.Logical operators(AND,OR,NOT)
Logical operators are used to compare multiple conditions and returns either true or false.
➢ AND ===========> ALL the conditions must be satisfied.
➢ OR ============> Atleast 1 condition must be satisfied
EXAMPLES
select ((5>2) AND (6>1));================>1
select ((5>2) AND (6>11));===============>0
select ((5>2) AND (6>1) AND (7>4));======>1
select ((5>2) OR (6>11));================>1
select ((5>12) OR (6>11));===============>0
9|Page
select NOT(0>1);=========================>1
select NOT(1>0);=========================>0
4.Special operators(IN,NOT IN,IS NULL,IS NOT NULL,BETWEEN,NOT BETWEEN,LIKE,ANY,ALL,EXISTS)
1.select * from book where bprice NOT between 5000 AND 7000;
2.select * from book where bprice not in (600,1000);
3.select * from book where bprice is not null;
4.select * from book where bname like '%anan%';
5.select * from book where bprice < Any(select bprice from book where bname='java by ananth');
6.select * from book where bprice < All(select bprice from book where bname='java by ananth');
7.select * from book where not exists (select bprice from book where bname='java by ananth');
5.Set operators (union,union all,intersect,minus)
❖ union =====> It removes duplicates and print remaining records.
❖ union all ==> It print all records including duplicates.
❖ intersect ==> It print common records.
❖ minus ====> It remove common records and print remaining records in 1st table.
It remove common records and print remaining records in 2nd table.
Examples
select * from first
union
select * from second
select * from first
union all
select * from second
10 | P a g e
select sno, sname from first
where (sno, sname) IN (
select sno, sname from second
);
select sno, sname from first
where (sno, sname) Not IN (
select sno, sname from second
);
**************************************************************************************************
Note
create database bhavi; =======> used to create database bhavi
use bhavi; ===================> used to access bhavi database
show tables; =================> used to get tables in database
SET SQL_SAFE_UPDATES = off; ==> used to perform unsafe operations(Bydefault SQL_SAFE_UPDATES ARE ON)
set autocommit=off; ==========> used to off autocommit(whatever the data we stored temporarly)
start transaction =============> used to start the transaction
**************************************************************************************************
11 | P a g e
SQL
1.SQL stands structured query language.
2.The purpose of SQL is to communicate with database and perform operations by using queries.
3.A query is a command/instruction used to perform operations on database.
4.SQL is a case insensitive.
5.SQL queries must be ends with ;
6.There are 5 types of sublanguages in sql.They are
1.DDL
1.DDL stands for data definition language.
2.The purpose of DDL is to define structure of the table.
3.There are 4 types of DDL commands.They are
1.create
2.alter
3.drop
4.truncate
1.create
create is used to create table columns.
syntax
create table tablename(columnname1 datatype(size),columnname2 datatype(size)............);
12 | P a g e
Example
create table students (
std_id int,
first_name varchar(50),
O/P==>
last_name varchar(50),
date_of_birth date,
major varchar(50),
cgpa decimal(3,2)
);
2.alter
alter is used to add,drop,rename,modify columns.
❖ add ========> add is used to add column
❖ drop =======> drop is used to delete column
❖ rename =====> rename is used to rename column.
❖ modify =====> modify is used to modify column datatype and size.
Syntax
➢ alter table tablename add column datatype(size);
➢ alter table tablename drop columname;
➢ alter table tablename rename column old column to new column;
➢ alter table tablename modify column datatype(size);
Example
alter table students add email varchar(100); ======>
alter table students drop column major;===>
alter table students rename column date_of_birth to DOB; ==>
alter table students modify column cgpa decimal(4,2); ==>
13 | P a g e
3.drop
drop is used to delete all rows and columns.
syntax
drop table tablename;
Example
alter table students drop column major;===>
4.truncate
truncate is used to delete all rows and not columns.
syntax
truncate table tablename;
Example
truncate table Students;
2.DML(insert,delete,update)
1.DML stands Data manipulation language.
2.The purpose of DML is to insert,delete,update the data.
3.There are 3 types of DML commands.They are
1.insert
2.delete
3.update
1.insert
insert is used to insert the record.
14 | P a g e
syntax
insert into tablename values(val1,val2,val3......);
Ex
insert into students values(101, 'Jyotsna', 'Chaudhari', '2001-09-30', 'IT', 9.66);==>
2.delete
delete is used to delete all rows and specific rows.
syntax
1.delete from tablename;===============================>all rows
2.delete from tablename where columnname=value;========>specific row
3.update
update is used to update specific rows and all rows.
syntax
1.update tablename set columnname=value; ===============================>all rows
2.update tablename set coulumnname=value where columnname=value; ========>specific row
Inserting multiple records at a time
insert into employee values
(101, 'Jyotsna', 'Chaudhari', '2001-09-30', 'IT', 9.86)
(102, 'Priyanka', 'More', '2000-11-11', 'CS', 8.77),
(103, 'Rohit', 'Chaudhari', '2004-01-28', 'EEE', 10.46),
(104, 'Nilesh', 'Chaudhari', '2003-01-26', 'AI', 8.99);
Note: If we want to update/delete specific row where condition is required
If we want to update/delete all rows where condition is not required.
**************************************************************************************************
3.DQL
1.DQL stands for Data Querying language.
15 | P a g e
2.The purpose of DQL is used to get/fetch/retrive/select the specific/all records.
3.There are 1 type of DQL commands.They are
1.select
select
select is used to get/fetch/retrive/select the specific/all records.
syntax
select column1,column2...... from tablename; ==========================================>all records
select column1,column2...... from tablename where condition; ==========================>specific records
Examples
select eno,ename from employee;
select ename from employee where eno=1;
**************************************************************************************************
Difference b/w truncate,drop and delete
truncate drop delete
• truncate is a ddl • drop is a ddl command. • delete is a dml command.
command. • drop is used to delete all • delete is used to delete
• truncate is used to delete rows and cloumns. specific/all rows.
all rows and not columns. • where condition is not • where condition is present
• where condition is not present in drop. in delete.
present in truncate.
4.TCL
1.TCL stands for Transaction control language.
2.TCL is used to perform data operations like data save permanently, rollback transactions and rollback transactions
to certain point.
3.There are 3 types of TCL commands.They are
1.commit
2.rollback
16 | P a g e
3.savepoint
4.TCL commands are performed in DML commands.
1.commit
commit is used to save data permanently.
syntax
commit;
2.rollback
rollback is used to take transaction/operation to previous state.
syntax
rollback
3.savepoint
savepoint is used to rollback transaction/operation to certain point.
syntax
rollback to name;
Note:If we want to use TCL commands then we have start transaction and set autocommit=off.
5.DCL
DCL stands for Data control language
DCL is used to give privilges to users and take privilges to users.
They are 2 types of DCL commands.They are
1.grant
2.revoke
1.grant
grant is used to give privileges(select,update,delete) to users.
17 | P a g e
syntax
grant privileges(select,update....) on tablename to user1,user2......
2.revoke
revoke is used to take privileges(select,update,delete) from users.
syntax
revoke select,update ontablename from user1,user2........
grant select,update on emp to bhavi;
revoke update on emp from bhavi;
Note:we cannot grant privileges to root user
we can set our own users
Go to server====user and privileges======username=====password
*************************************************************************************************
❖ Integrity constraints
1.Integrity constraints are set of rules or condition.
2.The purpose of Integrity constraints is to prevent invalid data from user.
3.There are 5 Integrity constraints.They are
1.primary key
2.Not null
3.unique
4.check
5.foreign key
6.default
7.auto increment
18 | P a g e
1.primary key
1.primary key is a combination of unique and not null.
we can apply primary key for only column of a table.
we can apply not null and unique for multiple columns of a table.
Note: All null values are not same.
Ex : bno int(20) primary key
2.Not null
Not null constraint does not allow null values(i.e it is a mandatory field)
Ex : bname varchar(40) not null
3.unique
unique constraint does not allow duplicate values.
Ex: email varchar(40) unique
4.check
check constraint is used to perform validations.
Ex: sal double(5,2) check(sal>0)
5.Foreign key
1.Foreign key is used to establish relationship between 2 tables.
2.First table is a parent table and second table is child table.
3.In 1st table write 1 primary key and in 2nd table give reference of primary key as foreign key.
4.Foreign key allows duplicate values and null values.
5.primary key(parent) and foreign key(child) values must be matched.
19 | P a g e
Ex: bno int,foreign key(bno) references bank(bno)
create table bank (
bno int primary key,
bname varchar(30) not null,
email varchar(30) unique,
bal int check (bal>1000)
);
create table emp(eid int(30),ename varchar(30),bno int,foreign key(bno) references bank(bno));
6.default
default constraint is used to give default values to complete column.
cname varchar(40) default='Excelr'
7.auto increment
auto increment is used to give automatic incremented value especially for primary key.
create table bank1
bno int auto_increment primary key,
bname varchar(40) not null,
email varchar(40) unique,
amt double check(amt>0),
cname varchar(40) default='Excelr'
);
insert into bank1(bname,email,amt)
values('sbi','abc@gmail.com',342.41);
20 | P a g e
create table bank1
bno int auto_increment primary key,
bname varchar(40) not null,
email varchar(40) unique,
amt double check(amt > 0),
cname varchar(40) default 'Excelr'
) auto_increment = 200;
create table emp1
eno int auto_increment primary key,
ename varchar(40) not null,
bno int,
foreign key (bno) references bank1(bno)
);
**************************************************************************************************
❖ predefine/Built in functions in MySQL
The functions which are already present MYSQL software
These functions are developed by MySQL developers.
➢ String functions ================> operate on string data types.
➢ Numeric functions ===============> operate on numeric data types.
➢ Date functions ==================> operate on date data types.
➢ Aggregate functions =============> operate on all datatypes and returns single value.
1.String functions
❖ upper() =================> converts any string into upper case.
21 | P a g e
❖ lower() =================> converts any string into lower case.
❖ length() ================> get total number of characters of a string.
❖ trim() ==================> delete specified characters in left and right side.
❖ INSTR() =================> to get index value of a String.
❖ substring() ==============> to get particular sequence of characters of a string.
❖ concat() ================> combines 2 strings.
2.Numeric functions
❖ ABS() ================> to get absolute number.
❖ SQRT() ===============> to get square root number.
❖ MOD() ================> to get modulus of a number.
❖ POWER() ==============> to get power of a number.
❖ TRUNCATE() ===========> to get truncate value of a number.
❖ GREATEST() ===========> to get big value of a number.
❖ LEAST() ==============> to get small value of a number.
3.Date functions
❖ CURRENT_DATE() ===========> to get current date.
❖ CURRENT_TIME() ===========> to get current time.
❖ NOW() ====================> to get current date and time.
❖ SYSDATE() ================> to get system date and time.
❖ MONTH() ==================> to get month.
❖ YEAR() ==================> to get year.
❖ DAY() ====================> to get day.
4.Aggregate functions
1.count() =================> count total number of records without nulls.
2.max() ===================> to get maximun value of a column.
3.min() ===================> to get minimun value of a column.
4.avg() ===================> to get average value of a column.
5.sum() ===================> to get sum of values of a column.
Examples
select upper('virat'); ======================>VIRAT
select lower('virat'); ======================>virat
select length('virat'); =====================>5
22 | P a g e
select substring('virat',2,2); ==============>ir
select concat('virat','kohli'); =============>viratkohli
select trim('z' from 'zzoraclezz'); =========>oracle
select instr('zebraz','b'); =================>3
select abs(-66);============================>66
select sqrt(25);============================>5
select pow(2,3);============================>8
select mod(10,2);===========================>0
select greatest(1,2,3,4,5);=================>5
select least(1,2,3,4,5);====================>1
select truncate(16.1234,2);=================>16.12
select truncate(1678,-1);==================>1670
select truncate(1678,-2);==================>1600
select truncate(1678,-3);==================>1000
select current_date();====================>26-7-2024
select current_time();====================>16:5:54
select now();=============================>26-7-2024 16:5:54
select sysdate();=========================>26-7-2024 16:5:54
select month('2024-07-26');===============>7
select day('2024-07-26');=================>26
select year('2024-07-26');================>2024
select upper(ename) from emp;
select * from emp where length(ename)=3;
Aggregate Functions (IMP For I)
Aggregate Functions are used to process multiple values and returns 1 value.
23 | P a g e
1.count() ---------> count of values of a column/attribute without duplicates.
2.sum() -----------> sum of all values of a column/attribute.
3.avg() -----------> average of all values of a column/attribute.
4.min() -----------> minimum value of a column/attribute.
5.max() -----------> maximum value of a column/attribute.
1.count(*) --------->count of values of a column/attribute with null values.
1.count(distinct col)---------> count of values of a column/attribute without null values and duplicates.
select count(*) from bank;
select count(distinct bal) from bank;
select count(bal) from bank;
select sum(bal) from bank;
select min(bal) from bank;
select max(bal) from bank;
select avg(bal) from bank;
**************************************************************************************************
❖ Joins
1. The process of combining 2 or more tables is called join.
2. There are 4 types of joins.
1.Inner join/equi join/natural join
2.outer join
1.left outer join
2.right outer join
3.full outer join
3.self join
4.Theta join/cartesian join/cross join
24 | P a g e
1.Inner join/equi join/natural join
Inner join will returns records based on common fields.
select * from s inner join d on s.depid=d.depid;
2.left outer join
left outer join will returns all records of S and common records of D.
select * from s left outer join d on s.depid=d.depid;
right outer join
right outer join will returns all records of D and common records of S.
select * from s right outer join d on s.depid=d.depid;
full outer join
full outer join will returns all records of S and D.
select * from s left outer join d on s.depid=d.depid
union
select * from s right outer join d on s.depid=d.depid;
3.self join
1.The process of considering 1 table into 2 tables is called self join.
2.we have 2 alias names for single table.
select distinct e.ename from emp e inner join emp m on e.empid=m.mid;
4.Theta join/cartesian join/cross join
Theta join/cartesian join/cross join will returns cross product or cartesian product of 2 tables.
select * from j cross join c on j.price>c.price;
25 | P a g e
❖ clauses
1.clauses are the conditional keywords or statements.
2.clauses are used for querying.
Ex
❖ where
❖ order by
❖ distinct
❖ group by
❖ having
➢ where
1.where clause is used to get specific row/rows from table.
2.where clause contains condition.
3.If condition is true row is selected.
4.If condition is false row is not selected.
syntax
select columns from tabname where condition;
select * from c where price=4000;
➢ order by
order by clause is used to sort data based on one or more columns either in asc/desc order.
Bydefault it is in asc order.
syntax
select columns from tabname where cond order by columname [asc/desc]
select * from c order by price asc;
select * from c order by price desc;
26 | P a g e
select * from c order by price ;
➢ distinct
distinct clause is used to remove duplicate fields and print unique fields.
syntax
select distinct columns from tabname;
select distinct price from c;
➢ group by
group by clause is used to group the rows based on columns.
group by clause is applied on aggregate functions.
syntax
select columns from tablename group by column1......;
select branch,count(sid) from student group by branch;
select gender,count(sid) from student group by gender;
➢ having
having clause is used to select specific groups.
having clause is applied on after group by clause.
syntax
select columns from tabname group by column having condition.
SELECT branch, COUNT(sid)
FROM student
GROUP BY branch
HAVING COUNT(sid) = 1;
**************************************************************************************************
27 | P a g e
❖ Normalization
1.The process of arranging the data in structured format is called normalization.
2.The purpose of normalization is to reduce data redundancy.
3.There are 6 types of normalization.They are
1. INF
2. 2NF
3. 3NF
4. BCNF
5. 4NF
6. 5NF
1.INF
1.A table is said to be 1NF if there are no multivalued attributed in it or all the attributes in tables are atomic(single).
2.2NF
1.A table is said to be 2NF if it is in 1NF.
2.If there are no partial dependencies in it.
3.3NF
1.A table is said to be 3NF if it is in 2NF.
2.If there are no transitive dependencies in it.
4.BCNF
1.BCNF stands for Boyce-Codd Normal Form.
2.A table is said to be BCNF if it is in 3NF.
3.In BCNF, each column in a table must depend osnly on the primary key and not on any other attribute.
Full / functional dependency
In a table if non primary key fields depends on primary key is called full dependency.
28 | P a g e
Partial dependency
In a table if non primary key fields depends on part of primary key is called partial dependency.
Transitive dependency
In a table if non primary key fields depends on non primary key is called transitive dependency.
select * from j cross join c on j.price>c.price;
**************************************************************************************************
❖ subqueries/Nested Queries
1.The process of defining 1 query in another query is called subqueries/Nested Queries.
2.One query is called inner query.
3.Other query is called outer query.
4.There are 5 types of subqueries.They are
1.single row subqueries
2.Multirow row subqueries
3.corelated subqueries
4.inline views
5.scalar subqueries
➢ single row subqueries
1.If subquery returns one value then it is called single row subqueries.
2.Relational operators(<,>,<=,>=,=,<>) used in single row subqueries.
3.First inner query executed and later outer query executed.
syntax
select columns from tablename where column rop(select statement);
select * from employee where esal=(select esal(max) from employee);
29 | P a g e
➢ Multirow subqueries
1.If subquery returns multiple values then it is called multiple row subqueries.
2.special operators(IN,NOTIN,ANY,ALL...) used in multi row subqueries.
3.First inner query executed and later outer query executed.
syntax
select solumns from tablename where column sop(select statement);
select * from employee where ename In(select ename from employee where ename='jones' OR ename='scott');
Example
SELECT *
FROM employee
WHERE esal > ANY (
SELECT esal
FROM employee
WHERE emp_name IN ('scott', 'allen')
);
➢ corelated subqueries
1st outer query executed and later inner executed then it is called corelated subqueries.
select * from employee e1 where 1=(select count(esal) from employee e2 where e2.esal>e1.esal);
select * from employee e1 where 1=(select count(esal) from employee e2 where e2.esal>e1.esal);
select * from employee where ename In(select ename from employee where ename='jones' OR ename='scott');
select * from employee where esal=(select esal(max) from employee);
➢ inline views subqueries
subqueries in from clause are called inline views subqueries.
30 | P a g e
syntax
select columns from(sub query);
Example
SELECT emp_id, emp_name, esal
FROM (
SELECT *, AVG(esal) AS avg_salary
FROM employee
) inline_view
WHERE esal > avg_salary;
➢ scalar subqueries
subqueries in select clause are called scalar subqueries.
syntax
select (subquery) from tabname where cond;
Example
select * from employee
emp_id emp_name esal
101 jones 25000
102 scott 15000
103 allen 30000
104 smith 68000
105 (null) 7000
SELECT *,
(SELECT AVG(esal) FROM employee) AS avgsal
31 | P a g e
FROM employee;
emp_id emp_name esal avgsal
101 jones 25000 29000.0000
102 scott 15000 29000.0000
103 allen 30000 29000.0000
104 smith 68000 29000.0000
105 (null) 7000 29000.0000
**************************************************************************************************
❖ MYSQL Objects
✓ Tables
✓ views
✓ synonymus
✓ sequences
✓ Indexes
✓ Materialized views
➢ Tables
1.A table is a predefine object.
2.Table is a collection of rows and columns.
3.Rows are records and columns are fields.
4.Table is used to store the data in tabular format.
➢ views
1.A view is a predefine object.
2.view is virtual table constructed from existing table.
3.Existing table can be single or multiple tables.
4.If we done any changes in table it will reflects to view.
5.If we done any changes in view it will reflects to table.
6.There are 2 types of views.They are
32 | P a g e
1.simple views
2.complex views
1.simple views
A view is said to be simple view if it is created based on 1 table.
syntax
create view viewname as select statement;
2.complex views
A view is said to be complex view if it is created based on multiple tables.
create view civstudent as select * from student where branch='civil';
update student set sname='binladan' where sno=105;
create view studentcontact as select student.sno,student.sname,contact.email,contact.mobile from student,contact
where student.sno=contact.sno;
❖alias
alias is a another name/alternative name for column or table .
select * from student;
select * from student as virat;
select sname from student;
select sname as javastudents from student;
➢ synonyms
33 | P a g e
1.synonyms is a object.
2.synonymous is a another name/alternative name for column or table.
syntax
create synonym synonymname for tablename;
Example
create synonym e1 for EmployeeDetails;
select * from e1;
Difference between alias and synonym
alias synonym
alias is not stored in database. synonym is stored in database.
alias is not permanent synonym is permanent
alias scope is upto query synonym is scope is upto schema(user)
Note: synonym is not valid/use in MYSQL.
➢ sequences
1.sequences is an object.
2.sequences is used to increment values of a column by using auto-increment.
Example
create table excelr(eno int(20)primary key auto_increment,ename varchar(30),esal int(30));
select * from excelr;
insert into excelr(ename,esal) values('srikar',3000);
create table excelr(eno int(20)primary key auto_increment,ename varchar(30),esal int(30));
34 | P a g e
alter table excelr auto_increment=1000;
select * from excelr;
insert into excelr(ename,esal) values('jashwa',1000);
➢ Indexes
1.Index is a database object.
2.Index is used to retrieve/fetch/get/select the records.
3.They are 3 types of indexes.They are
1.BITREE INDEX
1.simple btree index
2.composite btree index
2.BITMAP INDEX
3.UNIQUE INDEX
1.simple bitree index
If index created on single column then it is called simple btree index.
syntax
create index indexname on tabname columname;
Example
create index I1 on Employee(esal);
2.composite btree index
If index created on multiple columns then it is called composite btree index.
syntax
create index indexname on tabname coln1,coname2......;
Example
35 | P a g e
create index I2 on Employee(esal,ename);
❖ Table scan
In table scan MySQL scans the complete table row by row.
❖ Index scan
In index scan MySQL scans the only half of the table row by row.
Note: Index scan is faster than Table scan.
Note: Tables are recommend to perform insertion/deletion/updation operations.
Indexes are recommend to perform retrival operations.
2.BITMAP index
BITMAP index are created on low cordinality columns i.e column that contains less duplicate/distinct values.
create index e3 on tcs(ename);
3.UNIQUE INDEX
1.unique index doesn't allow duplicate values into column on which index is created.
2.select primary key column as unique index column.
create unique index e3 on tcs(eno);
➢ Materialized views
Materialized views are like regular views, but unlike views, the result of a materialized view is stored physically in the
database.
It stores the data from the query result in a table, which can be refreshed periodically.
Materialized views improve query performance by avoiding recalculating the query each time.
36 | P a g e
syntax
CREATE TABLE materialized_view AS
SELECT * FROM some_table WHERE condition;
**************************************************************************************************
❖ stored procedures
1.stored procedures is a collection of statements.
2.The purpose of stored procedures is to perform task and produce code reusability.
3.stored procedures contains 3 parts.They are
1.procedure heading
2.procedure body
3.procedure calling
4.formal parameters are used to take values from procedure calling.
5.Actual arguments are used to send values to procedure heading.
syntax
delimiter $$
create procedure procedure_name (formal parameters)
begin
group of statements;
end $$
Example
Ex1. call procedure_name(actual arguments);
delimiter $$
create procedure empDetails()
37 | P a g e
begin
select * from tcs;
end $$
Ex2. call empDetails();
delimiter $$
create procedure empDetails1(num int)
begin
select * from tcs where eno=num;
end $$
Ex3.call empDetails1(103);
delimiter $$
create procedure showdata()
begin
declare x int;
set x=5;
select x as result;
end $$
Ex 4.call showdata();
delimiter $$
create procedure addnum(p int,q int)
begin
declare fn int;
declare sn int;
declare rn int;
set fn=p;
38 | P a g e
set sn=q;
set rn=fn+sn;
select rn as additionvalue;
end $$
call addnum(10,5);
**************************************************************************************************
❖ functions
1.function is a collection of statements.
2.The purpose of function is to perform task and produce code reusability.
3.function contains 3 parts.They are
1.function heading
2.function body
3.function calling
4.formal parameters are used to take values from function calling.
5.Actual arguments are used to send values to function heading.
Note: Difference b/w stored procedures and functions
➢ stored procedures ➢ functions
1.stored procedures are recommended to 1.functions are recommended to perform
perform dml operations(insert,delete,update) dql operations(select) and calculations.
2.stored procedures gives multiple values as 2.functions gives single value as output.
output.
39 | P a g e
syntax
delimiter $$
create function function_name(formal parameters)
begin
group of statements;
end $$
Example
call function_name(actual arguments);
delimiter
DELIMITER $$
CREATE FUNCTION first_fun()
RETURNS VARCHAR(20)
DETERMINISTIC
NO SQL
BEGIN
RETURN 'virat';
END $$
DELIMITER ;
select first_fun()
DELIMITER $$
CREATE FUNCTION second_fun(a int(20))
RETURNS INT(20)
DETERMINISTIC
NO SQL
40 | P a g e
BEGIN
RETURN a*a;
END $$
DELIMITER ;
select second_fun(7)
DELIMITER $$
CREATE FUNCTION third_fun(num INT)
RETURNS VARCHAR(40)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE empname VARCHAR(30);
-- Assuming 'eno' is a typo and should be 'eid' based on your employee table
SELECT ename INTO empname FROM employee WHERE eid = num;
RETURN empname;
END $$
DELIMITER ;
-- Call the function
SELECT third_fun(107);
---------------------------------------------------------------------------------------------------------------------
delimiter $$
create procedure empDetailsda(num int)
begin
select * from tcs where eno>num;
end $$
41 | P a g e
call empDetailsda(5);
eno ename esal
101 veena 10
102 srikar 20
103 sandeep 30
104 kalyan 40
105 karan 50
----------------------------------------------------------------------------------------------------------------------
DELIMITER $$
CREATE FUNCTION third_fun1(num INT)
RETURNS VARCHAR(40)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE empname VARCHAR(30);
-- Assuming 'eno' is a typo and should be 'eid' based on your employee table
SELECT ename INTO empname FROM employee WHERE eid >num;
RETURN empname;
END $$
DELIMITER ;
-- Call the function
SELECT third_fun1(5);
SELECT third_fun1(5) LIMIT 0, 1000 Error Code: 1172. Result consisted of more than one row 0.000 sec
**************************************************************************************************
42 | P a g e
❖ cursors
1.cursor is a MySQL block.
2.cursor is used to oterate one by one recored by using select statement.
syntax
1.declare cursor_name cursor for select statement
2.open cursor_name
3.decalre continue handler for not found records
4.fetch cursor_name into variables list.
5.close cursor_name
Examples
delimiter $$
create procedure cursor_ex()
begin
declare done boolean default false;
declare c_ename varchar(20);
declare c_esal int(20);
declare c1 cursor for select ename,esal from employee;
declare continue handler for not found set done=true;
open c1;
read_loop:loop
fetch c1 into c_ename,c_esal;
if done then
leave read_loop;
end if;
select c_ename,c_esal;
end loop;
43 | P a g e
close c1;
end $$
call cursor_ex()
**************************************************************************************************
❖ Triggers
1.Triggers is a collection of statements.
2.Triggers are used to perform validations automatically when event occurs.
3.There are 2 types of triggers.They are
1.before triggers
1.before insert
2.before update
3.before delete
2.after triggers
1.after insert
2.after update
3.after delete
syntax
delimter $$
create trigger trigger_name
event on tablename
for each row
begin
-----------
-----------
44 | P a g e
end $$
delimiter ;
DELIMITER $$
CREATE TRIGGER checkingsal
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF NEW.esal < 0 THEN
SET NEW.esal = 0;
END IF;
END $$
DELIMITER ;
How to implement before insert trigger steps
1.create table with columns and not rows
2.write insertbefore trigger code
3.insert rows into table
4.select table
**************************************************************************************************
45 | P a g e
46 | P a g e
47 | P a g e