Sie sind auf Seite 1von 80

Database Management System | 2130703

m
PRACTICAL 1
TO STUDY DDL-CREATE AND DML-INSERT COMMANDS

.co
 DDL (Data Definition Language)
It is a set of SQL commands used to create, modify and delete database objects such as tables,
views, indices, etc.

ss
It is normally used by DBA and database designers.
It provides commands like:

re
• CREATE: to create objects in a database.
• ALTER: to alter the schema, or logical structure, of the database.
• DROP: to delete objects from the database.

dp
• TRUNCATE: to remove all records from the table.

 DML (Data Manipulation Language)


or
It is a set of SQL commands used to insert, modify and delete data in a database.
It is normally used by general users who are accessing database via pre-developed
.w
applications.
It provides commands like:
• INSERT: to insert data into a table.
lit

• UPDATE: to modify existing data in a table.


• DELETE: to delete records from a table.
e

• LOCK: to lock tables to provide concurrency control among multiple users.


at

 DQL (Data Query Language)


It is a component of SQL that allows data retrieval from the database.
ajp

It provides command like SELECT. This command is a heart of SQL, and allows data
retrieval in different ways.

 DCL (Data Control Language)


/

It is set of SQL commands used to control access to data and database. Occasionally DCL
s:/

commands are grouped with DML commands.


It provides commands like:
tp

• COMMIT: to save work permanently.


• ROLLBACK: to undo work and restore database to previous state.
• SAVEPOINT: to identify a point in a transaction to which work can be undone.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 1


Database Management System | 2130703

m
• GRANT: to give access privileges to users on the database .
• REVOKE: to withdraw access privileges given to users on the database.

.co
 DATA TYPES:

1. CHAR (Size): This data type is used to store character strings values of fixed length.
The size in brackets determines the number of characters the cell can hold. The

ss
maximum number of character is 255 characters. The data held is right padded with
spaces to whatever length specified.

re
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 4000 character. Inserted value

dp
will not be padded with spaces. CHAR is much faster that VARCHAR sometimes up to
50%.

3. or
NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.
The precision (p) determines the number of places to the right of the decimal. If scale is
.w
omitted then the default is zero. If precision is omitted, values are stored with their
original precision up to the maximum of 38 digits.
lit

4. DATE: This data type is used to represent date and time. To enter dates other than the
standard format, use the appropriate functions. Date time stores date in the 24-Hours
e

format. By default the time in a date field is 12:00:00 am, if no time portion is specified.
at

The default date for a date field is the first day the current month.

5. LONG: This data type is used to store variable length character strings containing up to
ajp

2GB. Long data can be used to store arrays of binary data in ASCII format. LONG
values cannot be indexed, and the normal character functions such as SUBSTR cannot be
applied. Only one LONG value can be define per table.

6. RAW: The RAW data type is used to store binary data, such as digitized picture or
/
s:/

image. Data loaded into columns of these data types are stored without any further
conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW data
type can contain up to 2GB.
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 2


Database Management System | 2130703

m
 CONSTRAINTS:
A constraint is a rule that restricts the values that may be present in the database.

.co
Constraints can be mainly classified in to two categories.
1. Input/Output Constraints
2. Business Constraints

ss
Oracle
Constraints

re
Input/Output Business Rule
Constraints Constraints

dp
Primary Key Foreign Key Unique Key Not Null Check

 Primary Key Constraint or


• “A primary key is a set of one or more columns used to identify each record uniquely in
a column.”
.w
• A single column primary key is called a simple key, while a multi-column primary key is
called composite primary key.
lit

• Oracle provides a primary key constraint to define primary key for a table.

• A table cannot have more than one primary key.


e

• A primary key constraint is combination of UNIQUE constraint and NOT NULL


at

constraint

• A column, defined as a primary key, cannot have duplicate values across all records
and cannot have a null value.
ajp

• Primary Key is not mandatory but it is recommended.

• Primary key helps to identify one record from another record and also helps in relating
tables with one another.
/

• Primary Key can’t be LONG and LONG RAW.


s:/

• If multiple columns need to be defined as primary key column, then only table level
definition is applicable.
tp

• Maximum 16 columns can be combined as a composite primary key in a table.

Primary Key Defined at Column Level using Constraint Name


ht

<Columnname> <Datatype>(size) CONSTRAINT Cons_name Primary Key

Alpha College of Engineering and Technology Department of Information Technology | Page 3


Database Management System | 2130703

m
Primary Key Defined at Table Level using Constraint Name

CREATE TABLE table_name

.co
(
column1 datatype null/not null,
column2 datatype null/not null,
...

ss
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column n));

re
Create Primary Key - Using ALTER statement

You can create a primary key in Oracle with the ALTER TABLE statement.

dp
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);
Drop Primary Key - Using ALTER statement or
You can drop a primary key in Oracle using the ALTER TABLE statement.
.w
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
lit

Disable/Enable Primary Key

ALTER TABLE table_name


e

DISABLE/ENABLE CONSTRAINT constraint_name;


at

 Foreign Key Constraint


• A foreign key constraint represents relationships between two tables.
ajp

• This constraint is used to ensure consistency among records of the two tables.

• The table, in which a foreign key is defined, is called a foreign table, detail table or
child table.
/

• The table, of which primary key or unique key is defined, is called a primary table,
s:/

master table or parent table.

• Child may have duplicates and nulls but unless it is specified.


tp

Restriction on child table:

• Child table contains a foreign key. And, it is related to master table.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 4


Database Management System | 2130703

m
• Insert or update operation involving value of foreign key is not allowed, if corresponding
value does not exist in a master table.

.co
Restriction on master table :

• Master table contains a primary key, which is referred by foreign key in child table.
• Delete or update operation on records in master table are not allowed, if corresponding

ss
records are present in child table.

Foreign Key Defined at Column Level using Constraint Name

re
<Columnname> <Datatype>(size) REFERENCES <parenttablename>
[<columnname>][ON DELETE CASCADE]

dp
Foreign Key Defined at Table Level using Constraint Name

CREATE TABLE table_name


(
column1 datatype null/not null,
column2 datatype null/not null,
or
...
.w
CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
lit

REFERENCES parent_table (column1, column2, ... column_n)


);
e

Create Foreign Key - Using ALTER statement


at

You can create a Foreign key in Oracle with the ALTER TABLE statement.

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
ajp

FOREIGN KEY (column1, column2, ... column_n)


REFERENCES parent_table (column1, column2, ... column_n);

What is a foreign key with ON DELETE CASCADE in Oracle?


/

A foreign key with cascade delete means that if a record in the parent table is deleted, then
s:/

the corresponding records in the child table will automatically be deleted. This is called a
cascade delete in Oracle.
tp

A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or
an ALTER TABLE statement.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 5


Database Management System | 2130703

CREATE TABLE table_name

m
(
column1 datatype null/not null,
column2 datatype null/not null,

.co
...

CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)

ss
ON DELETE CASCADE
);

re
Create Foreign Key with ON DELETE CASCADE - Using ALTER statement
You can create a Foreign key in Oracle with the ALTER TABLE statement.

dp
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE;
or
Drop Foreign Key - Using ALTER statement
.w
You can drop a foreign key in Oracle using the ALTER TABLE statement.
lit

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;
e

Disable/Enable Foreign Key


at

ALTER TABLE table_name


DISABLE/ENABLE CONSTRAINT constraint_name;

 Unique Constraint
ajp

• Sometime there may be requirement that column cannot contain duplicate values.
• A column, defined as a unique, cannot have duplicate values across all records.
• Though, a unique constraint does not allow duplicate values, NULL values can be
/

duplicated in a column defined as a UNIQUE column.


s:/

• A table can have more than one column defined as a unique column.
• If multiple columns need to be defined as composite unique column, then only table level
definition is applicable.
tp

• Unique index is automatically created.


• Maximum 16 columns can be combined as a composite unique key in a table
ht

• Unique Key cannot be LONG Datatype.

Alpha College of Engineering and Technology Department of Information Technology | Page 6


Database Management System | 2130703

m
Unique Key Defined at Column Level using Constraint Name

<Columnname> <Datatype>(size) CONSTRAINT Cons_name UNIQUE

.co
Unique Key Defined at Table Level using Constraint Name

CREATE TABLE table_name

ss
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],

re
...

CONSTRAINT constraint_name UNIQUE (uc_col1, uc_col2, ... uc_col_n));

dp
Create Unique Key - Using ALTER statement

You can create a Unique key in Oracle with the ALTER TABLE statement.
ALTER TABLE table_name or
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ...
column_n);
.w
Drop Unique Key - Using ALTER statement

