You are on page 1of 20

INDEX

Sr.
No.
Experiments Remark
1. Introduction to DBMS

2. To create a table, alter and drop table.

3. To perform select, update, insert and delete
operation in a table

4. To make use of different clauses viz where,
groupby, having, order by, union, intersection
,set difference

5. To study different constraints

6. To use SQL functions viz aggregate, numeric
,converison, string functions.

7. To understand use and working of joins

8. To understand use and working of sub - queries

9. To make use of transaction control statements
viz rollback, commit and savepoint

10. To make views of a table



EXPERIMENT NO: 5
AIM: TO STUDY DIFFERENT CONSTRAINTS
THEORY:
CONSTRAINTS
CONSTRAINTS enforces RULES at the table level
Constraints prevent the deletion of the table if there is DEPENDENCIES from the other table.
Basically, Constraints are used to PREVENT INVALID DATA ENTRIES INTO THE
TABLES.
HOW TO DEFINE A CONSTRAINT:
SYNTAX:
SQL> CREATE TABLE [table name] (column datatype [Default expr]
[column_constraint], .. [table_constraint][,.]);
NOT NULL : THE NOT NULL CONSTRAINT
This constraint ensures that the column contains no null values. As column without the NOT
NULL constraint can contain NULL values BY DEFAULT.
Here, On table STUDENT NOT NULL constraint is added to the LAST_NAME i.e. now
LAST_NAME cant be NULL
If we try to add NULL value in this column then following message will be displayed as
ERROR.
Whereas we can add NULL value to the NAME column as there exist no NOT NULL
constraint.

PRIMARY KEY:
A PRIMARY KEY constraint creates a primary key for a table. Only one primary key can be
created for each table.
A PRIMARY KEY constraint is a column or a set of columns that are uniquely identifies each
row in the table.
This constraint enforces UNIQUENESS of the column or column combination and ensures that
no column that is part of the primary key can contain a NULL value.
NULL VALUES are NOT ALLOWED & ALREADY existing values are not replaced.
In this Department_id is a PRIMARY KEY. i.e.
It do not contain DUPLICATE entries & NO NULL values.
If we try to add DUPICATE values than following ERROR is encountered.
If we try to add NULL value than following ERROR is encountered.
PRIMARY KEY constraint can be defined at the COLUMN LEVEL or TABLE LEVEL. A
composite PRIMARY KEY is created by using the TABLE-LEVEL definition.
A table can have only one PRIMARY KEY constraint but can have several UNIQUE
constraints. We can call them ALTERNATE KEYS.
FOREIGN KEY:
The FOREIGN KEY, or refrential integrity constraint, designates a column or combination of
columns as a foreign key and establishes a relationship between a primary key or a unique key
in the same table or a different table.
A FOREIGN KEY value must match an existing value in the parent table or be NULL
FOREIGN KEYS are based on data values and are purely logical, not physical, pointers.
SYNTAX:
SQL> CREATE TABLE table2 ( department_id NUMBER(4) CONSTRAINT
emp_deptid_fk REFERENCES table1(department_id), )
The FOREIGN KEY is defined in the child table, and the table containing the referenced
column is the Parent table. The FOREIGN KEY is defined using the combination of the
following keywords:
FOREIGN KEY: is used to define the column in the child table at the table constraint level.
REFERENCES: identifies the table and column in the parent table.
ON DELETE CASCADE: indicates that when the row in the parent table is deleted, the
dependent rows in the chile table will also be deleted.
ON DELETE SET NULL: converts foreign key values to the NULL when parent value is
REMOVED.
Here, 5 NOT ALLOWED value as 5 doesnt EXIT
CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table
is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the
following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CHECK (P_Id>0)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND
City='Sandnes')
To DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT chk_Person
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons"
table is created:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
ALTER TABLE Persons ADD UNIQUE (P_Id)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
To DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE Persons DROP CONSTRAINT uc_PersonID




EXPERIMENT NO: 6
AIM: TO USE FUNCTIONS VIZ AGGREGATE, NUMERIC
,CONVERISON, STRING FUNCTIONS.
THEORY: Aggregate Functions
COUNT : This function returns the number of rows or non-null values for column x.

