You are on page 1of 34

CS 333 Application Software Development Lab

Ex. No: 1
Creation of a database and writing mysql queries to retrieve information from the database.

AIM
Creation of a database using DDL commands

COMMANDS

mysql> create database testdb;

Query OK, 1 row affected (0.01 sec)

mysql> use testdb;

Database changed

mysql> create table student (stname varchar(30), stid varchar(10), stage int(2), starea varchar(20));

Query OK, 0 rows affected (0.34 sec)

mysql> desc student;

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| stname | varchar(30) | YES | | NULL | |
| stid | varchar(10) | YES | | NULL | |
| stage | int(2) | YES | | NULL | |
| starea | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql> alter table student modify stage int(5);

Query OK, 0 rows affected (0.05 sec)

Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table student add stdept varchar(20);

Query OK, 0 rows affected (0.56 sec)

Records: 0 Duplicates: 0 Warnings: 0

1
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

mysql> desc student;

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| stname | varchar(30) | YES | | NULL | |
| stid | varchar(10) | YES | | NULL | |
| stage | int(5) | YES | | NULL | |
| starea | varchar(20) | YES | | NULL | |
| stdept | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> alter table student drop stdept;

Query OK, 0 rows affected (0.55 sec)

Records: 0 Duplicates: 0 Warnings: 0

mysql> desc student;

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| stname | varchar(30) | YES | | NULL | |
| stid | varchar(10) | YES | | NULL | |
| stage | int(5) | YES | | NULL | |
| starea | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> truncate table student;

Query OK, 0 rows affected (0.25 sec)

mysql> desc student;

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| stname | varchar(30) | YES | | NULL | |
| stid | varchar(10) | YES | | NULL | |
| stage | int(5) | YES | | NULL | |
| starea | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

2
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

mysql> drop table student;

Query OK, 0 rows affected (0.18 sec)

mysql> desc student;

ERROR 1146 (42S02): Table 'testdb.student' doesn't exist

3
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No : 2

Performing DML commands like Insertion, Deletion, Modifying, Altering, and Updating
records based on conditions.

AIM
To manipulate database using DML commands.

COMMANDS

CREATION OF TABLE

mysql> create table student (stname varchar(30), stid varchar(10), stage int(2), starea varchar(20),
stbranch varchar(20));

Query OK, 0 rows affected (0.33 sec)

INSERTION OF VALUES INTO THE TABLE

mysql> insert into student values ('ashly',101,19,'nehru nagar','aeronautical');

Query OK, 1 row affected (0.05 sec)

mysql> insert into student values ('havesh',102,18,'ayyanthole','marine');

Query OK, 1 row affected (0.06 sec)

mysql> insert into student values ('ruthvik',103,20,'nehru nagar','aerospace');

Query OK, 1 row affected (0.06 sec)

mysql> insert into student values ('harith',104,20,'west fort','mechanical');

Query OK, 1 row affected (0.04 sec)

mysql> select * from student;

+---------+------+-------+-------------+--------------+
| stname | stid | stage | starea | stbranch |
+---------+------+-------+-------------+--------------+
| ashly | 101 | 19 | nehru nagar | aeronautical |
| havesh | 102 | 18 | ayyanthole | marine |
| ruthvik | 103 | 20 | nehru nagar | aerospace |
| harith | 104 | 20 | west fort | mechanical |
+---------+------+-------+-------------+--------------+
4 rows in set (0.00 sec)
4
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

RENAMING THE TABLE ‘STUDENT’

mysql> rename table student to students;

Query OK, 0 rows affected (0.16 sec)

ARITHMETIC OPERATION

mysql> select stname, stid+100 "stidno" from students;

+---------+--------+
| stname | stidno |
+---------+--------+
| ashly | 201 |
| havesh | 202 |
| ruthvik | 203 |
| harith | 204 |
+---------+--------+
4 rows in set (0.01 sec)

DISPLAY ONLY DISTINCT VALUES

mysql> select distinct starea from students;

+-------------+
| starea |
+-------------+
| nehru nagar |
| ayyanthole |
| west fort |
+-------------+
3 rows in set (0.00 sec)