You can drop a unique key in Oracle using the ALTER TABLE statement.
lit

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;
e

Disable/Enable Unique Key


at

ALTER TABLE table_name


DISABLE/ENABLE CONSTRAINT constraint_name;
ajp

 Check constraint
• The check constraint is used to implement business rule. So, it is also called business rule
constraint.
• Example of business rule: A balance in any account should not be negative.
/

• Business rule define a domain for a particular column.


s:/

• The check constraint is bound to a particular column.


• Once check constraint is implemented, any insert or update operation on that table must
follow this constraint.
tp

• If any operation violates condition, it will be rejected.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 7


Database Management System | 2130703

m
Check Constraint Defined at Column Level using Constraint Name

<Columnname> <Datatype>(size) CHECK (<Logical Expression>)

.co
Check Constraint Defined at Table Level using Constraint Name

CREATE TABLE table_name

ss
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],

re
...

CHECK (<Logical Expression>), CHECK (<Logical Expression>),… );

dp
Create Check Constraints - Using ALTER statement

You can create check constraints in Oracle with the ALTER TABLE statement.
ALTER TABLE table_name
or
ADD CONSTRAINT constraint_name CHECK (column_name condition)
[DISABLE];
.w
Drop Check Constraints - Using ALTER statement

You can drop a unique key in Oracle using the ALTER TABLE statement.
lit

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;
e

Disable/Enable Check Constraints


at

ALTER TABLE table_name


DISABLE/ENABLE CONSTRAINT constraint_name;
ajp

 Not Null constraint


• A null value indicates ‘not applicable’, ‘missing’, or ‘not known’.
• A null value is different from zero or blank space.
/

• A column, defined as a not null, cannot have a null value.


s:/

• Such a column become a mandatory (compulsory) column and cannot be left empty for
any record.
tp

Not Null Constraint Defined at Column Level using Constraint Name

<Columnname> <Datatype>(size) [ NULL | NOT NULL ],


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 8


Database Management System | 2130703

m
Table-1: Countries_____

COUNTRY_ID COUNTRY_NAME REGION_ID

.co
CA Canada 2
DE Germany 1
UK United Kingdom 1
US United States of America 2

ss
CREATE TABLE COUNTRIES_____
(COUNTRY_ID CHAR(2),

re
COUNTRY_NAME VARCHAR2(40),
REGION_ID NUMBER(4));

Write Create table query using Constraints:

dp
or
.w
lit

Write Insert query for COUNTRIES Table

INSERT INTO COUNTRIES_____ VALUES ('CA','Canada',2);


e
at
ajp

ADD COUNTRY_ID AS PRIMARY KEY using Alter query


/
s:/

ADD COUNTRY_NAME AS NOT NULL using Alter query


tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 9


Database Management System | 2130703

m
ADD REGION_ID AS FOREIGN KEY using Alter query

.co
Table-2: Departments_____

ss
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

10 Administration 200 1700


20 Marketing 201 1800

re
50 Shipping 124 1500
60 IT 103 1400

dp
80 Sales 149 2500
90 Executive 100 1700
110 Accounting 205 1700
190 Contracting or - 1700

CREATE TABLE DEPARTMENTS_____


.w
(DEPARTMENT_ID NUMBER(4),
DEPARTMENT_NAME VARCHAR2(30),
MANAGER_ID NUMBER(6),
LOCATION_ID NUMBER(4));
lit

Write Create table query using Constraints:


e
at
ajp

Write Insert query for DEPARTMENTS Table


/
s:/

INSERT INTO DEPARTMENTS_____ VALUES


(10,'Administration',200,1700);
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 10


Database Management System | 2130703

m
.co
ss
re
ADD DEPARTMENT_ID AS PRIMARY KEY

dp
ADD DEPARTMENT_NAME AS NOT NULL

or
ADD Location_ID AS Foreign Key
.w
lit

ADD Manager_ID AS Foreign Key


e
at

Table-3: Employees_____
ajp

CREATE TABLE EMPLOYEES_____


(EMPLOYEE_ID NUMBER(6),
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
/

PHONE_NO VARCHAR2(20),
HIRE_DATE DATE,
s:/

JOB_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
tp

DEPARTMENT_ID NUMBER(4));
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 11


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 12


Database Management System | 2130703

m
Write Create table query using Constraints:

.co
ss
re
dp
or
.w
Write Insert query for Employees_____ Table
lit

