DBMS Laboratory Observation of 10 experiments
DBMS Laboratory Observation of 10 experiments
AIM: To create a table and to write SQL queries to perform modifications to the table in
RDBMS.
Create Table:
This command is used to create database tables in RDBMS.
Syntax
CREATE TABLE <table_name> (<colname1> <datatype>, <colname2>
<datatype>,<colname3> < datatype>, …..…<colnamen> <datatype>);
Alter Table:
This command is used to add or drop or modify the attributes from the existing table.
Syntax
Adding an attribute:
ALTER TABLE <table_name> ADD <column_name> <datatype>;
Dropping an attribute:
ALTER TABLE <table_name> DROP COLUMN <column_name>;
Modifying an attribute:
ALTER TABLE <table_name> MODIFY <column_name> <newdatatype>;
Drop Table:
This command is used to remove a relation from an SQL database. This command deletes not
only the records of the table but also the entire schema of the database.
Syntax:
DROP TABLE <table_name>;
CONSTRAINTS
Constraints are the rules enforced on the data columns of a table. This ensures the accuracy and
reliability of the data in the database.
DML COMMANDS
Insert
Select
Update
Delete
INSERT:
Insert command is used to insert the values into the table. There are three ways to insert a record
into the database.
Syntax
INSERT INTO <table_name>(col1,col2,…….,coln)
VALUES(val1,val2,……,valn);
2. Inserting Values:
Syntax
INSERT INTO <table_name> VALUES(val1,val2,……...,valn);
Syntax
SELECT:
The select statement is used to query a database. This statement is used to retrieve the
information from the database. The SELECT statement can be used in many ways. They are:
Syntax
SELECT <column name> FROM <table_name>;
Syntax
SELECT * FROM <table_name>;
UPDATE:
Syntax:
UPDATE <table_name>
SET <column name> =new value
WHERE <column name>=some value;
DELETE:
Syntax:
EXERCISES:
NAME TYPE
DNO NUMBER(4)
DNAME VARCHAR2(20)
NAME TYPE
EID NUMBER(4)
NAME VARCHAR2(30)
DOB DATE
ADDR VARCHAR2(50)
PIN NUMBER(10)
GENDER CHARACTER
DESIG VARCHAR2(25)
DEPTNO NUMBER(4)
SALARY NUMBER(8,2)
RESULT:
Thus the database is created and the DML commands were executed in RDBMS.
EX NO 2. CONSTRAINTS
CONSTRAINTS
Constraints are a set of rules. It is used to maintain the quality of information. Constraints ensure
that the data insertion, updating, and other processes have to be performed in such a way that
data integrity is not affected. Constraints are the rules enforced on the data columns of a table.
These are used to limit the type of data that can go into a table.
TYPES OF CONSTRAINTS
NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY
Syntax:
CREATE TABLE <table_name>
( <column1> <datatype> not null, <column2> <datatype>);
Unique Constraint
A unique constraint prevents duplicate values. It ensures that all values in a column are different.
Syntax:
CREATE TABLE <table_name>
( <column1> <datatype> unique, <column2> <datatype>);
Check Constraint
A check constraint allows you to specify a condition for a column in a table. It ensures that the
values in a column satisfies a specific condition.
Syntax:
CREATE TABLE <table_name>
( <column1> <datatype>, <column2> <datatype> CHECK (<column_name> <condition>));
Syntax:
CREATE TABLE <table_name>
(<column1> <datatype>, <column2> <datatype>,
PRIMARY KEY(<column1>));
Syntax:
Syntax:
ALTER TABLE <table_name> ADD constraint <constraint name> primary
key(<column_name>);
Syntax:
AIM:
To query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
SELECT:
The select statement is used to query a database. This statement is used to retrieve the
information from the database. The SELECT statement can be used in many ways.
They are:
Syntax
SELECT <column name1, column name2> FROM <table_name>;
Syntax
SELECT * FROM <table_name>;
3. Filtering Data
Select command is used to filter data by providing a single or multiple conditions based on user
requirement.
Syntax:
The select statement along with like clause is used to match strings. The like condition is used to
specify a search pattern in a column.
Syntax:
SELECT <columnname> FROM table_name WHERE <column name> LIKE “% or-“;
Rows can be retrieved from the table by combining multiple conditions with ( AND
OR)Operator.
We can filter data by using the different logical operator(s) in where condition and can check
null value to using IS NULL or IS NOT NULL operators.
Syntax:
SELECT * FROM <tableName> WHERE <condition1> [AND|OR] <condition2>;
6.Sorting Data
We can retrieve rows from the table in ascending or descending order which is depending on the
condition specified with the select statement.ORDER BY Clause sorts results set based on the
column specified. It can only be used with SELECT Statements.
Sort order can be ASC(Ascending) or DESC(Descending). By default, Sort order is ascending ,
if any order is not specified.
Syntax:
SELECT * FROM <tableName> ORDER BY <ColumnName1> ASC;
7.Aggregate Functions
The functions that work on a set of numeric values are termed an aggregate function.
For example, COUNT is a function, which counts the number of occurrences of the values/field
passed by the user.
Syntax:
SELECT <aggregate functionName> (<ColumnName>) from <tableName>;
Syntax:
SELECT <columnname> FROM <table_name> WHERE
<column name> IN(value1,value2,……,value n);
BETWEEN can be used to get those items that fall within a range.
Syntax:
SELECT <column name> FROM <table_name> WHERE
<Column name> BETWEEN <value1> AND <value2>;
We can use the SELECT statement to select the ‘null’ values also. For retrieving rows where
some of the columns have been defined as NULLs there is a special comparison operator of the
form IS[NOT]NULL.
Syntax:
SELECT <column name> FROM <table_name> WHERE <Column name> IS NULL;
SELECT <column name> FROM <table_name> WHERE <Column name> IS NOT NULL;
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange
these rows in a group.
Syntax:
SELECT <column name> FROM <table_name> GROUP BY <Column name>;
EXERCISES:
1. Create the following tables with the given specifications and appropriate constraints.
AIM: To write and execute queries to perform different types of Joins in RDBMS.
JOIN
This command is used for joining two or more relations into a single relation. The
different types of joins are namely,
Inner join
Natural Join
Outer join
*Left Outer Join
*Right Outer Join
*Full Outer Join
1) INNER JOIN
Only pairs of tuples that match the join condition are retrieved from the two different
relations.
Syntax:
SELECT <attribute names> from ( <table name1> INNER JOIN <tablename2> on
<condition>);
2)NATURAL JOIN
A natural join in SQL combines rows from two or more tables based on the common column(s)
between them. The common columns on which the tables are joined must have the same name
and data type across the tables.
Syntax:
3) OUTER JOIN
Outer joins are joins that return matched values and unmatched values from either or both tables.
There are a few types of outer joins:
*Left Outer Join
*Right Outer Join
*Full Outer Join
LEFT OUTER JOIN
Every tuple in the left table must appear in the result; if it does not have a matching tuple,
it is padded with NULL values for the attributes of the right table
Syntax:
SELECT <attribute name> from ( <table name1> LEFT OUTER JOIN <tablename2> on
<condition>);
Every tuple in the right table must appear in the result; if it does not have a matching
tuple, it is padded with NULL values for the attributes of the left table
Syntax:
SELECT <attribute name> from ( <table name1> RIGHT OUTER JOIN <tablename2> on
<condition>);
Every tuple in the left table and right table must appear in the result; if it does not have a
matching tuple, it is padded with NULL values.
Syntax:
SELECT <attribute name> from ( <table name1> FULL OUTER JOIN <tablename2> on
<condition>);
EXERCISES
1. Create the following tables with the given specifications and insert 4 records in both the
relations.
2. Write a SQL query to perform NATURAL JOIN on both the relations and record the output.
3. Write a SQL query to perform EQUI JOIN on both the relations and record the output.
4. Write a SQL query to perform INNER JOIN on both the relations and record the output.
5. Write a SQL query to perform LEFT OUTER JOIN on both the relations and record the
output.
6. Write a SQL query to perform RIGHT OUTER JOIN on both the relations and record the
output.
7. Write a SQL query to perform FULL OUTER JOIN on both the relations and record the
output.
Ex No 5 SUB QUERIES
AIM
To execute sub queries or nested sub queries in RDBMS.
DEFINITION
A subquery is a SQL query nested inside a larger query.
The sub query can be nested inside a SELECT, INSERT, UPDATE, or DELETE
statement or inside another subquery.
A sub query is usually added within the WHERE Clause of another SQL SELECT
statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, or ALL.
A sub query is also called an inner query or inner select, while the statement containing a
sub query is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner query
can be passed to the outer query.
Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They mark the
usage of single row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use of
multiple row comparison operators like IN, ANY, ALL. There can be sub queries
returning multiple columns also.
SQL ANY
SQL ANY compares a value of the first table with all values of the second table and
returns the row if there is a match with any value.
SYNTAX
Select <fieldname> from <tablename> where <fieldname> = ANY ( select <fieldname>
from <tablename> where <condition>);
SQL ALL
SQL ALL compares a value of the first table with all values of the second table and
returns the row if there is a match with all values.
SYNTAX
Select <fieldname> from <tablename> where <fieldname> = ALL (select <fieldname>
from <tablename> where <condition>);
QUESTIONS
1.Create the following tables with the given specifications and appropriate constraints.
10.Display the passengers who had booked the journey from Mumbai to Chennai.
11.Display the Booking details of the passengers those who are having age of 25,30 or 35.
Ex No 6 TCL & DCL Commands
AIM
To execute TCL and DCL queries in RDBMS.
DEFINITION
TCL statements help to control and manage transactions in database. It helps to maintain the
integrity of data within SQL statements.
Commit
Rollback
Savepoint
Commit
Commit command is used to save the changes permanently into the database.
Syntax
Commit;
ROLLBACK
ROLLBACK is a transactional control language command in SQL. It lets a user undo those transactions
that aren't saved yet in the database. One can make use of this command if they wish to undo any
changes or alterations since the execution of the last COMMIT.
Syntax
rollback;
SAVE POINT
A SAVEPOINT is a marker within a transaction that allows for a partial rollback. As changes are made in
a transaction, we can create SAVEPOINTs to mark different points within the transaction. If we
encounter an error, we can rollback to a SAVEPOINT or all the way back to the beginning of the
transaction.
Create a Save point:
Syntax
Partial Rollback:
Syntax
Data control language (DCL) is used to access the stored data. It is mainly used for revoke and to grant
the user the required access to a database. It is a part of the structured query language (SQL). It helps in
controlling access to information stored in a database. It provides the administrators, to remove and set
database permissions to desired users as needed.
Grant
Revoke
GRANT Command
It is employed to grant a privilege to a user. GRANT command allows specified users to perform
specified tasks
Syntax
REVOKE Command
It is employed to remove a privilege from a user. REVOKE helps the owner to cancel previously granted
permissions.
Syntax
1. Create the following tables with the given specifications and appropriate constraints.
OBJECTIVE:
To study and execute the procedures and functions using control structures in PL/SQL.
PROBLEM DEFINITION:
The main concept is to understand the how procedures are created and implemented in
PL/SQL .
BASIC TERMINOLOGIES:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination
of SQL along with the procedural features of programming languages. It was developed by
Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
PL/SQL Engine
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be
stored in the client system (client-side) or in the database (server-side).
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.
<local declarations>;
begin
(executable statements)
[exception] (exception handlers)
end;
A procedure has two parts, namely, specification and body. The procedure specification
begins with the keyword procedure and ends with the procedure name or parameter list. The
procedure body begins with the keyword is and ends with the keyword end. It can also include
declarative, executable and exceptional parts within the keywords are and end.
FUNCTIONS
A function is a subprogram that computes a value.The syntax for creating a function is given
below.
create or replace function <function_name> [argument]
return datatype is
(local declaration)
begin
(exectable statements)
[Exception]
(exception handlers)
end;
Similar to a procedure, a function also has two parts, namely, the function specification
and the function body. The function specification begins with the keyword function and ends
with the return clause. The function body begins with the keyword is and ends with the keyword
end. A PL/SQL block can also be included in a function body.
EXERCISES:
1) To create a procedure to display the salary of the specified employee from employee table
2) To create a PL/SQL program which calls a procedure to print 0 if salary is less than 15000
else print 1.
3) To create and execute a function to multiply the given number by 1000
RESULT:
Thus the procedures and functions using control structures were studied and executed in
PL/SQL.
Ex. No: 8
Date:
TRIGGERS
OBJECTIVE:
PROBLEM DEFINITION:
The main concept is to understand the concept of triggers and functions in PL/SQL and
implement them in simple programs
BASIC TERMINOLOGIES:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination of SQL
along with the procedural features of programming languages. It was developed by Oracle
Corporation in the early 90’s to enhance the capabilities of SQL.
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 (CREATES, ALTER, or DROP).
● A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
PARTS OF A TRIGGER
A database trigger has three parts, namely, a trigger statement, a trigger body and a trigger
restriction.
Trigger Statement: -
A trigger statement specifies the DML statements like update, delete and insert and it fires the
trigger body. It also specifies the table to which the trigger is associated.
Trigger Body: -
Trigger body is a PL/SQL block that is executed when a triggering statement is issued.
Trigger Restriction: -
Restrictions on a triggers can be achieved using the WHEN clause as shown in the syntax for
creating triggers. They can be included in the definition of a row trigger, where in, the condition
in the WHEN clause is evaluated for each row that is affected by the trigger.
Syntax for creating a trigger
Create or Replace trigger <trigger_name>
[before/after] [insert/update/delete] on <table_name>
[for each statement/for each row]
[when <condition>]
PL/SQL block;
EXERCISES:
2) Write a PL/SQL program to create a trigger before the user deletes the data from the
Account table.
3) Write a PL/SQL program to create a trigger before the user changes the value of the
Amount(>10)in the Transaction table.
RESULT:
AIM:
To create views and index in RDBMS.
VIEW
Views are used to provide security for the data. They provide a virtual image for a database.
#Create View:
This command is used to create database view in RDBMS.
Syntax
CREATE VIEW <view_name> as select <columnname> from <tablename> where <condition>;
#Update View:
This command is used to change a value of a record in the database.
Syntax
UPDATE <view_name> SET <column name> = <new value> WHERE <column name>=
< value>;
#Drop View:
Drop command is used to drop the view.
Syntax
INDEX
An index can be used by the Oracle server to speed up the retrieval of rows by using a pointer
• Can reduce disk I/O by using a rapid path access method to locate data quickly
• Is independent of the table that it indexes
Syntax to create SQL index
QUESTIONS
Book(BID,book_name,author_name,price,quantity)
Loan(BID,CID,Name,Dateof_issue)
1.Create a view for the Book table with the fields BID, book_name & author_name.
2.Display the details in the view.
3. Update the author_name in the view.
4.Drop the view.
5.Create a view for the Book table with records having quantity >100.
6.Create an index for the CID column in the Loan table.
7. Create an index for the BID and book_name columns in the Book table.
8.Drop the index.
Ex No 10 XML Database Validation
Aim
Validate XML document against a XML Schema (XSD) in an Oracle database.
Procedure
1.Register an XML Schema
First register the schema using the DBMS_XMLSCHEMA.REGISTERSCHEMA procedure. This
allows you to specify the XML schema using
a VARCHAR2, BFILE, BLOB, CLOB, XMLTYPE or URIType types. The parameter list is quite
important. By default the REGISTERSCHEMA procedure will create database types and object
tables, allowing documents to be shredded into object tables.
SQL> DECLARE
2 l_schema CLOB;
3 BEGIN
4
26 <xs:element ref="name"/>
27 <xs:element ref="address"/>
28 <xs:element ref="city"/>
29 <xs:element ref="country"/>
30 </xs:sequence>
31 </xs:complexType>
32 </xs:element>
33
34 <xs:element name="item">
35 <xs:complexType>
36 <xs:sequence>
37 <xs:element ref="title"/>
47 <xs:sequence>
48 <xs:element ref="orderperson"/>
49 <xs:element ref="shipto"/>
50 <xs:element ref="item" maxOccurs="unbounded"/>
51 </xs:sequence>
52 <xs:attribute ref="orderid" use="required"/>
53 </xs:complexType>
54 </xs:element>
55
56 </xs:schema>';
57
58 DBMS_XMLSCHEMA.registerSchema(schemaurl => 'my_schema.xsd',
65 END;
66 /
--------------------------------------------------------------------------------
my_schema.xsd
SQL> DECLARE
2 l_xml CLOB;
3 l_xmltype XMLTYPE;
4 BEGIN
5
6 l_xml := '<?xml version="1.0" encoding="UTF-8"?>
7 <shiporder orderid="889923">
8 <orderperson>John Smith</orderperson>
9 <shipto>
10 <name>Ola Nordmann</name>
11 <address>Langgt 23</address>
12 <city>4000 Stavanger</city>
13 <country>Norway</country>
14 </shipto>
15 <item>
16 <title>Empire Burlesque</title>
17 <note>Special Edition</note>
18 <quantity>1</quantity>
19 <price>10.90</price>
20 </item>
21 <item>
22 <title>Hide your heart</title>
23 <quantity>1</quantity>
24 <price>9.90</price>
25 </item>
26 </shiporder>';
27 l_xmltype := XMLTYPE(l_xml, 'my_schema.xsd');
28 l_xmltype.schemavalidate;
29 END;
30 /
PL/SQL procedure successfully completed.
SQL> DECLARE
2 l_xml CLOB;
3 l_xmltype XMLTYPE;
4 BEGIN
5
12 <city>4000 Stavanger</city>
13 <country>Norway</country>
14 </shipto>
15 <item>
16 <title>Empire Burlesque</title>
17 <note>Special Edition</note>
18 <quantity>1</quantity>
19 <price>10.90</price>
20 </item>
21 <item>
22 <title>Hide your heart</title>
23 <quantity>1</quantity>
24 <price>9.90</price>
25 </item>
26 </shiporder>';
27
28 l_xmltype := XMLTYPE(l_xml, 'my_schema.xsd');
29 l_xmltype.schemavalidate;
30
31 END;
32 /
DECLARE
*
ERROR at line 1:
Result
Thus the XML document was validated against a XML Schema (XSD) in an Oracle database.