USING THE WHERE CLAUSE

mysql> select stname,stage from students where stage<=19;

+--------+-------+
| stname | stage |
+--------+-------+
| ashly | 19 |
| havesh | 18 |
+--------+-------+
2 rows in set (0.00 sec)

5
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

BETWEEN OPERATOR

mysql> select stname,starea, stid from students where stid between 102 and 104;

+---------+-------------+------+
| stname | starea | stid |
+---------+-------------+------+
| havesh | ayyanthole | 102 |
| ruthvik | nehru nagar | 103 |
| harith | west fort | 104 |
+---------+-------------+------+
3 rows in set (0.01 sec)

PATTERN MATCHING

mysql> select stname, starea from students where starea like '%g%';

+---------+-------------+
| stname | starea |
+---------+-------------+
| ashly | nehru nagar |
| ruthvik | nehru nagar |
+---------+-------------+
2 rows in set (0.00 sec)

LOGICAL OR & AND OPERATOR

mysql> select stname ,stid from students where stid>102 and starea='nehru nagar';
+---------+------+
| stname | stid |
+---------+------+
| ruthvik | 103 |
+---------+------+
1 row in set (0.00 sec)

mysql> select stname ,stid from students where stid>102 or starea='nehru nagar';
+---------+------+
| stname | stid |
+---------+------+
| ashly | 101 |
| ruthvik | 103 |
| harith | 104 |
+---------+------+
3 rows in set (0.00 sec)

6
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

UPDATING THE TABLE

mysql> alter table students add stpocket varchar(20);

Query OK, 0 rows affected (0.64 sec)

Records: 0 Duplicates: 0 Warnings: 0

mysql> update students set stpocket=750 where stid=101;

