Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

NOIDA INSTITUTE OF ENGINEERING AND

TECHNOLOGY
GREATER NOIDA-201306
(An Autonomous Institute)

Department of Information Technology

Session (2022 – 2023)


LAB FILE
ON
Database Management System
(ACSAI0452)
(IV Semester)
Submitted To: Submitted By:
Mr. Ram Kumar Sharma RAJA KUMAR
Harsh Kumar(2101330130100)
(0211ITE167)
(2101330130054)

Affiliated to Dr. A.P.J Abdul Kalam Technical University, Uttar Pradesh,


Lucknow.
NOIDA INSTITUTE OF ENGINEERING AND
TECHNOLOGY
GREATER NOIDA-201306
(An Autonomous Institute)
School of Computer Sciences & Engineering
Session 2022-23
Course & Branch: B.Tech (IT) Semester : IVth

Lab Name: -Database Management System Lab Lab Code:-ACSAI0452

INDEX
FACULTY
PAGE
S.NO PRACTICAL CONDUCTED DATE SIGNATU
NO
RE
1 Installation of oracle 11G.
Introduction of structural query language (SQL) And Implementation
2 of DDL, DML, DQL And DCL

10

11

12
Program 1: -Installation oracle 11g
Oracle Database (known as Oracle RDBMS) is a Database Management System produced and
marketed by Oracle Corporation.
The Most Fundamental and common usage of Oracle Database is to store a Pre-Defined type of
Data. It supports the Structured Query language (SQL) to Manage and Manipulate the Data
that it has. It is one of the most Reliable and highly used Relational Database Engines.

There are many versions of Oracle Database like Oracle Database 10g, Oracle Database 11g,
Oracle Database 12c, Oracle Database 19c, etc. from which Oracle 19c is the Latest Version.
In this article, we will learn how to Install version 11g on Windows.
Downloading the Installation Files
Step 1: Go to oracle.com and Click on Options Menu.

Step 2: Click the Download Button and Scroll Down to Database Section.
Step 3: Click Database 11g Enterprise/Standard Editions, after which you’ll find different
versions of Oracle for different OS. Download the Files according to your OS.

Step 4: After Clicking the Download Button, the page will be directed to Login Screen where
you’ll need to Sign In in Oracle Account. If you don’t have one, then you must Sign Up,
because without that you won’t be able to download the Files.
Step 5: Repeat the same steps for both the Files and Download them.

After downloading the files Successfully, you’ll find both Files in Downloads Folder where
both of them will be in Compressed Form, so you’ll need to Extract them.
Extraction of Downloaded Files
Step 1: Extract both the files with the use of WinRAR or any other extraction tool of your
choice in the same directory.

Step 2: Go to Folder database -> Stage -> Components Copy all the content of this Folder

Step 3: Go to Main Database -> Stage Paste the copied content in Components Folder
Installation of Oracle Database
Step 1: Go to Main Database Folder where you’ll find Setup. Right click the setup.exe file
and choose Run as Administrator.
Step 2: Click Yes to continue. This will start Oracle Universal Installer.

Step 3: Provide your Email Address to receive all the Notifications and News Alerts from
Oracle.

In case you don’t want to receive any Alerts from Oracle, then Simply leave these fields empty
and click on Next to move ahead.
+
Step 4: Select any of the three different Installation Options according to your needs.

• Option 1 – If you want to Install Oracle Server Software and want to Create Database
also.
• Option 2 – If you want to Install Oracle Server only.
• Option 3 – If you want to Upgrade your Existing Database.
Step 5: Choose between Server Class and Desktop Class as per your requirement and click
on Next.

Note: Ignore the warning related to the Admin Password.


Step 6: Configure the basic settings and create a Password for your database. Once the
configuration is done click on Next to continue.

Step 7: Here, Oracle Universal Installer(OUI) will check for the Prerequisites such as
Hardware compatibility.
If there will be any Errors, then OUI will show them here and will recommend the changes.
Step 8: Click on Finish to start the Installation process. This installation might take some
time depending on your Hardware.
Step 9: Click OK to finish the installation.
Step 10: Copy the localhost link provided to open your Enterprise Manager.