SYNTAX
COUNT([DISTINCT|ALL]COLUMN NAME)
EXAMPLE
SQL>SELECT COUNT(EMPNO)FROM EMP;
SUM : This function ireturns the sum of values for the column x. This function is applied on
columns having numeric datatype and it returns the numeric value.

SYNTAX
SUM([DISTINCT|ALL]COLUMN NAME)
EXAMPLE
SQL>SELECT SUM(SAL) FROM EMP;
AVG : Ths function returns the average of values for the column x. It ignores the null values
in the column x.

SYNTAX
AVG([DISTINCT|ALL]COLUMN NAME)
EXAMPLE
SQL>SELECT AVG(SAL),COUNT(SAL) FROM EMP;
MIN : This function returns the minimum of values for the column x for all the rows.

SYNTAX
MIN([DISTINCT|ALL]COLUMN NAME)
EXAMPLE
SQL>SELECT MIN(SAL) FROM EMP;
MAX : This function returns the maximum of values for the column x for all the rows.

SYNTAX
MAX([DISTINCT|ALL]COLUMN NAME)
EXAMPLE
SQL>SELECT MIN(SAL),MAX(SAL) FROM EMP;
NUMERIC FUNCTIONS:
Numeric functions are used to perform operations on numbers. They accept numeric values as
input and return numeric values as output. Few of the Numeric functions are:
Function Name Return Value
ABS (x) Absolute value of the number 'x'
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places
The following examples explains the usage of the above numeric functions
Function Name Examples Return Value
ABS (x)
ABS (1)
ABS (-1)
1
-1
CEIL (x)
CEIL (2.83)
CEIL (2.49)
CEIL (-1.6)
3
3
-1
FLOOR (x) FLOOR (2.83) 2
FLOOR (2.49)
FLOOR (-1.6)
2
-2
TRUNC (x, y)
ROUND (125.456, 1)
ROUND (125.456, 0)
ROUND (124.456, -1)
125.4
125
120
ROUND (x, y)
TRUNC (140.234, 2)
TRUNC (-54, 1)
TRUNC (5.7)
TRUNC (142, -1)
140.23
54
5
140
These functions can be used on database columns.
ROUND FUNCTION:
SYNTAX:
SQL> SELECT ROUND(45.923, 2), ROUND(45.923,0),
ROUND(45.923,-1) FROM DUAL;
TRUNC FUNCTION:
SYNTAX:
SQL> SELECT TRUNC(45.923, 2), TRUNC(45.923,0),
TRUNC(45.923,-1) FROM DUAL;
MOD FUNCTION:
SYNTAX:
SQL> SELECT MOD(300,10), MOD(23,9) FROM DUAL;
SQL> SELECT ename, MOD(sal,200) FROM emp;
CONVERSION FUNCTIONS:
These are functions that help us to convert a value in one form to another form. For Ex: a null
value into an actual value, or a value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name Return Value
TO_CHAR (x [,y])
Converts Numeric and Date values to a character string value. It
cannot be used for calculations since it is a string value.
TO_DATE (x [, Converts a valid Numeric and Character values to a Date value.
date_format]) Date is formatted to the format specified by 'date_format'.
NVL (x, y)
If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same
datatype.
DECODE (a, b, c, d, e,
default_value)
Checks the value of 'a', if a = b, then returns 'c'. If a = d, then
returns 'e'. Else, returns default_value.

The below table provides the examples for the above functions
Function Name Examples Return Value
TO_CHAR ()
TO_CHAR (3000, '$9999')
TO_CHAR (SYSDATE, 'Day, Month YYYY')
$3000
Monday, June 2008
TO_DATE () TO_DATE ('01-Jun-08') 01-Jun-08
NVL () NVL (null, 1) 1