Query OK, 1 row affected (0.04 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> update students set stpocket=500 where stid=102;

Query OK, 1 row affected (0.04 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> update students set stpocket=250 where stid=103;

Query OK, 1 row affected (0.05 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> update students set stpocket=100 where stid=104;

Query OK, 1 row affected (0.06 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from students;

+---------+------+-------+-------------+--------------+----------+
| stname | stid | stage | starea | stbranch | stpocket |
+---------+------+-------+-------------+--------------+----------+
| ashly | 101 | 19 | nehru nagar | aeronautical | 750 |
| havesh | 102 | 18 | ayyanthole | marine | 500 |
| ruthvik | 103 | 20 | nehru nagar | aerospace | 250 |
| harith | 104 | 20 | west fort | mechanical | 100 |
+---------+------+-------+-------------+--------------+----------+
4 rows in set (0.00 sec)

7
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

DELETION

mysql> delete from students where stid=101;

Query OK, 1 row affected (0.08 sec)

mysql> select * from students;

+---------+------+-------+-------------+------------+----------+
| stname | stid | stage | starea | stbranch | stpocket |
+---------+------+-------+-------------+------------+----------+
| havesh | 102 | 18 | ayyanthole | marine | 500 |
| ruthvik | 103 | 20 | nehru nagar | aerospace | 250 |
| harith | 104 | 20 | west fort | mechanical | 100 |
+---------+------+-------+-------------+------------+----------+
3 rows in set (0.00 sec)

8
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No : 3

Performing DCL commands GRANT and REVOKE

AIM
To manipulate database using DCL commands.

COMMANDS

Grant Privileges on Table

You can grant users various privileges to tables. These permissions can be any combination of
SELECT, INSERT, UPDATE, DELETE, INDEX, CREATE, ALTER, DROP, GRANT OPTION or
ALL.

Syntax

GRANT privileges ON object TO user;

Revoke Privileges on Table

Once you have granted privileges, you may need to revoke some or all of these privileges. To do
this, you can run a revoke command. You can revoke any combination of SELECT, INSERT,
UPDATE, DELETE, REFERENCES, ALTER, or ALL.

Syntax

REVOKE privileges ON object FROM user;

mysql -u root -p

create user 'UI@localhost' identified by 'jecc@1234';

create database class;

use class;

create table stud (id int primary key auto_increment,name char(20),age int);

mysql -u UI@localhost -p

use class;

create table students (id int primary key auto_increment,name char(50),dob date, age int);

CREATE command denied to user 'UI@localhost'@'localhost' for table 'students'

insert into stud (name,age) values ('naveen',20);


9
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

select * from stud;


+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | naveen | 20 |
+----+--------+------+

delete from stud;

DELETE command denied to user 'UI@localhost'@'localhost' for table 'stud'

mysql -u root -p

use class;

select * from stud;


+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | naveen | 20 |
+----+--------+------+

GRANT ALL ON class.* to 'UI@localhost' WITH GRANT option ;

create user 'GUI@localhost' identified by 'jecc@1234';

mysql -u UI@localhost -p

use class;

create table student (id int primary key auto_increment,name char(50),dob date, age int);

show tables;
+-----------------+
| Tables_in_class |
+-----------------+
| stud |
| student |
+-----------------+

insert into stud (name,age) values ('nas',20);

select * from stud;


+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | naveen | 20 |
| 2 | nas | 20 |
+----+--------+------+
10
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

delete from stud where id=2 ;

select * from stud;


+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | naveen | 20 |
+----+--------+------+

GRANT INSERT,SELECT ON class.* to 'GUI@localhost';

mysql -u GUI@localhost -p

use class;

create table student (id int primary key auto_increment,name char(50),dob date, age int);

CREATE command denied to user 'UI@localhost'@'localhost' for table 'students'

insert into stud (name,age) values ('nas',20);

select * from stud;


+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | naveen | 20 |
| 3 | nas | 20 |
+----+--------+------+

mysql -u root -p

REVOKE ALL ON class.* from 'UI@localhost';

mysql -u UI@localhost -p

use class;

insert into stud (name,age) values ('naveen',20);

INSERT command denied to user 'UI@localhost'@'localhost' for table 'stud'

mysql -u GUI@localhost -p

11
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No : 4

Performing TCL commands COMMIT and ROLLBACK

AIM
To manipulate database using TCL commands.

These statements provide control over use of transactions:

START TRANSACTION or BEGIN start a new transaction.

COMMIT commits the current transaction, making its changes permanent.

ROLLBACK rolls back the current transaction, canceling its changes.

SET autocommit disables or enables the default autocommit mode for the current session.

By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a
statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent.
The change cannot be rolled back.

create database cserebels;

create table stud (id int primary key auto_increment,name char(50),dob date,age int);

start transaction;

insert into students (name,dob,age) values ('naveen',"1996-08-20",20);

insert into students (name,dob,age) values ('sathya',"1996-06-10",21);

SELECT * FROM students;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1996-09-10 | 21 |
+----+------------+--------------------+------+

ROLLBACK;

SELECT * FROM students;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1996-09-10 | 21 |
+----+------------+--------------------+------+
12
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

SET autocommit=0 ;

savepoint s1;

update students SET dob="1997-09-10" where id=2;

SELECT * FROM students;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1997-09-10 | 21 |
+----+------------+--------------------+------+

ROLLBACK to s1;

SELECT * FROM students;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1996-09-10 | 21 |
+----+------------+--------------------+------+

update students SET dob="1997-09-10" and age=20 where id=2;

SELECT * FROM students;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1997-09-10 | 20 |
+----+------------+--------------------+------+

commit;

insert into students (name,dob,age) values ('kathir',"1995-06-15",22);

SELECT * FROM students;

+----+-----------+--------------------+--------+
| id | name | dob | age |
+----+------------+-------------------+--------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1997-09-10 | 20 |
| 3 | kathir | 1995-06-15 | 22 |
+----+-------------+-------------------+-------+
13
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

ROLLBACK;

+----+-------------+-------------------+------+
| id | name | dob | age|
+----+-------------+-------------------+------+
| 1 | naveen | 1997-08-20 | 20 |
| 2 | sathya | 1997-09-10 | 20 |
+----+------------+--------------------+------+

14
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No : 5

Performing SET operations, Nested and Join queries

AIM

To query database using SET operations, nested and join queries

UNION is used to combine the result from multiple SELECT statements into a single result set.

mysql> select * from students;


+-------+--------+------------+------+
| id | name | phno | age |
+-------+--------+------------+------+
| 12345 | | 1234123412 | 19 |
| 12346 | arjith | 1234123413 | 17 |
| 12347 | arjith | 1234123417 | 13 |
| 12348 | | 1234123418 | 13 |
| 12349 | NULL | 1234123410 | 13 |
+-------+--------+------------+------+

mysql> select * from sub;


+------+-------+-------+------+
| code | sname | id | dept |
+------+-------+-------+------+
| 123 | dda | 12347 | ME |
| 123 | ddc | 12346 | CS |
+------+-------+-------+------+
2 rows in set (0.00 sec)

mysql> select id from sub where id IN (select id from students where age=13);
+-------+
| id |
+-------+
| 12347 |
+-------+
1 row in set (0.00 sec)

mysql> select * from students UNION select * from sub;


+-------+--------+------------+------+
| id | name | phno | age |
+-------+--------+------------+------+
| 12345 | | 1234123412 | 19 |
| 12346 | arjith | 1234123413 | 17 |
| 12347 | arjith | 1234123417 | 13 |
| 12348 | | 1234123418 | 13 |
| 12349 | NULL | 1234123410 | 13 |
| 123 | dda | 12347 | ME |
| 123 | ddc | 12346 | CS |
15
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
+-------+--------+------------+------+
7 rows in set (0.00 sec)

mysql> select students.id,students.name,sub.id,sub.sname from students LEFT JOIN sub ON


students.id=sub.id;+-------+--------+-------+-------+
| id | name | id | sname |
+-------+--------+-------+-------+
| 12345 | | NULL | NULL |
| 12346 | arjith | 12346 | ddc |
| 12347 | arjith | 12347 | dda |
| 12348 | | NULL | NULL |
| 12349 | NULL | NULL | NULL |
+-------+--------+-------+-------+
5 rows in set (0.00 sec)

mysql> select * from students join sub on students.id=sub.id;


+-------+--------+------------+------+------+-------+-------+------+
| id | name | phno | age | code | sname | id | dept |
+-------+--------+------------+------+------+-------+-------+------+
| 12347 | arjith | 1234123417 | 13 | 123 | dda | 12347 | ME |
| 12346 | arjith | 1234123413 | 17 | 123 | ddc | 12346 | CS |
+-------+--------+------------+------+------+-------+-------+------+
2 rows in set (0.00 sec)

mysql> select id,name from students where EXISTS (select sname from sub where id=students.id);
+-------+--------+
| id | name |
+-------+--------+
| 12346 | arjith |
| 12347 | arjith |
+-------+--------+
2 rows in set (0.00 sec)

mysql> select id,name from students where NOT EXISTS (select sname from sub where
id=students.id);
+-------+------+
| id | name |
+-------+------+
| 12345 | |
| 12348 | |
| 12349 | NULL |
+-------+------+
3 rows in set (0.00 sec)

16
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No : 6

To implement stored functions

AIM

To implement stored functions in database.

Stored Functions

A stored function is a special kind stored program that returns a single value. You use stored
functions to encapsulate common formulas or business rules that are reusable among SQL
statements or stored programs. Different from a stored procedure, you can use a stored function in
SQL statements wherever an expression is used. This helps improve the readability and
maintainability of the procedural code.

Syntax

CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ]


RETURNS return_datatype

BEGIN

declaration_section

executable_section

END;

mysql> DELIMITER $$
mysql>
mysql> CREATE FUNCTION CustomerLevel(p_creditLimit double) RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE lvl varchar(10);

IF p_creditLimit > 50000 THEN


SET lvl = 'PLATINUM';
ELSEIF (p_creditLimit <= 50000 AND p_creditLimit >= 10000) THEN
SET lvl = 'GOLD';
ELSEIF p_creditLimit < 10000 THEN
SET lvl = 'SILVER';
END IF;

RETURN (lvl);
END
$$
Query OK, 0 rows affected (0.00 sec)
17
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
mysql>

SELECT customerName, CustomerLevel(creditLimit)


FROM
customers
ORDER BY customerName;
$$
ERROR 1146 (42S02): Table 'test.customers' doesn't exist
mysql> SELECT name, CustomerLevel(creditLimit) FROM cust ORDER BY name;$$
+------+----------------------------+
| name | CustomerLevel(creditLimit) |
+------+----------------------------+
| ann | GOLD |
| annu | PLATINUM |
| anu | GOLD |
+------+----------------------------+
3 rows in set (0.04 sec)

18
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No: 7

To implement stored procedures

AIM

To implement stored procedures in database.

A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular


computing language, stored in database. A procedure has a name, a parameter list, and SQL
statement(s).

Syntax

CREATE PROCEDURE procedure_name [ (parameter datatype [, parameter datatype]) ]

BEGIN

declaration_section

executable_section

END;

DELIMITER $$
CREATE PROCEDURE CountOrderByStatus(IN orderStatus VARCHAR(25),OUT total INT)
BEGIN
SELECT count(orderNumber) INTO total FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;

CALL CountOrderByStatus('Shipped',@total);
SELECT @total;

Delimiter

19
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
The delimiter is the character or string of characters which is used to
complete an SQL statement. By default we use semicolon (;) as a delimit-
er. But this causes problem in stored procedure because a procedure can
have many statements, and everyone must end with a semicolon. So for your
delimiter, pick a string which is rarely occur within statement or within
procedure

mysql> DELIMITER $$ ;

Now the default DELIMITER is "$$". Let execute a simple SQL command :

mysql> SELECT * FROM user $$


+----------+-----------+--------+
| userid | password | name |
+----------+-----------+--------+
| scott123 | 123@sco | Scott |
| ferp6734 | dloeiu@&3 | Palash |
| diana094 | ku$j@23 | Diana |
+----------+-----------+--------+
3 rows in set (0.00 sec)

Now execute the following command to resume ";" as a delimiter :

mysql> DELIMITER ; $$

TO SET DELIMITER
delimiter $$
select * from Salesman $$

+-------------+--------+---------+------------+
| salesman_id | name | city | commission |
+-------------+--------+---------+------------+
| 5000 | James | NewYork | 0.2 |
| 5001 | Sharon | London | 0.25 |
| 5003 | Hammer | London | 0.25 |
| 5002 | Nail | Paris | 0.3 |
+-------------+--------+---------+------------+

CREATE PROCEDURE

create procedure selector()


begin
select city from Salesman;
end
$$

mysql> call selector()$$


+---------+
| city |
+---------+
| NewYork |
| London |
| London |
| Paris |
+---------+

20
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

GIVING PARAMETERS

create procedure getinput(IN city_name varchar(20))


begin
select * from Salesman where city=city_name;
end
$$

call getinput("London")$$
+-------------+--------+--------+------------+
| salesman_id | name | city | commission |
+-------------+--------+--------+------------+
| 5001 | Sharon | London | 0.25 |
| 5003 | Hammer | London | 0.25 |
+-------------+--------+--------+------------+

TAKING OUTPUT

create procedure inout1(IN c float, OUT total int)


begin
select count(*) into total from Salesman where commission=c;
end
$$

mysql> call inout1(0.25,@total)$$


mysql> select @total$$
+--------+
| @total |
+--------+
| 2 |
+--------+
USING IF STATEMENTS

select * from details;


-> $$
+----+--------+------+--------+
| id | name | age | totalm |
+----+--------+------+--------+
| 1 | john | 19 | 100 |
| 2 | don | 16 | 80 |
| 3 | laya | 22 | 99 |
| 4 | manu | 10 | 80 |
| 5 | mariya | 20 | 100 |
| 6 | mary | 22 | 100 |
| 7 | mujeeb | 20 | 75 |
| 8 | neeva | 20 | 74 |
+----+--------+------+--------+

create procedure marklessn(IN a int,OUT names varchar(20))


begin declare c int;
select count(*) into c from details where totalm<a;
if(c>1) then select name from details where totalm<a;
end if;
end
$$
call marklessn(80,@names)$$

21
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
+--------+
| name |
+--------+
| mujeeb |
| neeva |
+--------+
create procedure outin(IN c float, OUT total int)
begin
select count(*) into total from Salesman where commission=c;
if(total>1) then
select distinct city from Salesman where commission=c ;
end if;
end
$$
call outin(0.25,@total)$$

+--------+
| city |
+--------+
| London |
| London |
+--------+
IF ELSE IF STATEMENTS SYNTAX

if (exp) then
statement;
elseif (exp) then
statement;
else
statement;
end if;

FOR LOOP
delimiter #
create procedure insrt(IN num float)
begin declare x int;
set x=0; label1:
loop insert into number values(rand());
set x=x+1;
if x>num then leave label1;
end if;
end loop;
end#

create table number(num float);


call insrt(5)#
select* from number#
+-----------+
| num |
+-----------+
| 0.0350382 |
| 0.24464 |
| 0.118086 |
| 0.856508 |
| 0.928282 |
| 0.0718884 |
+-----------+

22
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No: 8

To implement cursors

AIM

To implement cursors in database.

1 DECLARE cursor_name CURSOR FOR SELECT_statement;


The cursor declaration must be after any variable declaration. If you declare a cursor before varia-
bles declaration, MySQL will issue an error. A cursor must always be associated with a SELECT
statement.
Next, you open the cursor by using the OPEN statement. The OPEN statement initializes the result set
for the cursor, therefore, you must call the OPEN statement before fetching rows from the result set.

2 OPEN cursor_name;
Then, you use the FETCH statement to retrieve the next row pointed by the cursor and move the cur-
sor to the next row in the result set.
3 FETCH cursor_name INTO variables list;
After that, you can check to see if there is any row available before fetching it.
Finally, you call the CLOSE statement to deactivate the cursor and release the memory associated
with it as follows:
4 CLOSE cursor_name;
When the cursor is no longer used, you should close it.
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the situa-
tion when the cursor could not find any row. Because each time you call the FETCH statement, the
cursor attempts to read the next row in the result set. When the cursor reaches the end of the result
set, it will not be able to get the data, and a condition is raised. The handler is used to handle this
condition.
To declare a NOT FOUND handler, you use the following syntax:
5 DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
Where finished is a variable to indicate that the cursor has reached the end of the result set. Notice
that the handler declaration must appear after variable and cursor declaration inside the stored pro-
cedures.
The following diagram illustrates how MySQL cursor works.

23
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

mysql> DELIMITER $$
mysql>
mysql> CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
BEGIN

DECLARE v_finished INTEGER DEFAULT 0;


DECLARE v_email varchar(100) DEFAULT "";

-- declare cursor for employee email


DEClARE email_cursor CURSOR FOR
SELECT email FROM employees;

-- declare NOT FOUND handler


DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

OPEN email_cursor;

get_email: LOOP

FETCH email_cursor INTO v_email;

IF v_finished = 1 THEN
LEAVE get_email;
END IF;

-- build email list


SET email_list = CONCAT(v_email,";",email_list);

END LOOP get_email;

CLOSE email_cursor;

END$$
Query OK, 0 rows affected (0.09 sec)
mysql>

24
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
mysql> DELIMITER ;
mysql> SET @email_list = "";
Query OK, 0 rows affected (0.00 sec)
mysql> CALL build_email_list(@email_list);
Query OK, 0 rows affected (0.05 sec)
mysql> SELECT @email_list;
+----------------------------+
| @email_list |
+----------------------------+
| jim@jecc;tim@jecc;tom@abc; |
+----------------------------+
1 row in set (0.00 sec)

25
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No: 9

To implement triggers

AIM

To implement triggers in database.

A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is executed
or fired whenever an event associated with a table occurs e.g., insert, update or delete.
A SQL trigger is a special type of stored procedure. The main difference between a trigger and a
stored procedure is that a trigger is called automatically when a data modification event is made
against a table whereas a stored procedure must be called explicitly.

We can to define maximum six triggers for each table.


 BEFORE INSERT – activated before data is inserted into the table.
 AFTER INSERT – activated after data is inserted into the table.
 BEFORE UPDATE – activated before data in the table is updated.
 AFTER UPDATE – activated after data in the table is updated.
 BEFORE DELETE – activated before data is removed from the table.
 AFTER DELETE – activated after data is removed from the table.

Syntax

CREATE TRIGGER trigger_name trigger_time trigger_event


ON table_name
FOR EACH ROW
BEGIN
...
END;

mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));


Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
FOR EACH ROW SET @sum = @sum + NEW.amount;
Query OK, 0 rows affected (0.01 sec)
mysql> SET @sum = 0;
mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);
mysql> SELECT @sum AS 'Total amount inserted';
CREATE TRIGGER ins_transaction BEFORE INSERT ON account
26
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
FOR EACH ROW PRECEDES ins_sum
SET
@deposits = @deposits + IF(NEW.amount>0,NEW.amount,0),
@withdrawals = @withdrawals + IF(NEW.amount<0,-NEW.amount,0);
CREATE TABLE employees_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
employeeNumber INT NOT NULL,
lastname VARCHAR(50) NOT NULL,
changedat DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL
);
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;

