Dbms Lab Manual Reg2021 24-25
Dbms Lab Manual Reg2021 24-25
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.
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:
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:
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
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));
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.
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.
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)
SELECT COMMANDS
Selects all rows from the table
Syntax: Select * from tablename;
Example: Select * from IT;
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;
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)
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.
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
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
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.
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.
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.
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
sales 9876
marketing 5432
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
ONAME OID
chair 2005
table 2006
chair 2007
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
CNAME CID
jones 506
hayden 508
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
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
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
400
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
1024
15.36
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
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;
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;
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:
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’.
6.Determine the max and min salary and rename the column as max_salary and min_salary.
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.
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");
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;
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;
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
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;
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
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);
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:
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
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
SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));
Table created.
1 row created.
1row created.
1row created.
Procedure created.
Procedure created.
SQL> exec
yyy(103);
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./
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.
2.last day
3.Months between
4.next_day
5.round
This function returns the date, which is rounded to the unit specified by the format model.
CHARACTER FUNCTIONS
replace (char,search select replace(“jack and jue”,”j”,”bl”) from black and blue
string, replace string); dual;
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.
2.to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Miscellaneous Functions
1.uid - This function returns the integer value (id) corresponding to the user currently logged in.
3.nyl - The null value function is mainly used in the case where we want to consider null values as zero.
COUNT FUNCTION
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.
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:
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.
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
SQL Commands:
DCL Commands
GRANT COMMAND
<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.
[ 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:
COMMIT: Commit;
Queries
Tables Used
Ans.
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.
Revoke succeeded.
Q4. Develop a query to revoke some privileges of employees table from departments table
Ans.
Revoke succeeded.
Ans.
Savepoint created.
1 row created.
1 row created.
Commit complete
Executable SQL Commands using MySQL:
SQL Queries :
Table used
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
Types of Triggers
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;
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.
*
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’;
*
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’
*
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’
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);
ERROR at line 1:
ERROR at line 1:
Result:
Thus the above SQL Triggers for Insert, Delete, and Update Operations in a Database Table executed
successfully.