STRING FUNCTIONS
UPPER FUNCTION:
SYNTAX:
SQL> SELECT UPPER(ename)|| is a || job AS EMPLOYEE DETAILS FROM emp;
LOWER FUNCTION
SYNTAX:
SQL> SELECT LOWER(ename) NAME, UPPER(job) JOB FROM emp WHERE sal>2000;
INITCAP FUNCTION:
SQL> SELECT INITCAP(ename) NAME, UPPER(job) JOB FROM emp WHERE sal>2000;
CONCAT FUNCTION
SYNTAX:
SQL> SELECT CONCAT(ename,sal) NAME FROM emp;
LENGTH FUNCTION
SYNTAX:
SQL> SELECT LENGTH(ename), sal FROM emp;
LPAD FUNCTION
SYNTAX:
SQL> SELECT LPAD(sal,8,*) FROM EMP;
RPAD FUNCTION:
SYNTAX:
SQL> SELECT RPAD(sal,8,$) FROM emp WHERE sal>3000;
SUBSTRING FUNCTION:
SYNTAX:
SQL> SELECT sal,job FROM emp WHERE SUBSTR(ename,-1,1)=n;
INSTRING FUNCTION:
SYNTAX:
SQL> SELECT ename,INSTR(ename,A), job FROM emp WHERE sal>2000;
EXPERIMENT NO: 7
AIM: TO UNDERSTAND USE AND WORKING OF JOINS
THEORY: JOINS
A JOIN can be recognized in sql select statement if its has more than one table after from
keyword. This join condition is based on primary keys and foreign keys. There must be n-1 join
conditions for n joins to tables. If join condition is omitted then the result is Cartesian product.
SYNTAX
SQL>SELECT list of columns FROM table1, table2 WHERE condition;
TYPES OF JOINS
EQUI JOIN : It returns all rows from tables where there is a match. Tables are joined on
columns that have the same datatype & size in table. It is also known as equality join or simple
join or inner join.

SYNTAX:
SELECTfield1,field2 FROM table1,table2 WHERE table1.field=table2.field;
EXAMPLE
SQL>SELECT ename, dname FROM emp, dept WHERE emp.deptno=dept.deptno;

CARTESION JOIN : When the join condition is omitted the result is Cartesian join of
two or more tables in which all the combinations of rows will be displayed. All the rows are
joined to all rows of the second table.

SYNTAX
SQL>SELECT field1, field2 FROM table1, table2;
EXAMPLE
SQL>SELECT ename, dname FROM emp, dept;


OUTER JOIN : While using equi join we see that if there exists certain rows in one table
which dont have corresponding values in the second table thn those rows will not be selected.
We can forcefully select those rows by outer join. The rows for those columns will have NULL
values.

SYNTAX
SELECT table1.col, table2.col FROM table1, table2 WHERE table1.col (+) =
table2.col;
EXAMPLE
SQL>SELECT empno, ename, emp.deptno, dname FROM emp, dept WHERE
emp.deptno (+) = dept.deptno;

SELF JOIN : The self join can be seen as join of two copies of the same table. The table is
not actually copied but sql performs the command as though it were.

EXAMPLE
SQL>SELECT e.ename, m.ename FROM emp e, emp m WHERE e.mgr=e.empno;
EXPERIMENT NO: 8
AIM: TO UNDERSTAND USE AND WORKING OF SUB -
QUERIES
THEORY: SUBQUERIES
A sub query is a form of an SQL statement that appears inside another SQL statement. It is also
termed as nested query. The statement containing a sub query is called a parent statement. The
parent statement uses the rows returned by the sub query. It can be used by the following
commands:
To insert records in a target table.
To create tables and insert records in the table created.
To update records in a target table.
To create views.
To provide values for conditions in WHERE, HAVING, IN etc. used with SELECT,
UPDATE, and DELETE statements.

TYPES OF SUB QUERIES
SINGLE ROW
It returns one row from inner nested query.
EXAMPLE IS:
SQL>SELECT deptno FROM emp WHERE ename =MILLER;
MULTIPLE ROW
Subqueries that return more than one row called multiple row queries. Operators like
IN,ALL,ANY are used.

EXAMPLE
SQL>SELECT ename,sal,deptno FROM emp WHERE sal IN (SELECT min(sal) FROM
emp GROUP BY deptno);

EXPERIMENT NO: 9
AIM: TO MAKE USE OF TRANSACTION CONTROL
STATEMENTS VIZ ROLLBACK, COMMIT AND SAVEPOINT
THEORY:
SQL-Transaction Statements control transactions in database access. This subset of SQL is also
called the Data Control Language for SQL (SQL DCL).
A transaction is a sequence of one or more SQL statements that together form a logical
unit of work. The SQL statements that form the transaction are typically closely related
and perform interdependent actions. Each statement in the transaction performs some
part of a task, but all of them are required to complete the task. Grouping the statements
as a single transaction tells the DBMS that the entire statement sequence should be executed
atomicallyall of the statements must be completed for the database to be in a
consistent state. A transaction mechanism, that ideally would guarantee the ACID properties, in
order to ensure data integrity, despite concurrent user accesses (concurrency control), and faults
(fault tolerance).
Transaction control statements are used to either save the modified data or to undo the changes
if they were made in error. Until the data has been permanently saved to the table, no other
users will be able to view any of the changes you have made. A transaction is a term used to
describe a group of DML statements representing data actions that logically should be
performed together.
COMMIT and ROLLBACK