27
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No: 10

To create views

AIM

To create views in database.

A database view is a virtual table or logical table which is defined as a SQL SELECT query with
joins. Because a database view is similar to a database table, which consists of rows and columns,
so you can query data against it. Most database management systems, including MySQL, allow you
to update data in the underlying tables through the database view with some prerequisites.

CREATE VIEW [database_name].[view_name]


AS
[SELECT statement]

select * from bint1;


+----+---------+------+------------+
| id | name | age | phone |
+----+---------+------+------------+
| 1 | bineesh | 30 | 9945944 |
| 2 | aneesh | 31 | 2147483647 |
+----+---------+------+------------+

select * from bint2 ;


+------+-------+------+------+
| id | sname | code | dept |
+------+-------+------+------+
| 1 | dc | 307 | cs |
| 3 | toc | 308 | cs |
| 4 | itc | 309 | ec |
| 2 | ddc | 306 | me |
+------+-------+------+------+

create view v as select bint1.name, bint1.phone from bint1, bint2 where


bint1.id = bint2.id;
desc v;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| phone | int(11) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+

create view v1 as select bint1.name, bint1.phone, bint2.sname, bint2.dept


from bint1, bint2 where bint1.id = bint2.id;

28
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

desc v1;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| phone | int(11) | YES | | NULL | |
| sname | varchar(20) | YES | | NULL | |
| dept | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+

