0% found this document useful (0 votes)
16 views73 pages

Dbms Lab Manual Reg2021 24-25

The document outlines a series of experiments focused on SQL commands and database management, including creating tables, adding constraints, and performing data manipulation. It details the use of Data Definition Language (DDL) and Data Manipulation Language (DML) commands, along with integrity constraints and examples of SQL queries. Additionally, it covers advanced topics such as SQL injection and data encryption techniques.

Uploaded by

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

Dbms Lab Manual Reg2021 24-25

The document outlines a series of experiments focused on SQL commands and database management, including creating tables, adding constraints, and performing data manipulation. It details the use of Data Definition Language (DDL) and Data Manipulation Language (DML) commands, along with integrity constraints and examples of SQL queries. Additionally, it covers advanced topics such as SQL injection and data encryption techniques.

Uploaded by

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

INDEX

EX
DATE NAME OF THE EXPERIMENT PAGE STAFF SIGN
.
NO.
NO
Create a database table, add constraints (primary
key, unique, check, Not null), insert rows, update
and delete rows using SQL DDL and DML
1 Commands.

Create a set of tables, add foreign key constraints


2. and incorporate referential integrity.

Query the database tables using different ‘where’


Clause Conditions and also Implement aggregate
3 functions.
Query the database tables and explore sub queries
and simple join operations.
4

Query the database tables and explore natural, equi


5 and outer joins

Write​ user​ defined​ functions​ and​


6 stored procedures in SQL.

Execute complex transactions and realize DCL


and TCL commands.
7
Write SQL Triggers for insert, delete and update
operations in a database table.
8

Create a view and index for database tables with a


9 large number of records.

10 Use SQLi to authenticate as administrator, to get


unauthorized access over sensitive data,
to inject malicious statements into the form field.
11 Write programs that will defend against the SQLi
attacks.

12 Write queries to insert encrypted data into the


database and to retrieve the data using
decryption.
Create a Database Table, Add Constraints (Primary Key, Unique, Check, Not Null),
EXP. NO: 1
Insert Rows, Update and Delete Rows using SQL DDL and DML Commands.
DATE:

Aim:

To create a Database Table, Add Constraints (Primary Key, Unique, Check, Not Null), Insert Rows, Update
and Delete Rows using SQL DDL and DML Commands.

Procedure:

DATA DEFINITION LANGUAGE (DDL) COMMANDS


1.​DDL COMMAND
- It is used to communicate with database. DDL is used to:
✔​ Create an object
✔​ Alter the structure of an object
✔​ To drop the object created.
2.​The commands used are: Create, Alter, Drop, Truncate

3.​INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. It has
enforcing the rules for the columns in a table. The types of the integrity constraints are:
(a) Domain Integrity (b) Entity Integrity (c) Referential Integrity
(a)​Domain Integrity
This constraint sets a range and any violations that take place will prevent the user from performing the
manipulation that caused the breach. It includes:
Not Null constraint:
While creating tables, by default the rows can have null value the enforcement of not null constraint in a table
ensure that the table contains values.
Principle of null values:
✔​ Setting null value is appropriate when the actual value is unknown, or when a value would not
be meaningful.
✔​ A null value is not equivalent to a value of zero.
✔​ A null value will always evaluate to null in any expression.
✔​ When a column name is defined as not null, that column becomes a mandatory i.e., the user has
to enter data into it.
✔​ Not null Integrity constraint cannot be defined using the alter table command when the table
contain rows.
Check Constraint
Check constraint can be defined to allow only a particular range of values. When the manipulation violates this
constraint, the record will be rejected. Check condition cannot contain sub queries.

b)​Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table represents an instance of
that entity. To identify each row in a table uniquely we need to use this constraint. There are 2 entity
constraints:

Unique key constraint


It is used to ensure that information in the column for each record is unique, as with telephone or drivers
license numbers. It prevents the duplication of value with rows of a specified column in a set of column. A
column defined with the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination of column cannot be specified.
Maximum combination of columns that a composite unique key can contain is 16.

Primary Key Constraint


A primary key avoids duplication of rows and does not allow null values. It can be defined on one or more
columns in a table and is used to uniquely identify each row in a table. These values should never be changed
and should never be null.
A table should have only one primary key. If a primary key constraint is assigned to more than one column or
combination of column is said to be composite primary key, which can contain 16 columns.

c)​Referential Integrity
It enforces relationship between tables. To establish parent-child relationship between 2 tables having a
common column definition, we make use of this constraint. To implement this, we should define the column in
the parent table as primary key and same column in the child table as foreign key referring to the
corresponding parent entry.

Foreign key
A column or combination of column included in the definition of referential integrity, which would refer to a
referenced key.

Referenced key
It is a unique or primary key upon which is defined on a column belonging to the parent table.
SQL Commands:

Create Table
​ It is used to create a table
Syntax:
Create table tablename (column_name1 data_type constraints, column_name2 data_type constraints ...)
Example:
Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint unique, DeptNo
number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null, dob date not null);

Rules
1.​Reserved words cannot be used.
2.​Underscore, numerals, letters are allowed but not blank space.
3.​Maximum length for the table name is 30 characters.
4.​Different tables should not have same name.
5.​We should specify a unique column name.
6.​We should specify proper data type along with width.
7.​We can include "not null" condition when needed. By default it is,null".

Alter Table
Alter command is used to
1.​Add a new column.
2.​Modify the existing column definition.
3.​To include or drop integrity constraint.
Syntax:
Alter table tablename add/modify (attribute datatype(size));
Example:
1.​Alter table emp add (phone_no char (20));
2.​Alter table emp modify(phone_no number (10));
3.​ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
Drop Table
It will delete the table structure provided the table should be empty.
Example: drop table prog20;
Here prog20 is table name

Truncate Table
If there is no further use of records stored in a table and the structure has to be retained then the records alone
can be deleted.
Syntax:
TRUNCATE TABLE <TABLE NAME>;
Example: Truncate table stud;

DESC
This is used to view the structure of the table.
Example: desc
emp;
Name Null? Type

EmpNo NOT NULL number(5)


ENameVarChar(15)
Job NOT NULL Char(10)
DeptNo NOT NULL number(3)
PHONE NO number (10)

DOMAIN INTEGRITY
Example:
Create table cust(custid number(6) not null, name char(10));
Alter table cust modify (name not null);

CHECK CONSTRAINT
Example
Create table student (regno number (6), mark number (3) constraint b check (mark>=0 and mark <=100));
Alter table student add constraint b2 check (length(regno<=4));
ENTITY INTEGRITY
(a)​ Unique key
constraint Example
Create table cust(custid number(6) constraint uni unique, name char(10));
Alter table cust add(constraint c unique(custid));

(b)​ Primary Key


Constraint Example
Create table stud(regno number(6) constraint primary key, name char(20));

Queries:
Q1. Create a table called EMP with the following
structure. Name​ Type
----------------​ --------------------------------
EMPNO​ ​ NUMBER(6)
ENAME​ VARCHAR2(20)
JOB​ VARCHAR2(10)
DEPTNO​ NUMBER(3)
SAL​ NUMBER(7,2)
Allow NULL for all columns except ename and job.