Click the Close Button and you are done with the Installation Process.
Getting Started with Oracle Enterprise Manager
There are two ways to start Oracle Enterprise Manager:
• One way to launch Enterprise Manager is using the Link provided in last step
of Installation Process.
Note: In case if you misplace this link in the future, follow the next step to start it the other
way.
• Go to Start Menu and
• Search Oracle Folder
• Click on Database Control – Oracle (Your Global Database Name)
• This will take you to the Login Screen of your Oracle Enterprise Manager.

Incase the above Error arises, just Click Advanced ->Proceed To Localhost

Login with your Credentials and begin using the Oracle Database 11g on your Windows.
Program No 2: -Introduction of Structure Query language(SQL) &
Implementation of SQL statement using ORACLE/MYSQL
(DDL,DML,DCL,DQL, TCL)

DATABASE
A database is a collection of Data (Information). Examples of databases, which we use in
our daily life, is an Attendance Register, Telephone Directory and Inventory Management
System etc.
DBMS
DBMS
Database Management System (DBMS): A database management system is a collection of
programs written to manage a database. That is, it acts as an interface between user and database.
RDBMS
A Database Management System based on Relational Data Model is known as Relational
Database Management System (RDBMS).
Relational Data Model was developed by Dr. E.F. CODD. He developed the relational data
model by taking the concept from Relational Algebra in June - 1970.
Relational Data Model has some 12 Rules which are named after Codd as Codd Rules.
According to Codd a package can be called as RDBMS only if it satisfies the Codd Rules.
What is SQL?
SQL stands for Structured Query Language It is a computer language that provide an interface to
relational database system.SQL was developed by IBM in the 1970 for use in R System.
(SEQUEL which stands for Structured English QueryLanguage for their RDBMS.).
SQL is both an ISO and an ANSI (American National Standards Institute) standard.
What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve, insert, update, delete data from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
• SQL language is divided into five types of primary language statements: DML, DDL,
DCL, TCL and DQL.
• Using these statements, we can define the structure of a database by creating and altering
database objects, and we can manipulate data in a table through updates or deletions.
• We also can control which user can read/write data or manage transactions to create a
single unit of work.
The Five main categories of SQL statements are as follows: -
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. DCL (Data Control Language)
4. TCL (Transaction Control Language)
5. DQL (Data Query Language)
1. Data Definition Language (DDL) DDL statements are used to alter/modify a database or
table structure and schema. These statements handle the design and storage of database objects.
DDL Command by default are auto commit.
DDL statements include the following:
❑ CREATE - to create objects in the database
❑ ALTER - alters the structure of the database
❑ DROP - delete objects from the database
❑ TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
❑ COMMENT - add comments to the data dictionary
❑ RENAME - rename an object

2. Data Manipulation Language (DML) DML statements affect records in a table. These
are basic operations we perform on data such as selecting a few records from a table,
inserting new records, deleting unnecessary records, and updating/modifying existing
records.
DML statements include the following:
❑ INSERT - insert data into a table
❑ UPDATE - updates existing data within a table
❑ DELETE - deletes all records from a table, the space for the records remains
❑ MERGE - UPSERT operation (insert or update)
❑ CALL - call a PL/SQL or Java subprogram
❑ EXPLAIN PLAN - explain access path to data
❑ LOCK TABLE - control concurrency
3. Data Control Language (DCL), DCL statements control the level of access that users
have on database objects statements.
DCL statements include the following
❑ GRANT - gives user's access privileges to database
❑ REVOKE - withdraw access privileges given with the GRANT command
4. Transaction Control Language (TCL) statements are used to manage the changes made
by DML statements. It allows statements to be grouped together into logical transactions.
TCL statements allow you to control and manage transactions to maintain the integrity of
data within SQL statements.
TCL statements include the following
❑ COMMIT - save work done
❑ SAVEPOINT - identify a point in a transaction to which you can later roll back
❑ ROLLBACK - restore database to original since the last COMMIT
❑ SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use
Data Query Language (DQL), The commands of SQL that are used to retrieve data from the
database are collectively called as DQL. So, all Select statements comes under DQL.
DQL statement include the following
❑ Select: To retrieve data from the database table.
Keyword and data types
• SQL have approximate 107 reserve words (Keywords).
For Example