create view detailed as select bint1.id, bint1.name, bint2.sname,


bint2.code from bint1, bint2 where bint1.id = bint2.id;

desc detailed;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| name | varchar(20) | YES | | NULL | |
| sname | varchar(20) | YES | | NULL | |
| code | int(11) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+

create table new (id int auto_increment not null primary key, mark1 int
not null, mark2 int not null);

desc new;
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| mark1 | int(11) | NO | | NULL | |
| mark2 | int(11) | NO | | NULL | |
+-------+---------+------+-----+---------+----------------+

alter table new add column studentid int after id;

desc new;
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| studentid | int(11) | YES | | NULL | |
| mark1 | int(11) | NO | | NULL | |
| mark2 | int(11) | NO | | NULL | |
+-----------+---------+------+-----+---------+----------------+

insert into new (studentid, mark1, mark2) values (1, 40, 50);
insert into new (studentid, mark1, mark2) values (2, 50, 50);
insert into new (studentid, mark1, mark2) values (3, 50, 60);
insert into new (studentid, mark1, mark2) values (4, 56, 60);

29
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

select * from new;


+----+-----------+-------+-------+
| id | studentid | mark1 | mark2 |
+----+-----------+-------+-------+
| 1 | 1 | 40 | 50 |
| 2 | 2 | 50 | 50 |
| 3 | 3 | 50 | 60 |
| 4 | 4 | 56 | 60 |
+----+-----------+-------+-------+