SQL supports database transactions through two SQL transaction processing
Statements
COMMIT and ROLLBACK statement syntax diagrams

The COMMIT statement signals the successful end of a transaction. It tells the DBMS
that the transaction is now complete; all of the statements that comprise the
transaction have been executed, and the database is self-consistent.

The ROLLBACK statement signals the unsuccessful end of a transaction. It tells the
DBMS that the user does not want to complete the transaction; instead, the DBMS
should back out any changes made to the database during the transaction. In effect,
the DBMS restores the database to its state before the transaction began.

The COMMIT and ROLLBACK statements are executable SQL statements, just like
SELECT, INSERT, and UPDATE.
A COMMIT statement ends the transaction successfully, making its database changes
permanent. A new transaction begins immediately after the COMMIT statement.

A ROLLBACK statement aborts the transaction, backing out its database changes. A
new transaction begins immediately after the ROLLBACK statement.

About SAVEPOINT

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.
SQL> INSERT INTO AUTHOR
2 VALUES ('A11l', 'john',
3 'garmany', '123-345-4567',
4 '1234 here st', 'denver',
5 'CO','90204', '9999');

1 row created.

SQL> savepoint in_author;

Savepoint created.

SQL> INSERT INTO BOOK_AUTHOR VALUES ('A111', 'B130', .20);
1 row created.

SQL> savepoint in_book_author;

Savepoint created.
SQL> INSERT INTO BOOK
2 VALUES ('B130', 'P002', 'easy oracle sql',
3 'miscellaneous', 9.95, 1000, 15, 0, '',
4 to_date ('02-20-2005','MM-DD-YYYY'));
1 row created.

SQL> rollback to in_author;

Rollback complete.
In the example above, I inserted a row into the AUTHOR table and created a SAVEPOINT
called in_author. Next, I inserted a row into the book_author table and created another
SAVEPOINT called in_book_author. Finally, I inserted a row in the BOOK table. I then issued
a ROLLBACK to in_author.




EXPERIMENT NO: 10
AIM: TO MAKE VIEWS OF A TABLE
THEORY:
VIEWS :
A view is very commonly used database object that is derived at runtime.
A view contains data of its own. Its contents are derived from another table. The command for
creating view is CREATE VIEW command. Editing in the tables are automatically reflected in
the views. It is virtual table & does not have any data of its own.
SYNTAX TO CREATE A VIEW IS:
SQL>CREATE [OR REPLACE] VIEW view name AS sub query
[WITH CHECK OPTION] [WITH READ ONLY];
EXAMPLE IS:
SQL>CREATE VIEW monika AS SELECT empno, ename, sal, comm FROM emp;

TYPES OF VIEWS
JOIN VIEW
It is defined as view that has more than one table specified in from clause and does not contain
following clauses i.e. distinct, aggregation, group by. This type of view allows update, insert
and delete command to change data in table.

SYNTAX
SQL>CREATE OR REPLACE VIEW monika AS SELECT ename, empno, sal FROM
emp, dept WHERE emp.deptno = dept.deptno;
The views to be updateable must not include the following are
o Set operators , aggregate functions
o Distinct operator , rownum pseudo columns
o Group by clause , having clause

INLINE VIEW

Oracle also offers an inline view that is very handy and inline view is part of SQL statements. It
allows you in body of SQL statement to define SQL for view that SQL statement will use to
resolve its query.

MATERIALIZED VIEW

Snapshot also called materialized view. It is defined as copy of part of table or entire table. It
reflects the current status of table that is being copied. The original status table is also called
master table. Two types are Read only and update. Read-only does not allow changes to be
made in view. It simply publishes and subscribes the replications. It allows changes in local
copy which periodically updates master table.

You might also like