Solution:
1.​Understand create table syntax.
2.​Use the create table syntax to create the said tables.
3.​Create primary key constraint for each table as understand from logical table structure.
Ans.
SQL> create table emp(empno number(6),ename varchar2(20)not null job varchar2(10) not null, deptno
number(3), sal number(7,2));
Table created.

Q2. Add a column experience to the emp table. experience numeric null allowed.
Solution:
1.​Learn alter table syntax.
2.​Define the new column and its data type.
3.​Use the alter table syntax.
Ans.
SQL> alter table emp add(experience number(2));
Table altered.
Q3. Modify the column width of the job field of emp table.
Solution:
1.​Use the alter table syntax.
2.​Modify the column width and its data type.
Ans.
SQL> alter table emp modify(job varchar2(12));
Table altered.
SQL> alter table emp modify(job varchar(13));
Table altered.

Q4. Create dept table with the following structure.


Name​ Type
------------------​ -------------------------------
DEPTNO​ NUMBER(2)
DNAME​ VARCHAR2(10)
LOC​ VARCHAR2(10)
Deptno as the primarykey
Solution:
1.​Understand create table syntax.
2.​Decide the name of the table.
3.​Decide the name of each column and its data type.
4.​Use the create table syntax to create the said tables.
5.​Create primary key constraint for each table as understand from logical table structure.
Ans.
SQL> create table dept(deptno number(2) primary key.dname varchar2(10),loc varchar2(10));
Table created.

Q5. Create the empl table with ename and empno, add constraints to check the empno value while
entering (i.e) empno> 100.
Solution:
1.​Learn alter table syntax.
2.​Define the new constraint [columns name type]
3.​Use the alter table syntax for adding constraints.
Ans.
SQL> create table empl(ename varchar2(10),empno number(6) constraint check(empno>100));
Table created.
Q6. Drop a column experience to the emp table.
Solution:
1. Learn alter table syntax. Use the alter table syntax to drop the column.
Ans.
SQL> alter table emp drop column experience;
Table altered.

Q7. Truncate the emp table and drop the dept table
Solution:
1.​Learn drop, truncate table syntax.
Ans.
SQL> truncate table emp;
Table truncated.
SQL> drop table dept;
Table dropped.

DATA MANIPULATION LANGUAGE (DML) COMMANDS

1.​DML COMMAND
DML commands are the most frequently used SQL commands and is used to query and manipulate the
existing database objects. Some of the commands are Insert, Select, Update, Delete
2.​Insert Command
This is used to add one or more rows to a table. The values are separated by commas and the data types char
and date are enclosed in apostrophes. The values must be entered in the same order as they are defined.
3.​Select Commands
It is used to retrieve information from the table. it is generally referred to as querying the table. We can either
display all columns in a table or only specify column from the table.
4.​Update Command
It is used to alter the column values in a table. A single column may be updated or more than one column
could be updated.
5.​Delete command
After inserting row in a table we can also delete them if required. The delete command consists of a from
clause followed by an optional where clause.
(c)​ SQL
Commands INSERT
COMMAND
Inserting a single row into a table
Syntax: insert into <table name> values (value list)
Example: insert into s values(“S3","sup3","blore",10)

Inserting more than one record using a single insert


commands Syntax: insert into <table name> values (&coll,
&col2,​ )
Example: insert into stud values(&reg, &name, &percentage);

Skipping the fields while inserting


insert into <tablename(coln names to which datas to be inserted)> values (list of values);
Other way is to give null while passing the values.

SELECT COMMANDS
Selects all rows from the table
Syntax: Select * from tablename;
Example: Select * from IT;

The retrieval of specific columns from a table


It retrieves the specified columns from the table
Syntax: Select column_namel,​ ,column_namen from table name;
Example: Select empno, empname from emp;

Elimination of duplicates from the select clause


It prevents retrieving the duplicated values. Distinct keyword is to be used.
Syntax: Select DISTINCT coll, col2 from table name;
Example: Select DISTINCT job from emp;

Select command with where clause


To select specific rows from a table we include “where" clause in the select command. It can appear only after
the "from" clause.
Syntax: Select column_namel,​ ,column_namen from table name where condition;
Example: Select empno, empname from emp where sal>4000;
Select command with order by clause
Syntax: Select column_namel,​ ,column_namen from table name where conditionorder by colmnname;
Example: Select empno, empname from emp order by empno;

Select command to create a table


Syntax: create table tablename as select * from existing_tablename;
Example: create table empl as select * from emp;

Select command to insert records:


Syntax: insert into tablename (select columns from existing_tablename);
Example: insert into empl (select * from emp);

UPDATE COMMAND
Syntax: update tablename set field=values where condition;
Example: Update emp set sal = 10000 where empno =135;

DELETE COMMAND
Syntax: Delete from table where conditions;
Example: delete from emp where empno =135;

Queries
Q1. Insert a single record into dept table.
Solution:
1.​Decide the data to add in dept.
2.​Add to dept one row at a time using the insert into syntax.
Ans.
SQL> insert into dept values (1,”TT”, “Tholudur");
1 row created.

Q2. Insert more than a record into emp table using a single insert command.
Ans.
SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename:Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal:
10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
SQL> /
Enter value for empno: 2
Enter value for ename: Arjun
Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2, 'Arjun','ASP',2,12000)
1 row created.
SQL> /
Enter value for empno: 3
Enter value for ename: Gugan
Enter value for job: ASP
Enter value for deptno: 1
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(3,'Gugan','ASP',1,12000)
1 row created.

Q3. Update the emp table to set the salary of all employees to Rs15000/- who are working as ASP
Ans.
SQL> select * from emp;

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL


-------------------------------------------------------------------
1.​ Mathi AP 1 10000
2.​ Arjun ASP 2 12000
3.​ Gugan ASP 1 12000

SQL> update emp set sal=15000 where job=’ASP’;


2 rows updated.
SQL> select * from emp;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
--------------------------------------------------------------------------
1.​ Mathi AP 1 10000
2.​ Arjun ASP 2 15000
3.​ Gugan ASP 1 15000

Q4.Create a pseudo table employee with the same structure as the table emp and insert rows into the
table using select clauses.
Ans.
SQL> create table employee as select * from emp;
Table created.
SQL> desc employee;
Name​ Null? Type
------------------------------------------------------------------------
EMPNO​ NUMBER(6)
ENAME​ NOT NULL VARCHAR2(20)
JOB​ NOT NULL VARCHAR2(13)
DEPTNO​ ​ NUMBER(3)
SAL​ NUMBER(7,2)

Q5. Select employee name, job from the emp table


Ans.
SQL> select ename, job from emp;
ENAME​ JOB

Mathi​ AP
Arjun​ ASP
Gugan​ ASP
Karthik​ Prof
Akalya​ AP
Suresh​ Lect
6 rows selected.
Q6: Delete only those who are working as lecturer
Ans.
SQL> select * from emp;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
------------------------------------------------------------
1.​ Mathi AP 1 10000
2.​ Arjun ASP 2 15000
3.​ Gugan ASP 1 15000
4.​ Karthik Prof 2 30000
5.​ Akalya AP 1 10000
6.​ Suresh Lect 1 8000
6 rows selected.

SQL> delete from emp where job='lect';


1 row deleted.
SQL> select * from emp;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
------------------------------------------------------------
1.​ Mathi AP 1 10000
2.​ Arjun ASP 2 15000
3.​ Gugan ASP 1 15000
4.​ Karthik Prof 2 30000
5.​ Akalya AP 1 10000

Q7. List the records in the emp table orderby salary in ascending order.
Ans.
SQL> select * from emp order by sal;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
------------------------------------------------------------
1. Mathi AP 1 10000
5. Akalya AP 1 10000
2. Arjun AP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
Q8. List the records in the emp table order by salary in descending order.
Ans.
SQL> select * from emp order by sal desc;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
----------------------------------------------------------------
4 Karthik Prof 2 30000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
1 Mathi AP 1 10000
5 Akalya AP 1 10000

Q9. Display only those employees whose deptno is 30.


Solution:
1.​Use SELECT FROM WHERE syntax.
Ans.
SQL> select * from emp where deptno=1;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
----------------------------------------------------------------
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000

Q10. Display deptno from the table employee avoiding the duplicated values.
Solution:
1.​Use SELECT FROM syntax..
2.​Select should include distinct clause for the deptno.
Ans.
SQL> select distinct deptno from emp;
DEPTNO
-------------
1
2
Executed SQL Commands using MySQL:

CREATE DATABASE

ENTITY INTEGRITY

a).​ Unique key