create view rank as select new.id, new.studentid, new.mark1+new.mark2 as


total from new order by total desc;

desc rank;
+-----------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| studentid | int(11) | YES | | NULL | |
| total | bigint(12) | NO | | 0 | |
+-----------+------------+------+-----+---------+-------+
select * from rank;
+----+-----------+-------+
| id | studentid | total |
+----+-----------+-------+
| 4 | 4 | 116 |
| 3 | 3 | 110 |
| 2 | 2 | 100 |
| 1 | 1 | 90 |
+----+-----------+-------+

create view rank2 as select new.id, new.studentid, new.mark1+new.mark2 as


total from new order by total asc;
Query OK, 0 rows affected (0.04 sec)

mysql> select * from rank2;


+----+-----------+-------+
| id | studentid | total |
+----+-----------+-------+
| 1 | 1 | 90 |
| 2 | 2 | 100 |
| 3 | 3 | 110 |
| 4 | 4 | 116 |
+----+-----------+-------+

30
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Ex. No: 11

To import a database

AIM

To import a sample database.

URL:https://raw.githubusercontent.com/datacharmer/test_db/master/sakila/s
akila-mv-schema.sql

:https://raw.githubusercontent.com/datacharmer/test_db/master/sakila/saki
la-mv-data.sql

Download schema and data from above link

