Mysql Notes
Mysql Notes
Index
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
12 Functions 40
13 Cursors 44
14 Triggers 45
1|Page
❖ Data
1.Data is a collection of raw facts(numbers,digits,symbols....)
❖ Information
1.Information is used to processing the data.
❖ Database
1.Database is a one type of software.
6.By using SQL we can communicate with Database and perform operations by using queries.
2|Page
❖ MySQL
❖ DBMS
3.The purpose of DBMS is to create the data and manage the data.
❖ RDBMS
❖ ORDBMS
1. Definition DBMS stands for database RDBMS stand for Relatinal databse management
3. Data access In DBMS each data elements are In RDBMS multiple data elements are
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
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.
➢ Numeric Types
➢ Date & Time Types
➢ String Types
1.Numeric Types
➢ 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.
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
5|Page
BIGINT 8 -9223372036854775808 9223372036854775807 0 18446744073709551615
Floating-point Types
--------------------------------------------------------------------------------------------------- ------------------------------------------
**************************************************************************************************
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
TIMESTAMP values are converted from the current zone YYYY-MM-DD HH:MM:SS '1970-01-01 00:00:01' UTC
utc to the current time zone when retrived '2038-01-19 03:14:07' UTC
**************************************************************************************************
6|Page
3.STRING TYPES
STRING TYPES is used to store multiple characters enclosed with single or double quotes.
Examples
Gender char(1)
name varchar(30)
Bhavadeesh
OPTION ENUM('one,'two','three')
OPTION SET('one,'two','three')
**************************************************************************************************
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
**************************************************************************************************
❖ Operators
1.operator is a symbol.
1.Arithmetic operators(+,-,*,/,%)
2.Relational operators(>,<,>=,<=,=,<>)
3.Logical operators(AND,OR,NOT)
1.Arithmetic operators(+,-,*,/,%)
Arithmetic operators are used to perform operations like addition,subtraction,multiplication and division.
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.
EXAMPLES
9|Page
select NOT(0>1);=========================>1
select NOT(1>0);=========================>0
1.select * from book where bprice NOT between 5000 AND 7000;
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');
Examples
union
union all
);
);
**************************************************************************************************
Note
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)
**************************************************************************************************
11 | P a g e
SQL
2.The purpose of SQL is to communicate with database and perform operations by using queries.
1.DDL
1.create
2.alter
3.drop
4.truncate
1.create
syntax
12 | P a g e
Example
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
Syntax
Example
13 | P a g e
3.drop
syntax
Example
4.truncate
syntax
Example
2.DML(insert,delete,update)
1.insert
2.delete
3.update
1.insert
Ex
2.delete
syntax
3.update
syntax
**************************************************************************************************
3.DQL
1.select
select
syntax
Examples
**************************************************************************************************
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.
1.commit
2.rollback
16 | P a g e
3.savepoint
1.commit
syntax
commit;
2.rollback
syntax
rollback
3.savepoint
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
1.grant
2.revoke
1.grant
17 | P a g e
syntax
2.revoke
syntax
*************************************************************************************************
❖ Integrity constraints
1.Integrity constraints are set of rules or condition.
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
we can apply not null and unique for multiple columns of a table.
2.Not null
Not null constraint does not allow null values(i.e it is a mandatory field)
3.unique
4.check
5.Foreign key
3.In 1st table write 1 primary key and in 2nd table give reference of primary key as foreign key.
);
6.default
7.auto increment
auto increment is used to give automatic incremented value especially for primary key.
);
values('sbi','[email protected]',342.41);
20 | P a g e
create table bank1
) auto_increment = 200;
bno int,
);
**************************************************************************************************
1.String functions
2.Numeric functions
3.Date functions
4.Aggregate functions
Examples
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 month('2024-07-26');===============>7
select day('2024-07-26');=================>26
select year('2024-07-26');================>2024
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.
1.count(distinct col)---------> count of values of a column/attribute without null values and duplicates.
**************************************************************************************************
❖ Joins
1. The process of combining 2 or more tables is called join.
2.outer join
3.self join
24 | P a g e
1.Inner join/equi join/natural join
left outer join will returns all records of S and common records of D.
right outer join will returns all records of D and common records of S.
union
3.self join
Theta join/cartesian join/cross join will returns cross product or cartesian product of 2 tables.
25 | P a g e
❖ clauses
1.clauses are the conditional keywords or statements.
Ex
❖ where
❖ order by
❖ distinct
❖ group by
❖ having
➢ where
1.where clause is used to get specific row/rows from table.
syntax
➢ order by
order by clause is used to sort data based on one or more columns either in asc/desc order.
syntax
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
➢ group by
group by clause is used to group the rows based on columns.
syntax
➢ having
having clause is used to select specific groups.
syntax
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.
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
3.3NF
4.BCNF
3.In BCNF, each column in a table must depend osnly on the primary key and not on any other attribute.
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.
**************************************************************************************************
❖ subqueries/Nested Queries
1.The process of defining 1 query in another query is called subqueries/Nested Queries.
3.corelated subqueries
4.inline views
5.scalar subqueries
1.If subquery returns one value then it is called single row subqueries.
syntax
29 | P a g e
➢ Multirow subqueries
1.If subquery returns multiple values then it is called multiple row subqueries.
syntax
select * from employee where ename In(select ename from employee where ename='jones' OR ename='scott');
Example
SELECT *
FROM employee
SELECT esal
FROM employee
);
➢ 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');
30 | P a g e
syntax
Example
FROM (
FROM employee
) inline_view
➢ scalar subqueries
subqueries in select clause are called scalar subqueries.
syntax
Example
SELECT *,
31 | P a g e
FROM employee;
**************************************************************************************************
❖ MYSQL Objects
✓ Tables
✓ views
✓ synonymus
✓ sequences
✓ Indexes
✓ Materialized views
➢ Tables
1.A table is a predefine object.
➢ views
1.A view is a predefine object.
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
2.complex views
A view is said to be complex view if it is created based on multiple tables.
where student.sno=contact.sno;
❖alias
alias is a another name/alternative name for column or table .
➢ synonyms
33 | P a g e
1.synonyms is a object.
syntax
Example
alias synonym
alias is not stored in database. synonym is stored in database.
➢ sequences
1.sequences is an object.
Example
34 | P a g e
alter table excelr auto_increment=1000;
➢ Indexes
1.Index is a database object.
1.BITREE INDEX
2.BITMAP INDEX
3.UNIQUE INDEX
syntax
Example
syntax
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.
2.BITMAP index
BITMAP index are created on low cordinality columns i.e column that contains less duplicate/distinct values.
3.UNIQUE INDEX
1.unique index doesn't allow duplicate values into column on which index is created.
➢ 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
**************************************************************************************************
❖ stored procedures
1.stored procedures is a collection of statements.
2.The purpose of stored procedures is to perform task and produce code reusability.
1.procedure heading
2.procedure body
3.procedure calling
syntax
delimiter $$
begin
group of statements;
end $$
Example
delimiter $$
37 | P a g e
begin
end $$
delimiter $$
begin
end $$
Ex3.call empDetails1(103);
delimiter $$
begin
declare x int;
set x=5;
select x as result;
end $$
Ex 4.call showdata();
delimiter $$
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.
1.function heading
2.function body
3.function calling
39 | P a g e
syntax
delimiter $$
begin
group of statements;
end $$
Example
delimiter
DELIMITER $$
RETURNS VARCHAR(20)
DETERMINISTIC
NO SQL
BEGIN
RETURN 'virat';
END $$
DELIMITER ;
select first_fun()
DELIMITER $$
RETURNS INT(20)
DETERMINISTIC
NO SQL
40 | P a g e
BEGIN
RETURN a*a;
END $$
DELIMITER ;
select second_fun(7)
DELIMITER $$
RETURNS VARCHAR(40)
DETERMINISTIC
BEGIN
-- Assuming 'eno' is a typo and should be 'eid' based on your employee table
RETURN empname;
END $$
DELIMITER ;
SELECT third_fun(107);
---------------------------------------------------------------------------------------------------------------------
delimiter $$
begin
end $$
41 | P a g e
call empDetailsda(5);
101 veena 10
102 srikar 20
103 sandeep 30
104 kalyan 40
105 karan 50
----------------------------------------------------------------------------------------------------------------------
DELIMITER $$
RETURNS VARCHAR(40)
DETERMINISTIC
BEGIN
-- Assuming 'eno' is a typo and should be 'eid' based on your employee table
RETURN empname;
END $$
DELIMITER ;
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.
syntax
2.open cursor_name
5.close cursor_name
Examples
delimiter $$
begin
open c1;
read_loop:loop
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.
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 $$
event on tablename
begin
-----------
-----------
44 | P a g e
end $$
delimiter ;
DELIMITER $$
BEGIN
SET NEW.esal = 0;
END IF;
END $$
DELIMITER ;
4.select table
**************************************************************************************************
45 | P a g e
46 | P a g e
47 | P a g e