consntraint. Example:-

Create table cust(custid number(6) constraint uni unique, name char(10));

Alter table cust add(constraint c unique (custid));

b).​ Primary key


constraint. SQL Queries :-
1.​Create a table called EMP with the following structure.
2.​Add a column experience to the emp table, experience numeric null allowed.

3.​Modify the column width of the job field of emp table.


SQL> alter table emp modify (job vrchar2(12));
Table altered.
SQL> alter table emp modify(job varchar(13));
Table altered.

4.​Create dept table with the following structure.

5.​ Create the emp1 table with ename and empno, add constraints to check the empno value
entering (i.e) empno>100.
6.​Drop a column experience to the emp table.

7.​Truncate the emp table and drop the dept table.

INSERT COMMAND
SQL Command.
1.​Insert a single record into dept table.
2.​Insert more than a record into emp table using a single insert command.

3.​Update the emp table to set the salary of all employees to Rs 15000/- who are working as ASP.

4.​ Create a pseudo table employee with the same structure as the table emp and insert rows into the
table using select clauses.
5.​ Select employee name, job from the emp table.

6.​ Delete only those who are working as lecturer.

7.​List the records in the emp table orderly salary in ascending order.
8.​List the records in the emp table order by salary in descending order.

9.​Display only those employee whose deptno is 30.

10.​Display deptno from the table employee avoiding the duplicated values.

Result:
Thus the above SQL queries using DDL and DML Commands executed successfully.
EXP. NO: 2
Create a set of tables, add foreign key constraints and incorporate referential
DATE: integrity.

Aim:
To study the various constraints available in the SQL query language.

Procedure:
DOMAIN INTEGRITY CONSTRAINTS
NOT NULL CONSTRAINT
SQL> create table empl (ename varchar2(30) not null, eid varchar2(20) not null);
Table created.
SQL> insert into empl values ('abcde',11);
1 row created.
SQL> insert into empl values ('fghij',12);
1 row created.
SQL> insert into empl values (‘klmno',null);
insert into empl values ('klmno',null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("ITA". "EMPL". "EID")
SQL> select * from
empl; ENAME​ EID

abcde​ 11
fghij​ 12
12

CHECK AS A COLUMN CONSTRAINT


SQL> create table depts (dname varchar2(30) not null, did number(20) not null check (did<10000));
Table created.
SQL> insert into depts values ('sales',9876);
1 row created.
SQL> insert into depts values (‘marketing’,5432);
1 row created.
SQL> insert into depts values ('accounts',789645);
insert into depts values ('accounts,789645)
*
ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003179) violated
SQL> select * from depts;
DNAME​ DID

sales​ 9876
marketing​ 5432

CHECK AS A TABLE CONSTRAINT


SQL> create table airports (aname varchar2(30) not null, aid number(20) not null, acity varchar2(30) check(
acity in ('chennai', 'hyderabad', 'bangalore')));
Table created.
SQL> insert into airports values( 'abcde',
100,'chennai'); 1 row created.
SQL> insert into airports values( 'fghij', 101, ‘hyderabad’);
1 row created.
SQL> insert into airports values('klmno', 102, 'bangalore');
1 row created.
SQL> insert into airports values( 'pqrst', 103,'mumbai');
insert into airports values( 'pqrst', 103, 'mumbai') *
ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003187) violated
SQL> select * from airports;

ANAME​ AID​ ACITY

abcde 100 chennai


fghij 101 hyderabad
klmno 102 bangalore
ENTITY INTEGRITY CONSTRAINTS
UNIQUE AS A COLUMN CONSTRAINT

SQL> create table book (bname varchar2(30) not null, bid number(20) not null unique);
Table created.
SQL> insert into book values ('fairy tales', 1000);
1 row created.
SQL> insert into book values (‘bedtime stories',1001);
1 row created.
SQL> insert into book values ('comics', 1001);
insert into book values ('comics', 1001)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003130) violated
SQL> select * from book;
BNAME​ BID

fairy tales​ 1000


bedtime stories​ 1001

UNIQUE AS A TABLE CONSTRAINT


SQL> create table orders(oname varchar2(30) not null, oid number(20) not null, unique(oname,oid));
Table created.
SQL> insert into orders values ('chair',
2005); 1 row created.
SQL> insert into orders values ('table', 2006);
1 row created.
SQL> insert into orders values ('chair',2007);
1 row created.
SQL> insert into orders values ('chair', 2005);
insert into orders values ('chair', 2005)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003152) violated
SQL> select * from orders;

ONAME OID

chair 2005
table 2006
chair 2007

PRIMARY KEY AS A COLUMN CONSTRAINT

SQL> create table custo ( cname varchar2(30) not null, cid number(20) not null primary key);
Table created.
SQL> insert into custo values ('jones', 506);
1 row created.
SQL> insert into custo values (‘hayden',508);
1 row created.
SQL> insert into custo values ('ricky',506);
insert into custo values ('ricky',506)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003165) violated

SQL> select * from custo;

CNAME​ CID

jones​ 506
hayden​ 508

PRIMARY KEY AS A TABLE CONSTRAINT

