DBMS Lab Manual
DBMS Lab Manual
Semester : IV
Prepared By
Contents
6. Lab Experiments 13
3
Vision Mission
To transform the (rural) youth into top class
professionals and technocrats willing to serve
To be an institution of eminence of local and global society with ethical integrity, by
optimal human development, excellent providing vibrant academic experience of
engineering education and pioneering learning, research and innovation and stimulating
research towards developing a technically- opportunities to develop personal maturity and
empowered humane society. professional skills, with inspiring and high
caliber faculty in a quality and serene
infrastructural environment.
Objectives Values
To transform our students into fully-functioning human Efficiency that leads to
persons and empowering leaders with autonomy and Excellence
passion for continuous self-learning. Excellence that leads to Eminence
To equip them with contemporary scientific and technical Genuineness that leads to
knowledge with student centered teaching methods. authenticity
To animate them into pioneering researchers and Transparency that leads to
investors. credibility
To train them to excel with cutting edge technical, Person centeredness that leads to
entrepreneurial and managerial skills for a successful family-ness
career. Appreciation that leads to high
To expose them to challenging opportunities of self- motivation
discovery and to commit themselves to lead a value-based Altruism that leads to humane
life of humane service. service
To recruit faculty who inspire the students with their Critical thinking that leads to
passion for knowledge and transmit knowledge to the scientific approach
students by student-centered creative and innovative Fidelity that leads to
teaching and learning methods, lead them by example in responsibility
high-end researchers, and edify the students with their life Knowledge that leads to wisdom
of integrity and ethics. Innovative research that leads to
To provide standard infrastructure, serene and stimulating inventions
environment that is most conducive to learning. Hardwork that leads to
To develop avenues of continuous and responsive achievements
collaboration with stakeholders for the optimal Eco friendliness that leads to
4
Vision
Creating top-notch Information Technology Engineers, innovative researchers and successful
entrepreneurs towards developing a technically-empowered humane society.
Mission
Providing quality technical education and high caliber skill training that meets
M1
the needs of society and latest technical expectations of the industry.
Fostering innovative and rigorous research culture among staff and students to
M2
find optimal solutions for complex problems.
Imparting value-based education to imbibe ethical principles and act with social
M3
responsibility, team spirit, and leadership.
Promoting and developing entrepreneurial skills of the students and handhold
M4
them towards commercial success.
Program Educational Objectives (PEO)
To ensure graduates will be proficient in utilizing the fundamental knowledge of
PEO 1 basic sciences, mathematics and Information Technology for the applications
relevant to various streams of Engineering and Technology.
To enrich graduates with the core competencies necessary for applying
PEO 2 knowledge of computers and telecommunications equipment to store, retrieve,
transmit, manipulate and analyse data in the context of business enterprise.
To enable graduates to think logically, pursue lifelong learning and will have the
PEO 3 capacity to understand technical issues related to computing systems and to
design optimal solutions.
To enable graduates to develop hardware and software systems by
PEO 4 understanding the importance of social, business and environmental needs in the
human context.
To enable graduates to gain employment in organizations and establish
themselves as professionals by applying their technical skills to solve real world
PEO 5 problems and meet the diversified needs of industry, academia and research.
Course Description
The aim of this laboratory is to inculcate the abilities of applying the principles of the database
management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.
Course Objectives
1.
To understand data definitions and data manipulation commands
2.
To learn the use of nested and join queries
3.
To understand functions, procedures and procedural extensions of data bases
4.
To be familiar with the use of a front end tool
5.
To understand design and implementation of typical database applications
Course Outcomes
CS8481. 1 3 - -
CS8481. 2 3 - -
CS8481. 3 3 - -
CS8481. 4 3 - -
CS8481. 5 3 - -
CS8481 3 - -
Syllabus
CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C 0 0 4 2
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating
and retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
TOTAL: 60 PERIODS
11
1 Internal Assessment Marks (75% Observation and Record, 25% Model Exam) 20
Grade Point
Marks Range Grade Points Letter Grade
91-100 10 O
81-90 9 A+
71-80 8 A
61-70 7 B+
50-60 6 B
<50 0 RA
GPA or CGPA= (ΣCiGPi)/(ΣCi); Ci-credit of the i-th course, GPi-grade point obtained for the course.
Methods of Evaluation
1) Continuous Assessment (Pls. tick)
Viva
2) University Examination
Target
12
CO attainment 3
22 6 7 7 2
List of Experiments
Ex. CO Page
Title
No. Mapping No.
6. Triggers 3 51-57
Ex. CO Page
Title
No. Mapping No.
Aim:
To study and work with DDL Commands (Create, Describe, Alter, Rename, Drop, Truncate)
Algorithm/Procedure:
Switch on the system and go to the terminal and type 'sqlplus64
<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.
DBMS:
The collection of data is called database. Database system supports single user and multi-
user. When data are stored in a computer file using a database management system such as
FOXPRO, DBMS III plus, ORACLE etc., the file is called database file.
RDBMS:
INTRODUCTION OF ORACLE:
ORACLE is a DBMS package developed by the ubuntu supportable front end to connect
oracle database ORACLE Corporation, various versions are oracle, oracle8, and oracle8i.Oracle8
is an Object Relational Database Management System (ORDBMS) package. It supports both
object oriented and relational concepts.
A table is a unit of storage which holds data in the form of rows and columns. Collection
of tables with their interrelation could be termed as database.
TOOLS OF ORACLE:
15
• SQL/PLUS
• PL/SQL
• Forms
• Reports
SQL/PLUS:
Structured Query Language is used for accessing and manipulating the database. Through
SQL plus we can store, retrieve, and edit the SQL commands. To communicate with the database
SQL supports the following commands.
▪ CREATE
▪ ALTER
▪ TRUNCATE
▪ DESC
▪ DROP
▪ INSERT
▪ SELECT
▪ UPDATE
▪ DELETE
▪ GRANT
▪ REVOKE
16
▪ COMMIT
▪ SAVE POINT
▪ ROLL BACK
Advantages of SQL:
➢ Simple commands
➢ Non-Procedural Language
1. CHAR
Syntax:
CHAR (size)
Where
Example:
2. VARCHAR2
This data type is used to store variable length strings. It can also store alpha
numerical values. The size of this data types varies from 1 to 2000 bytes.
Syntax:
VARCHAR2 (size)
3. LONG
Number data type is used to declare a column to store only numbers. This type
supports the storage of integers, real numbers, floating-point numbers etc.
Syntax:
NUMBER (P)
Syntax:
DATE
The standard date format in ‘DD-Mon-YY’ Where DD refers the date in number,
on stands for the first three letter abbreviation of a month (like Mar, Jan etc.) and YY
stands for the last two digits of the year.
Syntax:
RAW (size)
Binary data up to a maximum size of 2GB can be stored in this data type.
Syntax:
The Data Definition Language (DDL) is used for the following purposes.
1. To create an object
3. To drop an object
18
1) CREATING A TABLE
Syntax:
e) Underscore, numerals and letters are allowed. Blank space and single quote are
not allowed.
2) ALTERING A TABLE
The structure of a table can be changed using ALTERING command. Using this
command we can do the following.
Syntax:
To delete a column
b) Cannot drop more than one column at a time from the table
Syntax:
4) TRUNCATING A TABLE
This command is used to delete all records stored in a table. If we use this command, the
structure of the table is retained.
Syntax:
5) DROPPING A TABLE
Syntax:
6) RENAME A TABLE
Syntax:
20
Program:
EXERCISE:
DOB date
DOJ date
5. Change data type for dname field to varchar2 (10) in department table.
Output:
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Result:
Thus the program was executed successfully
22
Aim:
Algorithm/ Procedure:
Switch on the system and go to the terminal and type 'sqlplus64
<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.
Program:
Commands:
1.INSERT
Syntax:
Table:
It’s a name of the table into which rows are to be inserted.If you specified view oracle
insert close into the views table.
Column:
It is a column of the table or view in the inserted row each column in the list is assign a
value from a values clause are the subquery.If you emitt one of the tables column from this list
the columns values for the inserted row these columns default values as specified when the table
was created.If you vomit the column list altogether the values clause of the query must specified
values for all columns in the table.
Values:
Specifies a row of values to be inserted into the table or view.We must specifies the value
in the value clause for each column in the column list.
Example:
2.UPDATE
23
Syntax:
3. DELETE
Syntax:
4. RENAME
Syntax:
EXERCISE:
6.Decrement the fees amount of the student susi and Ravi by Rs.1000
Output:
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
25
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Result:
Thus the program was executed successfully
26
Output
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
Result
Aim:
PROCEDURE:
VIEWS
In SQL, a view is a virtual table based on the result-set of an SQL statement.A view
contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
Program
Exercises
ISBN is 4566.
6. Create view named book_view with name,book by joining two relations BOOK and
AUTHOR.
32
INDEX
SQL automatically creates some indexes based on column types and attributes.
SYNTAX:
Output
Exercises
Sample output
index created
index dropped.
Savepoint
TCL COMMANDS:
33
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
SYNTAX:
COMMIT:
This command is used for save the work done. The syntax is:
COMMIT;
ROLLBACK:
This command is used to restore the database to original since the last commit.
The syntax is:
ROLLBACK;
SAVEPOINT:
A savepoint is a point in a transaction that you can roll the transaction back to
without rolling back the entire transaction.
DCL COMMANDS:
1. GRANT
2. REVOKE
GRANT:
REVOKE:
EXERCISES:
1. Create a transaction by creating a table project with the fields project name,dept
name,no.of employees, start date(SD),completion date(CD),project manager name,
budget.
6. Update the details of a project manager and display all the records from the table.
7. Create a savepoint s2. Delete the details of project whose budget is less than 50000 and
display all the records from the table.
8. Undo all changes made after the creation of the savepoint s2 and display all the records
from the table.
Result
Thus, the implementation of views, savepoints, synonyms, sequence and indexes were
executed.
35
Aim:
PROCEDURE:
Cursors
Oracle creates a memory area, known as the context area, for processing an SQL statement,
which contains all the information needed for processing the statement; for example, the number
of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
• Implicit cursors
• Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
Program
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes −
36
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.
Output
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
37
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −
6 customers selected
If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Example:
table created
1 row created.
39
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
40
SQL> /
1 row created.
1 4 9-jan-09 10-jan-10
1 0 6-jan-07 10-jan-07
2 0 9-mar-18 11-mar-18
3 0 1-feb-06 9-feb-06
4 0 2-dec-05 23-dec-05
5 0 5-sep-07 5-sep-07
6 rows selected.
SQL> commit;
Commit complete.
SQL> declare
ds disc % rowtype;
begin
41
if ds.delidate<ds.duedate then
end if;
end if;
end if;
end loop;
end;
/ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 3 9-jan-09 10-jan-10
1 3 6-jan-07 10-jan-07
2 3 9-mar-18 11-mar-18
3 2 1-feb-06 9-feb-06
4 2 2-dec-05 23-dec-05
5 6 5-sep-07 5-sep-07
6 rows selected.
42
Result
Thus, the cursor implementation such as implicit and explicit were executed.
43
Aim:
PROCEDURE:
Procedure:
A stored procedure in PL/SQL is nothing but a series of declarative SQL statements which can
be stored in the database catalogue. A procedure can be thought of as a function or a method.
They can be invoked through triggers, other procedures, or applications on Java, PHP etc.
A stored procedure is a set of Structured Query Language (SQL) statements with an assigned
name, which are stored in a relational database management system as a group, so it can be
reused and shared by multiple programs.
Function:
Function must return a value but in Stored Procedure it is optional. Even a procedure can return
zero or n values. Functions can have only input parameters for it whereas Procedures can have
input or output parameters . Functions can be called from Procedure whereas Procedures cannot
be called from a Function.
Program/ output
Example:
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
46
SQL> /
1 row created.
GRADE SALARY
-------------------- ----------
designer 15000
artist 20000
architect 50000
lecturer 25000
cnt number(5):0;
begin
if cnt=0 then
else
end if;
end;
/ 2 3 4 5 6 7 8 9 10 11 12 13 14
SQL>
cnt number(5):0;
begin
if cnt=0 then
else
end if;
48
end;
execute changesalary(‘designer’,35000);
execute changesalary(‘supervisor’,40000);
Functions
Example:
return number is
s number:=1;
i number;
begin
for i in 1..n
loop
s:=s*I;
end loop;
return(s);
end;
SQL> DECLARE
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
50
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
END;
/ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Factorial 6 is 720
Result
EX.No:6 TRIGGERS
Aim:
Triggers:
Triggers are stored programs, which are automatically executed or fired when some events
occur.
Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Program
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
52
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the
trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and
old values for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once when
the SQL statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Output
Example
CUSTOMERS table
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
55
6 Komal 22 MP 4500
6 rows selected.
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
SQL> CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/ 2 3 4 5 6 7 8 9 10 11 12 13
Trigger created.
10. If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
11. The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but you can write your trigger
on a single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
When a record is created in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
1 row created.
Because this is a new record, old salary is not available and the above result comes as null. Let
us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement
will update an existing record in the table −
SQL> UPDATE customers
SET salary = salary + 500
WHERE id = 2;
1 row updated.
When a record is updated in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −
Result
Thus, the program was executed successfully
58
Aim:
PROCEDURE:
Exception:
Program
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
60
Output
Example
The following example illustrates the concept. This program asks for a customer ID, when the
user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
Result
AIM:
PROCEDURE:
SQL
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute) standard
Entity - Attributes
Entity
• Something that exists and is capable of being described
• Entities are comprised of attributes
Attributes
An attribute is a characteristic of an entity.
Every attribute does one of three things:
• Describe
• Identify
• Relate
Relationships
• Define how the different entities are associated with each other
• A relationship is defined by the keys of the participating entities
63
Key Concepts
• Data Types
• Constraints
• Primary Key
• Nullability
• Fixed- Variable length
• Identity Columns
• Indexes (Clustered - Non Clustered)
Program
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action,
the action is aborted by the constraint.
Constraints can be specified when the table is created
or after the table is created.
SQL CREATE TABLE + CONSTRAINT Syntax
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
Output
Example
--Display last and first name and the title of the employees that are situated in USA and are born
before 1960, alphabetically by their names.
SELECT EmployeeID, LastName, FirstName, Title
FROM Employees
WHERE Country = 'USA'
AND BirthDate < '1960-01-01'
ORDER BY LastName, FirstName;
Examples
-- Returns Customers from Bern, Berlin and Bergamo
SELECT * FROM Customers
WHERE City LIKE 'ber%';
-- Returns Customers from Bruxelles, Resende, Buenos Aires etc.
SELECT * FROM Customers
WHERE City LIKE '%es%';
-- Returns Customers with regions CA and WA
select *
from Customers
where Region like '_A'
NULL values
• NULL values represent missing unknown data
• By default a column can hold NULL values
• NULL is different from zero
• To check for NULL we use IS or IS NOT NULL instead of = or <>.
Syntax example:
-- Get all customers for whom we have fax numbers.
SELECT *
67
FROM Customers
WHERE Fax IS NOT NULL;
Result
Aim:
Run
Program
<?php
echo "Hello World!";
?>
</body>
</html>
Output
Hello World!
Example: gedit
<?php
?>
http://localhost/sample.php
73
output
name: jemila
rollno:151
mark200
name: ramala
rollno:15
mark300
name: persha
rollno:18
mark500
Result
Thus, the php program was executed successfully
74
http://localhost/sample.php
output
employeename: jemila
employeeid:151
salary20000
employeename: ramala
employeeid:15
salary 30000
77
Result
Thus the php program was executed successfully
78
Most of the services we enjoy on the Web are provided by web database applications. Web-
based email, online shopping, forums and bulletin boards, corporate web sites, and sports and
news portals are all database-driven. To build a modern web site, you need to develop a database
application.
This book presents a highly popular, easy, low-cost way to bring together the Web and databases
to build applications. The most popular database management system used in these solutions is
MySQL, a very fast and easy-to-use system distributed under an Open Source license by its
manufacturer, MySQL AB. We discuss MySQL in detail in this book.
With a web server such as Apache (we assume Apache in this book, although the software
discussed here works with other web servers as well) and MySQL, you have most of what you
need to develop a web database application. The key glue you need is a way for the web server to
talk to the database; in other words, a way to incorporate database operations into web pages.
The most popular glue that accomplishes this task is PHP.
PHP is an open source project of the Apache Software Foundation and it’s the most popular
Apache web server add-on module, with around 53% of the Apache HTTP servers having PHP
capabilities.[1] PHP is particularly suited to web database applications because of its integration
tools for the Web and database environments. In particular, the flexibility of embedding scripts
in HTML pages permits easy integration of HTML presentation and code. The database tier
integration support is also excellent, with more than 15 libraries available to interact with almost
all popular database servers. In this book, we present a comprehensive view of PHP along with a
number of powerful extensions provided by a repository known as PEAR.
Apache, MySQL, and PHP can run on a wide variety of operating systems. In this book, we
show you how to use them on Linux, Mac OS X, and Microsoft Windows.
This is an introductory book, but it gives you the sophisticated knowledge you need to build
applications properly. This includes critical tasks such as checking user input, handling errors
79
robustly, and locking your database operations to avoid data corruption. Most importantly, we
explain the principles behind good web database applications. You’ll finish the book with not
only the technical skills to create an application, but also an appreciation for the strategies that
make an application secure, reliable, maintainable, and expandable.
The Web
When you browse the Web, you use your web browser to request resources from a web server
and the web server responds with the resources. You make these requests by filling in and
submitting forms, clicking on links, or typing URLs into your browser. Often, resources are
static HTML pages that are displayed in the browser. Figure 1-1 shows how a web browser
communicates with a web server to retrieve this book’s home page. This is the classic two-tier or
client-server architecture used on the Web.
Figure 1-1. A two-tier architecture where a web browser makes a request and the web server
responds