CP4152 Database Practices Lab Record
CP4152 Database Practices Lab Record
CP4152 Database Practices Lab Record
REGULATION 2021
CONTENTS
2A INTEGRITY CONSTRAINTS
2D IMPLEMENTATION OF VIEWS
3A IMPLEMENTATION OF TRIGGERS
4 XML DATABASES
INTRODUCTION OF SQL
SQL stands for “Structured Query Languages”. It is used to communicate with a database
which has been already created. According to American National Standard Institute [ANSI], it is
the standard language for relational database management system [DBMS].
SQL is a very powerful and diverse database language use to storing data into databases. SQL is
loosely typed language so you can learn easily.
SQL statements are used to perform tasks such as information updating or retrieval of
information from a database. Some common relational database management systems that use
SQL are,
Oracle
Microsoft SQL Server
Microsoft Access
MySQL
Although most DBMSs use SQL, they have their unique and own additional proprietary
extensions. Some of common, standard SQL commands are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP commands. These commands can be used to accomplish almost
everything that one heads to do with a database.
Oracle has provided the following data types which can be used while creating new table.
Rules:
1. Oracle reserved words cannot be used for naming tables and attributes.
2. Table name should be an unique name and it can have underscore, numerals, letters are
allowed but not blank space.
3. Maximum length for the table name is 30 characters.
5. Each attribute (column) should be followed data type along with size.
6. Integrity constraints can be specified while creating new table and default value for
attribute is ‘null’.
Ex. No: 1a
Study of DDL Commands
[Data Definition Language]
AIM:
PROCEDURE
1. Create the table with its essential attributes.
2. Execute different Commands and extract information from the table.
Ex. No: 1b
Study of DML Commands
[Data Manipulation Language]
AIM:
PROCEDURE:
1. Create the table with its essential attributes.
2. Insert the record into table
3. Update the existing records into the table
4. Delete the records in to the table
2. DELETE OPERATIONS
a) Remove all rows
Syntax:
DELETE FROM <table_name>;
Ex. No: 1c
Study of TCL Commands
[Transaction Control Language]
AIM:
1. Use save point if any changes occur in any portion of the record to undo its original
state.
2. Use rollback for completely undo the records
3. Use commit for permanently save the records.
ROLLBACK: Restore database to original since the last commit or last rollback done.
Syntax:
ROLLBACK TO <savepoint_name>;
(or)
ROLLBACK;
Ex. No: 2A
Integrity Constraints
AIM:
To study the various types of integrity constraints
INTRODUCTION:
Constraints are condition for the data item to be stored into a
database. Constraints can be specified when the table is created (with create table
statement) or after the table is created (with alter table statement).
SQL constraints are,
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NOT NULL:
This enforces a column to not accept NULL values. It enforces the field to always
certain a value i.e. it cannot insert or update without adding value to this field.
e.g.:
CREATE TABLE person(ID integer NOT NULL, f_name varchar2(10), l_name
varchar2(10), city varchar2(10));
UNIQUE:
Uniquely identify the each record in the database table. The primary key constraints
automatically has a unique constraints defined on it. There can be many unique constraints
per table but only one primary constraint for a table.
To allow naming of unique constraints and for defining unique constraints on multiple
columns:
CREATE TABLE person(ID integer NOT NULL, f_name varchar2(10), l_name
varchar2(10), city varchar2(10), CONSTRAINT unique_name
UNIQUE(ID,f_name));
PERSON TABLE
PID NAME CITY
1 JONES ATLANDA
2 JOHNSON CHICAGO
3 HAYES LONDON
ORDER TABLE
OID O_NUMBER PID
41 73560 2
42 55361 3
43 99440 1
The foreign key constraint is used to prevent actions that would destroy links between
tables. The foreign key constraints also prevent the invalid data from being inserted into the
foreign key column because it has to be one of the values contain in the table it points to.
CHECK CONSTRAINTS:
CHECK constrains is used to limt the value range that can be placed in the column. If
we define check constraint in single column it allows only certain values for this column.
e.g.:
CREATE TABLE person(PID integer CHECK(PID>0), name varachar2(20), city
varchar2(10));
DEFAULT CONSTRAINTS:
The default constraint is used to insert default value into column. These default
values will be added to all the new record if no other value is specified.
e.g.:
CREATE TABLE friend(ID integer, name varchar2(10), city varchar2(10)
DEFAULT ‘TRICHY’);
Ex. No: 2B
SQL Functions and Operators
AIM:
To study the various operators and built-in functions in SQL in Oracle 9i.
PROCEDURE:
An operator is a reserved word or a character used primarily in an SQL statement's
WHERE clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate condition.
SQL OPERATORS:
ARITHMETIC
DESCRIPTION
OPERATORS
+, - ,*, / To perform basic arithmetic operations
RELATIONAL
DESCRIPTION
OPERATORS
= Equal to
!= Not equal to
< Less than
> Greater than
<= Less than (or) Equal to
>= Greater than (or) equal to
LIKE Column value is similar to specified characters
IN Column value is equal to any of the specified values
BETWEEN AND Column value is between two values
IS NULL Column value does not exist
LOGIC
DESCRIPTION
OPERATORS
OR For the row to be selected at least one of the condition must be true
AND For the row to be selected all the specified condition must be true.
NOT For the row to be selected the specified condition must be false.
SQL FUNCTIONS:
These functions group the rows of data based on the values returned by the query. This is
discussed in SQL GROUP functions. The group functions are used to calculate the aggregate
values like total/average, which returns just one total/one average value after processing a
group of rows.
NUMERIC FUNCTIONS:
DATE FUNCTIONS:
CONVERSION FUNCTIONS:
CHARACTER/TEXT FUNCTIONS:
Group functions are built-in SQL functions that operate on groups of rows and return
one value for the entire group. These functions are: COUNT, MAX, MIN,
AVG, SUM, DISTINCT
COUNT() : This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query
would be:
SELECT COUNT (*) FROM employee WHERE dept = 'Electronics';
If you want the total number of employees in all the department, the query would take the
form:
SELECT COUNT (*) FROM employee;
MAX(): This function is used to get the maximum value from a column. To get
the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;
MIN(): This function is used to get the minimum value from a column. To get
the minimum salary drawn by an employee, he query would be:
SELECT MIN (salary) FROM employee;
AVG(): This function is used to get the average value of a numeric column. To
get the average salary, the query would be
SELECT AVG (salary) FROM employee;
Ex. No: 2C
Join Queries and Sub Queries
AIM:
To study and implement join queries and sub queries in SQL.
INTRODUCTION:
JOIN QUERIES:
SQL joins are used to query data from two or more tables, based on a relationship
between certain columns in these tables. The JOIN keyword is used in an SQL statement to
query data from two or more tables based on a relationship between certain columns in these
tables.
General Format:
SELECT <COLUMN 1>,<COLUMN 2>,…
<COLUMN n> FROM <TABLE 1>,<TABLE
2>
WHERE
<TABLE 1>.<COLUMN NAME 1> join_op <TABLE 2>.<COLUMN NAME
2>;
EQUI JOIN:
An EQUI JOIN is a join with a join condition containing an equality operator (=) in
the where clause. An EQUI JOIN combines rows that have equivalent values for the specified
columns.
Syntax:
SELECT <COLUMN 1>,<COLUMN 2>,…
<COLUMN n> FROM <TABLE 1>,<TABLE
2>
WHERE
<TABLE 1>.<COLUMN_NAME 1> = <TABLE 2>.<COLUMN_NAME 2>;
CROSS JOIN:
SQL CROSS JOIN will return all records where each row from the first table is
combined with each row from the second table which also mean CROSS JOIN returns the
Cartesian product of the sets of rows from the joined tables.
A CROSS JOIN can be specified into two ways either by using JOIN Syntax or by
listing the tables in the FROM clause separated by comma, without using a WHERE clause to
supply join criteria.
Syntax:
SELECT * FROM [TABLE 1] CROSS JOIN [TABLE 2];
(or)
SELECT * FROM [TABLE 1], [TABLE 2];
NATURAL JOIN:
A NATURAL JOIN is a join statement that compares the common columns of both
tables with each other. One should check whether common columns exist in both tables
before doing a natural join. Natural joins may cause problems if columns are added or
renamed. Also No more than two tables can be joined using this method.
Syntax:
SELECT * FROM [TABLE 1] NATURAL JOIN [TABLE 2];
SQL ALIAS:
Alias is used to rename a table or a column by using another name. This can be used
when the table name or column name is very long or complex. An alias name could be
anything but usually it is short.
Syntax:
SELECT <column_list> FROM <table_name> ALIAS name;
e.g.:
SELECT * FROM emp a, emp b;
(Here a and b are alias names)
SUB QUERIES:
A sub query is a query that is nested inside a SELECT, INSERT, UPDATE or
DELETE statement or inside another sub query. Sub query are an alternate way of returning
data from multiple tables.
Sub queries can be used with the following SQL statements along with the
comparison operators like <, >, <=, >=, etc,. Sub query or inner query or nested query is a
query in a query.
Single Row Subqueries: The subquery returns only one row. Use single row comparison
operators like =, > etc while doing comparisions.
Multiple Row Subqueries: The subquery returns more than one row. Use multiple row
comparison operators like IN, ANY, ALL in the comparisons.
Ex. No: 2D
Implementation of Views
AIM:
To study and implement View, Index, Sequence and Synonym concepts using Oracle
9i.
VIEW
INTRODUCTION:
A VIEW is a virtual table through which a selective portion of the data from one or
more table can be seen views do not certain data of their own. They are used to restrict access
to the database or to hide data complexity. A view is stored as a SELECT statement in the
database.
The DML operations on a view like INSERT, UPDATE and DELETE can be
performed only of the query that defines the views meets all of these restrictions.
DISTINCT - must not be specified i.e., duplicate rows must not be eliminated
from the query results.
The FROM clause must specify only one table that is the view must have a
single underlying source table.
The SELECT list cannot expressions calculated columns or column functions.
The WHERE clause must not include a sub query, only simple row-by-row
search conditions may appear.
A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to create a view.
Views, which are kind of virtual tables, allow users to do the following:
8. Structure data in a way that users or classes of users find natural or intuitive.
9. Restrict access to the data such that a user can see and (sometimes) modify
exactly what they need and no more.
10. Summarize data from various tables which can be used to generate reports.
GENERAL FORMAT:
The view_name is the name of the VIEW. The SELECT statement is used to define
the columns
and rows that have to be displayed.
DROPPING A VIEW:
DROP VIEW view_name;
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of
the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the
condition(s) in the view definition. If they do not satisfy the condition(s), the UPDATE or
INSERT returns an error.
The following is an example of creating same view CUSTOMERS_VIEW with the WITH
CHECK
OPTION:
CREATE VIEW CUSTOMERS_VIEW
AS SELECT * FROM CUSTOMERS WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values
in the view's AGE column, because the view is defined by data that does not have a NULL
value in the AGE column.
Updating a View:
A view can be updated under certain conditions:
7. The SELECT clause may not contain the keyword DISTINCT.
8. The SELECT clause may not contain summary functions.
9. The SELECT clause may not contain set functions and set operators.
10. The SELECT clause may not contain an ORDER BY or GROUP BY or HAVING
clause.
11. The FROM clause may not contain multiple tables.
12. The WHERE clause may not contain sub queries.
13. Calculated columns may not be updated.
14. All NOT NULL columns from the base table must be included in the view in order
for the
INSERT query to function.
So if a view satisfies all the above-mentioned rules then you can update a view. Following
is an example to update the age of Ramesh:
Note: This would ultimately update the base table CUSTOMERS and same would
reflect in the
CUSTOMERS_VIEW itself.
Read-Only View
A view can be created with read-only option to restrict access to the view. Syntax to
create a view with Read-Only Access is as follows,
CREATE or REPLACE force view view_name AS
SELECT <column_name> FROM table_name
WHERE <condition> with read-only
The above syntax will create view for read-only purpose, Any Update or Insert data into read-
only view, will throw an error.
Ex. No: 3A
IMPLEMENTATION OF TRIGGERS
AIM:
INTRODUCTION:
A trigger is a SQL procedure that initiates an action when any one of event (INSERT,
DELETE or UPDATE) occurs, since triggers are event driven specialized procedures, they are
stored in and managed by the DBMS. A trigger cannot be called or executed; the DBMS
automatically fires the triggers as a result of a data modification to the associated table.
Triggers are used to maintain the referential integrity of data by changing the data in a
systematic function. Each trigger is attached to a single, specified table in the database.
Triggers are used to implement complex validation, security, auditing and replication of data.
In order to maintain the consistency of data during execution of triggers, oracle enforces a
restriction on the row trigger in terms of mutating and constraining table.
MUTATING TABLE:
A mutating table is the table, which is affected directly by DML statement or indirectly because
of ON_DELETE_CASCADE clause in referential integrity constraint.
CONSTRAINING TABLE:
A constraining table is the table, which is directly read by the SQL statement in the trigger or
indirectly because of foreign key constraint.
1. TRIGGER STATEMENT:
It is a SQL statement that creates a trigger and fires it upon insertion, updation or
deletion of rows in a particular table.
2. TRIGGER ACTION:
A trigger action in the PL/SQL code will be executed when a triggering statement is
encountered. The PL/SQL block contains SQL and PL/SQL block have access to column
values of the table being processed.
:new field name will contain the new value i.e. after execution of the triggering
statement.
:old field name will contain the old value i.e. before execution of the triggering
statement.
DELETING TRIGGER:
RAISE_APPLICATION_ERROR:
It ends the execution of subprogram and roll backs any database changes it has made in
previous operations and returns the error message with user defined error code.
Syntax:
raise_application_error(<error_number>,<error_message>);
There are some restrictions on PL/SQL code, which have to be written in the trigger. The
restrictions are,
1. The user cannot write any transactional control statements like COMMIT, SAVEPOINT and
ROLL BACK, inside the trigger block.
2. If the row trigger is not properly written then it generates the effect which depends on order
in which rows are processed.
AIM:
5. Connected Database must be closed at the end of the program using close() function.
6. Commit() used to save the changes made in database otherwise the changes will not be
reflected in database.
7. A cursor holds the rows returned by SQL Statement.It helps to traverse over the records
returned. Need a cursor object to do all database operations. Cursor() function is used
to create a cursor
Syntax : <<connection_object>> =
cx_Oracle.connect('username/password@servicename')
>>>import cx_Oracle
>>>con = cx_Oracle.connect('system / system@localhost')
>>>cursor = con.cursor()
>>>con.commit()
>>>con.close()
8. Creation of Table
# importing module
import cx_Oracle
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
print(con.version)
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
9. Insertion of Table
# importing module
import cx_Oracle
#con.autocommit = True
# Inserting a record into table employee
cursor.execute('insert into employee values(10001,\'Rahul\',50000.50)')
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
AIM:
INTRODUCTION :
XML database is a data persistence software system used for storing the huge
amount of information in XML format. It provides a secure place to store XML
documents.
AIM :
To create a Database and write a simple query using MongoDB
INTRODUCTION :
Example
If you want to use a database with name <mydb>, then use DATABASE statement would be
as follows −
> use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.emp.insert({"name":"XXX"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be
stored in test database.
db.dropDatabase()
This syntax will delete the selected database. In the case you have not selected any database, it
will delete default "test" database.