SQL> create table branches( bname varchar2(30) not null, bid number(20) not null,primary key(bname,bid));
Table created.
SQL> insert into branches values ('anna nagar', 1005);
1 row created.
SQL> insert into branches values ('adyar',1006);
1 row created.
SQL> insert into branches values ('anna nagar',1007);
1 row created.
SQL> insert into branches values ('anna nagar', 1005);
insert into branches values ('anna nagar', 1005)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003173) violated
SQL> select * from branches;
BNAME BID

anna nagar 1005


adyar 1006
anna nagar 1007

REFERENTIAL INTEGRITY CONSTRAINTS


TO CREATE 'DEPTS' TABLE
SQL> create table depts(city varchar2(20), dno number(5) primary key);
Table created.
SQL> insert into depts values('chennai', 11);
1 row created.
SQL> insert into depts values(‘hyderabad’, 22);
1 row created.

TO CREATE 'SEMP' TABLE


SQL> create table semp(ename varchar2(20), dno number(5) references depts(dno));
Table created.
SQL> insert into semp values('x', 11);
1 row created.
SQL> insert into semp values(‘y’,22);
1 row created.
SQL> select * from semp;
ENAME​ DNO

x​ 11
Y​ 22

ALTER TABLE
SQL> alter table semp add(address varchar2(20));
Table altered..
SQL> update semp set address='10 gandhi road' where dno=11;
1 row updated.
SQL> update semp set address='12 m.g. road' where dno=22;
1 row updated.
SQL > select * from semp;
ENAME DNO ADDRESS
x 11 10 gandhi road
y 22 12 m.g. road
SQL> select city, ename from depts, s2emp where depts.dno = s2emp.dno;
CITY​ ENAME

Chennai​ x
Hyderabad​ y

Executed SQL Commands using MySQL:

DOMAIN INTEGRITY COMNSTRIANTS

NOT NULL CONSTRAINT


CHECK AS A COLUMN CONSNTRAINT

CHECK AS A TABLE CONSNTRAINT

ENTITY INTEGRITY CONSTRAINT


UNIQUE AS A COLUMN CONSTRAINT
UNIQUE AS A TABLE CONSTRAINT

PRIMARY KEY AS COLUMN CONSTRIANT

PRIMARY KEY AS TABLE CONSTRIANT


REFERENTIAL INTEGRITY CONSTRAINT
TO CREATE ‘DEPTS’ TABLE

TO CREATE ‘SEMP’ TABLE

ALTER TABLE

Result:
Thus the various constraints were implemented and the tables were created using the respective constraints.
EXP. NO: 3 Query the Database Tables using Different 'Where' Clause Conditions and also
Implement Aggregate Functions
DATE:

Aim:
To query the database tables using different 'Where' clause conditions and also implement aggregate functions.

Procedure:
AGGREGATE FUNCTIONS

AVG (N): It returns average value of n ignoring null values.


SQL> select avg(spocket) result from studs;
RESULT

400

MIN (EXPR): It returns minimum value of the expression.


SQL> select min(spocket) result from studs;
RESULT

100

COUNT (EXPR): It returns the number of rows where expression is not null.
SQL> select count(spocket) result from studs;
RESULT

4
SQL> select count(spocket) result from studs where sarea=’anna nagar’;
RESULT

COUNT(*): It returns the number of rows in the table including the duplicates and those with null values.
SQL> select count(*) result from studs;
RESULT

4
MAX (EXPR): It returns maximum value of the expression.
SQL> select max(spo ket) result from studs;
RESULT

750
SUM(N): It returns sum of values of n.
SQL> select sum(spocket) result from studs;
RESULT

1600

GROUP BY CLAUSE
The group by clause is another section of the select statement. This optional class tells oracle to group rows
based on distinct values that exists for specified columns.
HAVING CLAUSE
The having clause can be used in conjunction with the group by clause. Having imposes a condition on the
group by clause, which further filters the groups created by the group by clause.

NUMERIC FUNCTIONS
SQL> select abs(-20) result from dual;
RESULT

20

SQL> select power (2,10) result from dual;


RESULT

1024

SQL> select round(15.359,2) result from dual;


RESULT

15.36

SQL> select sqrt (36) result from dual;


RESULT

6
SPECIAL OPERATORS
In/not in - used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between/not between-used to find between the ranges
Like/not like-used to do the pattern matching

Queries
Q1. Display all the details of the records whose employee name starts with _A.
Solution:
1.​Use SELECT FROM WHERE syntax.
2.​Select should include all in the given format.
3.​From should include employee
4.​where should include condition on empname like “A%",
Ans.
SQL> select * from emp where ename like 'A%';
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
----------------------------------------------------------------
2 Arjun ASP 2 15000
5 Akalya AP 1 10000

Q2. Display all the details of the records whose employee name does not starts with _A.
Ans.
SQL> select * from emp where ename not like 'A%';
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
----------------------------------------------------------------
1. Mathi AP 1 10000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000

Q3. Display the rows whose salary ranges from 15000 to 30000.
Ans.
SQL> select * from emp where sal between 15000 and 30000;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
----------------------------------------------------------------
2.​ Arjun ASP 2 15000
3.​ Gugan ASP 1 15000
4.​ Karthik Prof 2 30000
Q4. Calculate the total and average salary amount of the emp table.
Ans.
SQL> select sum(sal), avg(sal) from
emp; SUM(SAL)​AVG(SAL)

80000​ 16000

Q5: Count the total records in the emp table.


Ans.
SQL>select * from emp;

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL


----------------------------------------------------------------
1.​ Mathi ASP 1 10000
2.​ Arjun ASP 2 15000
3.​ Gugan ASP 1 15000
4.​ Karthik Prof 2 30000
5.​ Akalys AP 1 10000

SQL> select count(*) from emp;


COUNT(*)

Q6. Determine the max and min salary and rename the column as max_salary and min_salary.
Solution:
1.​Use the MIN & MAX aggregate function in select clause.
2.​Rename the column as min_sal&max_sal.
Ans.
SQL> select max(sal) as max_salary, min(sal) as min_salary from emp;

MAX_SALARY​ MIN SALARY