Data type: - Data type come in several forms and sizes, allowing the programmer to
create table suited to the scope of the project. Some of common data types are used
S No. Data Type Description Range

1 Char(size) Used for to store character string 255 characters


values of fixed length

2 Varchar (Size) Store Alphanumeric data Hold up to 4000


characters

3 Varchar2(Size) The string value's length will be Hold up to 4000


stored on disk with the value itself. characters
(Inserted value not be padded with
space)

4 Date & Time DD-MON-YYYY

5 Number Store Numbers(Fixed or Floating


point)

6 LONG Store variable length character Up to 2 GB.


string
1. DDL Commands
Create table command
Syntax: Create table <TableName> (<Columnname1><Datatype> (<size>),………………,
(<ColumnnameN><Datatype> (<size>));
The Column Specification includes –
– column name
– data type
– [size or length of column] //[] means optional
– [constraints] // [] means optional
Displaying table structure
Syntax: Desc <TableName>
Or
Describe <TableName>
Q1. Create a table called Student with the following structure.

Roll No S_NAME Branch Age

2. INSERT COMMAND
Inserting a single row into a table:
Syntax: insert into <table name> values (value list)
Example: insert a row into Student table.
Inserting a single row into a table with particular columns:
Syntax: insert into <table name> (<columnname1>,<columnname2>) values
(<experssion1>,<expression2>)
Example: insert a row into Student table
Inserting more than one record using a single insert commands:
Syntax: insert into <table name> values (&col1, &col2, ….)
Example: Insert 5 rows into Student table,
Roll No S_NAME Branch Age

001 Arpit IT 19

002 Mohit CS 20

003 Apeksha IT 18

004 Shubham IT 17

005 Rajesh CS 18

006 Rahul CS 19

007 Vishal CMC 21

3.
DQL Command
Viewing data in the table
All row and all column
Syntax: SELECT * from <Table Name>;
EXAMPLE: Select * from Student;
Filtering table data
Selected column and all rows
Syntax: SELECT <columnname1>, <columnname2> from <table>;
Selected row and all columns
Syntax: SELECT * from <table name>where <condition>;
Selected columns and selected Rows
Syntax: SELECT <columnname1>, <columnname2> from <table>where <condition> ;
Updating the contents of a table (DML Command)
• Updating all rows
Syntax: Update <Table Name> set <ColumnName1> = <expression 1>,
<ColumnName2>=<expression2>;
Example: Update the student table by changing the Age to ‘19’, for all students.
SQL Query: - UPDATE STUDENT SET age =19;
• Updating rows conditionally
Syntax: Update <Table Name> set <ColumnName1> = <expression 1>,
<ColumnName2>=<expression2> where <Condition>;
Example: Update the student name Vishal with branch name by IT.
Delete operations (DML Command)
• Removal of all rows from table
Syntax: Delete from <Table Name>;
Or
Delete <Table Name>;
• Removal of specific rows
Syntax: Delete from <Table Name> where <condition>;
Program 3:- Implementing the keyword Distinct, Desc, Order by etc and
Elimination of duplicates from the select clause:
It prevents retrieving the duplicated values ,Distinct keyword is to be used.
Syntax: Select DISTINCT col1, col2 from table name;
Example: Select DISTINCT Branch Name from Student;
Sorting Data in a table
• It sorts the result set based on columns specified.
Syntax: Select column_name1, …..,column_nameN from table name where condition order by
colmnname;
Example:i)
i) Sort the table ascending order.
Select sname from student order by rollno;
ii)Sort the table in descending order of age.
Syntax : Select * from stdeunt order by age desc;
Select command to create a table:
Syntax: create table tablename as select * from existing_tablename;
Example: create table student1 as select * from student;
CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table);
CREATE TABLE employee_IT AS (SELECT * FROM student WHERE rollNo> 17133001);
CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM
old_table_1, old_table_2, ... old_table_n)
Question
• How can I create a SQL table from another table without copying any values from the old
table?
CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2);
Modifying structures of tables (DDL Commands)
• Adding new columns
Alter table <TableName> add (<NewColumnname1><Datatype> (<size>),
(<NewColumnname2><Datatype> (<size>),………………, (<NewColumnnameM><Datatype>
(<size>));
• Dropping a column from a table
Alter table <TableName> drop column <columnName>;
• Modifying existing columns
Alter table <tablename> Modify (Columnname><NewDatatype> (<Newsize>))
Renaming,truncating,destroying(DDLCOMMANDS)
Renaming tables
Rename <TableName> to <NewTableName>;
Truncating tables
Truncate table <TableName>;
Destroying tables
drop table <TableName>;

Exercise-1
1. Create table emp with attributes
1. Emp_no<datatype><size>
2. E_name<datatype><size>
3. JOB <datatype><size>
4. Address <datatype><size>
2. Insert data into the table

EMP_NO E_NAME JOB ADDRESS

1001 Arpit AP NOIDA

1002 Mohit AP DELHI

1003 Apeksha AP GR. NOIDA


1004 Shubham Lecture NOIDA

1002 Anchal AP DELHI

1006 Ramesh Peon DELHI

1007 Vishal Manager NOIDA

3. Select Address, ename from emp working as peon.


4. Select distinct job from emp.
5. Select e_name from emp ascending and descending order
6. Update apeksha job as a HOD .
7. Describe all table.
8. Delete employee arpit from table emp.
9. Add a column salary in emp.
10. Drop a column salary from emp.
11. Modify existing column ename with name in emp.
12. Create table emp123 from tableemp with record.
13. Create table emp12 fromemp without populated any record.
14. Rename table emp to employee123.
15.Delete all record from emp.
16. Drop structure of emp.
SQL> create table emp1(Emp_no number (5),E_name char(15),JOB
char(8),Address varchar(10));

Table created.

SQL> insert into emp1 values(1001,'Arpit','AP','NOIDA');

1 row created.

SQL> insert into emp1 values(1002,'Mohit','AP','DELHI');

1 row created.

SQL> insert into emp1 values (1003,'Apeksha','AP','GR. NOIDA');

1 row created.

SQL> insert into emp1 values(1004,'Shubham','Lecture','Nodia');

1 row created.

SQL> insert into emp1 values(1002,'Amchal','AP','DELHI');

1 row created.

SQL> insert into emp1 values(1006,'Ramesh','Peon','DELHI');

1 row created.

SQL> insert into emp1 values(1007,'Vishal’, Manager','NOIDA');


ERROR:
ORA-01756: quoted string not properly terminated

SQL> SELECT *FROM emp1;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1001 Arpit AP NOIDA
1002 Mohit AP DELHI
1003 Apeksha AP GR. NOIDA
1004 Shubham Lecture Noida
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI

6 rows selected.

SQL> insert into emp1 values(1007,'Vishal','Manager','NOIDA');

1 row created.

SQL> SELECT *FROM emp1;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1001 Arpit AP NOIDA
1002 Mohit AP DELHI
1003 Apeksha AP GR. NOIDA
1004 Shubham Lecture Noida
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

7 rows selected.

SQL> select Address, E_name from emp1 where JOB='Peon';

ADDRESS E_NAME
---------- ---------------
DELHI Ramesh

SQL> select job from emp1;

JOB
--------
AP
AP
AP
Lecture
AP
Peon
Manager

7 rows selected.

SQL> select distinct job from emp1;

JOB
--------
Peon
Manager
Lecture
AP

SQL> select E_name from emp1 ORDER BY ase;


select E_name from emp1 ORDER BY ase
*
ERROR at line 1:
ORA-00904: "ASE": invalid identifier

SQL> select E_name from emp1 ORDER BY desc;


select E_name from emp1 ORDER BY desc
*
ERROR at line 1:
ORA-00936: missing expression
SQL> select * from emp1 order by E_name asc;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Amchal AP DELHI
1003 Apeksha AP GR. NOIDA
1001 Arpit AP NOIDA
1002 Mohit AP DELHI
1006 Ramesh Peon DELHI
1004 Shubham Lecture Nodia
1007 Vishal Manager NOIDA

7 rows selected.

SQL> select * from emp1 order by E_name desc;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1007 Vishal Manager NOIDA
1004 Shubham Lecture Nodia
1006 Ramesh Peon DELHI
1002 Mohit AP DELHI
1001 Arpit AP NOIDA
1003 Apeksha AP GR. NOIDA
1002 Amchal AP DELHI

7 rows selected.

SQL> update emp1 set JOB='HOD' where E_name='Apeksha';

1 row updated.

SQL> select * from emp1;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1001 Arpit AP NOIDA
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

7 rows selected.

SQL> desc emp;


Name Null? Type
----------------------------------------- -------- ----------------------
------
EMP_NO CHAR (5)
E_NAME VARCHAR2(15)
JOB CHAR (12)
ADDRESS VARCHAR2(15)
SQL> desc emp1;
Name Null? Type
----------------------------------------- -------- ----------------------
------
EMP_NO NUMBER (5)
E_NAME CHAR (15)
JOB CHAR (8)
ADDRESS VARCHAR2(10)

SQL> delete from emp1 where E_name='Arpit';

1 row deleted.

SQL> select *from emp1;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> alter table emp1 add salary int (10);


alter table emp1 add salary int (10)
*
ERROR at line 1:
ORA-01735: invalid ALTER TABLE option

SQL> alter table emp1 add (salary int (10));


alter table emp1 add (salary int (10))
*
ERROR at line 1:
ORA-00907: missing right parenthesis

SQL> alter table emp1 add (salary number(10));

Table altered.

SQL> select * from emp1;

EMP_NO E_NAME JOB ADDRESS SALARY


---------- --------------- -------- ---------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> alter table emp1 drop column(salary);


alter table emp1 drop column(salary)
*
ERROR at line 1:
ORA-00904:: invalid identifier

SQL> alter table emp1 drop column salary;

Table altered.

SQL> select * from emp1;

EMP_NO E_NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> alter table emp1 rename column e_name to name


2 ;

Table altered.

SQL> desc emp;


Name Null? Type
----------------------------------------- -------- ----------------------
------
EMP_NO CHAR (5)
E_NAME VARCHAR2(15)
JOB CHAR (12)
ADDRESS VARCHAR2(15)

SQL> desc emp1;


Name Null? Type
----------------------------------------- -------- ----------------------
------
EMP_NO NUMBER (5)
NAME CHAR (15)
JOB CHAR (8)
ADDRESS VARCHAR2(10)

SQL> select * from emp;

no rows selected
SQL> select * from emp1;

EMP_NO NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> create table emp123 as(select * from emp1);

Table created.

SQL> select *from emp123;

EMP_NO NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> create table emp12 as (select * from emp123);

Table created.

SQL> select *from emp12;

EMP_NO NAME JOB ADDRESS


---------- --------------- -------- ----------
1002 Mohit AP DELHI
1003 Apeksha HOD GR. NOIDA
1004 Shubham Lecture Nodia
1002 Amchal AP DELHI
1006 Ramesh Peon DELHI
1007 Vishal Manager NOIDA

6 rows selected.

SQL> alter table emp123 rename emp;


alter table emp123 rename emp
*
ERROR at line 1:
ORA-14155: missing PARTITION or SUBPARTITION keyword
SQL> spool off
Program No 5:- Implementation of Data Constraint (I/O constraints) like Primary key,
Foreign key and Unique Constraint etc.

 Data constraints:
 Business rules, which are enforced on data being stored in a table, are called Constraints.
Constraints, super control the data being entered into a table for permanent storage.
Data Constraints apply both
1. Table level
2. Column level
Once the constraints are attached to a table column, any SQL insert or update statement
automatically applied to data priori it is being inserted into a column table.
Data Constraint are two types
1. I/O constraints
2. Business Constraints
1.I/O constraints
The input/output data constraints are further divided into three distinctly different constraints
1. Primary key constraints
2. Foreign key constraints
3. Unique key constraints
1. Primary key Constraint
Features of primary key
 Primary key is a column or set of columns that uniquely identifies a row. Its main
purpose is the record uniqueness.
 Primary key will not allow duplicate values.
 Primary key will also not allow Null values.
 Primary key is not compulsory but it is recommended.
 Primary key helps to identify one record from another record and also helps in relating
table with one another.
 Primary key cannot be LONG or LONG RAW data type.
 Only one Primary key is allowed per table.
 Unique index is created automatically if there is a Primary key.
 One table can combine up to 16 columns in a composite Primary key.
Implementation
Defining primary key constraint at table level
 Create table <TableName> (<columnName1><Datatype> (<size>)
,<columnName2><Datatype> (<size>), Primary key (columnName));
Defining primary key constraint at column level
Syntax:
 Create table <TableName> (<columnName1><Datatype> (<size>) Primary key,
<columnName2><Datatype> (<size>));
Example:-
Create a table called EMP with primary key (EMPNO) the following structure.

EMPNO ENAME JOB

1 Arpit Singh Sales Manager

2 Atul Kumar Team Leader

3 Apeksha Developer

4 Shubham Peon

5 Rajesh MANAGER

Primary key constraints by alter command


Defining primary key constraint by Alter command
Syntax
Alter table <TableName> add Primary key (columnName));
Drop primary key constraint by Alter Command
Syntax:
 Alter table <TableName> drop Primary key (columnName2);
Foreign key constraints
Feature of foreign key
 Foreign key is a column (s) that references a column(s) of a table and it can be the same
table also.
 Parent that is being referenced has to be unique or primary key.
 Child may have duplicates and nulls but unless it is specified.
 Foreign key constraint can be specified on child but not on parent.
 Parent record can be deleted provided no child record exists.
 Master table cannot be updated if child record exist.
Syntax
Defining foreign key constraint at column level
 <columnName><dataType> (<size>) Constraint f_1 references<TableName>
[(<columnName>)]
Defining foreign key constraint at table level
 Constraint f_1 foreign key (column1, column2) references <tableName>
(<columnName>, <columnName>);
Example of primary key & Foreign key
Create a table called DEPT with primary key (DEPTNO) the following structure.

DEPTNO DName

D1 Research

D2 Development

D3 Software Testing

EMP Table with foreign Key DEPTNO

EMPNO E_NAME JOB DEPTNO

1 Arpit Singh Sales Manager D1

2 Atul Kumar Team Leader D2

3 Apeksha Developer D2

4 Shubham Peon D1

5 Rajesh Manager D3
Foreign key can be used with on delete cascade, on delete set null option.

1) Rejects insert or update of a value, if a corresponding value dose not currently exists in
the master table.
2) If the ON DELET CASCADE option is set. a DELETE operation in the master table
will trigger a DELETE operation for corresponding record in all detail table
3) If the ON DELETE SET NULL option is set DELETE operation in the master table
will set the value held by the foreign key of the details tables to null.
4) Rejects a DELETE from the master table if corresponding records in the DETAIL table
exists.
5) Must References a Primary key or UNIQUE column(s) in primary table.