INSERT INTO EMPLOYEES VALUES (100,'Steven','King',


'sking@gmail.com','5151234567',TO_DATE('17-JUL-1987','DD-MON-Y
YYY'),'AD_PRES',24000,NULL, NULL,90);
e
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 13


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 14


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 15


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
lit

ADD EMPLOYEE_ID AS PRIMARY KEY


e
at

ADD LAST_NAME, EMAIL, HIRE_DATE, JOB_ID AS NOT NULL


/ ajp

ADD JOB_ID AS FOREIGN KEY


s:/
tp

ADD EMAIL AS UNIQUE KEY


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 16


Database Management System | 2130703

m
APPLY CHECK CONSTRAINTS ON SALARY where salary must not be less
that 2500/-

.co
Table-4: Jobs_____

ss
JOB_ID JOB_TITLE MIN_SALARY MAX_SALARY

AC_ACCOUNT Public Accountant 4200 9000


AC_MGR Accounting Manager 8200 16000

re
AD_ASST Administration Assistant 3000 6000
AD_PRES President 20000 40000
AD_VP Administration Vice President 15000 30000

dp
IT_PROG Programmer 4000 10000
MK_MAN Marketing Manager 9000 15000
MK_REP Marketing Representative 4000 9000
SA_MAN
SA_REP
Sales Manager
Sales Representative
or 10000
6000
20000
12000
ST_CLERK Stock Clerk 2000 5000
.w
ST_MAN Stock Manager 5500 8500
lit

CREATE TABLE JOBS_____


(JOB_ID VARCHAR2(10),
JOB_TITLE VARCHAR2(35),
MIN_SALARY NUMBER(6),
e

MAX_SALARY NUMBER(6));
at

Write Create table query using Constraints:


/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 17


Database Management System | 2130703

m
Write Insert query for Jobs Table

INSERT INTO JOBS____ VALUES ('AD_PRES','President',20000,40000);

.co
ss
re
dp
or
.w
e lit
at
/ ajp

ADD PRIMARY KEY ON JOB_ID


s:/
tp

ADD JOB_TITLE AS NOT NULL


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 18


Database Management System | 2130703

m
Table 5: Job_grades_____

GRADE_LEVEL LOWEST_SAL HIGHEST_SAL

.co
A 1000 2999
B 3000 5999
C 6000 9999
D 10000 14999

ss
E 15000 24999
F 25000 40000

re
CREATE TABLE JOB_GRADES_____
(GRADE_LEVEL VARCHAR2(3),
LOWEST_SAL NUMBER,

dp
HIGHEST_SAL NUMBER);

Write Create table query using Constraints:


or
.w
e lit

Write Insert query for Job_Grades Table


at

INSERT INTO JOB_GRADES_____ VALUES('A',1000,2999);


/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 19


Database Management System | 2130703

m
Table 5: Job_history_____

EMPLOYEE_ID START_DATE END_DATE JOB_ID DEPARTMENT_ID

.co
101 28-10-1993 15-03-1997 AC_MGR 110
101 21-09-1989 27-10-1993 AC_ACCOUNT 110
102 13-01-1993 24-07-1998 IT_PROG 60
114 24-03-1998 31-12-1999 ST_CLERK 50

ss
122 01-01-1999 31-12-1999 ST_CLERK 50
176 01-01-1999 31-12-1999 SA_MAN 80
176 24-03-1998 31-12-1998 SA_RE 80

re
200 17-09-1987 17-06-1993 AD_ASST 90
200 01-07-1994 31-12-1998 AC_ACCOUNT 90

dp
201 17-02-1996 19-12-1999 MK_REP 20

CREATE TABLE JOB_HISTORY_____


(EMPLOYEE_ID NUMBER(6),
START_DATE DATE,
END_DATE DATE,
or
JOB_ID VARCHAR2(10),
.w
DEPARTMENT_ID NUMBER(4));

Write Create table query using Constraints:


e lit
at
/ ajp

Write Insert query for Job_History Table


s:/

INSERT INTO JOB_HISTORY VALUES (102,


TO_DATE('13-JAN-1993','DD-MON-YYYY'),
TO_DATE('24-JUL-1998','DD-MON-YYYY'),'IT_PROG',60);
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 20


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
e lit

ADD EMPLOYEE_ID, START_DATE, END_DATE, JOB_ID AS NOT NULL


at
/ ajp

ADD EMPLOYEE_ID FOREIGN KEY


s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 21


Database Management System | 2130703

m
ADD JOB_ID AS FOREIGN KEY

.co
Table 6: Locations_____

ss
LOCATION_ID STREET_ADRESS POSTAL_CODE CITY STATE_PROVINCE COUNTRY_ID

1400 2014 Jabberwocky Rd 26192 Southlake Texas US


South San

re
1500 2011 Interiors Blvd 99236 California US
Francisco
1700 2004 Charade Rd 98199 Seattle Washington US

dp
1800 460 Bloor St. W. ON M5S 1X8 Toronto Ontario CA
Magdalen Centre, The
2500 OX9 9ZB Oxford Oxford UK
Oxford Science Park

CREATE TABLE LOCATIONS_____


(LOCATION_ID NUMBER(4),
STREET_ADRESS VARCHAR2(40),
or
POSTAL_CODE VARCHAR2(12),
.w
CITY VARCHAR2(30),
STATE_PROVINCE VARCHAR2(25),
COUNTRY_ID CHAR(2));
lit

Write Create table query using Constraints:


e
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 22


Database Management System | 2130703

m
Write Insert query for Locations Table

INSERT INTO LOCATIONS_____ VALUES (1400,'2014 Jabberwocky


Rd','26192','Southlake','Texas','US');

.co
ss
re
dp
or
ADD LOCATION_ID AS PRIMARY KEY
.w
lit

ADD COUNTRY_ID AS FOREIGN KEY


e
at
ajp

ADD CITY AS NOT NULL


/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 23


Database Management System | 2130703

m
Table 6: Regions_____

REGION_ID REGION_NAME

.co
1 Europe
2 Americas
3 Asia
4 Middle East and Africa

ss
CREATE TABLE REGIONS_____

re
(REGION_ID NUMBER(4),
REGION_NAME VARCHAR2(25));

Write Create table query using Constraints:

dp
or
.w
Write Insert query for Regions Table
lit

INSERT INTO REGIONS_____ VALUES (1,'Europe');


e
at
ajp

ADD REGION_ID AS PRIMARY KEY


/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 24


Database Management System | 2130703

m
PRACTICAL 2
TO STUDY DQL-SELECT COMMANDS
 ALIASES

.co
Oracle ALIASES can be used to create a temporary name for columns or tables.
• COLUMN ALIASES are used to make column headings in your result set easier to

ss
read.
• TABLE ALIASES are used to shorten your SQL to make it easier to read or when you
are performing a self-join (ie: listing the same table more than once in the FROM

re
clause).

dp
The syntax to ALIAS A COLUMN in

column_name AS alias_name

The syntax to ALIAS A TABLE


or
.w
table_name alias_name

Note:
lit

• If the alias_name contains spaces, you must enclose the alias_name in quotes.
• It is acceptable to use spaces when you are aliasing a column name. However, it is not
generally good practice to use spaces when you are aliasing a table name.
e

• The alias_name is only valid within the scope of the SQL statement.
at

 DISTINCT
ajp

The Oracle DISTINCT clause is used to remove duplicates from the result set. The
DISTINCT clause can only be used with SELECT statements.

The syntax for the DISTINCT clause


/

SELECT DISTINCT expressions


s:/

FROM tables
[WHERE conditions];
tp

Note:
• When only one expression is provided in the DISTINCT clause, the query will return
the unique values for that expression.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 25


Database Management System | 2130703

m
• When more than one expression is provided in the DISTINCT clause, the query will
retrieve unique combinations for the expressions listed.

.co
In Oracle, the DISTINCT clause doesn't ignore NULL values. So when using the
DISTINCT clause in your SQL statement, your result set will include NULL as a
distinct value.

ss
 WHERE

The Oracle WHERE clause is used to filter the results from a SELECT, INSERT, UPDATE,

re
or DELETE statement.
The syntax for the WHERE clause

dp
WHERE conditions;

 AND conditions or
The Oracle AND condition (also called the AND Operator) is used to test for two or more
.w
conditions in a SELECT, INSERT, UPDATE, or DELETE statement along with WHERE.
The syntax for the AND Condition
lit

WHERE condition1
AND condition2
...
e

AND condition_n;
at

Note:
• The Oracle AND condition allows you to test 2 or more conditions.
ajp

• The Oracle AND condition requires that all of the conditions (ie: condition1,
condition2, condition_n) be must be met for the record to be included in the result set.

 OR conditions
/

The Oracle OR condition is used to test multiple conditions where records are returned when
s:/

any one of the conditions are met. It can be used in a SELECT, INSERT, UPDATE, or
DELETE statement along with WHERE.
tp

The syntax for the AND Condition


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 26


Database Management System | 2130703

m
WHERE condition1
OR condition2
...

.co
OR condition_n;

Note:
• The Oracle OR condition allows you to test 2 or more conditions.

ss
• The Oracle OR condition requires that any of the conditions (ie: condition1, condition2,
condition_n) be must be met for the record to be included in the result set.

re
 BETWEEN conditions
The Oracle BETWEEN conditions is used to retrieve values within a range in a SELECT,

dp
INSERT, UPDATE, or DELETE statement.

The syntax for the BETWEEN condition

expression BETWEEN value1 AND value2;


or
.w
Note:
• The Oracle BETWEEN conditions will return the records where expression is within
lit

the range of value1 and value2 (inclusive).


• value1 must be always less than value2.
e

 COMPARISION Operators
at

Comparison operators are used in the WHERE clause to determine which records to select.
Here is a list of the comparison operators that you can use in Oracle/PLSQL:
ajp

Comparison Operator Description


= Equal
<> Not Equal
/

!= Not Equal
s:/

> Greater Than


>= Greater Than or Equal
< Less Than
tp

<= Less Than or Equal


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 27


Database Management System | 2130703

m
The syntax for the COMPARISION operator

SELECT *

.co
FROM table_name
WHERE column_name operator parameter/value;

 IN condition/Operator

ss
The Oracle IN condition is used to help reduce the need to use multiple OR conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.

re
The syntax for the IN condition

expression IN (value1, value2, ... value_n);

dp
Note:
• The Oracle IN condition will return the records where expression is value1, value2..., or
value_n.
or
• The Oracle IN condition is also called the Oracle IN operator.
.w
 IS NULL condition
lit

The Oracle IS NULL condition is used to test for a NULL value. You can use the Oracle IS
NULL condition in either a SQL statement or in a block of PLSQL code.
e

The syntax for the IS NULL condition


at

expression IS NULL

Note:
ajp

• If expression is a NULL value, the condition evaluates to TRUE.


• If expression is not a NULL value, the condition evaluates to FALSE.
/

 LIKE condition
s:/

The Oracle LIKE condition allows wildcards to be used in the WHERE clause of a
SELECT, INSERT, UPDATE, or DELETE statement. This allows you to perform pattern
tp

matching.
The syntax for the LIKE condition
ht

expression LIKE 'pattern' [ ESCAPE 'escape_character' ]

Alpha College of Engineering and Technology Department of Information Technology | Page 28


Database Management System | 2130703

m
Wildcard Explanation
% Allows you to match any string of any length (including zero length)

.co
_ Allows you to match on a single character

Using Escape Characters


It is important to understand how to "Escape Characters" when pattern matching. These

ss
examples deal specifically with escaping characters in Oracle.

Let's say you wanted to search for a % or a _ character in the Oracle LIKE condition. You can

re
do this using an Escape character.

Please note that you can only define an escape character as a single character (length of 1).

dp
 NOT condition
The Oracle NOT condition (also called the NOT Operator) is used to negate a condition in a
SELECT, INSERT, UPDATE, or DELETE statement. or
The syntax for the NOT condition
.w
NOT condition
lit

Note:
• The Oracle NOT condition requires that the opposite of the condition be must be met
for the record to be included in the result set.
e
at

Combine with IN condition


The syntax for the NOT IN condition
ajp

expression NOT IN (value1, value2, ... value_n);

Combine with IS NULL condition


The syntax for the IS NOT NULL condition
/
s:/

expression IS NOT NULL

Combine with LIKE condition


tp

The syntax for the NOT LIKE condition

Expression NOT LIKE 'pattern' [ ESCAPE 'escape_character' ]


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 29


Database Management System | 2130703

m
Combine with BETWEEN conditions
The syntax for the NOT BETWEEN condition

.co
Expression NOT BETWEEN value1 AND value2;

 ORDER BY Clause

ss
The Oracle ORDER BY clause is used to sort the records in your result set. The ORDER BY
clause can only be used in SELECT statements.

re
The syntax for the ORDER BY clause

SELECT expressions

dp
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

Note:

or
If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will
be sorted by expression in ascending order (which is equivalent to ORDER BY
.w
expression ASC)
lit

SQL Queries

1. Describe Countries_____
e
at

2. Describe Regions_____
ajp

3. Retrieve all the data from Employees_____


/
s:/

4. Retrieve all the data from Jobs_____


tp

5. Retrieve all the data from Job_History_____


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 30


Database Management System | 2130703

m
6. Retrieve data from Job_Grades_____ and assign title of the

.co
column “Grade Level”, “Minimum Salary” and “Maximum Salary”
Respectively.

ss
re
7. Retrieve the First Name, Last Name and Joining Date of the

dp
Employee, assign appropriate column name and arrange the data
as per the First Name.

or
.w
8. Display the names of employee who are Stock Clerk.
lit

9. Retrieve all Jobs whose minimum salary is less than 5000.


e
at

10. Display the name of Department whose Location ID is 1700.


ajp

11. Display all the Job id and title whose minimum salary is
greater than 5000 and maximum salary is less than 18000.
/
s:/

12. Display the entire employee name, whose hire date is between
tp

01 Jul, 1995 and 01 Jan, 1997.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 31


Database Management System | 2130703

m
.co
ss
13. Display City and State whose Country ID is US

re
14. Retrieve the Employees names that are having salary greater
than 10000 in descending order.

dp
15. or
Find out the grade level for salary 23000
.w
16. Display Employee ID and Job ID for that employee who does
lit

job in 80, 90 and 110 Department ID with the help of IN operator.


e
at

17. Display Employee ID, First Name and Mobile no of those


employees whose department lies between 40 and 70. Assign
appropriate alias name for columns.
ajp

18. Display the First and Last Name of Employees whose commission
/

percentage IS NULL.
s:/
tp

19. Display list of employees who do not belong to any Department.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 32


Database Management System | 2130703

m
20. Display the First Name of Employees whose name contains ‘en’.

.co
21. Display all the record of employees whose Job ID start with
ST.

ss
re
22. Display all employees whose name start with ‘J’ and third
character is ‘n’.

dp
23. Display name, Email ID, Hire date of those employee whose
or
name is 5 character long and mobile no start with ‘59’
.w

24. Display the null value of employee and employee last name
lit

last character is ‘s’.


e
at

25. Display the non-null values of employees whose First Name


2 char contains ‘e’ and Last name 2 char contains ‘a’.
ajp

26. What will be output if you are giving LIKE predicate as ‘%\_%’
ESCAPE ‘\’ in JOBS table?
/
s:/

27. Display details of employee whose Job ID is 7 Character long


tp

and third character is ‘_’


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 33


Database Management System | 2130703

m
PRACTICAL 3
TO PERFORM VARIOUS AGGREGATE FUNCTIONS AND SORTING
CONCEPT ON ALL CREATED TABLES

.co
FUNCTIONS NAME
1. Group Function (Aggregate Functions)

ss
Functions that act on a set of values are called Group Functions. For ex SUM is a functions
which calculate the total set of numbers. A group functions returns a single result row for a

re
group of queried rows.

2. Scalar Function (Single Row Functions)

dp
Functions that act on only one value at a time are called scalar Functions. For ex LENGTH
is a function which calculates the length of one particular string value. A single row function
returns one result for every row of a queried table or view

 AGGREGATE FUNCTIONS
or

.w
AVG

Return an average value of ‘n’ ignoring null value in a column


lit

Syntax
AVG([<DISTINCT>|<ALL>]<n>)
e

• MIN
at

Return minimum value of Expression

Syntax
ajp

MIN([<DISTINCT>|<ALL>]<expr>)

• COUNT

Return the number of rows where expr is not null


/
s:/

Syntax

COUNT([<DISTINCT>|<ALL>]<expr>)
OR
tp

COUNT(*)
ht

Returns the number of rows in the table including duplicates and with null.

Alpha College of Engineering and Technology Department of Information Technology | Page 34


Database Management System | 2130703

m
• MAX

Return maximum value of Expression

.co
Syntax

MAX([<DISTINCT>|<ALL>]<expr>)

ss
• SUM

re
Return Sum value of ‘n’

Syntax

dp
SUM([<DISTINCT>|<ALL>]<n>)

 NUMERIC FUNCTIONS
• DUAL TABLE or
The DUAL table is a special one-row, one-column table present by default in Oracle and
.w
other database installations. In Oracle, the table has a single VARCHAR2(1) column called
DUMMY that has a value of 'X'. It is suitable for use in selecting a pseudo column such as
SYSDATE or USER
lit

• ABS
e

Return the absolute value of ‘n’


at

Syntax

ABS(n)
ajp

Ex: Select ABS(-5) from Dual

• POWER

Return m raised to the nth power n must be an integer, else an error is returned
/

Syntax
s:/

POWER(m,n)
Ex: Select POWER(3,2) from Dual
tp

• ROUND
Return n. rounded to m place to the right of a decimal point. If m is omitted, n is rounded
ht

to 0 places

Alpha College of Engineering and Technology Department of Information Technology | Page 35


Database Management System | 2130703

m
Syntax

ROUND(n[,m])

.co
Ex: Select ROUND(15.19, 1) from Dual

• SQRT

Return square root of n if n<0, NULL

ss
Syntax

re
SQRT(n)
Ex: Select SQRT(25) from Dual

dp
• EXP

Return e raised to the nth power where e=2.71828183

Syntax or
EXP(n)
.w
Ex: Select EXP(5) from Dual

• GREATEST
lit

Return the greatest value in a list of the expression.

Syntax
e

GREATEST(expr_1, expr_2, … expr_n)


at

Ex: Select GREATEST(4, 5, 17) from Dual

• LEAST
ajp

Return the smallest value in a list of the expression.

Syntax
/

LEAST(expr_1, expr_2, … expr_n)


s:/

Ex: Select LEAST(4, 5, 17) from Dual

• MOD
tp

Returns the remainder of a first no divided by second no passed as a parameter. If the


second no is 0, the result is same as the first no.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 36


Database Management System | 2130703

m
Syntax

MOD(m,n)

.co
Ex: Select MOD(15, 7) from Dual

• TRUNC

Return a number truncated to a certain number of decimal places. The decimal place

ss
value be an integer.

re
Syntax

TRUNC(number,[Decimal_place])

dp
Ex: Select TRUNC(125.815, 1), TRUNC(125.815, -2) from Dual

• FLOOR(n)

or
Return the largest integer value that is equal to or less than a number.

Syntax
.w
FLOOR(n)
Ex: Select FLOOR(24.8), FLOOR(13.15) from Dual
lit

• CEIL

Return the smallest int value that is greater than or equal to a number.
e

Syntax
at

CEIL(n)
Ex: Select CEIL(24.8), CEIL(13.15) from Dual
ajp

 STRING FUNCTIONS
• LOWER
/

Return char with all letters in the lower case.


s:/

Syntax
LOWER(char)
tp

• INITCAP

Return a string with the first letter of each word in upper case and rest will be in lower
ht

case char with all letters in the lower case.

Alpha College of Engineering and Technology Department of Information Technology | Page 37


Database Management System | 2130703

m
Syntax

INITCAP(char)

.co
• UPPER

Return char with all letters in the upper case.

Syntax

ss
UPPER(char)

re
• SUBSTR

Return a portion of character, beginning at char m, and going upto character n. If n is

dp
omitted, the result returned is upto the last character in the string. The First position of
character is 1.

Syntax
SUBSTR(<string>,<start_position>,<length>)
or

.w
ANCII(<Single_character>)

Return the number code that represents the specified character. If more than one char is
lit

entered, the function will return the value for first char and ignore rest of all characters.

Syntax
e

ANSCII(<Single_Char>)
at

• INSTR

Return the location of a sub string in a string.


ajp

Syntax

INSTR(<string_1>,<string_2>,[<start_position>],[<nth_appeare
nce>])
/

Ex: Select INSTR('AMIT on the net','t'), INSTR('AMIT on the


s:/

net','t',1 ,2) from Dual

• LENGTH
tp

Return the length of a word.

Syntax
ht

LENGTH(word)

Alpha College of Engineering and Technology Department of Information Technology | Page 38


Database Management System | 2130703

m
• LTRIM

Remove the char from the left of char with Initial char removed upto the first char not in

.co
a set.

Syntax

LTRIM(char[,set]>)

ss
Ex: Select LTRIM('AMIT','A') from Dual

• RTRIM

re
Remove the char from the final character removed after the last char not in a set.

dp
Syntax
RTRIM(char[,set]>)
Ex: Select RTRIM('AMIT','A') from Dual

• TRIM
or
.w
Remove all specifies characters either from the beginning or the ending of a string.

Syntax
lit

TRIM([Leading|Trailing|Both[<trim_char> from]]<string>)
Ex: Select TRIM(BOTH 'x' FROM 'xxAMITxx') from Dual
e

• LPAD
at

Returns char_1, left padded to length n with the sequences of character specifies in
char_2. If char2 is not specified, oracle uses blank by default.
ajp

Syntax

LPAD(char1,n[,char2])
Ex: Select LPAD('Page1',10,*) from Dual
/


s:/

RPAD

Returns char_1, right padded to length n with the sequences of character specifies in
char_2. If char2 is not specified, oracle uses blank by default.
tp

Syntax
RPAD(char1,n[,char2])
ht

Ex: Select RPAD('Page1',10,*) from Dual

Alpha College of Engineering and Technology Department of Information Technology | Page 39


Database Management System | 2130703

m
 CONVERSION FUNCTIONS
• TO_CHAR

.co
The TO_CHAR function converts a number or date to a string.

Syntax
TO_CHAR(n[,format])

ss
TO_CHAR(date[,format])
Ex:

re
Select TO_CHAR(1210.73, '9999.9') from Dual
Select TO_CHAR(1210.73, '$9,999.00') from Dual

dp
Select TO_CHAR(sysdate, 'yyyy/mm/dd') from Dual
Select TO_CHAR(sysdate, 'MON DDTH, YYYY') from Dual
Select TO_CHAR(sysdate, 'DDSP') from Dual
or
Select TO_CHAR(sysdate, 'MONTH DDSPTH') from Dual
.w
• TO_DATE

The TO_DATE function converts a string to a date.


lit

Syntax

TO_DATE(string[,format])
e

Ex:
at

Select TO_DATE('2003/07/09', 'yyyy/mm/dd') from Dual


Select TO_DATE('20020315', 'yyyymmdd') from Dual
ajp

 DATE CONVERSION FUNCTIONS

• ADD_MONTHS
/

Returns date after adding the number of months specified in function


s:/

Syntax
ADD_MONTHS(d,n)
Where d stands for Date or date column & n stands for integer
tp

number or number of months to be added.


Ex: Select ADD_MONTHS(sysdate, 4) from Dual
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 40


Database Management System | 2130703

m
• LAST_DAY

Returns the last date of the Month specified with the functions

.co
Syntax
LAST_DAY(d)
Ex: Select LAST_DAY(sysdate) from Dual

ss
• MONTHS_BETWEEN

re
Returns no of months between d1 and d2

Syntax

dp
MONTHS_BETWEEN(d1,d2)
Ex: Select MONTHS_BETWEEN (TO_DATE ('2003/01/01',
'yyyy/mm/dd'), TO_DATE ('2003/03/14', 'yyyy/mm/dd')) from Dual

• NEXT_DAY
or
.w
Returns the date of the first weekday named by char that is after the date named by date.
Char must be a day of the week.
lit

Syntax

NEXT_DAY(date,char)
e

Ex: Select NEXT_DAY('01-Aug-18', 'TUESDAY') from Dual


at

SQL Queries
ajp

1. Count total number of departments.


/

2. List total salary credited in employee account.


s:/
tp

3. Display average salary credited in dept. no 50.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 41


Database Management System | 2130703

m
4. Mention the minimum salary, employee name in dept. no 80

.co
5. Mention the maximum salary, Employee name whose manager ID is
149.

ss
6. Display First character capital and rest of them small in

re
Employee first and Last name, email ID must be in small character
& Job id must be in Capital Letters.

dp
or
7. Display the Job title and mention the length of Job titles.
.w
lit

8. Sort the records of employee on bases of Hire date.


e
at

9. Sort the records of Jobs on bases of minimum salary.


ajp

10. Display Employee ID of those employees who have left the


company in ascending order.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 42


Database Management System | 2130703

m
PRACTICAL 4
TO STUDY SINGLE-ROW FUNCTIONS

.co
SQL Queries

1. Write a query to display the current date. Label the column Date

ss
2. For each employee, display the employee number, job, salary,

re
and salary increased by 15% and expressed as a whole number.
Label the column New Salary

dp
or
3. Modify your query no 4.(2) to add a column that subtracts the
old salary from the new salary. Label the column Increase
.w
lit

4. Write a query that displays the employee’s names with the first
e

letter capitalized and all other letters lowercase, and the


at

length of the names, for all employees whose name starts with
J, E, or S. Give each column an appropriate label. Sort the
ajp

results by the employees’ last names.


/
s:/

5. Write a query that produces the following for each employee:


<employee First name> <employee Last name> earns <salary>
tp

monthly.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 43


Database Management System | 2130703

m
6. Display the name, hire date, number of months employed and day

.co
of the week on which the employee has started. Order the results
by the day of the week starting with Monday.

ss
re
7. Display the hire date of employees in a format that appears as
Seventh of June 1994 12:00:00 AM.

dp
or
8. Write a query to calculate the annual compensation of all
employees (sal+comm.) & round it to 0 places.
.w
lit

9. Append additional character (*) up to 10 character in front of


e

name of employees in uppercase.


at
ajp

10. Identify which department does not have any employee without
using aggregate functions.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 44


Database Management System | 2130703

m
PRACTICAL 5
DISPLAYING DATA FROM MULTIPLE TABLES (JOINS)

.co
JOIN
• Sometime it is necessary to work with multiple tables as though they were a single

ss
entity.
• Then a single SQL Statement can manipulate data from all the tables.
• Tables are joined on columns that have a same datatype and data width

re
TYPES OF JOIN

dp
• INNER JOIN (or sometimes called simple join)
• LEFT OUTER JOIN (or sometimes called LEFT JOIN)
• RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)


or
FULL OUTER JOIN (or sometimes called FULL JOIN)
CROSS JOIN
.w
SYNTAX:
ANSI Style
lit

SELECT <col_1>, <col_2>, <col_n> FROM <tablename_1>


INNER JOIN <tablename_2>
e

ON <tablename_1>.<col_1> = <tablename_2>.<COL_2>
at

WHERE <condition>
ORDER BY <col_1>, <col_2>
ajp

THETA STYLE

SELECT <col_1>, <col_2>, <col_n> FROM


/

<tablename_1>, <tablename_2>
s:/

WHERE <tablename_1>.<col_1> = <tablename_2>.<COL_2>


AND <condition>
ORDER BY <col_1>, <col_2>
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 45


Database Management System | 2130703

m
 INNER JOIN (simple join)
Chances are, you've already written a statement that uses an Oracle INNER JOIN. It is the

.co
most common type of join. Oracle INNER JOINS return all rows from multiple tables where
the join condition is met.

ss
re
dp
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
or
.w
The Oracle INNER JOIN would return the records where table1 and table2 intersect.

 LEFT OUTER JOIN


lit

Another type of join is called an Oracle LEFT OUTER JOIN. This type of join returns all
rows from the Left-hand table specified in the ON condition and only those rows from the
e

other table where the joined fields are equal (join condition is met).
at
/ ajp

SELECT columns
s:/

FROM table1
LEFT JOIN table2
tp

ON table1.column = table2.column;

The Oracle LEFT OUTER JOIN would return the all records from table1 and only those
ht

records from table2 that intersect with table1.

Alpha College of Engineering and Technology Department of Information Technology | Page 46


Database Management System | 2130703

m
 RIGHT OUTER JOIN
Another type of join is called an Oracle RIGHT OUTER JOIN. This type of join returns all

.co
rows from the Right-hand table specified in the ON condition and only those rows from the
other table where the joined fields are equal (join condition is met).

ss
re
dp
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
or
.w
The Oracle RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.
lit

 FULL OUTER JOIN


e

Another type of join is called an Oracle FULL OUTER JOIN. This type of join returns all
rows from the Left-hand table and Right-hand table with nulls in place where the join
at

condition is not met.


/ ajp
s:/

SELECT columns
FROM table1
tp

FULL JOIN table2


ON table1.column = table2.column;
ht

The Oracle FULL OUTER JOIN would return the all records from both table1 and table2.

Alpha College of Engineering and Technology Department of Information Technology | Page 47


Database Management System | 2130703

m
 INTERSECT Operator
The Oracle INTERSECT operator is used to return the results of 2 or more SELECT

.co
statements. However, it only returns the rows selected by all queries or data sets. If a record
exists in one query and not in the other, it will be omitted from the INTERSECT results.

ss
re
dp
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
INTERSECT
or
SELECT expression1, expression2, ... expression_n
.w
FROM tables
[WHERE conditions];
lit

Note
• There must be same number of expressions in both SELECT statements and have
e

similar data types.


at

 MINUS Operator
The Oracle MINUS operator is used to return all rows in the first SELECT statement that are
ajp

not returned by the second SELECT statement. Each SELECT statement will define a dataset.
The MINUS operator will retrieve all records from the first dataset and then remove from the
results all records from the second dataset.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 48


Database Management System | 2130703

m
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]

.co
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables

ss
[WHERE conditions];

Note

re
• There must be same number of expressions in both SELECT statements and have
similar data types.

dp
 UNION Operator
The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT
or
statements. It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number of fields in
.w
the result sets with similar data types.

SELECT expression1, expression2, ... expression_n


lit

FROM tables
[WHERE conditions]
e

UNION
SELECT expression1, expression2, ... expression_n
at

FROM tables
[WHERE conditions];
ajp

Note
• There must be same number of expressions in both SELECT statements.

 UNION ALL Operator


/
s:/

The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT
statements. It does not remove duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number of fields in
tp

the result sets with similar data types.


Note
• There must be same number of expressions in both SELECT statements.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 49


Database Management System | 2130703

m
SELECT expression1, expression2, ... expression_n
FROM tables

.co
[WHERE conditions]
UNION ALL
SELECT expression1, expression2, ... expression_n

ss
FROM tables
[WHERE conditions];

re
SQL Queries

dp
1. Give the name of employees and department name in which
particular employer is working with appropriate title.
or
.w
lit

2. List departments and name of manager of all departments.


e
at

3. Mention Employee name, salary and range of min salary and max
ajp

salary for particular job.


/
s:/

4. Mention Employee name, salary and Job grades for all employees.
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 50


Database Management System | 2130703

m
5. List full address of all the managers with manager name.

.co
ss
6. Display first name, last name, department no for all Employees
who belongs to dept no 50 and 80.

re
dp
or
7. List the name of employees who are working in washington.
.w

8. Display all departments including those where does not have any
lit

employee.
e
at
ajp

9. Display Employee name, Department of Employee, Locations of


Department (City and State) province for United States of
America order by Department name.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 51


Database Management System | 2130703

m
10. Display those employees which contain a letter ‘e’ to their
first name and also display their last name, department, city,

.co
state and country.

ss
re
11. Display first and last name and salary for those employees

dp
who earns less than the employee earn whose no is 202.

or
.w

12. Display the first name of all employees including the first
lit

name of their manager with appropriate title.


e
at
ajp

13. Display Job Title, Department, Full name of employee and


starting date for all the jobs which started on or after 1st Jan,
1993 and end with on or before 31st Aug, 1997.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 52


Database Management System | 2130703

m
14. Display Job Title, full name of employees and difference
between maximum salary for the job and salary of the employee.

.co
ss
re
15. Display the name of the country, city and the department which
are running there.

dp
or
.w
16. Display the details of Job which was done by any of the
employees who is presently earning a salary on and above 10000.
e lit
at

17. Display the country, name, city and number of those


ajp

departments where at least 2 employees are working.


/
s:/
tp

18. Display Full Name, Job Title, starting and Ending date of
last jobs for those employees with worked without a commission
PCT.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 53


Database Management System | 2130703

m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 54


Database Management System | 2130703

m
PRACTICAL 6
TO APPLY THE CONCEPT OF AGGREGATING DATA USING
FUNCTIONS.

.co
 GROUP BY Clause
The Oracle GROUP BY clause is used in a SELECT statement to collect data across multiple

ss
records and group the results by one or more columns. The group by clauses create a data set,
containing several sets of records grouped together based on conditions.

re
SYNTAX

SELECT expression1, expression2, ... expression_n,

dp
aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
or
 HAVING Clause
.w
The Oracle HAVING clause is used in combination with the GROUP BY clause to restrict
the groups of returned rows to only those, whose the condition is TRUE. Having clause can
lit

be used in conjunction with the group by clause.

Having imposes conditions on the group by clause, which further filters the group created by
e

the group by clauses.


at

SYNTAX
SELECT expression1, expression2, ... expression_n,
ajp

aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING having condition;
/
s:/

RULES FOR GROUP BY AND HAVING CLAUSES


1. Column listed in the Select statement have to be listed in the Group by clause.
2. Column listed in the Group by clause need not to be listed in the select statement.
tp

3. Only group functions can be used in the Having clauses


4. The group function listed in the having clause need not be listed in the select
ht

statement.

Alpha College of Engineering and Technology Department of Information Technology | Page 55


Database Management System | 2130703

m
SQL Queries

1. List total Salary of employee having join after 01-01-1996.

.co
ss
2. List total salary of employee whose manager is Steven.

re
dp
3. List employees who are working under each Manager.

or
4. List maximum salary of employee who is working in sales dept.
.w
lit

5. Display the total number of employee hired in year 1997, 1998,


e

1999.
at
ajp

6. Find the avg salaries for each dept and mention its dept name.
/
s:/

7. Display the total salary being paid to each dept. Within each
dept.
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 56


Database Management System | 2130703

m
8. Find the avg salary > 8000 for each dept displaying with dept
no.

.co
ss
9. List the Job id having avg salary more than 10000

re
10. List the department where at least two employees are working.

dp
11.
or
Display the Grade, Number of employees, and maximum salary
.w
of each grade.
e lit

12. Display the department name, grade, no. of employees where


at

at least two employees are working as a SALESMAN


/ ajp

13. List the no. of employees in each department where the no.
s:/

is less than 4.
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 57


Database Management System | 2130703

m
PRACTICAL 7
TO SOLVE QUERIES USING THE CONCEPT OF SUB QUERY.

.co
• A sub query is a form of an SQL statement that appears inside SQL statement.

• It is also termed as nested query.

• The statement containing a sub query is called a parent statement. The parent statements use

ss
the rows returned by the sub query.
• A sub query must be enclosed in parentheses.

• A sub query must be placed on the right side of the comparison operator.

re
• Use single-row operators with single-row sub queries.

dp
 Type of Sub queries

• Single row sub query: Returns zero or one row.

or
• Multiple row sub query: Returns one or more rows.

• Multiple column sub queries: Returns one or more columns.

• Correlated sub queries: Reference one or more columns in the outer SQL statement. The sub
.w
query is known as a correlated sub query because the sub query is related to the outer SQL
statement.
lit

• Nested sub queries: Sub queries are placed within another sub query.
e

Some Important points to be remember.


• A sub query must produce a single column of data as its result.
at

• Sub queries cannot manipulate their results internally; therefore ORDER BY clause
cannot be added into a sub query. You can use an ORDER BY clause in the main
ajp

SELECT statement (outer query) which will be the last clause.


• If a sub query (inner query) returns a null value to the outer query, the outer query will
not return any rows when using certain comparison operators in a WHERE clause.
• A sub query cannot be a UNION only a single select statement is allowed.
/

• Using IN or Not IN predicate


s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 58


Database Management System | 2130703

m
SQL Queries

1. List all the Employees who are working under Shipping

.co
Department.

ss
re
2. List Country Name and ID who belongs to region Europe.

dp
or
3. Display Employee ID and Name whose Job Title is Sales
.w
Representative
e lit
at

4. List the name of Employees who have left the country.


/ ajp

5. Display the full address for Region America.


s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 59


Database Management System | 2130703

m
6. Give the name of employees having same dept as Jonathan and
having salary amount greater than 10000.

.co
ss
re
7. Create a query to display the Employee ID and First Name of all
Employees who earn more than avg salary. Sort the result in
descending order of salary.

dp
or
.w
8. Give the Employee details of employee whose Job Title is Stock
Clerk and Dept. is shipping.
e lit
at
ajp

9. Give the Employee Details of Employee’s whose manager name is


Alexander.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 60


Database Management System | 2130703

m
10. List the name of Department who is having highest salary
credit.

.co
ss
re
11. List all the employees except ‘PRESIDENT’ & ‘MGR’ in asc
order of Salaries.

dp
or
.w
12. Display all the details of the employee whose salary is more
than the Sal of any SA_REP.
e lit
at

13. Display the department ID, full name (first and last name),
ajp

salary for those employees who are highest salary drawer in a


department.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 61


Database Management System | 2130703

m
14. Display the details of departments managed by Kevin.

.co
ss
re
15. Display all the information about those employees who earn
second lowest salary of all the employees

dp
or
.w
16. Display the details of the current job for those employees
lit

who worked as a Sales Representative in the past.


e
at
ajp

17. Display the full name (first and last name) of manager who
is supervising 4 or more employees.
/
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 62


Database Management System | 2130703

m
18. Display the detail information of those departments which
starting salary is at least 8000.

.co
ss
re
19. Display the details of those departments which max salary
is 7000 or above for those employees who already done one or
more jobs.

dp
or
.w
lit

20. Display the city of the employee who’s ID 134 and works there.
e
at
ajp

21. Display the first and last name, salary, and department ID
for those employees who earn less than the minimum salary of
/

a department which ID is 70.


s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 63


Database Management System | 2130703

m
22. Display the first and last name, salary, and department ID
for those employees who earn more than the minimum salary of

.co
a department which ID is 40.

ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 64


Database Management System | 2130703

m
PRACTICAL 8
DATA MANIPULATION COMMANDS

.co
 Modifying the structure of Tables.
• The structure of table can be modifying by using the ALTER TABLE command.
• ALTER TABLE allows changing the structure of an existing table.

ss
• With alter table queries it is possible to add, delete columns, create or destroy
indexes, change the data type of the existing columns or rename columns or table

re
itself.

Adding New Columns

dp
SYNTAX

ALTER TABLE <table_name>


ADD (<new_column_name> <datatype>(<size>),
<new_column_name> <datatype>(<size>)...)
or
.w
Dropping a column from a table
ALTER TABLE <table_name>
lit

DROP COLUMN <column_name>

Modifying Existing column


e

ALTER TABLE <table_name>


at

MODIFY (<column_name> <datatype>(<size>))


ajp

Restriction on the ALTER TABLE


• Change the name of TABLE
• Change the name of COLUMNS
• Decrease the size of the column if table date exists.
/
s:/

 RENAMING TABLE
Oracle allows renaming of tables. The rename operations is done atomically, which means that
no other thread can access any of the tables while the rename process is running.
tp

SYNTAX

RENAME <table_name> TO <new_tablename>


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 65


Database Management System | 2130703

m
 UPDATING TABLE DATA
The UPDATE command is used to change or modify data values in a table.

.co
Updating all rows
SYNTAX

UPDATE <table_name>

ss
SET <column_name1> = <expression>,
<column_name2> = <expression>

re
Above query will update all the rows from the table without any intimation.
Updating specific rows
SYNTAX

dp
UPDATE <table_name>
SET <column_name1> = <expression>,
<column_name2> = <expression>
WHERE <conditions>
or
.w
Above query will update selected rows from the table that satisfy the conditions without any
intimation.
lit

 DELETE TABLE
The DELETE command deletes rows from the table that satisfies the condition provided by its
e

where clause, and returns the number of records deleted.


at

Removal of all rows


SYNTAX
DELETE FROM <table_name>
ajp

Above query will delete all the rows from the table without any intimation.
Note:
Be careful while using delete query. User may loss all the data from the table.
/

Removal of Specific Row(s)


s:/

SYNTAX
DELETE FROM <table_name>
WHERE <conditions>
tp

Above query will delete selected rows from the table that satisfy the conditions without any
intimation.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 66


Database Management System | 2130703

m
 TRUNCATING TABLES

.co
• Truncating table empties a table completely. It is similar to the Delete but practically
different.
Truncate table differs from Delete in following ways.

ss
• Truncating table drop the table and recreate empties table, which is much faster than
deleting rows one by one.

re
• Truncate opts are not transaction-safe (an error will occur if an active transaction or an
active table lock exists)

dp
• The numbers of deleted rows are not returned.
SYNTAX

TRUNCATE TABLE <table_name>


or
 DESTROYING TABLES
.w
Sometime we need to remove the whole table which is not in used.
SYNTAX
lit

DROP TABLE <table_name>


e
at

SQL Queries
ajp

1. Create table worker from table employees with all column


/
s:/

2. Create table Depts. from table Departments with first two


columns.
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 67


Database Management System | 2130703

m
3. Create table Job from table Jobs with no record

.co
4. Insert the data into Job from Jobs whose second character should

ss
be ‘a’ and the Job ID should be 6 characters long.

re
5. Delete all the rows from Depts.

dp
or
6. Delete the details of worker whose manager id is 149.
.w
7. Rename the table Job
e lit

8. Destroy table Depts. with all the data.


at

9. Update the value dept id to 110 where manager id is 101 and dept
ajp

id is 10.
/
s:/

10. Update the postal code to 25432 for location id 1800.


tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 68


Database Management System | 2130703

m
PRACTICAL 9
TO STUDY THE CONCEPT OF CURSOR AND STORE PROCEDURE

.co
 CURSORS
Oracle creates a memory area, known as context area, for processing an SQL statement,
which contains all information needed for processing the statement, for example, number of

ss
rows processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.

re
A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.

dp
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors:

• Implicit cursors
or
• Explicit cursors
.w
Implicit Cursors
lit

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
e

cursors and the information in it.


at

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
ajp

to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
/

has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
s:/

SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,


designed for use with the FORALL statement. The following table provides the description of
the most used attributes:
tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 69


Database Management System | 2130703

m
S.No Attribute & Description
1 %FOUND

.co
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
2 %NOTFOUND

ss
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned no rows.

re
Otherwise, it returns FALSE.
3 %ISOPEN

dp
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
4 %ROWCOUNT
or
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
.w
EXAMPLE
lit

Implicit Cursor
The following program would update the table and increase salary of each customer by 500
e

and use the SQL%ROWCOUNT attribute to determine the number of rows affected:
at

DECLARE
total_rows number(2);
ajp

BEGIN
UPDATE EMPLOYEESAJPATELIT
SET SALARY = SALARY + 500;
/

IF sql%notfound THEN
s:/

dbms_output.put_line('NO EMPLOYEES SELECTED');


ELSIF sql%found THEN
total_rows := sql%rowcount;
tp

dbms_output.put_line( total_rows || ' EMPLOYEES SELECTED');


END IF;
ht

END;

Alpha College of Engineering and Technology Department of Information Technology | Page 70


Database Management System | 2130703

m
OUTPUT
20 EMPLOYEES SELECTED
PL/SQL procedure successfully completed.

.co
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context

ss
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It
is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is :

re
CURSOR cursor_name IS select_statement;

dp
Working with an explicit cursor involves four steps:
• Declaring the cursor for initializing in the memory
• Opening the cursor for allocating memory


Fetching the cursor for retrieving data or
Closing the cursor to release allocated memory
.w
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
lit

For example:

CURSOR E_EMPLOYEESAJPATELIT is SELECT EMPLOYEE_ID,


e

FIRST_NAME, LAST_NAME FROM EMPLOYEESAJPATELIT;


at

Opening the Cursor


Opening the cursor allocates memory for the cursor and makes it ready for fetching the rows
ajp

returned by the SQL statement into it. For example, we will open above-defined cursor as
follows:

OPEN E_EMPLOYEESAJPATELIT;
/

Fetching the Cursor


s:/

Fetching the cursor involves accessing one row at a time. For example we will fetch rows
from the above-opened cursor as follows:
tp

FETCH E_EMPLOYEESAJPATELIT into E_ID, E_FNAME, E_LNAME;


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 71


Database Management System | 2130703

m
Closing the Cursor
Closing the cursor means releasing the allocated memory. For example, we will close

.co
above-opened cursor as follows:

CLOSE E_EMPLOYEESAJPATELIT;

EXAMPLE

ss
Explicit Cursor

re
DECLARE
E_ID EMPLOYEESAJPATELIT.EMPLOYEE_ID%type;

dp
E_FNAME EMPLOYEESAJPATELIT.FIRST_NAME%type;
E_LNAME EMPLOYEESAJPATELIT.LAST_NAME%type;
CURSOR E_EMPLOYEESAJPATELIT is
SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME FROM
EMPLOYEESAJPATELIT;
BEGIN
or
OPEN E_EMPLOYEESAJPATELIT;
.w
LOOP
FETCH E_EMPLOYEESAJPATELIT into E_ID, E_FNAME, E_LNAME;
EXIT WHEN E_EMPLOYEESAJPATELIT%notfound;
lit

dbms_output.put_line(E_ID || ' ' || E_FNAME || ' ' ||


E_LNAME);
END LOOP;
e

CLOSE E_EMPLOYEESAJPATELIT;
END;
at

OUTPUT
ajp

100 Steven King


101 Neena Kochhar
102 Lex De Haan
103 Alexander Hunold
/

104 Bruce Ernst


107 Diana Lorentz
s:/

124 Kevin Mourgos


141 Trenna Rajs
142 Curtis Davies
tp

143 Randall Matos


144 Peter Vargas
149 Eleni Zlotkey
ht

174 Ellen Abel

Alpha College of Engineering and Technology Department of Information Technology | Page 72


Database Management System | 2130703

m
176 Jonathon Taylor
178 Kimerely Grant
200 Jennifer Whalen

.co
201 Michael Hartstein
202 Pat Fay
205 Shelley Higgins
206 William Gietz

ss
 STORE PROCEDURE
A Procedure or Function is a logically grouped set of SQL and PL/SQL statements that

re
perform a specific task.

dp
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of Subprograms:

• or
Functions: these subprograms return a single value, mainly used to compute and
return a value.
• Procedures: these subprograms do not return a value directly, mainly used to perform
.w
an action.
S.No Parts & Description
lit

1 Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start with
e

the DECLARE keyword. It contains declarations of types, cursors, constants, variables,


at

exceptions, and nested subprograms. These items are local to the subprogram and cease
to exist when the subprogram completes execution.
2 Executable Part
ajp

This is a mandatory part and contains statements that perform the designated action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
/
s:/

WHY Store Procedure is used or Advantages of SP…?

• Performance
tp

Stored procedures are compiled once and stored in executable form, so procedure calls are
quick and efficient. Executable code is automatically cached and shared among users. This
lowers memory requirements and invocation overhead.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 73


Database Management System | 2130703

m
By grouping SQL statements, a stored procedure allows them to be executed with a single
call. This minimizes the use of slow networks, reduces network traffic, and improves

.co
round-trip response time. OLTP applications, in particular, benefit because result set
processing eliminates network bottlenecks.

Additionally, stored procedures enable you to take advantage of the computing resources of

ss
the server. For example, you can move computation-bound procedures from client to server,
where they will execute faster. Likewise, stored functions called from SQL statements

re
enhance performance by executing application logic within the server.

• Productivity and Ease of Use

dp
By designing applications around a common set of stored procedures, you can avoid
redundant coding and increase your productivity. Moreover, stored procedures let you extend
the functionality of the RDBMS. For example, stored functions called from SQL statements
enhance the power of SQL.
or
.w
• Scalability
Stored procedures increase scalability by isolating application processing on the server. In
lit

addition, automatic dependency tracking for stored procedures aids the development of
scalable applications.
e

The shared memory facilities of the Multi-Threaded Server (MTS) enable Oracle to support
at

more than 10,000 concurrent users on a single node. For more scalability, you can use the
Net8 Connection Manager to multiplex Net8 connections.
ajp

• Maintainability
Once it is validated, a stored procedure can be used with confidence in any number of
applications. If its definition changes, only the procedure is affected, not the applications that
/

calls it. This simplifies maintenance and enhancement. Also, maintaining a procedure on the
s:/

server is easier than maintaining copies on various client machines.

• Security
tp

You can restrict access to Oracle data by allowing users to manipulate the data only through
stored procedures that execute with their definer's privileges. For example, you can allow
access to a procedure that updates a database table, but deny access to the table itself.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 74


Database Management System | 2130703

m
• Replication
With Oracle Advanced Replication, stored procedures can be replicated (copied) from one

.co
Oracle database to another. This feature makes them ideal for implementing a central set of
business rules. Once written, the stored procedures are replicated and distributed to work
groups and branch offices throughout the company. In this way, policies can be revised on a
central server rather than on individual servers.

ss
CREATING A PROCEDURE

re
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows:

dp
SYNTAX
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
or
BEGIN
.w
< procedure_body >
END procedure_name;

Where,
lit

• procedure-name specifies the name of the procedure.


• [OR REPLACE] option allows modifying an existing procedure.
e

• The optional parameter list contains name, mode and types of the parameters. IN
at

represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
ajp

• procedure-body contains the executable part.


• The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
/

EXAMPLE
s:/

CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
tp

dbms_output.put_line('Hello World!');
END;
/
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 75


Database Management System | 2130703

m
RUN
BEGIN
greetings;

.co
END;

DELETING A PROCEDURE
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for

ss
deleting a procedure is:

re
SYNTAX
DROP PROCEDURE procedure-name;

dp
EXAMPLE
DROP PROCEDURE greetings;

PARAMETER MODES IN PL/SQL PROCEDURE


or
S.No Parameter Mode & Description
.w
1 IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a
lit

value. You can pass a constant, literal, initialized variable, or expression as an IN


parameter. You can also initialize it to a default value; however, in that case, it is
e

omitted from the subprogram call. It is the default mode of parameter passing.
at

Parameters are passed by reference.


2 OUT
ajp

An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by value.
3 IN OUT
/

An IN OUT parameter passes an initial value to a subprogram and returns an updated


s:/

value to the caller. It can be assigned a value and the value can be read.

The actual parameter corresponding to an IN OUT formal parameter must be a variable,


tp

not a constant or an expression. Formal parameter must be assigned a value. Actual


parameter is passed by value.
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 76


Database Management System | 2130703

m
EXAMPLE-1

DECLARE

.co
a number;
b number;
c number;

ss
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN

re
z:= x;
ELSE
z:= y;

dp
END IF;
END;

BEGIN
a:= 23;
b:= 45;
or
findMin(a, b, c);
.w
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
lit

OUTPUT
Minimum of (23, 45) : 23
e

EXAMPLE-2
at

DECLARE
a number;
ajp

PROCEDURE squareNum(x IN OUT number) IS


BEGIN
x := x * x;
END;
/
s:/

BEGIN
a:= 23;
squareNum(a);
tp

dbms_output.put_line(' Square of (23): ' || a);


END;

OUTPUT
ht

Square of (23): 529

Alpha College of Engineering and Technology Department of Information Technology | Page 77


Database Management System | 2130703

m
PRACTICAL 10
TO STUDY TRANSACTION CONTROL COMMANDS

.co
Transaction Control Language (TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML
statements. It also allows statements to be grouped together into logical transactions.

ss
 COMMIT COMMAND
COMMIT command is used to permanently save any transaction into the database.

re
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by

dp
these commands are not permanent, until the current session is closed, the changes made by
these commands can be rolled back.

or
To avoid that, we use the COMMIT command to mark the changes as permanent.

Following is commit command's syntax,


.w
COMMIT;
lit

 ROLLBACK COMMAND
This command restores the database to last committed state. It is also used with SAVEPOINT
e

command to jump to a save point in an ongoing transaction.


at

If we have used the UPDATE command to make some changes into the database, and realize
that those changes were not required, then we can use the ROLLBACK command to rollback
ajp

those changes, if they were not committed using the COMMIT command.

Following is rollback command's syntax,


/

ROLLBACK TO savepoint_name;
s:/

 SAVEPOINT COMMAND
SAVEPOINT command is used to temporarily save a transaction so that you can roll back to
tp

that point whenever required.


ht

Alpha College of Engineering and Technology Department of Information Technology | Page 78


Database Management System | 2130703

m
Following is save point command's syntax,

SAVEPOINT savepoint_name;

.co
In short, using this command we can name the different states of our data in any table and
then roll back to that state using the ROLLBACK command whenever required.
Using Save point and Rollback

ss
Following is the table class,

re
ID NAME
1 Abhi
2 Adam

dp
4 Alex

Let’s use some SQL queries on the above table and see the results.

INSERT INTO class VALUES(5, 'Rahul');


or
COMMIT;
.w
UPDATE class SET name = 'Abhijit' WHERE id = '5';
lit

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');


e

SAVEPOINT B;
at

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;
ajp

SELECT * FROM class;

The resultant table will look like,


/

ID NAME
s:/

1 Abhi
2 Adam
4 Alex
tp

5 Abhijit
6 Chris
ht

7 Bravo

Alpha College of Engineering and Technology Department of Information Technology | Page 79


Database Management System | 2130703

m
Now let's use the ROLLBACK command to roll back the state of data to the save point B.

ROLLBACK TO B;

.co
SELECT * FROM class;

Now our class table will look like,

ss
ID NAME
1 Abhi

re
2 Adam
4 Alex

dp
5 Abhijit
6 Chris

Now let's again use the ROLLBACK command to roll back the state of data to the save point A

ROLLBACK TO A;
or
.w
SELECT * FROM class;

Now the table will look like,


lit

ID NAME
1 Abhi
e

2 Adam
at

4 Alex
5 Abhijit
ajp

 AUTOCOMMIT
AUTOCOMMIT command automatically commits each transaction after its execution. If this
command is set, then no need to explicitly issue commit. We cannot rollback our transactions,
if AUTOCOMMIT is on. This needs to be set /unset before we begin any transactions.
/
s:/

SET AUTOCOMMIT ON; -- Sets AUTOCOMMIT to ON

SET AUTOCOMMIT OFF; -- Sets AUTOCOMMIT to OFF


tp
ht

Alpha College of Engineering and Technology Department of Information Technology | Page 80

Das könnte Ihnen auch gefallen