30000​ 10000
Q7. Display the month between-1-jun-10land 1-aug-10 in full.
Ans.
SQL>Select month between (“1-jun-2010","1-aug-2010") from dual;

Q8. Display the last day of that month in-05-Oct-091.


Ans.
SQL> Select last day ('1-jun-2009’) from dual;
LAST_DAY(

30-JUN-09

Q9. Find how many job titles are available in employee table.
Solution:
1.​Use select from clause.
2.​Use count function to get the result.
Ans.
SQL> select count(job) from emp;
COUNT(JOB)

4
SQL> select count(distinct job) from emp;
COUNT(DISTINCTJOB)

2
Q10. What is the difference between maximum and minimum salaries of employees in the organization?
Solution:
1.​Use select from clause.
2.​Use function max(),min() and find the difference between them to get the result.
Ans.
SQL> select max(sal), min(sal) from emp;
MAX(SAL)​ MIN(SAL)

20000​ 10000
Executed SQL Commands using MySQL:

CREATE THE TABLE

SQL commands:
1.​Display all the details of the records whose employee name starts with _A’.

2.​Display all the details of the records whose employee name does not starts with _A’.

3.​Display the rows whose salary ranges from 15000 to 30000.


4.​Calculate the total and average salary amount of the emp table.

5.​Count the total records in the emp table.

6.​Determine the max and min salary and rename the column as max_salary and min_salary.

7.​Display the month between –1-jun-10|| and 1-aug-10 in full.

8.​Display the last day of that month in –05-oct-09||.

Result:
Thus the above SQL commands using different ‘where’ clause conditions and also implement aggregate
functions executed successfully.
EXP. NO: 4
Query the Database Tables and Explore Sub Queries and Simple Join Operations
DATE:

Aim:
To write the SQL commands to query the database tables and explore sub queries and simple join operations.

Procedure:
1.​Nested Queries: Nesting of queries one within another is known as a nested queries.
Sub queries: The query within another is known as a sub query. A statement containing sub query is called
parent statement. The rows returned by sub query are used by the parent statement.

2.​Types
1.​Sub queries that return several values
Sub queries can also return more than one value. Such results should be made use along with the operators in
and any.
2.​Multiple queries
Here more than one sub query is used. These multiple sub queries are combined by means of "and" & "or"
keywords.
3.​Correlated sub query
A sub query is evaluated once for the entire parent statement whereas a correlated sub query is evaluated once
per row processed by the parent statement.

3.​Relating Data through Join Concept


The purpose of a join concept is to combine data spread across tables. A join is actually performed by the
"where" clause which combines specified rows of tables.
Syntax:
select columns from tablel, table2 where logical expression;
Types of Joins:
1.Simple Join 2.Self Join 3.Outer Join 4.Inner Join

4.​Simple Join
(a)​Equi-join: A join, which is based on equalities, is called equi- join.
(b)​Non Equi-join: It specifies the relationship between Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give an alias name to the
table in the "from" clause and use it instead of the name throughout the query
5.​ Self join: Joining of a table to itself is known as self-join. It joins one row in a table to another.
It can compare each row of the table to itself and also with other rows of the same table.

6.​ Outer Join: It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The symbol (+) represents
outer join.
Inner join: Inner join returns the matching rows from the tables that are being joined.

SQL Commands:

Nested Queries
Example: select ename, eno, address where salary>(select salary from employee whereename = "jones");

1.​Subqueries that return several values


Example: select ename, eno from employee where salary <any (select salary from employee where deptno
=”10");
2.​Correlated subquery
Example: select * from emp x where x.salary> (select avg(salary) from emp where deptno = x.deptno);

Simple Join
(a)​Equi-join
Example: select * from item, cust where item.id = cust.id;
(b)​Non Equi-join
Example: select * from item, cust where item.id<cust.id;

Self join
Example: select * from emp x, emp y where x.salary>= (select avg(salary) from x.emp where x.deptno =
y.deptno);

Outer Join
Example: select ename, job, dname from emp, dept where emp.deptno (+) = dept.deptno;
Queries
Q1. Display all employee names and salary whose salary is greater than minimum salary of the
company and job title starts with M.
Solution:
1.​Use select from clause.
2.​Use like operator to match job and in select clause to get the result.
Ans.
SQL> select ename, sal from emp where sal>(select min(sal) from emp where job like 'A%');
ENAME​ SAL
----------------​ ---------
Arjun​ 12000
Gugan​ 20000
Karthik​ 15000

Q2. Issue a query to find all the employees who work in the same job as Arjun.
Ans.
SQL> select * from emp;
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
-----------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select ename from emp where job = (select job from emp where ename='Arjun');
ENAME
-------------
Arjun
Gugan

Q3. Issue a query to display information about employees who earn more than any employee in dept 1.
Ans.
SQL> select * from emp where sal>(select max(sal) from emp where empno=1);
EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
-----------------------------------------------------------------------------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
JOINS
Tables used
SQL> select * from emp;

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL


---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select * from dept;

DEPTNO​ DNAME​ LOC


-----------------------------------------------------------
1 ACCOUNTING NEWYORK
2 RESEARCH DALLAS
3 SALES CHICAGO
4 OPERATIONS BOSTON

EQUI-JOIN
Q4. Display the employee details, departments that the departments are same in both the emp and dept.
Solution:
1.​Use select from clause.
2.​Use equi join in select clause to get the result.
Ans.
SQL> select * from emp, dept where emp.deptno = dept.deptno;

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL​ DEPTNO​ DNAME​ LOC


-----------------------------------------------------------------------------------------------------------------------------------
1 Mathi AP 1 10000 1 ACCOUNTING NEWYORK
2 Arjun ASP 2 12000 2 RESEARCH DALLAS
3 Gugan ASP 2 20000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 4 OPERATIONS BOSTON
NON-EQUIJOIN
Q5. Display the employee details, departments that the departments are not same in both the emp and
dept.
Solution:
1.​Use select from clause.
2.​Use non equi join in select clause to get the result.
Ans.
SQL> select * from emp,dept where emp.deptno!=dept.deptno;

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL​ DEPTNO​ DNAME​ LOC


-----------------------------------------------------------------------------------------------------------------------------------
2 Arjun ASP 2 12000 1 ACCOUNTING NEWYORK
3 Gugan ASP 2 20000 1 ACCOUNTING NEWYORK
1 Mathi AP 1 10000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 2 RESEARCH DALLAS
1 Mathi AP 1 10000 3 SALES CHICAGO
2 Arjun ASP 2 12000 3 SALES CHICAGO
3 Gugan ASP 2 20000 3 SALES CHICAGO
4 Karthik AP 1 15000 3 SALES CHICAGO
1 Mathi AP 1 10000 4 OPERATIONS BOSTON
2 Arjun ASP 2 12000 4 OPERATIONS BOSTON
3 Gugan ASP 2 20000 4 OPERATIONS BOSTON
4 Karthik AP 1 15000 4 OPERATIONS BOSTON

12 rows selected.
Executed SQL Commands using MySQL:
SQL Queries:-
1.​ Display all employee names and salary whose salary is greater than minimum salary of the
company and job title starts with _M’.

2.​Issue a query to find all the employee who work in the same job as arjun.

3.​Issue a query to display information about employee who earn more than any employee in dept 1.
JOIN
TABLE USED

EQUI – JOIN
4.​Display the employee details, departments that the departments are same in both the emps and dept

NON - EQUIJOIN
5.​Display the employee details,department that the department are not same in both the emps and dept.

Result:
Thus the above SQL commands for query the database tables and explore sub queries and simple join
operations executed successfully.
EXP. NO: 5
Query the Database Tables and Explore Natural, Equi and Outer Joins
DATE:

Aim:

To write the SQL commands to query the database tables and explore Natural, Equi and Outer Joins.

Procedure:

LEFTOUT-JOIN

Tables Used

SQL> select * from stud1;

Regno​ Name​ Mark1​ Mark2​ Result


-----------------------------------------------------------------
101 john 89 80 pass
102 Raja 70 80 pass
103 Sharin 70 90 pass
104 sam 90 95 pass

SQL> select * from stud2;

NAME​ GRA
----------------------
john​ s
raj​ s
sam​ a
sharin​ a

Q1. Display the Student name and grade by implementing a left outer join.
Ans.
SQL> select stud1.name,grade from stud1 left outer join stud2 on stud1.name=stud2.name;

NAME​ GRA
----------------------
john​ s
raj​ s
sam​ a
sharin​ a
smith​ null
RIGHTOUTER-JOIN

Q2. Display the Student name, register no, and result by implementing a right outer join.

Ans.

SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud 1.name = stud2.name;

Name​ Regno​ Result


----------------------------------------
john 101 pass
raj 102 pass
sam 103 pass
sharin 104 pass

Rollno Name Markl Mark2 Total


----------------------------------------------------------------
1 sindu 90 95 185
2 arul 90 90 180

FULLOUTER-JOIN

Q3. Display the Student name register no by implementing a full outer join.
Ans.
SQL> select stud1.name, regno from stud1 full outer join stud2 on (stud1.name=stud2.name);

Name​ Regno
--------------------------
john 101
raj 102
sam 103
sharin 104

SELFJOIN

Q4. Write a query to display their employee names.


Ans.
SQL> select distinct ename from emp x, dept y where x.deptno = y.deptno;

ENAME
------------
Arjun
Gugan
Karthik
Mathi
Q5. Display the details of those who draw the salary greater than the average salary.

Ans.

SQL> select distinct * from emp x where x.sal>= (select avg(sal) from emp);

EMPNO​ ENAME​ JOB​ DEPTNO​ SAL

3​ Gugan​ ASP​ 2​ 20000

4​ Karthik​ AP​ 1​ 15000

11​ Kavitha​ designer​ 12​ 17000

Executed SQL Commands using MySQL:

LEFTOUT – JOIN
TABLES USED
1.​Display the Student name and grade by implementing a left outer join.

RIGHTOUTER – JOIN
2.​Display the Student name, register no, and result by implementing a right outer join.

Result:
Thus the above SQL commands for query the database tables and explore Natural, Equi and Outer Joins
executed successfully.
EXP. NO: 6
Write user Defined Functions and Stored Procedures in SQL
DATE:

Aim:

To write user Defined Functions and Stored Procedures in SQL.

Procedure:

DEFINITION

A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task.
They are essentially sub-programs. Procedures and functions are made up of,
​ Declarative part
​ Executable part
​ Optional exception handling part

These procedures and functions do not show the errors.

KEYWORDS AND THEIR PURPOSES

REPLACE: It recreates the procedure if it already exists.

PROCEDURE: It is the name of the procedure to be created.

ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if no arguments are
present.

IN: Specifies that a value for the argument must be specified when calling the procedure ie., it is used to pass
values to a sub-program. This is the default parameter.

OUT: Specifies that the procedure passes a value for this argument back to it’s calling environment after
execution ie., it is used to return values to a caller of the sub-program.

INOUT: Specifies that a value for the argument must be specified when calling the procedure and that
procedure passes a value for this argument back to it’s calling environment after execution.

RETURN: It is the data type of the function’s return value because every function must return a value, this
clause is required.
PROCEDURES-SYNTAX

create or replace procedure <procedure name> (argument {in,out,inout} datatype)


{is,as}
variable declaration;
constant
declaration; begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;

CREATING THE TABLE 'ITITEMS' AND DISPLAYING THE CONTENTS

SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));

Table created.

SQL> insert into ititems values(101, 2000, 500, 201);

1 row created.

SQL> insert into ititems values(102, 3000, 1600, 202);

1​row created.

SQL> insert into ititems values(103, 4000, 600, 202);

1​row created.

SQL> select * from ititems;

ITEMID ACTUALPRICE​ ORDID​ PRODID


---------------------------------------------------------------
101 2000 500 201
102 3000 1600 202
103 4000 600 202

PROGRAM FOR GENERAL PROCEDURE - SELECTED RECORD'S PRICE IS INCREMENTED


BY 500, EXECUTING THE PROCEDURE CREATED AND DISPLAYING THE UPDATED TABLE

SQL> create procedure itsum(identity number, total number) is price number;


2.​null_price exception;
3.​begin
4.​select actualprice into price from ititems where itemid=identity;
5.​if price is null then
6.​raise null_price;
7.​else
8.​update ititems set actualprice=actualprice+total where itemid=identity;
9.​end if;
10.​exception
11.​when null_price then
12.​dbms_output.put_line(‘price is null’);
13.​end;
14.​/

Procedure created.

SQL> exec itsum(101, 500);

PL/SQL procedure successfully completed.

SQL> select * from ititems;

ITEMID ACTUALPRICE​ ORDID​ PRODID


---------------------------------------------------------------
101 2500 500 201
102 3000 1600 202
103 4000 600 202

PROCEDURE FOR 'IN' PARAMETER - CREATION, EXECUTION

SQL> set serveroutput on;

SQL> create procedure yyy (a IN number) is price number;


2​begin
3​select actualprice into price from ititems where itemid=a;
4​dbms_output.put_line('Actual price is ' || price);
5​if price is null then
6​dbms_output.put_line('price is null’);
7​end if;
8​end;
9​/

Procedure created.

SQL> exec
yyy(103);

Actual price is 4000

PL/SQL procedure successfully completed.


PROCEDURE FOR 'OUT' PARAMETER - CREATION, EXECUTION

SQL> set serveroutput on;

SQL> create procedure zzz (a in number, b out number) is identity number;


2.​begin
3.​select ordid into identity from ititems where itemid=a;
4.​if identity<1000 then
5.​b:=100;
6.​end if;
7.​end;
8.​/

Procedure created.

SQL> declare
2.​a number;
3.​b number;
4.​begin
5.​zzz(101,b);
6.​dbms_output.put_line(‘The value of b is ‘|| b);
7.​end;
8.​/

The value of b is 100

PL/SQL procedure successfully completed.

PROCEDURE FOR 'INOUT' PARAMETER - CREATION, EXECUTION

SQL> create procedure itit (a inout number) is


2.​begin
3.​a:=a+1;
4.​end;
5.​/

Procedure created.

SQL> declare
2.​a number:=7;
3.​begin
4.​itit(a);
5.​dbms_output.put_line(‘The updated value is '||a);
6.​end;
7.​/
FUNCTIONS

DATE FUNCTION

1.​Add_month

This function returns a date after adding a specified date with specified number of months.

Syntax: Add_months(d,n); where d-date n-number of months

Example: Select add_months(sysdate,2) from dual;

2.​last day

It displays the last date of that month.

Syntax: last day (d); where d-date

Example: Select last_day (“1-jun-2009") from dual;

3.​Months between

It gives the difference in number of months between dl & d2.

Syntax: month_between (d1,d2); where d1 & d2 -dates

Example: Select month_between (“1-jun-2009","1-aug-2009") from dual;

4.​next_day

It returns a day followed the specified date.

Syntax: next_day (d,day);

Example: Select next_day (sysdate, "wednesday") from dual;

5.​round

This function returns the date, which is rounded to the unit specified by the format model.

Syntax: round (d,[fmt]); where d- date, [fmt] - optional.

By default date will be rounded to the nearest day

Example: Select round (to_date(“1-jun-2009","dd-mm-yy"),"year") from dual;


Select round (“1-jun-2009","year") from dual;
NUMERICAL FUNCTIONS

Command Query Output

Abs(n) Select abs(-15) from dual; 15

Ceil(n) Select ceil(55.67) from dual; 56

Exp(n) Select exp(4) from dual; 54.59

Floor(n) Select floor(100.2) from dual; 100

Power(m,n) Select power(4,2) from dual; 16

Mod(m,n) Select mod(10,3) from dual; 1

Round(m,n) Select round(100.256,2) from dual; 100.26

Trunc(m,n) Select trunc(100.256,2) from dual; 100.23

Sqrt(m,n) Select sqrt(16) from dual; 4

CHARACTER FUNCTIONS

Command Query Output

initcap(char); select initeap("hello") from dual; Hello

lower (char); select lower (“HELLO") from dual; hello

upper (char); select upper (“hello") from dual; HELLO

ltrim (char,[set]); select ltrim (“cseit",”cse") from dual; select it

rtrim (char[set]); rtrim (“cseit",”it") from dual; cse

replace (char,search select replace(“jack and jue”,”j”,”bl”) from black and blue
string, replace string); dual;

substr (char,m,n); select substr (“information", 3, 4) from dual; Form


CONVERSION FUNCTION

1.​to_char()

Syntax: to_char(d,[format]);

This function converts date to a value of varchar type in a form specified by date format. If format is neglected
then it converts date to varchar2 in the default date format.

Example: select to_char (sysdate, "dd-mm-yy") from dual;

2.​to_date()

Syntax: to_date(d,[format]);

This function converts character to date data format specified in the form character.

Example: select to_date(“aug 15 2009","mm-dd-yy") from dual;

Miscellaneous Functions

1.​uid - This function returns the integer value (id) corresponding to the user currently logged in.

Example: select uid from dual;

2.​user - This function returns the logins user name.

Example: select user from dual;

3.​nyl - The null value function is mainly used in the case where we want to consider null values as zero.

Syntax: nvl(exp1, exp2)

If expl is null, return exp2. If expl is not null, return expl.

Example: select custid, shipdate, nvl(total,0) from order;

4.​vsize: It returns the number of bytes in expression.

Example: select vsize(“tech") from dual;


GROUP FUNCTIONS

A group function returns a result based on group of rows.

1.​avg - Example: select avg (total) from student;

2.​max - Example: select max (percentage1) from student;

3.​min - Example: select min (marks1) from student;

4.​sum - Example: select sum(price) from product;

COUNT FUNCTION

In order to count the number of rows, count function is used.

1.​count(*) - It counts all, inclusive of duplicates and nulls.

Example: select count(*) from student;

2.​count(col_name) - It avoids null value.

Example: select count(total) from order;

3.​count(distinct col_name) - It avoids the repeated and null values.

Example: select count(distinct ordid) from order;

Executed SQL commands using MySQL:

SQL Queries:-
Creating the table ‘ititems’ and displaying the contents.
PROGRAM FOR GENERAL PROCEDURE – SELCTED RECORD’S PRICE IS INCREMENTED
BY 500, EXECUTING THE PROCEDURE CREATE AND DISPLAYING THE UPDATED TABLE.
mysql > exec itsum(101,500);
2.​null_price exception;
3.​begin
4.​select actualprice into price from ititems where itemid=identity;
5.​if price is null then
6.​raise null_price;
7.​else
8.​update ititems set actualprice=actualprice+total where itemid=identity;
9.​end if;
10.​exception
11.​when null_price then
12.​dbms_output.put_line(‘price is null’);
13.​end;
14.​/
Procedure created.

PL/SQL procedure successfully completed.


mysql > select * from items;

PROCEDURE FOR “N” PARAMETER – CREATION, EXECUTION


mysql> set serveroutput on;
mysql> create procedure yyy (a IN number) is price number;
2.​begin
3.​select actualprice into price from ititems where itemid=a;
4.​dbms_output-put_line(‘Actual price is’ || price);
5.​if price is null then
6.​dbms_output.put_line(‘price is null’);
7.​end if;
8.​end;
9.​/
Procedure created.
mysql> exec yyy(103);
Actual price is 4000
PL/SQL procedure successfully completed.
PROCEDURE FOR ‘OUT’ PARAMETER – CREATION
mysql> set serceroutput on;
mysql> create procedure zzz(a in number, b out number) is identity number;
2.​begin
3.​select ordid into identity from ititems where itemid=a;
4.​if identity <1000 then
5.​b:=100;
6.​end if;
7.​end;
8.​/
Procedure
created. mysql>
declare
2.​a number;
3.​b number;
4.​begin;
5.​zzz(101,b);
6.​dbms_output.put_line(‘The value of b is’ || b);
7.​end;
8.​/
The value of b is 1—
PL/SQL procedure successfully completed.

PROCEDURE FOR ‘INPUT’ PARAMETER – CREATION, EXECUTION.


mysql> create procedure itit(a inout number) is
2.​begin
3.​a:=a+1;
4.​end;
5.​/
Procedure
created. mysql>
declare
2.​a number :=7;
3.​begin
4.​itit(a);
5.​ dbms_output.put_line(‘The update value is ‘||a);
6.​end;
7.​/

Result:
Thus the above SQL commands for user Defined Functions and Stored Procedures in SQL executed
successfully.
EXP. NO: 7
Execute Complex Transactions and Realize DCL and TCL Commands
DATE:

Aim:

To write the SQL commands to execute complex transactions and realize DCL and TCL Commands.

Procedure:

Data Control Language (DCL), Transaction Control Language (TCL) Commands

1.​DCL COMMAND

The DCL language is used for controlling the access to the table and hence securing the database. DCL is used
to provide certain privileges to a particular user. Privileges are rights to be allocated.

2.​The privilege commands are namely, Grant and Revoke

3.​ The various privileges that can be granted or revoked are, Select, Insert, Delete, Update,
References, ExecuteAll

4.​ GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user can grant
access to their database objects to other users.

5.​ REVOKE COMMAND: Using this command, the DBA can revoke the granted database
privileges from the user.

6.​TCL COMMAND

COMMIT: command is used to save the Records.

ROLL BACK: command is used to undo the Records.

SAVE POINT command is used to undo the Records in a particular transaction

SQL Commands:

DCL Commands

GRANT COMMAND

Grant <database_priv [database_priv…..]> to <user_name> identified by <password> [, password.​ ];

Grant <object_priv> | All on <object> to <user | public> [ With Grant Option];


REVOKE COMMAND

Revoke <database_priv> from <user [, user ] >;

Revoke <object_priv> on <object> from <user | public >;

<database_priv> -- Specifies the system level privileges to be granted to the users or roles. This includes create
/ alter /delete any object of the system.

<object_priv> -- Specifies the actions such as alter / delete / insert / references / execute / select / update for
tables.

<all> -- Indicates all the privileges.

[ With Grant Option ] - Allows the recipient user to give further grants on the objects.

The privileges can be granted to different users by specifying their names or to all users by using the "Public"
option.

TCL COMMANDS

Syntax:

SAVEPOINT: SAVEPOINT <SAVE POINT NAME>;

ROLLBACK: ROLL BACK <SAVE POINT NAME>;

COMMIT: Commit;

Queries

Tables Used

Consider the following tables namely "DEPARTMENTS" and "EMPLOYEES"

Their schemas are as follows,

Departments (dept_no, dept_name, dept_location);

Employees (emp_id, emp_name, emp_salary);


Q1. Develop a query to grant all privileges of employees table into departments table

Ans.

SQL> Grant all on employees to departments;

Grant succeeded.

Q2. Develop a query to grant some privileges of employees table into departments table

Ans.

SQL> Grant select, update, insert on departments to departments with grant option;

Grant succeeded.

Q3. Develop a query to revoke all privileges of employees table from departments table

Ans.

SQL> Revoke all on employees from departments;

Revoke succeeded.

Q4. Develop a query to revoke some privileges of employees table from departments table

Ans.

SQL> Revoke select, update, insert on departments from departments;

Revoke succeeded.

Q5. Write a query to implement the save point

Ans.

SQL> SAVEPOINT S1;

Savepoint created.

SQL> select * from emp;


EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000
SQL> INSERT INTO EMP VALUES(5,’Akalya’, ‘AP’,1,10000);

1 row created.

SQL> select * from emp;


EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000

Q6. Write a query to implement the rollback.


Ans.
SQL> rollback s1;

SQL> select * from emp;


EMPNO​ ENAME​ JOB​ DEPTNO​ SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000

SQL> INSERT INTO EMP VALUES(5,'Akalya', 'AP',1,10000);

1 row created.

Q7. Write a query to implement the commit


Ans.
SQL> COMMIT;

Commit complete
Executable SQL Commands using MySQL:
SQL Queries :
Table used

1.​ DEVELOP A QUERY TO GRANT ALL PRIVILEGES OF EMPLOYEES TABLE


INTO DEPARTMENTS TABLE.
mysql> Grant all on employees to deptments;
Grant succeeded.

2.​ DEVELOP A QUERY TO GRANT SOME PRIVILEGES OF EMPLOYEES TABLE


INTO DEPARTMENTS TABLE.
mysql> Grant select, update, insert on department to departments with grant option.
Grant succeeded.

3.​ DEVELO[ A QUERY TO REVOKE ALL PRIVILEGES TO EMPLOYEES TABLE


FROM DEPARTMENT TABLE.
mysql > Revoke all on employees from departments;
Revoke succeeded.

4.​ DEVELOP A QUERY TO REVOKE SOME PRIVILEGES PF EMPLOYEES TABLE


FROM DEPARTMENTS TABLE.
mysql > Revoke select, update, insert on departments from departments;
Revoke succeeded.

5.​WRITE A QUERY TO IMPLEMENT THE SAVE POINT.


6.​WRITE A QUERY TO IMPLEMENT THE ROLLBACK.
mysql > rollback s1;
mysql> select * from emp;

7.​WRITE A QUERY TO IMPLEMENT THE COMMIT .


mysql> COMMIT;
Commit complete.

Result:

Thus the above SQL commands for complex transactions and realize DCL and TCL Commands executed
successfully.
EXP. NO: 8
Write SQL Triggers for Insert, Delete, and Update Operations in a Database Table
DATE:

Aim:

To write SQL Triggers for Insert, Delete, and Update Operations in a Database Table.

Procedure:

Definition

​ A trigger is a statement that is executed automatically by the system as a side effect of a modification
to the database. The parts of a trigger are,
​ Trigger statement: Specifies the DML statements and fires the trigger body. It also specifies the table to
which the trigger is associated.
​ Trigger body or trigger action: It is a PL/SQL block that is executed when the triggering statement
is used.
​ Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,

​ To generate data automatically


​ To enforce complex integrity constraints
​ To customize complex securing authorizations
​ To maintain the replicate table
​ To audit data modifications

Types of Triggers

The various types of triggers are as follows,

​ Before: It fires the trigger before executing the trigger statement.


​ After: It fires the trigger after executing the trigger statement.
​ For each row: It specifies that the trigger fires once per row.
​ For each statement: This is the default trigger that is invoked. It specifies that the trigger fires
once per statement.
Variables used in Triggers
​ :new
​ :old

These two variables retain the new and old values of the column updated in the database. The values in these
variables can be used in the database triggers for data manipulation

TRIGGERS - SYNTAX

create or replace trigger triggername [before/after] {DML statements} on [tablename] [for each row/statement]
begin

exceptio
n end;

USER DEFINED ERROR MESSAGE

The package "raise_application_error" is used to issue the user defined error messages
Syntax: raise_application_error(error number, ‘error message’);
The error number can lie between -20000 and -20999.
The error message should be a character string.

TO CREATE A SIMPLE TRIGGER THAT DOES NOT ALLOW INSERT UPDATE AND DELETE
OPERATIONS ON THE TABLE

SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2.​begin
3.​raise_application_error(-20010,’You cannot do manipulation’);
4.​end;
5.​/

Trigger created.

SQL> insert into itempls values(‘aaa’,14,34000);

insert into itempls values(‘aaa’,14,34000)

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> delete from itempls where ename=’xxx’;

delete from itempls where ename=’xxx’

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger ‘STUDENT.ITTRIGG’

SQL> update itempls set eid=15 where ename=’yyy’;

update itempls set eid=15 where ename=’yyy’

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger ‘STUDENT.ITTRIGG’

TO DROP THE CREATED TRIGGER

SQL> drop trigger ittrigg;

Trigger dropped.

TO CREATE A TRIGGER THAT RAISES AN USER DEFINED ERROR MESSAGE AND DOES
NOT ALLOW UPDATION AND INSERTION

SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2.​declare
3.​triggsalitempls.salary%type;
4.​begin
5.​select salary into triggsal from itempls where eid=12;
6.​if(:new.salary>triggsal or :new.salary<triggsal) then
7.​raise_application_error(-20100,’Salary has not been changed’);
8.​end if;
9.​end;
10. /

Trigger created.
SQL> insert into itempls values (‘bbb’,16,45000);

insert into itempls values (‘bbb’,16,45000)

ERROR at line 1:

ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

SQL> update itempls set eid=18 where ename=’zzz’;

update itempls set eid=18 where ename=’zzz’

ERROR at line 1:

ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

Result:

Thus the above SQL Triggers for Insert, Delete, and Update Operations in a Database Table executed
successfully.

You might also like