3. Unique Key Constraint

Feature of Unique key constraint:

o Unique key will not allow duplicate values.


o Unique index is created automatically
o A table can have more than one unique key which is not possible in Primary key.
o Unique key can combine up to 16 columns in a composite unique key.
o Unique key cannot be LONG or LONG RAW data type.
Syntax

Defining unique key constraint at column level

• <columnName><Datatype> (size) unique


Defining unique key constraint at table level

• Create table TableName (<columnName1><datatype> (<size>),


<columnName2><datatype> (<size>), unique (<columnName1>, <columnName2>));

Example of Unique Key

Create a table called Project1 with primary key (Pno) and (Pname) Unique key the following
structure.
PNo PName Location

P1 Paytm Delhi

P2 Noida

EMP Table with foreign Key DEPTNO and also with project1 Table ( pname) as foreign key.

EMPNO E_NAME JOB DEPTNO PName

1 Arpit Singh Sales Manager D1 Paytm

2 Atul Kumar Team Leader D2 Null

3 Apeksha Developer D2 Paytm

4 Shubham Peon D1 Null

5 Rajesh Manager D3 Paytm

Exercise -2:- Implementation of Company Database Problem.


SQL> create table employee(Emp_no number(5),E_name char(15),Job
varchar(15));

Table created.

