DDM 1&2 (2)
DDM 1&2 (2)
1
This design is translated into internal model which includes mapping of all objects i.e design
of tables, indexes, views, transaction, access privileges etc.,
PHYSICAL DATABASE DESIGN
This phase selects and characterizes the data storage and data access of the database.
The data storage depends on the type of devices supported by the hardware, the data access
methods.
Physical design is very vital because of bad design which results in poor performance.
IMPLEMENTATION
Database implementation needs the formation of special storage related constructs.
These constructs consist of storage groups, table spaces, data files, tables etc.
DATA LOADING
Once the database has been created, the data must be loaded into the database.
The data required to be converted, if the loaded date is in a different format.
OPERATIONS
In this phase, the database is accessed by the end users and application programs.
This stage includes adding of new data, modifying existing data and deletion of absolute
data.
This phase provides useful information and helps management to make a business decision.
MAINTENANCE
It is one of the ongoing phases in DDLC.
The major tasks included are database backup and recovery, access management, hardware
maintenance etc.
Data redundancy is prevented in databases. Any changes are reflected immediately thus,
zero chance of encountering data duplication.
The database makes the sharing of data among its users more streamlined. Also, there are
various authorization levels to access and share data.
The data stored in the database stay accurate and consistent which helps maintain the
integrity of data.
2
Unauthorized users are not allowed to access the data from the database. Only authorized
users with valid user credentials can access the data.
Databases have different levels of access which allows specific users or groups of users to
access only specific types of data.
The database management system (DBMS) has in-built backup and recovery. Thus, no need
for periodic backup of the database.
Data restoration is possible and DBMS restores the database to its previous condition after
crash or failure.
Because of no data redundancy, all the data in the database appear consistently for all users
having access to that database.
ORACLE :
Oracle is an Object-Relational Database Management System.
ORACLE DATABASE :
Every Oracle Database Contains Logical and Physical Structures. Logical Structures are
table spaces, Schema objects, extents and segments. Physical Structures are Datafiles, Redo Log
Files, Control File.
Table :
A table is the data structure that holds data in a relational database. A table is composed of
rows and columns.
All the tables and other objects in Oracle are stored in tablespace logically, but physically they are
stored in the data files associated with the tablespace.
CODD‟S RULES :
1. Information Rule: All information in a relational database including table names,
column names are represented by values in tables.
3
2. Guaranteed Access Rule: Every piece of data in a relational database, can be accessed
by using combination of a table name, a primary key value that identifies the row and
column name which identified a cell.
3. Systematic Treatment of Nulls Rule: The RDBMS handles records that have unknown
or inapplicable values in a pre-defined fashion.
4. Active On-line catalog based on the relational model: The description of a database
and in its contents are database tables and therefore can be queried on-line via the data
manipulation language.
5. Comprehensive Data Sub-language Rule: A RDBMS may support several languages.
But at least one of them should allow user to do all of the following: define tables and
views, query and update the data, set integrity constraints, set authorizations and define
transactions.
6. View Updating Rule: Any view that is theoretically updateable can be updated using the
RDBMS.
7. High-Level Insert, Update and Delete: The RDBMS supports insertions, updation and
deletion at a table level.
8. Physical Data Independence: The execution of adhoc requests and application
programs is not affected by changes in the physical data access and storage methods.
9. Logical Data Independence: Logical changes in tables and views such adding/deleting
columns or changing fields lengths need not necessitate modifications in the programs or
in the format of adhoc requests.
10. Integrity Independence: Like table/view definition, integrity constraints are stored in
the on-line catalog and can therefore be changed without necessitating changes in the
application programs.
11. Distribution Independence: Application programs and adhoc requests are not affected
by change in the distribution of physical data.
12. No subversion Rule: If the RDBMS has a language that accesses the information of a
record at a time, this language should not be used to bypass the integrity constraints. This
is necessary for data integrity.
SQL (Structured Query Language) :
SQL (Structured Query Language) is a database computer language designed for the
4
retrieval and management of data in relational database management systems (RDBMS), database
schema creation and modification, and database object access control management. SQL is a
standard supported by all the popular relational database management systems in the market place.
The basis data structure in RDBMS is a table. SQL provides you the features to define
tables, define constraints on tables, query for data in table, and change the data in table by adding,
modifying, and removing data. SQL also supports grouping of data in multiple rows, combining
tables and other features. All these put together, SQL is a high-level query language standard to
access and alter data in RDBMS.
Various Data Types :
1. Character Datatypes:
Char – fixed length character string that can varies between 1-2000 bytes
Varchar / Varchar2 – variable length character string, size ranges from 1-
4000 bytes.
Long - variable length character string, maximum size is 2 GB
2. Number Datatypes :
Number – {p=38,s=0}
Number(p) - fixed point
Number(p,s) –floating point (p=1 to 38,s= -84 to 127)
3. Date Datatype: used to store date and time in the table.
DB uses its own format of storing in fixed length of 7 bytes for century, date,
month, year, hour, minutes, and seconds.
Default data type is ―dd-mon-yy‖
4. Raw Datatype: used to store byte oriented data like binary data and byte string.
5. Other :
CLOB – stores character object with single byte character.
BLOB – stores large binary objects such as graphics, video, sounds.
BFILE – stores file pointers to the LOB‘s.
5
Database Model
A Database model defines the logical design of data. The model describes the relationships
between different parts of the data. Historically, in database design, three models are commonly
used. They are,
Hierarchical Model
Network Model
Relational Model
Hierarchical Model
In this model each entity has only one parent but can have several children . At the top of
hierarchy there is only one entity which is called Root.
Network Model
In the network model, entities are organized in a graph, in which some entities can be
accessed through several path
6
Relational Model
In this model, data is organized in two-dimensional tables called relations. The tables or
relation are related to each other.
7
All DDL commands are auto-committed. That means it saves all the changes
permanently in the database.
8
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the
table. It has enforcing the rules for the columns in a table. The types of the integrity constraints are:
a) Domain Integrity - Not Null , Check
b) Entity Integrity - Unique , Primary Key
c) Referential Integrity - Foreign Key , References Key
General Types of Data Constraints:
Input/output Constraints
1. The Primary key Constraint
2. The Foreign key Constraint
Business Rule Constraints
1. Check Constraint
2. Unique Constraint
3. NOT NULL Constraint
Primary key :
A primary key is one or more column(s) in a table used to uniquely identify each row in the
table. A primary key column in a table has special attributes :
A primary key is the combination of (NOT NULL+UNIQUE) key constraints.
A single column primary key is called Simple key. And a multicolumn primary key is called
a Composite primary key.
PRIMARY KEY constraint defined at the column level :
Syntax :
<col_name> <datatype>(<size>) PRIMARY KEY
For example ,
CREATE TABLE Sales_Order(Order_no varchar2(6) PRIMARY
KEY,Order_Date date,Client_no varchar2(6),Dely_addr varchar2(25),Order_status varchar2(10));
9
Example:
CREATE TABLE sales_order_details (Detlorder_no varchar2(6), Product_no varchar2(7),
product_rate number(8,2),primary key (Detlorder_no, Product_no));
Foreign key :
Foreign keys represents the relationships between tables. A foreign key is a column(or group
of columns) whose values are derived from the primary or unique key of the some other tables.
The table in which the foreign key is defined is called a foreign table or detail table. The
table that defines the primary key or unique key and is referenced by the foreign key is called
primary table or master table.
Syntax:
<col_name> <datatype> (<size>) REFERENCES <table_name> [(<col_name>)]
Example:
Create table sales_order_details(Detlorder_no varchar2(6), product_no varchar2(6),
product_rate number(8,2) ,foreign key(detlorder_no) references sales_order.order_no);
Principal of Foreign Key/References:
Rejects an INSERT or UPDATE of a value, if a corresponding value does not exist currently
in the master key table or you can say Primary key table from where foreign key has
brought out.
If ON DELETE CASCADE option is set, a DELETE operation in the master table will
trigger a delete operation for corresponding records in all detail table.
Rejects a DELETE for the master table if corresponding records in the DETAIL table exist
or you can say if value exist in foreign table and you want to DELETE it from Primary key
table then it will rejected, First you have to DELETE from FOREIGN KEY TABLE then
PRIMARY KEY table.Foreign key table also called Detail Table.
It must be matching Data Type for both Primary key and Foreign key attribute.
The CHECK constraint:
CHECK constraint must be specified as a logical expression that evaluates either to TRUE
or FALSE
Syntax:
<col_name> <data_Type> (<size>) CHECK (<logical expression>)
10
Example :
CREATE TABLE Client_Master(client_no varchar2(6) CHECK (client_no like‘c%‘),
Name varchar2(20) CHECK (name=upper(name)), city varchar2(15) CHECK (city
IN(‗Allahabad‘,‘Lucknow‘)));
Unique key :
The Unique key disallows the similar value in same column of a table.
Syntax :
<col_name> <data_type>(<size>)UNIQUE
For Example,
CREATE TABLE Student (Reg_no varchar2(10) PRIMARY KEY,Name varchar2(30),
Phone number(10) UNIQUE, Address varchar2(50));
NULL Value :
A NULL value is different from a blank or a zero.
NOT NULL Constraint
When a column is defined as NOT NULL , then that column becomes a mandatory column.
it must be enter a value into that column.
For Example,
CREATE TABLE Student(Reg_no varchar2(10) PRIMARY KEY, Name varchar2(30) NOT
NULL, Phone number(10) UNIQUE,Address varchar2(50)NOT NULL , DOB date);
Creating a Database:
create database database-name;
Example,
create database Test;
ALTER TABLE Command :
ALTER TABLE Command we can add (or) modify field of our exiting table.
Syntax:
alter table tablename add/modify (attribute datatype(size));
Adding New Columns:
Syntax:
ALTER TABLE <table_name> ADD (<NewColumnName> <Data_Type>(<size>),.....n);
11
Example:
ALTER TABLE Student ADD (Age number(2), Marks number(3));
Dropping a Column from the Table:
Syntax:
ALTER TABLE <table_name> DROP COLUMN <column_name>
Example:
ALTER TABLE Student DROP COLUMN Age;
Modifying Existing Table :
Syntax:
ALTER TABLE <table_name> MODIFY (<column_name> <NewDataType>(<NewSize>))
Example:
ALTER TABLE Student MODIFY (Name Varchar2(40));
Restriction on the ALTER TABLE :
Using the ALTER TABLE clause the following tasks cannot be performed.
Change the name of the table
Change the name of the column
Decrease the size of a column if table data exists
Example:
1. Alter table emp add (phone_no char (20));
2. Alter table emp modify(phone_no number (10));
3. ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
DROP TABLE:
It will destroy the table and all data which will be recorded in it.
Syntax:
DROP TABLE <table_name>
Example:
DROP TABLE Student;
TRUNCATE TABLE
Truncate statement to delete all the rows from table permanently . But this command will not
destroy the table's structure.
12
Syntax:
TRUNCATE TABLE <Table_name>
Example:
TRUNCATE TABLE Student;
rename query :
The rename command is used to rename a table.
Syntax,
rename table old-table-name to new-table-name
For Example ,
rename table Student to Student-record;
DESC
This is command used to view the structure of the table.
Example:
SQL > desc emp;
Name Null? Type
EmpNo NOT NULL number(5)
EName VarChar(15)
Job NOT NULL Char(10)
DeptNo NOT NULL number(3)
PHONE_NO number (10)
DML command
Data Manipulation Language (DML) statements are used for managing data in database.
DML commands are not auto-committed. It means changes made by DML command are not
permanent to database, it can be rolled back.
INSERT :Use to Add Rows to existing table.
UPDATE :Use to Edit Existing Rows in tables.
DELETE :Use to Delete Rows from tables.
INSERT command
Insert command is used to insert data into a table.
INSERT into table-name values(data1,data2,..)
13
For example ,
// Insert all field values
INSERT into Student values(102,'Alex',null);
// Insert particular Field values
INSERT into Student(id,name) values(102,'Alex');
Inserting data into a table from another table:
Example :
Suppose you want to insert data from course table to university table then use this example:
Ex.: 1 INSERT INTO university SELECT course_id, course_name FROM
course;
Ex.: 2
UPDATE command:
Update command is used to update a row of a table.
Syntax:
UPDATE table-name set column-name = value where condition;
Example,
Eg. : 1 update Student set age=18 where s_id=102;
Eg. : 2 update emp set sal=sal+500 where empno = 104;
Eg. : 3 update emp set sal=sal+(sal*5/100);
Eg. : 4 update student set total=maths+phy+chem, average=(maths+phy+chem)/3;
// update the city field value in emp table from same city field value in dept table which match both
deptno is same
Eg. : 5 update emp set city=(select city from dept where deptno= emp.deptno);
14
Delete command:
Delete command is used to delete data from a table. Delete command can also be used with
condition to delete a particular row.
Syntax:
DELETE from table-name;
Delete all Records from a Table:
DELETE from Student;
To Delete a particular Record from a Table:
Eg.:1 DELETE from Student where s_id=103;
Eg.:2 delete from emp where salary > 2000;
Select (Data Query) Statement :
Use a SELECT statement or subquery to retrieve data from one or more tables, object tables,
views, object views, or materialized views
Eg. :1 select empno, ename, sal from emp; // to retrieve all rows from emp table.
Eg. :2 select * from emp; // * means select all columns
Eg. :3 select * from emp where sal > 5000; // Retrieve all values those who are all sal > 5000
// Using Logical Conditions
Eg. :4 select * from emp where not (sal IS NULL);
Eg. :5 select * from emp where not (salary BETWEEN 1000 AND 2000);
Eg. :6 select * from employees where ename ='SAMI' AND sal=3000;
Eg. :7 select * from emp where ename = 'SAMI' OR sal >= 1000;
// Using Membership conditions
Eg. :8 select * from emp where deptno IN (10,20);
Eg. :9 select * from emp where deptno in (select deptno from dept where city=‘hyd‘)
Eg. :10 select * from emp where ename not in ('scott', 'smith');
Eg. :11 select ename from emp where deptno is null;
// Using EXISTS Conditions
In EXISTS condition tests for existence of rows in a subquery.
Eg. :12 Select deptno from dept d where exists (select * from emp e where d.deptno = e.deptno);
// Using LIKE Conditions
The LIKE conditions specify a test involving pattern matching.
Note :
The percent sign (%) matches any string.
The underscore (_) matches any single character.
15
Eg. :13 Select * from emp where ename like ‗S%‘ // whose name starts with "S"
Eg. :14 ; // whose name ends with ―d‖
select * from emp where ename
// whose name starts with ‗A‘ and ends with like „%d‟;
‗d‘
Eg. :15 select * from emp where ename like ‗A%d‟;
Eg. :16 select * from emp where ename like „%a%‘; // whose name contains character ‗a‘
anywhere in the string.
// List whose name contains ‗a‘ in second position
Eg. :17 select * from emp where ename like „_a%‘;
// List whose name contains ‗a‘ as last second character Eg.
:18 select * from emp where ename like „%a_‘;
Aggregate Functions :
Aggregate functions return a single value based on groups of rows, rather than single value
for each row.
The important Aggregate functions are :
1. Avg 2. Sum 3.Max 4. Min 5.Count 6. Stddev 7. Variance
Eg. :19 Select avg(sal) ―Average Salary‖ from emp;
Eg. :20 Select sum(sal) ―Total Salary‖ from emp;
Eg. :21 Select max(sal) ―Max Salary‖ from emp;
Eg. :22 Select min(sal) ―Min Salary‖ from emp;
Eg. :23 Select count(*) from emp; // return no. of rows in table
// Counts the number of employees whose salary is not
null. Eg. :24 Select count(sal) from emp;
Eg. :25 select stddev(sal) from emp;
Eg. :26 select variance(sal) from emp;
For example ,
SELECT deptname, MAX(salary) AS "Highest salary" FROM employees GROUP BY
deptname;
// To display emp name with the minimum salary from each department
SELECT ename,department, MIN(salary) AS "Lowest salary" FROM employees GROUP BY
department;
HAVING Clause: (Must have atleast One Aggregate function + GROUP BY Clause)
The Oracle HAVING clause is used in combination with the GROUP BY clause to restrict
the groups of returned rows.
For example,
16
// To display departments with sales greater than $25,000 will be returned.
SQL > SELECT department, SUM(sales) AS "Total sales" FROM order_details GROUP BY
department HAVING SUM(sales) > 25000;
// To display number of employees in departments with salary less than $50,000 and having
more than 10 employee will be returned.
SQL > SELECT department, COUNT(*) AS "Number of employees" FROM employees WHERE
salary < 50000 GROUP BY department HAVING COUNT(*) > 10;
Sorting DATA:
The Rows retrieved from the table will be sorted in either Ascending or Descending order
depending on the condition specified in select statement, the Keyword has used ORDER BY.
Eg. :27 SELECT * FROM Student ORDER BY First_Name ASC;
Eg. :28 SELECT first_name, city,pincode FROM Student ORDER BY First_name DESC;
// Sorting By Multiple Columns
SELECT first_name, city,pincode FROM Student ORDER BY First_name, city
DESC;
// The TOP clause allows us to specify how many rows to return.
SQL > SELECT TOP 3 * FROM emp;
SQL > SELECT TOP 40 PERCENT * FROM emp;
SQL > SELECT TOP 40 PERCENT * FROM emp ORDER BY 2 DESC; // 2- Second field
Eliminating Duplicates:( to find unique values in a column)
A table could hold duplicate rows. In such a case, you can eliminate duplicates.
Syntax:
SELECT DISTINCT col, col, .., FROM table_name;
Eg. :29 SELECT DISTINCT * FROM Student;
Eg. :30 SELECT DISTINCT first_name, city, pincode FROM Student;
Date Functions and Operators:
To manipulate the Date values.
Eg. :31 select sysdate from dual;
Sample Output :
SYSDATE
8-AUG-03
Eg. 32: alter session set NLS_DATE_FORMAT=‘DD-MON-YYYY HH:MIpm‘;
Eg. 33: select sysdate from dual;
17
Sample Output :
SYSDATE
8-AUG-2003 03:05pm
Note : The default setting of NLS_DATE_FORMAT is DD-MON-YY
Eg. 34: SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
Sample Output :
SESSIONTIMEZONE CURRENT_DATE
THURSDAY
FORMAT MEANING
D Day of the week
DD Day of the month
DDD Day of the year
DAY Full day for ex. ‗Monday‘, ‘Tuesday‘, ‘Wednesday‘
DY Day in three letters for ex. ‗MON‘, ‗TUE‘,‘FRI‘
W Week of the month
WW Week of the year
MM Month in two digits (1-Jan, 2-Feb,…12-Dec)
MON Month in three characters like ―Jan‖, ‖Feb‖, ‖Apr‖
MONTH Full Month like ―January‖, ‖February‖, ‖April‖
RM Month in Roman Characters (I-XII, I-Jan, II-Feb,…XII-Dec)
Q Quarter of the Month
YY Last two digits of the year.
YYYY Full year
YEAR Year in words like ―Nineteen Ninety Nine‖
HH Hours in 12 hour format
18
HH12 Hours in 12 hour format
HH24 Hours in 24 hour format
MI Minutes
SS Seconds
FF Fractional Seconds
SSSSS Milliseconds
TO_DATE function :
To_Date function is used to convert strings into date values.
Eg. 38: select to_char(to_date (‘15-aug-1947‘,‘dd-mon-yyyy‘),‘Day‘) from dual;
Eg. 39: select sysdate+45 from dual;
ADD_MONTHS :
Eg. 40: Select ADD_MONTHS(SYSDATE,6) from dual;
MONTHS_BETWEEN:
Eg. 41: select months_between(sysdate,to_date(‘15-aug-1947‘)) from dual;
// To eliminate the decimal value use truncate function
Eg. 42: select trunc(months_between(sysdate,to_date(‘15-aug-1947‘))) from dual;
LAST_DAY :
Eg. 43: select LAST_DAY(sysdate) from dual; // last date of the month of a given date
NEXT_DAY :
Eg. 44: select next_day(sysdate) from dual;
EXTRACT :
Syntax :
EXTRACT ( YEAR / MONTH / WEEK / DAY / HOUR / MINUTE / TIMEZONE FROM DATE)
Eg. 45: select extract(year from sysdate) from dual;
19
Character Functions:
Eg. 46: select LOWER(‗SAMI‘) from dual; // Return lower case string
Eg. 47: select UPPER(‗Sami‘) from dual; // Return lower case string
Eg. 48: select INITCAP(‗med sami‘) from dual; // Initial letter in capital.
Eg. 49: select length(‗mohammed sami‘) from dual; // Return length of the
Eg. 50: string
with 10 position
Eg. 51 : select replace('hell mohd kfshan','mohd','mohammed') from dual;
Eg. 52 : select rpad(ename,'*',10) from emp;
Eg.52 : select lpad(ename,'*',10) from emp;
Eg. 53 : select ltrim(' Interface ') from dual;
Eg. 54 : select rtrim(' Interface ') from dual;
SUBQUERIES :
A query nested within a query is known as subquery. Here the sub query will first compute
the average salary and then main query will execute.
Eg. 55: Select * from emp where sal > (select avg(sal) from emp);
// To display the name and empno of that employee whose salary is maximum.
Eg. 56: Select * from emp where sal = (select max(sal) from emp);
// To see second maximum salary
Eg. 57: Select max(sal) from emp where sal < (select max(sal) from emp);
// To see the Third highest salary.
Eg. 58: Select max(sal) from emp where sal < (select max(sal) from emp where sal < (select
max(sal) from emp));
Eg. 59: // To List the top 5 salaries from employees table
Select sal from (select sal from emp order sal desc) where rownum <= 5;
Eg. 60: //To display the sum of salary by deptwise
Select sum(sal) from emp group by deptno;
Eg. 61: // To display the average total salary deptwise
Select avg(depttotal) from (select sum(sal) as depttotal from emp group by deptno);
Eg. 62 : // To display the sum of salary of all employees dept wise
Select deptno,sum(sal) from emp group by deptno;
Eg. 63 : // To display the Average of salary of all employees dept wise
SQL> Select deptno,avg(sal) from emp group by deptno;
Eg. 64: // To see the maximum salary in each department.
SQL> Select deptno,max(sal) from emp group by deptno;
Eg. 65 : // To see total salary department wise where the dept wise total salary is above 5000.
SQL> Select deptno,sum(sal) from emp group by deptno having sum(sal) >= 5000;
20
Eg. 66 : // To display deptname and average salary of them.
Select dname,avg(sal) from emp,dept where emp.deptno=dept.deptno group by dname;
Eg. 67: // To display deptname and sum salary of them.
Select dname,sum(sal) from emp,dept where emp.deptno=dept.deptno group by dname;
SQL Alias :
Alias is used to give an alias name to a table or a column. This is quite useful in case of large
or complex queries.
Syntax :
SELECT column-name from table-name as alias-name // Table alias Name
SELECT column-name as alias-name from table-name // Column Alias Name
For Eg. : SELECT C.ID, C.NAME, C.AGE, O.AMOUNT FROM CUSTOMERS AS C, ORDERS
AS O WHERE C.ID = O.CUSTOMER_ID;
Transaction Control Language (TCL) :
Transaction control statements manage changes made by DML statements.
A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the
statements should execute successfully or none of the statements should execute.
TCL Commands are ,
COMMIT : Make changes done in transaction permanent.
ROLLBACK : Rollbacks the state of database to the last commit point.
SAVEPOINT : Use to specify a point in transaction to which later you can rollback.
COMMIT :
Commit command is used to permanently save any transaaction into database.
Syntax :
COMMIT [WORK] ;
For Example
SQL> insert into emp (empno,ename,sal) values (101,‘Abid‘,2300);
SQL> commit;
ROLLBACK :
To rollback the changes done in a transaction give rollback statement. Rollback restore the
state of the database to the last commit point.
21
Syntax :
rollback to savepoint-name;
For example,
SQL> delete from emp;
SQL> rollback;
SAVEPOINT :
Specify a point in a transaction to which later you can roll back.
Syntax :
savepoint savepoint-name;
For Example,
SQL> insert into emp (empno,ename,sal) values (109,‘Sami‘,3000);
SQL> savepoint a;
SQL> insert into dept values
(10,‘Sales‘,‘Hyd‘); SQL> savepoint b;
SQL> insert into salgrade values (‗III‘,9000,12000);
SQL> rollback to a;
Join Types :
Depending on your requirements, you can do an "inner" join or an "outer" join. These are
different in a subtle way
Inner join
This will only return rows when there is at least one row in both tables that match the join
condition.
Syntax :
SELECT * FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name =
table_name2.column_name;
For Example ,
SQL> SELECT * FROM emp INNER JOIN customer ON emp.deptid = customer.deptid;
Left outer join (or left join)
This will return rows that have data in the left table (left of the JOIN keyword), even if
there's no matching rows in the right table.
Syntax :
SELECT * FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name =
table_name2.column_name;
For Example ,
SQL> SELECT * FROM emp LEFT JOIN customer ON emp.deptid = customer.deptid;
Right outer join (or right join)
This will return rows that have data in the right table (right of the JOIN keyword), even if
22
there's no matching rows in the left table.
Syntax :
SELECT * FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name =
table_name2.column_name;
For Example ,
SQL> SELECT * FROM emp RIGHT JOIN customer ON emp.deptid = customer.deptid;
Full outer join (or full join)
This will return all rows, as long as there's matching data in one of the tables.
Syntax :
SELECT * FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name =
table_name2.column_name;
For Example ,
SQL> SELECT * FROM emp FULL JOIN customer ON emp.deptid = customer.deptid
VIEWS :
A view in SQL is a logical subset of data from one or more tables. View is used to restrict
data access. Views are known as logical tables. They represent the data of one of more tables.
You can Query, Insert, Update and delete from views, just as any other table.
Syntax :
CREATE or REPLACE view view_name AS SELECT column_name(s) FROM table_name
WHERE condition
For example ,
// To Create View
SQL> CREATE or REPLACE view sale_view as select * from Sale where customer = 'Alex';
SQL>create view emp_det as select e.empno,e.ename,e.sal,e.deptno,d.dname,d.loc from emp e,
dept d where e.deptno=d.deptno;
// To display view
SQL> SELECT * from sale_view;
SQL> SELECT * from emp_det;
Force View Creation :
This keyword force to create View even if the table does not exist. After creating a force
View if we create the base table and enter values in it, the view will be automatically updated.
For Example ,
SQL> CREATE or REPLACE force view sale_view1 as select * from Sale1 where customer =
'Abhi';
Read-Only View :
We can create a view with read-only option to restrict access to the view.
23
For Example .
SQL> CREATE or REPLACE view sale_view2 as select * from Sale where customer =
'ABC' with read-only;
SEQUENCES :
A sequence is used to generate numbers in sequence.
Syntax :
CREATE Sequence sequence-name start with initial-value increment by increment-value maxvalue
maximum-value cycle | nocycle
For Example ,
SQL> create sequence bills start with 1 increment by 1 minvalue 1 maxvalue 100 cycle
cache 10;
Accessing Sequence Numbers :
To generate Sequence Numbers you can use NEXTVAL and CURRVAL.
SQL> Select bills.nextval from dual;
SQL> insert into sales (billno,custname,amt) values (bills.nextval,‘Sami‘,2300);
// Creating Table with sequences and default :
SQL> create table invoices (invoice_no number(10) default bills.nextval, invoice_date
date default sysdate,customer varchar2(100),invoice_amt number(12,2));
Altering Sequences :
To alter sequences use ALTER SEQUENCE statement.
For Example ,
SQL> ALTER SEQUENCE BILLS MAXVALUE 200;
Dropping Sequences :
SQL> drop sequence bills;
Listing Information About Sequences :
SQL> select * from user_sequences;
SYNONYMS :
A synonym is an alias or alternative name for objects like a table, view, snapshot,
sequence, procedure, function, or package.
Two types of SYNONYMS are,
Public Synonym
Private Synonym
Syntax :
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name FOR [schema .]
object_name [@ dblink];
24
For Example ,
SQL> create synonym employee for scott.emp;
SQL>create public synonym suppliers for scott.suppliers; // accessible to all users
View the Synonym :
SQL> select * from employee;
Dropping Synonyms :
SQL> drop synonym employee;
Listing information about synonyms
SQL> select * from user_synonyms;
INDEX :
An index is a performance-tuning method of allowing faster retrieval of records. An index
creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-
tree indexes.
Syntax :
CREATE INDEX index_name ON table_name (column_name);
For Example ,
SQL> CREATE INDEX empIndex ON emp(LastName); // Index on Single Column
SQL> CREATE INDEX supplier_idx ON supplier (supplier_name, city); // Index on
Multiple Column
SQL>create index empno_ind on emp (empno);
SQL>create index empdept_ind on emp (empno,deptno);
Rename an Index :
Syntax :
ALTER INDEX index_name RENAME TO new_index_name;
For Example ,
SQL> ALTER INDEX supplier_idx RENAME TO supplier_index_name;
Drop an Index :
Syntax :
DROP INDEX index_name;
For example:
SQL> DROP INDEX supplier_idx;
SQL>select * from user_indexes;
CLUSTERS :
A cluster is a group tables that share the same data blocks i.e. all the tables are physically
stored together.
25
Creating a cluster :
o To create clustered tables.
o First, create a cluster and create index on it.
o Then create tables in
it. For Example ,
// Create a cluster
SQL>create cluster emp_dept (deptno number(2));
// Then create index on it.
SQL>create index on cluster emp_dept;
// create table in the cluster
SQL> create table dept (deptno number(2),name varchar2(20),loc varchar2(20))cluster emp_dept
(deptno);
SQL> create table emp (empno number(5),name varchar2(20),sal number(10,2),deptno number(2))
cluster emp_dept (deptno)
Dropping Clusters :
SQL> drop cluster emp_dept;
SQL> drop cluster emp_dept including tables;
Listing Information about Clusters :
SQL> select * from user_clusters;
PL/SQL :
PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs
found in procedural languages,
Genera Structure :
DECLARE
//Declarative section: variables, types, and local subprograms
BEGIN
//Executable section: procedural and SQL statements go here.
//This is the only section of the block that is required.
EXCEPTION
//Exception handling section: error handling statements go here.
END;
26
Ex.:
-- Add two number
DECLARE
a integer := 30;
b integer := 40;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
Sample Output :
SQL> set serveroutput on
Value of c: 70
Value of f: 33.333333333333333333
PL/SQL procedure successfully completed.
Ex. : // Check the given number is Even or Add
DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN -- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Output Table :
27
declare
n number;
fac number:=1;
i number;
begin
n:=&n;
for i in 1..n
loop
fac:=fac*i;
end loop;
dbms_output.put_line('factorial='||fac);
end;
/
Sample Output :
Enter value for n: 10
old 7: n:=&n;
new 7: n:=10;
factorial=3628800
Ex. : PL/SQL Program to Reverse a String
declare
str1 varchar2(50):='&str';
str2 varchar2(50);
len number;
i number;
begin
len:=length(str1);
for i in reverse 1..len
loop
str2:=str2 || substr(str1,i,1);
end loop;
dbms_output.put_line('Reverse of String is:'||str2);
end;
/
28
Exception handling :
Predefined Exception :
Oracle exception name Oracle Explanation
error
DUP_VAL_ON_INDEX ORA- You tried to execute an INSERT or UPDATE
00001 statement that has created a duplicate value in a field
restricted by a unique index.
TIMEOUT_ON_RESOURCE ORA- You were waiting for a resource and you timed out.
00051
TRANSACTION_BACKED_OUT ORA- The remote portion of a transaction has rolled back.
00061
INVALID_CURSOR ORA- You tried to reference a cursor that does not yet
01001 exist. This may have happened because you've
executed a FETCH cursor or CLOSE cursor before
OPENing the cursor.
NOT_LOGGED_ON ORA- You tried to execute a call to Oracle before logging
01012 in.
LOGIN_DENIED ORA- You tried to log into Oracle with an invalid
01017 username/password combination.
NO_DATA_FOUND ORA- You tried one of the following:
01403 1. You executed a SELECT INTO statement
and no rows were returned.
2. You referenced an uninitialized row in a
table.
3. You read past the end of file with the
UTL_FILE package.
29
TOO_MANY_ROWS ORA- You tried to execute a SELECT INTO statement and
01422 more than one row was returned.
ZERO_DIVIDE ORA- You tried to divide a number by zero.
01476
INVALID_NUMBER ORA- You tried to execute a SQL statement that tried to
01722 convert a string to a number, but it was unsuccessful.
STORAGE_ERROR ORA- You ran out of memory or memory was corrupted.
06500
PROGRAM_ERROR ORA- This is a generic "Contact Oracle support" message
06501 because an internal problem was encountered.
VALUE_ERROR ORA- You tried to perform an operation and there was a
06502 error on a conversion, truncation, or invalid
constraining of numeric or character data.
CURSOR_ALREADY_OPEN ORA- You tried to open a cursor that is already open.
06511
Ex. : PL/SQL Program using Exception handling
CREATE OR REPLACE PROCEDURE add_new_order (order_id_in IN NUMBER, sales_in IN
NUMBER)
IS
no_sales EXCEPTION; // user defined exception
BEGIN
IF sales_in = 0 THEN
RAISE no_sales;
ELSE
INSERT INTO orders (order_id, total_sales ) VALUES ( order_id_in, sales_in );
END IF;
EXCEPTION
WHEN no_sales THEN
raise_application_error (-20001,'You must have sales in order to submit the order.');
WHEN DUP_VAL_ON_INDEX THEN
raise_application_error (-20001,'You have tried to insert a duplicate order_id.');
WHEN OTHERS THEN
raise_application_error (-20002,'An error has occurred inserting an order.');
END;
/
30
Ex. : ( Switch case )
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Average');
when 'F' then dbms_output.put_line('Passed with Grace');
else dbms_output.put_line('Failed');
END CASE;
END;
Sample Output :
Excellent
PL/SQL procedure successfully completed.
Types of PL/SQL Loops
There are 4 types of PL/SQL Loops.
1. Basic Loop / Exit Loop
2. While Loop
3. For Loop
4. Cursor For
Loop Ex. :
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN 1..10 // or FOR VAR2 IN REVERSE 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP;
END;
PL/SQL PROCEDURE :
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks.
The procedure contains a header and a body.
31
o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
How to pass parameters in procedure:
There is three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or function. The
value of the parameter cannot be overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or function,
but the value of the parameter can be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or function
and the value of the parameter can be overwritten by the procedure or function.
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Table creation:
SQL > create table user(id number(10) primary key,name varchar2(100));
Now write the procedure code to insert record in user table.
Procedure Code:
create or replace procedure "INSERTUSER" (id IN NUMBER, name IN VARCHAR2) is
begin
insert into user values(id,name);
end;
/
Sample Output:
Procedure created.
SQL > EXEC procedure_name;
SQL > EXEC insertuser(101,'Rahul');
PL/SQL program to call procedure
Let's see the code to call above created procedure.
32
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/
PL/SQL FUNCTION :
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other hand a
procedure may or may not return a value.
Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Ex. :
Create a function :
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
33
Output:
Addition is: 33
Statement processed.
0.05 seconds
Let's execute the following program to update the table and increase salary of each customer by
5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows affected:
34
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Sample Output:
6 customers updated
PL/SQL procedure successfully completed.
PL/SQL Explicit Cursors:
Steps:
You must follow these steps while working with an explicit cursor.
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.
Create Cursor procedure:
Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address
%type;
CURSOR c_customers is SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' ||
c_addr);
END LOOP;
CLOSE c_customers;
END;
35
Sample Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
PL/SQL TRIGGER :
Trigger is invoked by Oracle engine automatically whenever a specified event
occurs.Trigger is stored into database and invoked repeatedly, when specific condition match.
Advantages of Triggers
These are the following advantages of Triggers:
o Trigger generates some derived column values automatically
o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactions
General Syntax :
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)
BEGIN
--- sql statements
END;
36
Ex. : Create and display trigger for changing the salary on customer table
37
Ex. No. : 2 IMPLEMENT THE DATABASE USING SQL DATA DEFINITION
WITH CONSTRAINTS, VIEWS
AIM
To create a database and to retrieve the information from the database using SQL queries.
Problem 1.1: Create a table called EMP with the following structure.
Name Type
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
MGR NUMBER(4)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Ans:
Problem 1.2: Add a column commission to the emp table Commission numeric null allowed.
Solution:
Ans:
Problem 1.3: Modify the column width of the job field of emp table.
Solution:
Ans:
38
LOC VARCHAR2(10)
39
Set Deptno as the primarykey
Ans:
Problem 1.5: Add constraints to the emp table that empno as the primary key and deptno as
the foreign key.
Ans:
Problem 1.6: Add constraints to the emp table to check the empno value while entering
(i.e) empno > 100.
Ans:
Ans:
Ans:
Problem 1.9: Add and drop a column DOJ to the emp table.
Ans:
Problem 1.10: Insert few rows and truncate those from the emp1 table and also drop
40
it.(pseudo table)
Solution:
1. create a pseudo table emp1 from emp
2. truncate values.
3. drop the table.
Ans:
Problem 1: The organization wants to display only the details of the employees
those who are managers.( horizontal portioning)
Ans:
Ans:
Ans:
Problem 5: Drop a view.
Ans:
41
Problem1
1. Create Tables as follows by choosing appropriate data type and set the necessary primary
and foreign key constraints: Product (Prodid, Prodesc, Price, Stock)
Purchase (Purid, Proid, qty, supname)
Sales (Saleid, Proid, qty, custname)
c. Display list of product details (Prodid, Prodesc, Price) supplied by a particular supplier(―ABC‖).
Ans
c. Product details (Prodid, Prodesc, Price) of products which are purchased as well as sold.
a. Create a procedure which accepts a prodid and displays all the sales and purchase records of it.
Ans
42
CREATING AN EMPLOYEE DATABASE TO SET VARIOUS CONSTRAINTS
AIM
To create an employee database with various constraints.
PROCEDURE
Write a SQL query to Select constraint name, constraint_type
Create table " Emp" With Empno, As Unique Along With fields are Ename, Job , Salary As Not
Null .
Create table " location" with location-id as primary key along with fields are ename, job , salary as
not null .
Create table " dept" with dept-no, dname, location and which consist of location in
"india","America" and deptno between 10 and 70 .
Ex:
1. create a table ‗Persons‘ that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values.
43
2. Creates a UNIQUE constraint on the "ID" column when the
"vechicle" table is created: (UNIQUE Constraint on CREATE
TABLE)
4. Creates a CHECK constraint on the "Age" column when the "labour" table
is created. The CHECK constraint ensures that you can not have any person
below 18 years.
Primary key:
Foreign Key:
Patient Table.
9. How to drop a FOREIGN KEY constraint.
44
10. Create a Index on any table to to retrieve data
from the database very fast Syntax: create index
index_name on table_name (column1, column2, ...);
45