[10:41:20] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql -u root -p


Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 53
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights re-
served.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql> use databases;


ERROR 1049 (42000): Unknown database 'databases'
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| cerebrals |
| class |
| college |
| cse |
| jyothi |
| jyothi1 |
| lbook |
| mydb |
| mysql |
| performance_schema |
| phpmyadmin |
| s5csea |
| testdb |
31
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
| testdb1 |
+--------------------+
15 rows in set (0.00 sec)

mysql> create database cseb;


Query OK, 1 row affected (0.00 sec)

mysql> show databases;


+--------------------+
| Database |
+--------------------+
| information_schema |
| cerebrals |
| class |
| college |
| cse |
| cseb |
| jyothi |
| jyothi1 |
| lbook |
| mydb |
| mysql |
| performance_schema |
| phpmyadmin |
| s5csea |
| testdb |
| testdb1 |
+--------------------+
16 rows in set (0.00 sec)

mysql> exit
Bye
[10:43:26] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql cseb -u
root -p < sakila-mv-schema.sql
Enter password:
^[[A%
[10:43:39] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql cseb -u
root -p < sakila-mv-data.sql
Enter password:
[10:43:56] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql -u root -
pjoss
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 56
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights re-
served.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql> show databases;


+--------------------+

32
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab
| Database |
+--------------------+
| information_schema |
| cerebrals |
| class |
| college |
| cse |
| cseb |
| jyothi |
| jyothi1 |
| lbook |
| mydb |
| mysql |
| performance_schema |
| phpmyadmin |
| s5csea |
| sakila |
| testdb |
| testdb1 |
+--------------------+
17 rows in set (0.00 sec)

mysql> exit
Bye
[10:44:33] pe :: pe20 âžœ ~/Downloads » mysqldump sakila -u root -p >
backup.sql
Enter password:
[10:45:09] pe :: pe20 âžœ ~/Downloads » mysql -u root -pjoss
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 58
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights re-
served.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql> drop sakila;


ERROR 1064 (42000): You have an error in your SQL syntax; check the manu-
al that corresponds to your MySQL server version for the right syntax to
use near 'sakila' at line 1
mysql> drop database sakila;
Query OK, 23 rows affected (0.39 sec)

mysql> exit
Bye
[10:48:26] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql cseb -u
root -p < backup.sql
Enter password:
[10:48:52] pe :: pe20 ➜ ~/Downloads ‹master*› » mysql -u root -
pjoss
Welcome to the MySQL monitor. Commands end with ; or \g.

33
Jyothi Engineering. College Dept of Computer Science & Engg.
CS 333 Application Software Development Lab

Your MySQL connection id is 60


Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights re-
served.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql> use cseb;


Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_cseb |
+----------------------------+
| actor |
| actor_info |
| address |
| category |
| city |
| country |
| customer |
| customer_list |
| film |
| film_actor |
| film_category |
| film_list |
| film_text |
| inventory |
| language |
| nicer_but_slower_film_list |
| payment |
| rental |
| sales_by_film_category |
| sales_by_store |
| staff |
| staff_list |
| store |
+----------------------------

34
Jyothi Engineering. College Dept of Computer Science & Engg.

You might also like