SQL> insert into employee values(1,'Arpit Singh',Sales Manager');


ERROR:
ORA-01756: quoted string not properly terminated

SQL> insert into employee values(1,'Arpit Singh','Sales Manager');

1 row created.

SQL> insert into employee values(2,'Atul Kumar','Developer');

1 row created.

SQL> insert into employee values(3,'Apeksha',Team Leader');


ERROR:
ORA-01756: quoted string not properly terminated

SQL> insert into employee values(3,'Apeksha','Team Leader');

1 row created.

SQL> insert into employee values(4,'Shubham','Peon');

1 row created.

SQL> insert into employee values(5,'Rajesh','Manager');

1 row created.

SQL> select *from employee;

EMP_NO E_NAME JOB


---------- --------------- ---------------
1 Arpit Singh Sales Manager
2 Atul Kumar Developer
3 Apeksha Team Leader
4 Shubham Peon
5 Rajesh Manager

SQL> Alter table employee add(primary key(Emp_no));

Table altered.

SQL> Alter table employee add(primary key(E_name));


Alter table employee add(primary key(E_name))
*
ERROR at line 1:
ORA-02260: table can have only one primary key
SQL> select * from emp;

EMPNO ENAME JOB


---------- --------------- ---------------
1 Arpit Singh Sales Manager
2 Atul Kumar Team Leader
3 Apeksha Developer
4 Shubham Peon
5 Rajesh MANAGE

SQL> insert into employee values(5,'Rajesh','Tester');


insert into employee values(5,'Rajesh','Tester')
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C007005) violated

SQL> insert into employee values(null,'Rajesh','Tester');


insert into employee values(null,'Rajesh','Tester')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."EMPLOYEE"."EMP_NO")

