DBMS CODES_PLSQL
DBMS CODES_PLSQL
1 DDL
2 DML
3 DQL
4 DCL
5 Inbuilt Functions
6 Aggregate functions
7 Constraints
8 Joins
9 Views
10 Stored Procedure
11 Stored Functions
12 If else
13 While loop
14 Events
15 Exception Handling
16 Cursors
17 Triggers
18 PROJECT (REGISTER USING PYTHON WITH DATABASE
CONNECTIVITY)
19 Project on events and Trigger
20 PLSQL
SECTION 1
DDL (Data Defination Language)
1. Create
2. Alter – add, modify, rename , drop
3. Drop
4. Truncate
--create a database
create database person;
use person;
--create a table
create table student (
id int,
name varchar(50),
phno varchar(15),
fees int
);
--Alter
Alter table student add email varchar(50);
Alter table student modify column phno varchar(10);
Alter table student rename column phno to phone_no;
Alter table student drop column email;
--Drop
drop table student;
drop database person;
SECTION 2
--Insert
--Insert All values
--Update
--Update all the data
update student
set name=” Hanna”;
--Delete in a range
delete from student
where id between 3 and 4;
SECTION 3
1.4 Limit
--Select
select "Alfina";
--Order by
select * from actor order by first_name asc;
--(it will do order by first_name only and will not consider actor_id
while arranging the data)
--where
--Relational Operators
select * from actor where actor_id <100;
--Logical Opeartors
select * from actor where first_name = "nick" and actor_id<=100;
--Membership Operators
select * from actor where actor_id in (1,2,3,4,10,50,100);
select * from actor where first_name like "R%" or last_name like "N%";
--Limit
use sakila;
--Click on ‘+’ icon and build a connection and enter the username that you created in
‘Username’.
--Click on ‘Store in vault’ and enter the password that you created
--Grant
--Revoke
select pi();
--String functions
select ascii ('a'), ascii('A');
--Date function
-- m = month , d = date , y = 2 digit year , Y= 4 digit year , b= month with 3
character string, t = time , f = pecision of time
-- Distinct operations
-- duplicate records are eliminated
Aggregate functions
1. Min()
2. Max()
3. Avg()
4. Count()
5. Sum()
6. Group by clause
7. Having clause
use sakila;
--group by
-- will group all the same data and find the aggregate functions of it
--having clause
-- it is only used with group by clause
desc student;
-- inner join
select std1.* , dept.* from std1 inner join dept
on std1.id = dept.s_id;
-- full join
select std1.* , dept.* from std1 left outer join dept
on std1.id = dept.s_id
union
select std1.* , dept.* from std1 right outer join dept
on std1.id = dept.s_id;
-- cross join
select std1.* , subject1.* from std1 cross join subject1
where subject1.sub_name ="C";
SECTION 9
Views
1. View is commonly known as virtual table, based on the result set of
the sql statement
2. A view is a database object which contain select statement
3. The table reference in the views are known as base table
4. View do not store any data, the data are retrived at runtime from
base table
5. Mysql supports nested views. nested view is a view that is based on
another view
6. Mysql does not support materialized view. a masterialized view
means where view itself store data
7. Advantages of views:
simplified query
data security with view
DML operation with view
--Views
use sakila;
--Nested views
create view vw_actor2 as
select * from vw_actor
where first_name like "A%";
delimiter $$
create procedure actor1()
begin
select * from actor;
end $$
delimiter ;
call actor1();
call actor3(6);
call actor3(10);
--procedure with 2 arguments
delimiter $$
create procedure actor4(in f_name varchar(45), in l_name varchar(45))
begin
select * from actor where first_name= f_name and last_name = l_name;
end $$
delimiter ;
--drop procedure
Drop procedure actor4;
SECTION 11
Stored Functions
1. A stored function in SQL is a set of SQL statements that perform a
specific task and return a single value.
2. Unlike stored procedure, may or may not return a value, but stored
function will always return a value
3. The terms DETERMINISTIC and NOT DETERMINISTIC are used to describe
the behavior of stored functions in terms of their consistency and
predictability.
4. A DETERMINISTIC function is one that always produces the same output
given the same input parameters.
5. This means that the function's result depends solely on its input values
and does not vary based on other factors like the current date and time
6. A NOT DETERMINISTIC function is one that may produce different
outputs for the same input parameters.
--Stored Functions
--Deterministic
use vl;
delimiter $$
create function calculatetotalsalary (hourly_salary int, hours_worked int)
returns int
deterministic
begin
declare total_salary int;
set total_salary = hourly_salary * hours_worked;
return total_salary;
end$$
--Not Deterministic
create function getcurrentdatetime()
returns datetime
not deterministic
reads sql data
begin
return now();
end$$
Eg2)
create function random_add(n int)
returns int
not deterministic
begin
return n + floor(rand() * 10);
end;
select getcurrentdatetime() as currenttime;
SECTION 12
If else Syntax:
Inside stored procedure
Declare --------
If (condition) Then
Stmts;
Else
Stmts;
End if;
--greater between 2 numbers
use office;
show tables;
delimiter $$
create procedure if1()
begin
declare a int default 15;
declare b int default 20;
if(a>b)
then
select "A is greater" as msg;
else
select "B is greater" as msg;
end if;
end $$
delimiter ;
call if1();
--greater between 2 numbers (call by value)
delimiter $$
create procedure if2(in a1 int , in b1 int)
begin
declare a int default a1;
declare b int default b1;
if(a>b)
then
select "A is greater" as msg;
else
select "B is greater" as msg;
end if;
end $$
delimiter ;
call if1(10,5);
Hw.
1. Check if number is positive or not
2. Check if the number is zero or non zero
3. Check if number is even or odd
4. Check if entered year is leap year or not
5. Check if number is divisible by 3 or not
6. Check if number is divisible 3 and 5 both
SECTION 13
While loop
Syntax:
Inside stored Procedure
------Declare -------
While (condition)
Do
Stmts;
Inc/dec
End while;
--1 to 10
delimiter $$
create procedure whileloop()
begin
declare i int default 1;
while i<=10
do
select i;
set i = i+1;
end while;
end $$
delimiter ;
call whileloop();
--10 to1
delimiter $$
create procedure whileloop1()
begin
declare i int default 10;
while i>=1
do
select i;
set i = i-1;
end while;
end $$
delimiter ;
call whileloop1();
--1 to n
delimiter $$
create procedure whileloop2(in n int)
begin
declare i int default 1;
while i<=n
do
select i;
set i = i+1;
end while;
end $$
delimiter ;
call whileloop2(5);
Hw.
1. n-1
2. 1-10(even and odd)
3. Factorial of 5
4. Sum from 1-10
5. Square from 1-10
6. Sum of Cube from 1-10
7. Table of 5
SECTION 14
Events
1. An event is a block of code that is executed automatically according to
scheduler.
2. MySql supports one time event as well as recurring event.
3. The primary reason to use events to do various maintenance task
related to table.
4. There are two types of events
one time event
recurring event
--Events
use school;
--Recurring
create event recurringevent1
on schedule every 5 second
starts now()
ends now() + interval 3 minute
do
begin
insert into message(message, date1) values("Thank you for coming", default);
end $$
--Drop an event
drop event recurringevent;
show events;
SECTION 15
Exception handling
1. An error condition during a program execution is called as exception
2. The mechanism for resolving such an exception is exception
handling
3. My sql Supports conditional handler
Exit handler: Immediately exit the block
Continue handler: Stored procedure continue the handler. It
allow execution to continue in stored procedure
--Exception handling
use hospital;
create table class(id int primary key, name1 varchar(50) not null);
insert into class values(3, null); -- error code 1048 for not null inserting
insert into class values(3 , "Alfina"); -- error code 1062 for duplicate value
delimiter $
create procedure exception_handle(in id1 int, in value1 varchar(50))
begin
declare flag int default 0;
declare flag1 int default 0;
begin
declare exit handler for 1048 set flag = 1;
declare exit handler for 1062 set flag1 = 1 ;
if flag =1
then
select "Unsuccessful insert due to null value" as message;
elseif flag1 = 1
then
select "You have inserted duplicate value" as message;
end if;
end $
delimiter ;
call exception_handle(1 , "Umaima");
--Drop procedure
drop procedure exception_handle;
SECTION 16
Cursors
1. A cursor allows to iterate a set of rows return by a query and process
them accordingly.
2. A cursor is a method by which we can assign a name to a result of
select statement and manipulate the data within that sql statement.
3. Example: JDBC, NODEJS, PYTHON
4. Sql, we create cursor inside a stored procedure to handle the result
set return by a query
5. There are 2 types of cursor:
Implicit Cursor:
Implicit Cursor also known as default cursor. This cursor's are
allocated by sql server when the user perform DML operation.
Explicit Cursor:
This are created by user whenever the user requires them. Explicit
cursor's are used for fetching data from table in row by row
manner.
6. Steps involved to work with cursor :
Declare cursor name for select statement.
Open cursor name initialize the reult set for operation.
Fetch cursor name into variable list, to retrieve the next row
pointed by the cursor and move the cursor to the next row in the
result set.
Close cursor name to deactivate the cursor and release any
memory associated with it.
Deallocate
--Cursors
use office;
---- declaring variables that is will fetch the data from original table and keep it
in their respective temporary variables.
open emp_cursor;
cursorloop :loop
fetch emp_cursor into EMPID1,EMPNAME1, SALARY1;
if done1 = 1
then
leave cursorloop;
end if;
end $
call cursor2;
--Cursor that handle null
use vl;
delimiter $$
create procedure cursor1()
begin
declare id1 int ;
declare name1 varchar(50);
declare fees1 int;
declare total1 int default 0;
declare done1 int default 0;
declare b_cursor cursor for select sid , name , fees from students;
open b_cursor;
anusloop:loop
fetch b_cursor into id1, name1, fees1;
if done1 =1
then
leave anusloop;
end if;
end $$
--Call the cursor
call cursor1;
SECTION 17
Triggers
1. When we want to do some work automatically but only when we
perform some operation like insert update and delete.
2. Trigger are executed before or after DML operation. Trigger
execution is often called as trigger firing Trigger must be created
with for each row clause
3. The old key word gets a value from the row that is being updated or
deleted
4. The new keyword gets a value from the row that is being inserted or
updated
5. The are 2 types of trigger :
Before trigger :
Before trigger always execute before any DML operation.
Mostly used in update and insert.
After trigger:
After trigger always execute after any DML operation.
--Triggers
use hostel;
-- update trigger
create trigger before_update
before Update on Employees
for each row
set New.salary= New.hour_salary * 150;
update employees set hour_salary=100
where empid=1;
-- insert trigger
create trigger before_insert
before insert on employees
for each row
set New.salary= New.hour_salary * 150;
-- delete trigger
use hostel;
--drop trigger
drop trigger delete_trigger;
Section 18
PROJECT (REGISTER USING PYTHON WITH DATABASE CONNECTIVITY)
REGISTER.PY
'''
pip install mysql-connector-python
'''
‘’’pre requisite:
1. create a database in workbench.
2. create a table in workbench.
3. excute the code.
4. write select statement in workbench. '''
import mysql.connector
if existing_user:
print("Username already exists. Please choose a different one.")
else:
# Insert new user into the database
cursor.execute("INSERT INTO users (username, password, name, age,
gender) VALUES (%s, %s, %s, %s, %s)",
(username, password, name, age, gender))
conn.commit()
except mysql.connector.Error as e:
print("Database error:", e)
finally:
conn.close()
def register():
print("Welcome to the registration form.")
username = input("Enter username: ")
password = input("Enter password: ")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
delimiter //
delimiter ;
BEGIN
dbms_output.put_line(a);
END;
Addition of 2 numbers
declare
a number(10) :=&a;
b number(10) :=&b;
c number(10);
begin
c:=a+b;
dbms_output.put_line('Addition of 2 number is'||c);
end;
/
If else
Greater between 2 numbers
declare
a number(10) :=&a;
b number(10) :=&b;
begin
if (a>b)
then
dbms_output.put_line('A is greater');
else
dbms_output.put_line('B is greater');
end if;
end;
/
Even and odd
declare
a number(10) :=&a;
begin
if mod(a,2)=0
then
dbms_output.put_line('A is even');
else
dbms_output.put_line('A is odd');
end if;
end;
/
If else ladder
If <condition> then
Elsif <condition > then
Else
begin
if (a>b and a>c)
then
dbms_output.put_line('A is greater');
elsif (b>c)
then
dbms_output.put_line('B is greater');
else
dbms_output.put_line('C is greater');
end if;
end;
/
LOOPING
i number := 1;
begin
loop
dbms_output.put_line(i);
i := i+1;
end loop;
en/
/
While loop
declare
i number := 1;
begin
while i <= 10
loop
dbms_output.put_line(i);
i := i+1;
end loop;
end;
/
Factorial
declare
i number := 1;
fact number:=1;
n number:=&n;
begin
while i <= n
loop
fact := fact*i;
dbms_output.put_line(fact);
i := i+1;
end loop;
end;
For loop
declare
a number;
begin
a:=10;
for a in 1..10
loop
dbms_output.put_line(a);
end loop;
end;
/
Cursors
Declare, open, fetch and close
1. create a table
-- assume we have a table called employees
create table employees (
employee_id number primary key,
first_name varchar2(50),
last_name varchar2(50),
salary number
);