SQL> create table dept(Dept_no number(5),D_name char(15));


create table dept(Dept_no number(5),D_name char(15))
*
ERROR at line 1:
ORA-00955: name is already used by an existing object

SQL> select * from dept;

DEPTNO DNAME
-------- ---------------
D1 Research
D2 Development
D3 SoftwareTesting

SQL> alter table dept;


alter table dept
*
ERROR at line 1:
ORA-02210: no options specified for ALTER TABLE

SQL> drop table dept;

Table dropped.

SQL> create table dept1(Dept_no number(5),D_name char(15));


Table created.

SQL> insert into dept1 values(D1,'Research');


insert into dept1 values(D1,'Research')
*
ERROR at line 1:
ORA-00984: column not allowed here

SQL> insert into dept1 values('D1','Research');


insert into dept1 values('D1','Research')
*
ERROR at line 1:
ORA-01722: invalid number

SQL> drop table dept1;

Table dropped.

SQL> create table dept1(Dept_no varchar(5) primary key,D_name char(15));

Table created.

SQL> insert into dept1 values('D1','Research');

1 row created.

SQL> insert into dept1 values('D2','Developement');

1 row created.

SQL> insert into dept1 values('D3,'Software Testing');


ERROR:
ORA-01756: quoted string not properly terminated

SQL> insert into dept1 values('D3','Software Testing');


insert into dept1 values('D3','Software Testing')
*
ERROR at line 1:
ORA-12899: value too large for column "SYSTEM"."DEPT1"."D_NAME" (actual:
16,
maximum: 15)

SQL> insert into dept1 values('D3','SoftwareTesting');

1 row created.

SQL> alter table employee add costant fk-12 foreign key(Dept_no)


references dept1(Dept_no);
alter table employee add costant fk-12 foreign key(Dept_no) references
dept1(Dept_no)
*
ERROR at line 1:
ORA-01735: invalid ALTER TABLE option

SQL> alter table employee add costant fk_12 foreign key(Dept_no)


references dept1(Dept_no);
alter table employee add costant fk_12 foreign key(Dept_no) references
dept1(Dept_no)
*
ERROR at line 1:
ORA-01735: invalid ALTER TABLE option

SQL> alter table employee add costraint fk_12 foreign key(Dept_no)


references dept1(Dept_no);
alter table employee add costraint fk_12 foreign key(Dept_no) references
dept1(Dept_no)
*
ERROR at line 1:
ORA-01735: invalid ALTER TABLE option

SQL> alter table employee add constraint fk_12 foreign key(Dept_no)


references dept1(Dept_no);
alter table employee add constraint fk_12 foreign key(Dept_no) references
dept1(Dept_no)
*
ERROR at line 1:
ORA-00904: "DEPT_NO": invalid identifier

SQL> desc dept1;


Name Null? Type
----------------------------------------- -------- ----------------------
------
DEPT_NO NOT NULL VARCHAR2(5)
D_NAME CHAR(15)

SQL> alter table employee add constraint fk_12 foreign key(Dept_no)


references dept1(Dept_no);
alter table employee add constraint fk_12 foreign key(Dept_no) references
dept1(Dept_no)
*
ERROR at line 1:
ORA-00904: "DEPT_NO": invalid identifier

SQL> desc employee;


Name Null? Type
----------------------------------------- -------- ----------------------
------
EMP_NO NOT NULL NUMBER(5)
E_NAME CHAR(15)
JOB VARCHAR2(15)

SQL> alter table employee add(Dept_no varchar(5));

Table altered.

SQL> alter table employee add constraint fk_12 foreign key(Dept_no)


references dept1(Dept_no);

Table altered.

SQL> update employee set Dept_no='D1' where Emp_no=2;

1 row updated.

SQL> update employee set Dept_no='D2' where Emp_no=4;

1 row updated.

SQL> update employee set Dept_no='D1' where Emp_no=1;

1 row updated.

SQL> update employee set Dept_no='D3' where Emp_no=3;

1 row updated.

SQL> update employee set Dept_no='D2' where Emp_no=5;

1 row updated.

SQL> select *from employee


2 select *from employee;
select *from employee
*
ERROR at line 2:
ORA-00933: SQL command not properly ended

SQL> select *from employee;

EMP_NO E_NAME JOB DEPT_


---------- --------------- --------------- -----
1 Arpit Singh Sales Manager D1
2 Atul Kumar Developer D1
3 Apeksha Team Leader D3
4 Shubham Peon D2
5 Rajesh Manager D2

SQL> delete from dept1 where Dept_no='D1';


delete from dept1 where Dept_no='D1'
*
ERROR at line 1:
ORA-02292: integrity constraint (SYSTEM.FK_12) violated - child record
found

SQL> update dept1 set Dept_no='D2';


update dept1 set Dept_no='D2'
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C007006) violated

SQL> insert into employee values(6,'Ritik','CEO',null);

1 row created.

SQL> select *from employee;

EMP_NO E_NAME JOB DEPT_


---------- --------------- --------------- -----
1 Arpit Singh Sales Manager D1
2 Atul Kumar Developer D1
3 Apeksha Team Leader D3
4 Shubham Peon D2
5 Rajesh Manager D2
6 Ritik CEO

6 rows selected.

SQL> create table empit1(F_name varchar(15),L_name char(15),Job


varchar(15),primary key(F_name,L_name));

Table created.

SQL> insert into empit1 values('Arpit','Singh','Sales Manager');

1 row created.

SQL> insert into empit1 values('Atul','Kumar','Team Leader');

1 row created.

SQL> select *from empit1;

F_NAME L_NAME JOB


--------------- --------------- ---------------
Arpit Singh Sales Manager
Atul Kumar Team Leader

SQL> spool off

You might also like