Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
152 views

SQL Plus: Topics Covered in This Unit

This document provides an overview of SQL and SQL*Plus, including: 1. It describes SQL*Plus as an interactive tool and Oracle client for connecting to databases and executing queries. 2. It outlines several key data types supported in Oracle such as CHAR, VARCHAR2, NUMBER, DATE, and others. 3. It categorizes SQL commands into DDL, DML, DCL, and TCL and provides examples of commands like CREATE, INSERT, SELECT, ALTER.

Uploaded by

jaypal_mca
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
152 views

SQL Plus: Topics Covered in This Unit

This document provides an overview of SQL and SQL*Plus, including: 1. It describes SQL*Plus as an interactive tool and Oracle client for connecting to databases and executing queries. 2. It outlines several key data types supported in Oracle such as CHAR, VARCHAR2, NUMBER, DATE, and others. 3. It categorizes SQL commands into DDL, DML, DCL, and TCL and provides examples of commands like CREATE, INSERT, SELECT, ALTER.

Uploaded by

jaypal_mca
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 0

RDBMS SQL * Plus CCMCA-Wadhwan

Developed By: Jaypalsinh A. Gohil Page 1 of 54


5QL P!us
TOPICS COVERED IN THIS UNIT
Introduction
Oracle Data Types
Category of SQL * Plus Commands
SQL * Plus Operators
Creating a table from another table
Group by and Having Clause
Integrity Constraints
Input Output Constraints
Business Constraints
Join Operations
Set Operators
Sub Query
Dual Table
Oracle Functions
Views
Index
Sequence
Synonyms
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 2 of 54
(1) INTRODUCTION:
DBMS: -
Database is a collection of table. Table is a collection of columns and
rows.
DATABASE: -
Database is an organized collection of related information.
RDBMS: -
Relational Database Management System (RDBMS) works on the
relational logic.
COMPONENT OF RELATIONAL MODEL: -
1. Structural Components: -
Table (Relation)
Field (Column)
Record (Row, Touple)
2. Integrity Components: -
Constraints (Restricted Rules / Rights)
3. Manipulation Components: -
DDL (Data Definition Language)
DML (Data Manipulation Language)
DCL (Data Control Language)
TCL (Transaction Control Language)
ORACLE: -
Oracle is an RDBMS stands for Relational Database Management
System. An RDBMS is a computer program, which provides the user the
facility to store and retrieve data in a manner consistent with a defined model,
called the Relational model.
BENEFITS OF ORACLE: -
Support distributed database management system. Client Server
distributed system.
SQL: -
SQL stand for Structure Query Language. It is available in a number
of data base management packages based on the relational model of data, for
example, in DB2 of the IBM and UNIFY of the UNIFY. The major facilities
of SQL, namely, data manipulation, data definition and data control are bound
together in one integrated language framework.
The industry-standard database language used to query and manipulate
the data, structures, and permissions in a relational database.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 3 of 54
SQL*Plus: -
SQL*Plus us an extension to the standard SQL and it has an on-line
command interpreter. The users can create program files and generate
formatted reports. It is an interactive tool, an Oracle client provided by the
company, Oracle Corporation.
SQL*Plus has been around as long as the Oracle RDBMS itself. It is
the most basic tool available for connecting to the database and executing
queries against the tables in a database.
(2) DATA TYPES IN ORACLE:
Main Data Types Supported by ORACLE: -
Data Types Description
CHAR
It is used to store fixed length character data. Maximum size is 255 and
default is 1. It has right justified padding.
VARCHAR2
This data type is used to store variable length alphanumeric data. The
maximum size of this data type is 2000 characters.
NUMBER
This data type is used to store numeric 0, positive, negative fixed or
floating-point numbers. Numbers are stored up to 38 digits of precision
(Including floating point and signs). If precision is omitted the number is
maximum up to 38 digits.
DATE
This data type is us used to represent date and time. This data type stores
information such as century, year, month, day, hour, minute and second.
The default format is DD-MON-YY as in 12-JAN-06.
RAW It stores binary data up to 255 bytes.
LONG
This data type is used to store variable length character strings
containing up to 2GB. It is generally used to store arrays of binary data
in ASCII format. It cannot be indexed and you cannot apply generally
character functions such as SUBSTR. It is also known as MEMO data
type.
LONG RAW
It stores binary data up to 2GB.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 4 of 54
ROWID Hexadecimal string representing the unique address of row in a table. It
is returned by the pseudo-column ROWID.
Additional Data Type Supported by ORACLE: -
Data Types Description
NVARCHAR2
Store variable length character string having a maximum size of up to
4000 bytes, depending on the choice of national character set.
TIMESTAMP It stores and displays date in a date plus time format.
INTERVAL
YEAR TO
MONTH
Period of time in years and months.
INTERVAL
DAY TO
SECOND
Period of time in days, hours, minutes and seconds.
UROWID
Hexadecimal address of row in an index-organized table. Maximum
size is 4000 bytes
NCHAR This allows multi-byte character set version of CHAR.
CLOB It stores character large objects, up to 4GB in length.
NCLOB It stores multi-byte character set large objects, up to 4GB.
BLOB
It is used to store Binary large object, up to 4GB in length. It is
typically used to store graphics, sound, or video data.
BFILE It is used to store pointer to binary operating system file.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 5 of 54
() CATEGORIES OF SQL * PLUS COMMAND:
SQL commands can be roughly divide into three categories with regard to their
functionality. Firstly, there are those used to create and maintain the database
structure. The second category includes those commands that manipulate the data in
such structures, and thirdly there are those that control the use of the database.
SQL commands fall under the following categories:
DDL (Data Definition Language)
DML (Data Manipulation Language)
DCL (Data Control Language)
TCL (Transaction Control Language)
1. DDL (Date Definition Language): -
DDL is used to create and remove database objects. It is also used to alter
the structure of the objects. It is also useful in dropping (removing) the
objects.
Commands available in DDL are as follows:
1. CREATE
2. ALTER
3. TRUNCATE
4. DROP
CREATE COMMAND: -
This command is used to create database objects such as tables, views,
indexes etc. Generally it is used to create the database tables. The syntax is as
follows:
Syntax: -
CREATE TABLE <TABLE_NAME> (COLUMN_1 DATATYPE (SIZE),
COLUMN_2 DATATYPE (SIZE), COLUMN_N DATATYPE (SIZE));
Example: -
CREATE TABLE EMP (NO NUMBER (3), NAME VARCHAR,
B_DATE DATE, SALARY NUMBER (6,2));
Rules for Table and Column Names: -
1. Tables and Column names can be up to 30 characters.
2. Names must begin with an alphabet.
3. Names cannot contain quotes.
4. Names are NOT case sensitive.
5. Names can contain characters, a-z, 0-9, __ (Underscore),
$ (Dollar Sign), and # (Hash Sign).
6. Names cannot be reserved words.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 6 of 54
DESC OR DESCRIBE COMMAND: -
This command is used to view the structure of the table.
Syntax:
DESC <TABLE_NAME>;
DESCRIBE <TABLE_NAME>;
Example:
DESC EMP;
DESCRIBE EMP;
NOTE: - To show the list of tables, which is created by the user use
the following command.
SELECT * FROM TAB;
ALTER COMMAND: -
The ALTER statement allows the user to make some kind of change to
structure of some object in the database. The ALTER statement syntax can
then be simplified to one of two following statements:
Syntax: -
ALTER TABLE <TABLE_NAME>
ADD (NEWCOLUMN_NAME DATATYPE (SIZE), NEWCOLUMN_NAME DATATYPE
(SIZE));
OR
ALTER TABLE<TABLE_NAME>
MODIFY (COLUMN_NAME DATATYPE (NEW_SIZE));
Example: -
ALTER TABLE EMP ADD
(GENDER CHAR (1), DEPT VARCHAR2 (15));
ALTER TABLE EMP MODIFY (NO NUMBER (5));
NOTE: - If the data is already being entered in the table we cannot
modify the Data Type and we cannot decrease the size of the
column. We can only increase the size of the column.
RENAME COMMAND: -
This command is used to change the name of the table (Rename).
Syntax: -
RENAME <OLD_TABLENAME> TO <NEW_TABLENAME>;
Example: -
RENAME EMP TO EMP_DETAILS;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 7 of 54
TRUNCATE COMMAND: -
The TRUNCATE statement is similar to the DELETE statement. Both of
the statements will delete rows from a table. The main difference is that the
DELETE can be more selective (in other words, using a WHERE clause). The
TRUNCATE statement simply removes all rows from a table. The
TRUNCATE statement will also appear to run faster than a DELETE in most
cases.
Syntax: -
TRUNCATE TABLE <TABLE_NAME>;
Example: -
TRUNCATE TABLE EMP;
NOTE: - With TRUNCATE command Rollback (Recall) is not
possible but with DELETE command it is possible.
DROP COMMAND: -
When a table is no longer needed, it can be dropped. Both the table
definition and the rows in the table are dropped, and the space allocated for
the table is made available for other database objects. The syntax for the
DROP statement is about as simple as it gets:
Syntax: -
DROP TABLE <TABLE_NAME>;
Example: -
DROP TABLE EMP;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 8 of 54
2. DML (Data Manipulation Language): -
DML is used to manipulate the data in the tables & database. The
commands covered under the DML are used to manipulate the existing
objects.
Commands available in DML are as follows:
1. INSERT
2. SELECT
3. UPDATE
4. DELETE
INSERT COMMAND: -
This is used to add one or more rows (records) into the table. While
using this command values are separated by commas.
Syntax: -
INSERT INTO <TABLE_NAME> VALUES (V1, V2, );
OR
INSERT INTO <TABLE_NAME> VALUES
(&COLUMN_NAME, &COLUMN_NAME, ) ;
Example: -
INSERT INTO EMP VALUES (100,Ram,16-MAR-06, 10000,M);
INSERT INTO EMP (NO, NAME) VALUES (200,Sita);
OR
INSERT INTO EMP VALUES
(&NO,&NAME,&DATE, &SALARY,&GENDER);
NOTE: - Write character (including varchar2) and
Date fields inside . For e.g. &NAME,&DATE.
SELECT COMMAND: -
In its most basic form, the SELECT statement has a list of columns to
select from a table, using the SELECT ... FROM syntax. The * means "all
columns." The most basic SELECT syntax can be described as follows:
Syntax: -
SELECT [DISTINCT] COLUMN_1,COLUMN_2 , ..,COLUMN_N
FROM <TABLE_NAME>
[WHERE <Condition>] [Order by <Column> [Asc / Desc}];
NOTE: - It displays the information contained in the column, which
is selected in the query only.
OR
SELECT * FROM <TABLE_NAME>;
NOTE: - It displays the information contained in all the fields of the
table.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 9 of 54
OR
SELECT * FROM <TABLE_NAME> WHERE <CONDITION>;
NOTE: - It displays the information, which matches with the
condition given in the query.
Example: -
SELECT NO, NAME, GENDER FROM EMP;
SELECT * FROM EMP;
SELECT * FROM EMP WHERE NAME = Ram;
SELECT * FROM EMP WHERE SALARY=8000;
Other Examples: -
SELECT NAME, NO FROM EMP;
SELECT DISTINCT NO FROM EMP;
SELECT DISTINCT NAME FROM EMP;
SELECT DISTINCT NO, NAME FROM EMP;
SELECT * FROM EMP WHERE NO>200;
SELECT * FROM EMP WHERE NO=200;
SELECT * FROM EMP ORDER BY NAME;
SELECT DISTINCT NAME FROM EMP ORDER BY NAME;
SELECT DISTINCT NO, NAME FROM EMP ORDER BY NO;
SELECT DISTINCT NO, NAME FROM EMP ORDER BY NAME;
SELECT * FROM EMP ORDER BY NAME DESC;
SELECT * FROM EMP ORDER BY NO, NAME;
SELECT * FROM EMP ORDER BY NO, NAME DESC;
SELECT * FROM EMP ORDER BY NO DESC, NAME;
SELECT * FROM EMP ORDER BY NO DESC, NAME DESC;
UPDATE COMMAND: -
An UPDATE statement will change one or more rows in a database table.
The basic form of an UPDATE statement must specify which table to update,
which column(s) to change, and optionally, whether to change all the rows in
the table or just a few. The syntax is as follows:
Syntax: -
UPDATE <TABLE_NAME> SET <COLUMN_NAME>=VALUE;
OR
UPDATE <TABLE_NAME>
SET <COLUMN_NAME1>=VALUE1,<COLUMN_NAME2>=VALUE2
WHERE COLUMN_NAME=VALUE;
Example: -
UPDATE EMP SET SALARY = 8000;
NOTE: - The above command will update the Salarys of all the
employees to Rs.8000.
UPDATE EMP SET NO=300 WHERE NAME= Ravi;
UPDATE EMP SET NO=500, B_DATE=3-June-04 WHERE
NAME=Ram;
NOTE: - The above command will update only those rows, which
fall under the condition, and not all the rows of the table.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 10 of 54
DELETE COMMAND: -
As the name implies, the DELETE statement will remove rows from a
database table. You can delete all rows or use a WHERE clause to specify
rows, similar to the UPDATE statement. Heres the syntax:
Syntax: -
DELETE FROM <TABLE_NAME>;
DELETE FROM <TABLE_NAME> WHERE COLUMN_NAME=VALUE;
Example: -
DELETE FROM EMP;
DELETE FROM EMP WHERE NO=100;
3. DCL (Date Control Language): -
DCL is used to control the data access to the database. DCL concerns with
the Recovery and Security issue of database. This category of command
allows us to grant and revoke privileges and permissions.
Commands available in DCL are as follows:
1. GRANT
2. REVOKE
GRANT COMMAND: -
The GRANT statement is almost self-explanatory. GRANT will give a
privilege (either object or system) to a user, a role, or to all users. The basic
syntax for granting privileges is as follows:
Syntax: -
GRANT sys_privilege [, sys_privilege...]
TO user | role | PUBLIC [, user | role | PUBLIC...];
GRANT obj_privilege [(column list)] ON object
TO user | role | PUBLIC [WITH GRANT OPTION];
Example: -
GRANT CONNECT TO BCA;
GRANT RESORUCE TO BCA;
GRANT DBA TO MCA;
GRANT SELECT ON EMP TO MYROLE;
GRANT MYROLE TO MCA;
REVOKE COMMAND: -
As you would expect, the REVOKE statement is the opposite of the
GRANT statement. Either system privileges or object privileges can be
revoked with the following basic syntax:
Syntax: -
REVOKE obj_privilege | ALL [, obj_privilege] ON object
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 11 of 54
FROM user | role | PUBLIC [, user | role | PUBLIC...];
REVOKE sys_privilege | ALL [, sys_privilege...]
FROM user | role | PUBLIC [, user | role | PUBLIC...];
Example: -
REVOKE CONNECT FROM BCA;
REVOKE REOSOURCE FROM BCA;
REVOKE DBA FROM MCA;
2. TCL (Date Control Language): -
Transaction is a sequence of SQL statements that Oracle treats as a single
block of unit. To save a set of changes made to a table using DML commands
and to get back to the original state before changes have been made we use
TCL.
Commands available in DCL are as follows:
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
COMMIT COMMAND: -
A set of changes made to a table using DML (INSERT, UPDATE,
DELETE) commands are temporary. To make the changes permanent,
COMMIT command must be needed after DML commands.
Syntax: -
COMMIT;
Example: -
DELETE FROM EMP WHERE NO=500;
COMMIT;
ROLLBACK COMMAND: -
The ROLLBACK statement allows you to change your mind about a
transaction. It brings back the original state of the tables to the state as of the
last COMMIT statement or the beginning of the current transaction.
Syntax: -
ROLLBACK [TO SAVEPOINT <Savepoint_Name>];
Example: -
DELETE FROM EMP WHERE NO=500;
ROLLBACK;
NOTE: - You cannot ROLLBACK the transaction after the
COMMIT. So, After the COMMIT you cannot use ROLLBCAK
command.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 12 of 54
SAVEPOINT COMMAND: -
Additionally, you can use SAVEPOINT to further subdivide the DML
statements within a transaction before the final COMMIT of all DML
statements within the transaction. SAVEPOINT essentially allows partial
rollbacks within a transaction.
Syntax: -
SAVEPOINT <Savepoint_Name>;
ROLLBACK TO SAVEPOINT <Savepoint_Name>;
Example: -
DELETE FROM EMP WHERE NO=500;
SAVEPOINT A1;
ROLLBACK TO SAVEPOINT A1;
(!) SQL * PLUS OPERATORS:
RELATIONAL OPERATORS: -
1. > SELECT * FROM EMP WHERE SAL > 3000;
2. >= SELECT * FROM EMP WHERE SAL >= 3000;
3. < SELECT * FROM EMP WHERE SAL < 3000;
4. <= SELECT * FROM EMP WHERE SAL <= 3000;
5. = SELECT * FROM EMP WHERE SAL = 3000;
6. != OR <> SELECT * FROM EMP WHERE SAL! = 3000;
7. BETWEEN SELECT * FROM EMP WHERE SAL BETWEEN
3000 AND 5000;
8. IS NULL SELECT * FROM EMP WHERE SAL IS NULL;
LOGICAL OPERATORS: -
1. AND SELECT * FROM EMP WHERE NAME=RAHUL AND NO=300;
2. OR SELECT * FROM EMP WHERE NAME=RAHULOR
NAME=RAM;
3. NOT SELECT * FROM EMP WHERE NOT NO=300;
ARITHMETIC OPERATORS: -
1. + SELECT NO, NAME, SAL, SAL+500 FROM EMP;
2. - SELECT NO, NAME, SAL, -SAL, SAL-500 FROM EMP;
3. / SELECT NO, NAME, SAL, SAL/10 FROM EMP;
4. * SELECT NO, NAME, SAL, SAL*0.10 FROM EMP;
LIKE OPERATOR: -
% Matches all the characters.
_ Matches a single characters.
SELECT NAME FROM EMP WHERE NAME LIKE R%;
SELECT NAME FROM EMP WHERE NAME LIKE RA_;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 13 of 54
SELECT * FROM EMP WHERE NAME LIKE 'Ra%_';
SELECT * FROM EMP WHERE NAME LIKE '%_';
SELECT * FROM EMP WHERE NAME LIKE '_%';
SELECT * FROM EMP WHERE NAME LIKE 'R_a';
SELECT * FROM EMP WHERE NAME LIKE 'R___';
SELECT * FROM EMP WHERE NAME LIKE 'R___%';
IN OPERATOR: -
SELECT * FROM EMP WHERE NAME IN ('Ram', 'Ravi');
SELECT * FROM EMP WHERE NO IN (100, 300);
SELECT * FROM EMP WHERE NO NOT IN (300);
() CREATING A TABLE FROM ANOTHER TABLE:
WITH DATA: -
Syntax: -
CREATE TABLE <TABLE-NAME>
[(COL-NAME-1, , COL-NAME-N)]
AS SELECT COL-NAME-1, COL-NAME-2 FROM <TABLE-NAME>;
Example: -
CREATE TABLE EMP_SALARY (E_NO, E_NAME, E_SALARY)
AS SELECT NO, NAME, SAL FROM EMP;
WITHOUT DATA: -
Syntax: -
CREATE TABLE <TABLE-NAME>
[(COL-NAME-1, , COL-NAME-N)]
AS SELECT COL-NAME-1, COL-NAME-2 FROM <TABLE-NAME>
WHERE <CONDITION>;
Example: -
CREATE TABLE EMP_SALARY (E_NO, E_NAME, E_SALARY)
AS SELECT NO, NAME, SAL FROM EMP WHERE NO=0;
INSERTING A DATA FROM ONE TABLE TO ANOTHER TABLE: -
Syntax:
INSERT INTO <TABLE-NAME>
SELECT COL-NAME-1, COL-NAME-2 FROM <TABLE-NAME>;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 14 of 54
Example: -
INSERT INTO EMP_SALARY SELECT NO, NAME, SAL FROM EMP;
INSERT INTO EMP_SALARY SELECT NO, NAME, SAL FROM EMP
WHERE NO=300;
() GROUP BY AND HAVING: -
GROUP BY CLAUSE:
The GROUP BY clause is another section of the select statement. This
optional clause tells Oracle to group rows based on distinct values that exist
for specified columns. The GROUP BY clause creates a data set, containing
several sets of records grouped together based on a condition.
P_NO QTY_ORDER QTY_DISP

P1 10 10
P4 3 3
P6 7 7
P2 4 4
P5 10 10
P3 2 2
P1 6 6
P6 4 4
P4 1 1
P6 8 8
SELECT P-NO, SUM (QTY_ORDERD) TOTAL QTY FROM
SALES_DETAIL GROUP BY P_NO;
OUTPUT: -
P_NO TOTAL QTY

P1 16
P2 4
P3 2
P4 4
P5 10
P6 19
HAVING CLAUSE:
The HAVING clause can be used in combination with the GROUP BY
clause. HAVING imposes a condition on the GROUP BY clause, which
further filters the groups created by GROUP BY clause.
SELECT P-NO, SUM (QTY_ORDERD) TOTAL QTY FROM
SALES_DETAIL GROUP BY P_NO HAVING P_NO=P1 OR P_NO=P4;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 15 of 54
OUTPUT: -
P_NO TOTAL QTY
..
P1 16
P4 4
() INTEGRITY CONSTRAINTS:
INTIGRITY DATA CONSTRAINTS: -
1. Some of the restriction has to be applying on the database to ensure the
validity and integrity of database.
2. Rule, which are enforced on the data to be entered and prevents the user
from entering invalid data into the table. This mechanism is handled by
the constraints.
3. ORACLE checks the data using entered into the table columns against the
data constraints. If it passes the check than data is entered into the table
else data is rejected.
4. If a single column fails against a constraint entire record is rejected and
not stored into the table.
5. There are mainly two types of data constraints are there.
CATEGARIES OF CONSTRAINTS: -
DOMAIN CONSTRAINT (Associate with COLUMN)
NOT NULL
CHECK
DEFAULT
ENTITY CONSTRAINT (Associate with ROW)
PRIMARY KEY
UNIQUE
REFERENTIAL INTEGRITY CONSTRAINT (Link between two table)
FOREIGN KEY
INPUT OUTPUT CONSTRAINTS:
It determines the speed at which the data can be inserted or accessed from
oracle table.
It is dividing into two categories.
Primary Key Constraints: -
It is attached to one column or more than one column of the table. The
constraints that apply to the columns are unique and not null.
PRIMARY KEY = UNIQUE + NOT NULL.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 16 of 54
Foreign Key Constraints: -
It creates the relationship between the master table and detail table and
it ensures.
Records cant be inserted into the detail table, if corresponding record
in the master table doesnt exist.
Record of the master table cant be deleted, if corresponding record in
the detail table exist.
1. PRIMARY KEY: -
1. The Primary key is one or more column in a table use to uniquely identify
each row in the table.
2. The constraints that apply to the columns are unique and not null.
3. A single column primary key is called Simple Primary Key.
4. A multi column primary key is called Composite Primary Key.
5. Only when a record cant be uniquely identify the value in a single column
than composite primary key is required.
6. PRIMARY KEY = UNIQUE + NOT NULL.
Primary key constraints at column level: -
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE) PRIMARY KEY
Example:
CREATE TABLE EMP (E_NO NUMBER (3) PRIMARY KEY,
E_NAME VARCHAR2 (15));
Primary key constraints at table level: -
Syntax: -
PRIMARY KEY (COL1, COL2, .., COLN);
Example:
CREATE TABLE EMP (E_NO NUMBER (3),
E_NAME VARCHAR2 (15), PRIMARY KEY (E_NO));
To ADD constraints when the table is already there: -
Syntax: -
ALTER TABLE <TABLE-NAME> ADD PRIMARY KEY (COL-NAME)
Example: -
ALTER TABLE EMP ADD PRIMARY KEY (E_NO);
To DROP a constraints: -
Syntax: -
ALTER TABLE <TABLE-NAME> DROP <CONSTRAINT-NAME>;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 17 of 54
Example: -
ALTER TABLE EMP DROP PRIMARY KEY;
To give the constraints name on the Primary key: -
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE)
CONSTRAINT CONS-NAME PRIMARY KEY
Example: -
CREATE TABLE EMP (E_NO NUMBER (3) CONSTRAINT P_KEY
PRIMARY KEY, E_NAME VARCHAR2 (15));
2. FOREIGN KEY: -
1. A Foreign key is a column or group of columns whose values are derive
from the primary key or unique key of some other table.
2. The table in which the foreign key is defined is called foreign key table or
Detail table.
3. The table which define primary key is called Primary key table or Master
table.
4. It creates the relationship between the Master table and Detail table.
5. It ensures:
Records cant be inserted into the detail table, if corresponding
record in the master table doesnt exist.
Record of the master table cant be deleted, if corresponding
record in the detail table exist.
Foreign key constraints at column level: -
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE)
REFERANCES <TABLE-NAME>
[COL-NAME] [ON DELETE CASECADE]
Example: -
CREATE TABLE EMP_DETAIL (ENO NUMBER (3) REFERENCES
ENAME VARCHAR2 (15));
* Foreign key constraints at table level: -
Syntax: -
FOREIGN KEY (COL1, COL2, .., COLN)
REFERENCES <TABLE-NAME> [COL-NAME] ;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 18 of 54
Example: -
CREATE TABLE EMP_DETAIL (ENO NUMBER (3),
ENAME VARCHAR2 (15)
FOREIGN KEY (ENO) REFERANCES EMP (E_NO));
* To ADD constraints when the table is already there.
Syntax: -
ALTER TABLE EMP ADD PRIMARY KEY (E_NO);
Example: -
ALTER TABLE EMP_DETAIL CONSTRIANT FORAIGN KEY
REFERANCES EMP (E_NO);
3. NOT NULL: -
1. This constraint is applied only at column level and not for table level.
2. This constraint can be applied to single column or more than one column.
3. Because of that the NULL value is restricted to be entered into the
column.
Principles of NULL value: -
1. Setting a NULL value is appropriate when the actual value is
unknown.
2. A NULL value is not equivalent to zero for the number data-type
or space for Character data-type.
3. A NULL value will evaluated to null in any expression.
Example: - NULL * 10 = NULL
4. NULL value can be inserted into the columns of any data-type.
5. If a column has NULL values the oracle ignores the UNIQUE,
FOREIGN KEY, and CHECK constraints.
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE) NOT NULL
Example: -
CREATE TABLE EMP (E_NO NUMBER (3) NOT NULL,
E_NAME VARCHAR2 (15));
To ADD constraints when the table is already there: -
Example: -
ALTER TABLE EMP ADD CONSTRIANT EMPNO (E_NO) NOT NULL;
4. UNIQUE: -
1. The purpose of UNIQUE constraint is to ensure the information in the
column must be UNIQUE.
2. One table can contain many UNIQUE constraints.
3. The main aim of the UNIQUE constraint is to uniquely identify each row
from the table.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 19 of 54
Unique constraints at column level: -
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE)
[CONSTRAINT <CONSTRAINT-NAME>] UNIQUE;
Example: -
CREATE TABLE EMP (E_NO NUMBER (3) CONSTRAINT
E_UNQ UNIQUE, E_NAME VARCHAR2 (15));
* Unique constraints at table level: -
Syntax: -
UNIQUE (COL-NAME-1, .., COL-NAME-2)
Example: -
CREATE TABLE EMP (E_NO NUMBER (3),
E-NAME VARCHAR2 (15), UNIQUE (E_NO, E_NAME));
* To ADD a constraint when the table is already there: -
Example: -
ALTER TABLE EMP ADD CONSTRIANT E_UNQ (E_NO) UNIQUE;
BUSINESS CONSTRAINTS: -
1. For the integrity of data some of the rules must be implemented that is
known as Business rules or Business constraints.
Example: your employee no must start with a letter E.
2. Constraints can be connected to one column or more than one column of a
table.
3. A business rule constraint can be implemented through CHECK keyword.
4. The CHECK constraint evaluate the condition and gives true or false result.
5. It takes longer time to execute compare to NOT NULL, PRIMARY KEY,
FOREIGN KEY and UNIQUE constraint.
5. CHECK: -
Check constraints at column level: -
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE)
CHECK (LOGICAL EXPRESSION)
Example: -
CREATE TABLE EMP (E_NO NUMBER (3) CHECK (E_NO LIKE E%),
E_NAME VARCHAR2 (15));
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 20 of 54
Check constraints at table level: -
Syntax: -
CHECK (LOGICAL EXPRESSION)
Example: -
CREATE TABLE EMP (E_NO NUMBER (3),
E-NAME VARCHAR2 (15), CHECK (E_NO LIKE E%));
6. DEFAULT: -
1. When we are creating any table at that time we can assign a default value
to a column.
2. When user is inserting value in the columns and by mistake leaves the
column empty to which we have assign Default keyword, then the
oracle engine will automatically insert the default value in that column.
Syntax: -
COLUMN-NAME DATA-TYPE (SIZE) DEFAULT (VALUE);
Example: -
CREATE TABLE EMP
(E_NO NUMBER (3) DEFAULT 100 PRIMARY KEY,
E_NAME VARCHAR2 (15));
() JOIN OPERATIONS:
Join means to access rows from two or more tables. A Join operation involves
two table and table must be JOIN with a WHERE clause in which the common key
field must be specify.
The following are different types of joins.
JOINS
Equi-Join Self-Join Outer-Join
(Inner Join)
1. Equi-Join (Inner Join, Joining Multiple Table): -
When matching record are displayed from both the table is called as Equi
Join.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 21 of 54
Example: -
SALES_ORDER
O_NO CLIENT_NO ORDER_DATE

O001 C006 12-APR-04


O002 C002 25-DEC-04
O003 C001 03-OCT-04
O004 C005 18-JUN-04
O005 C002 20-AUG-04
O006 C001 12-JAN-04
CLIENT_MASTER
CLIENT_NO NAME BAL_DUE

C001 ASHOK 500


C002 VISHAL 1000
C003 AJAY 0
C004 ROHIT 0
C005 NALINI 0
C006 PARESH 0
C007 RAHUL 0
SELECT O_NO, NAME, ORDER_DATE ORDER-DATE
FROM SALES_ORDER, CLIENT_MASTER
WHERE CLIENT_MASTER.CLIENT_NO = SALES_ORDER.CLIENT_NO
ORDER BY ORDER_DATE;
2. Self-Join (Joining a table to itself): -
In some situation you may find it is necessary to join a table to itself.
As if you are joining two separate tables. In sort we are opening a single table
with a different name and join them as they are different tables present in
distinct memory location.
Example:
EMP_INFO
EMP_NO NAME MNGR_NO

E001 RAVI E002


E002 ARPIT E005
E003 RAHUL E004
E004 LAXMAN -
E005 SUMIT -
SELECT EMP.NAME, MNGR.NAME MANAGER FROM EMP_INFO
EMP, EMP_INFO MNGR WHERE EMP.EMP_NO = MNGR.MNGR_NO;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 22 of 54
Output: -
NAME MANAGER

ARPIT RAVI
LAXMAN RAHUL
SUMIT ARPIT
3. Outer Join (+): -
In previous two join operations, if the matching records are not present in
the second table, certain records from the first table will be not displayed.
To retrieve this record also we have to perform the outer join operation
using the outer join operator (+). The data, which is not available in the
second table, will be presented as the NULL values.
Example:
PLAYER MATCH
ROLL_NO NAME MATCH_NO ROLL_NO MATCH-DATE OPPONENT
-------------------------------- ----------------------------------------------------------------------------
10 VIJAY 1 20 10-JUL-96 WASINGTON
20 PEAS 2 30 12-JAN-96 SAHPRAS
30 ANAND 3 20 12-AUG-96 VIJAY
40 MAHESH 4 30 20-MAR-96 BORG
SELECT PLAYER.ROLL_NO, NAME, MATCH_DATE, OPPONENT
FROM PLAYER, MATCH WHERE PLAYER.ROLL_NO = MATCH.ROLL_NO (+);
Output: -
ROLL_NO NAME MATCH_DATE OPPONENT
--------------- -----------------------------------------------------------------------------
10 VIJAY - -
20 PAES 10-JUL-96 WASHINGTON
20 PAES 12-AUG-96 VIJAY
30 ANAND 12-JAN-96 SAHPRAS
30 ANAND 20-MAR-96 BORG
40 MAHESH - -
(^) SET OPERATORS: -
The oracle supports 4 set operators. All set operators combine the result of two
or more queries into a single set of result.
UNION: -
The UNION operator returns all the rows by the either query eliminating
the duplicate rows.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 23 of 54
Multiple queries can be put together and their output combines using the
union clause. The union clause merges the output of two or more query into a
single set of rows and columns.
OUTPUT = Records in query 1 + Records in query 2.
Example: -
CLIENT_MASTER SALES_MASTER
C_NO NAME CITY S_NO NAME CITY

C001 ASHOK MUMBAI S001 MANISH MUMBAI
C002 VISHAL DELHI S002 KIRAN DELHI
C003 AJAY MUMBAI S003 NITESH MUMBAI
C004 ROHIT CALCUTTA S004 MAHESH CALCUTTA
C005 NALINI MUMBAI S005 NALINI MUMBAI
C006 PARESH DELHI
C007 RAHUL BARODA
SELECT S_NO ID, NAME FROM SALES_MASTER WHERE CITY = MUMBAI
UNION
SELECT C_NO ID, NAME FROM CLIENT_MASTER WHERE CITY =
MUMBAI;
UNION ALL
The UNION ALL operator displays all the rows return by either query
and does not eliminate the duplicate rows.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 24 of 54
OUTPUT = Records in query 1 + Records in query 2 + Common records in both the
query
Example: -
FY SY
LANG1 LANG2

C ORACLE
C++ C++
PASCAL JAVA
SELECT LANG1 LANGUAGE FROM FY
UNION ALL SELECT LANG1 LANGUAGE FROM SY;
SELECT S_NO ID, NAME FROM SALES_MASTER WHERE CITY = MUMBAI
UNION ALL
SELECT C_NO ID, NAME FROM CLIENT_MASTER WHERE CITY =
MUMBAI;
INTERSECT
The INTERSECT operator returns all the rows which are in the both the
query.
Multiple query can be put together and their output are combine using the
intersect clause. The intersect clause displays the rows produced by both the
query intersected. That is it output only those rows that are retrieve by both the
query.
OUTPUT = Common records in both the query.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 25 of 54
Example:
SALES_MASTER SALES_ORDER
S_NO NAME CITY O_NO O_DATE S_NO
-------------------------------------- --------------------------------------------
S001 MANISH MUMBAI O1001 12-APR-04 S001
S002 KIRAN DELHI O1002 25-DEC-04 S003
S003 NITESH MUMBAI O1003 03-OCT-04 S001
S004 MAHESH CALCUTTA O1004 18-JUN-04 S004
O1005 20-AUG-04 S003
O1006 12-JAN-04 S002
SELECT S_NO, NAME FROM SALES_MASTER WHERE CITY = MUMBAI
INTERSECT
SELECT SALES_MASTER.S_NO, NAME FROM SALES_MASTER,
SALES_ORDER
WHERE SALES_MASTER.S_NO = SALES_ORDER.S_NO;
SELECT LANG1 LANGUAGE FROM FY
INTERSECT SELECT LANG1 LANGUAGE FROM SY;
MINUS
The MINUS operator produces the rows return 1st query but not the 2nd
query.
Multiple queries can be put together and their output combines using the
minus clause. The minus clause output the record produce by the 1st query after
filtering the rows return by the 2nd query.
OUTPUT = Records in query 1.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 26 of 54
Example: -
SALES_ORDER_DETAIL PRODUCT_MASTER
O_NO P_NO P_NO DESCRIPTION
----------------------------------- -------------------------------------------
O001 P001 P001 1.44 FLOPPIES
O001 P004 P002 MONITOR
O001 P006 P003 MOUSE
O002 P002 P004 1.22 FLOPPIES
O002 P005 P005 KEY BOARD
O003 P003 P006 CD DRIVE
O004 P001 P007 HDD
O005 P006 P008 1.44 DRIVE
O005 P004 P009 1.22 DRIVE
O006 P006
SELECT P_NO FROM PRODUCT_MASTER
MINUS SELECT P_NO FROM SALES_ORDER_DETAIL;
SELECT LANGUAGE1 LANGUAGE FROM FY
MINUS SELECT LANGUAGE2 LANGUAGE FROM SY;
(10) SUB QUERY: -
A SUB Query is a query within another query.
A SUB Query is a form of an SQL statement that appears inside another
SQL statement. It is also know as NESTED QUERY. The statement containing a
sub query is called PARENT STATMENT. The parent statement uses the rows
return by the sub query.
SUB QUERY can be used by the following commands: -
1. To Insert the records to a target table
2. To Create tables and To Insert the records in the new created table.
3. To Update records in a target table
4. To Create views
5. To provide values for conditions in WHERE, HAVING, IN, etc. used with
SELECT, UPDATE and DELETE statement.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 27 of 54
Example: -
SALES_ORDER CLIENT_MASTER
O_NO CLIENT_NO ORDER_DATE CLIENT_NO NAME BAL_DUE

O001 C006 12-APR-04 C001 ASHOK 500
O002 C002 25-DEC-04 C002 VISHAL 1000
O003 C001 03-OCT-04 C003 AJAY 0
O004 C005 18-JUN-04 C004 ROHIT 0
O005 C002 20-AUG-04 C005 NALINI 0
O006 C001 12-JAN-04 C006 PARESH 0
C007 RAHUL 0
SELECT * FROM SALES_ORDER WHERE CLIENT_NO =
(SELECT CLIENT_NO FROM CLIENT_MASTER WHERE NAME = ASHOK);
OUTPUT: -
O_NO CLIENT_NO O_DATE

O003 C001 03-OCT-04


O006 C001 12-JAN-04
EMP
EMP_NO EMP_NAME DEPT SALARY

100 RAM COMPUTER 3500


200 SITA MARKETING 5500
300 LAXMAN COMPUTER 2500
400 BHARAT MARKETING 6000
500 RAHUL SALES 2500
600 RAVI SALES 2500
700 RAHUL COMPUTER 6500
SELECT * FROM EMP WHERE SALARY < (SELECT AVG (SALARY) FROM
EMP);
OUTPUT: -
EMP_NO EMP_NAME DEPT SALARY

100 RAM COMPUTER 3500


300 LAXMAN COMPUTER 2500
500 RAHUL SALES 2500
600 RAVI SALES 2500
SELECT EMP_NO, EMP_NAME FROM EMP WHERE EMP_NO NOT IN
(SELECT EMP_NO FROM EMP WHERE DEPT = MARKETING);
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 28 of 54
OUTPUT: -
EMP_NO EMP_NAME

100 RAM
300 LAXMAN
500 RAHUL
600 RAVI
700 RAHUL
SELECT EMP_NO, EMP_NAME FROM EMP WHERE EMP_NO IN
(SELECT EMP_NO FROM EMP WHERE DEPT = MARKETING);
OUTPUT: -
EMP_NO EMP_NAME

200 SITA
400 BHARAT
SELECT * FROM EMP WHERE EMP_NO IN (SELECT EMP_NO FROM EMP
WHERE SALARY > 5000);
OUTPUT: -
EMP_NO EMP_NAME DEPT SALARY

200 SITA MARKETING 5500


400 BHARAT MARKETING 6000
700 RAHUL COMPUTER 6500
Using Sub Query to Create a new table: -
CREATE TABLE EMP1 AS SELECT * FROM EMP WHERE EMP_NO=0;
Using Sub Query to Insert the Data into a table: -
INSERT INTO EMP1 SELECT EMP_NO, EMP_NAME, DEPT, SALARY
FROM EMP;
Using Sub Query to Update the Data into table: -
UPDATE EMP1 SET (EMP_NO, EMP_NAME) =
(SELECT EMP_NO, EMP_NAME FROM EMP WHERE EMP_NO = 100)
WHERE EMP_NO = 200;
OUTPUT: -
1 row updated.
SELECT * FROM EMP1;
EMP_NO EMP_NAME DEPT SALARY

100 RAM COMPUTER 3500


100 RAM MARKETING 5500
300 LAXMAN COMPUTER 2500
400 BHARAT MARKETING 6000
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 29 of 54
500 RAHUL SALES 2500
600 RAVI SALES 2500
700 RAHUL COMPUTER 6500
Using a sub query to Delete the data into a table: -
DELETE FROM EMP1 WHERE EMP_NO IN
(SELECT EMP_NO FROM EMP WHERE EMP_NAME = RAHUL);
OUTPUT: -
2 rows deleted.
SELECT * FROM EMP1;
EMP_NO EMP_NAME DEPT SALARY

100 RAM COMPUTER 3500


100 RAM MARKETING 5500
300 LAXMAN COMPUTER 2500
400 BHARAT MARKETING 6000
600 RAVI SALES 2500
(11) DUAL TABLE: -
DUEL is a small oracle inbuilt table. The table is owned by SYS and it is
available for all the users.
The DUAL table consists only one column called DUMMY and a row
containing value X. It supports arithmetic calculation and data formatting. It is
also known as DUMMY table.
Example: -
SELECT 4*5 MULTIPLY FROM DUAL;
OUTPUT: -
MULTIPLY

20
SELECT SYSDATE FROM DUAL;
OUTPUT: -
SYSDATE

19-AUG-06
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 30 of 54
(12) ORACLE FUNCTION: -
An oracle function serves the purpose of manipulating the data items and
returning a function. Function are also capable of accepting user supplied
variables or constants and operates on them. Such variables and constants are
called as arguments. Any number of arguments can be passing to a function in
the following format.
FUNCTION-NAME (Arg-1, Arg-2, ., Arg-N)
Oracle function can be group to gather depending upon whether they
operate a single row or group of rows retrieve from a table.
Group Function / Aggregate Function: -
Function that act on a set of values are called as Group Function.
For Example: -
SUM is a function, which calculates the total set of values
provided as a argument in a function. A Group Function returns a single
result row for a group of query rows.
Categories of Group Function: -
AVG Function: -
Syntax: - AVG ([Distinct / All] N)
Purpose: - It returns the average value of N and it ignores the
NULL value.
Example: - SELECT AVG (SALARY) Avg - Salary FROM
EMP;
Output: - Avg - Salary

4142.85714
MIN Function: -
Syntax: - MIN ([Distinct / All] Expression)
Purpose: - It returns the minimum value of Expression.
Example: - SELECT MIN (SALARY) Minimum - Salary FROM
EMP;
Output: - Minimum - Salary

2500
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 31 of 54
MAX Function: -
Syntax: - MAX ([Distinct / All] Expression)
Purpose: - It returns the maximum value of Expression.
Example: - SELECT MAX (SALARY) Maximum - Salary
FROM EMP;
Output: - Maximum - Salary

6500
SUM Function: -
Syntax: - SUM ([Distinct / All] N)
Purpose: - It returns the total of value N.
Example: - SELECT SUM (SALARY) Total - Salary FROM
EMP;
Output: - Total - Salary

29000
COUNT Function: -
Syntax: - COUNT (* [Distinct / All] Expression)
Purpose: - It counts the number of expression in a given
column.
The * option returns number of rows including
duplicate values and NULL values. It gives number
of row count where expression is not Null.
Example: - SELECT COUNT (*) Total No of Rows FROM
EMP;
Output: - Total No Of Rows

7
Example: - SELECT COUNT (SALARY) Total No Of Salary
FROM EMP;
Output: - Total No Of Salary

7
Example of all Group Function: -
SELECT AVG (SALARY), MIN (SALARY), MAX (SALARY),
SUM (SALARY), COUNT (SALARY) FROM EMP;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 32 of 54
Output: -
AVG MIN MAX SUM COUNT
(SALARY) (SALARY) (SALARY) (SALARY) (SALARY)

4142.85714 2500 6500 29000 7


Scalar Function / Single Row Function: -
Functions that act on only one value at a time are called Scalar Function.
For Example: -
LENGTH is a function, which calculates the length of one
particular string value. A single row function returns one result for every
row of query table or view.
Categories of Scalar Function: -
1. String Function: -
This type of function works on string type of data.
Following are the various String Functions.
LOWER Function: -
Syntax: - LOWER (Char Set)
Purpose: - It returns set of character with all the letters in
the lower case.
Example: - SELECT LOWER (ORACLE) Lower Fun.
FROM DUAL;
Output: - Lower Fun.

oracle
UPPER Function: -
Syntax: - UPPER (Char Set)
Purpose: - It returns set of character with all the letters in
the upper case.
Example: - SELECT UPPER (oracle) Upper Fun. FROM
DUAL;
Output: - Upper Fun.

ORACLE
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 33 of 54
INITCAP Function: -
Syntax: - INITCAP (Char Set)
Purpose: - It returns the string with the first letter in capital
for every word in a string.
Example: - SELECT INITCAP (I am happy) Initcap Fun.
FROM DUAL;
Output: - Initcap Fun

I Am Happy
SUBSTR Function: -
Syntax: - SUBSTR (String, M, [N])
Purpose: - It returns the position of the character beginning
at character M exiting up to N character. If N is
omitted result is return up to the end character.
Example: - SELECT SUBSTR (SECURE,3,4) SUBSTR
FROM DUAL;
Output: - SUBSTR

CURE
LENGTH Function: -
Syntax: - LENGTH (String)
Purpose: - It returns the number of character in a given
string.
Example: - SELECT LENGTH (BCA) NO. OF CHAR
FROM DUAL;
Output: - NO. OF CHAR

3
LTRIM Function
Syntax: - LTRIM (String [SET])
Purpose: - It removes the character from the left of the
string with initial character remove up to the
first character.
Example: - SELECT LTRIM (_ _ _BCA) LTRIM FROM
DUAL;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 34 of 54
Output: - LTRIM

BCA
RTRIM Function: -
Syntax: - LTRIM (String [SET])
Purpose: - It returns the character with final character the
last character not in the set.
Example: - SELECT RTRIM (BCA_ _ _) RTRIM FROM
DUAL;
Output: - RTRIM

BCA
LPAD Function: -
Syntax: - LPAD (char-1, N, [char-2])
Purpose: - It returns char-1 left pedal to length N with the
sequence of characters in char-2 by default, if
char-2 is not provided then it takes blank
character.
Example: - SELECT LPAD (BCA, 10,*) LPAD
FROM DUAL;
Output: - LPAD

*******BCA
RPAD Function: -
Syntax: - RPAD (char-1, N, [char-2])
Purpose: - It returns char-1 right pedal to length N with the
character in char-2. It replicates as many times
as necessary, if char-2 is omitted then it takes
blank character.
Example: - SELECT RPAD (BCA, 5,*) RPAD FROM
DUAL;
Output: - RPAD

BCA**
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 35 of 54
INSTR Function: -
Syntax: - INSTR (string, [set])
Purpose: - It returns the occurrence of character in a given
string.
Example: - SELECT INSTR (EMP_NAME,A) First
INSTR (EMP_NAME,A, 1,1) Second
INSTR (EMP_NAME,A, 3,2) Third
INSTR (EMP_NAME,A, 1,2) Fourth
FROM EMP WHERE EMP_NAME=RAM;
SOUNDEX Function: -
Syntax: - SOUNDEX (string)
Purpose: - It gives the strings, which have the nearest
meaning in speaking.
Example: - CREATE TABLE SOUND (SOUND1
VARCHAR2 (10));
SELECT * FROM SOUND WHERE SOUNDEX
(SOUND1) =
SOUNDEX (COLOR);
2. Numeric Function: -
This type of function works for numeric data type.
Following are the various Numeric Functions.
ABS Function: -
Syntax: - ABS (N)
Purpose: - It returns the absolute value of N.
Example: - SELECT ABS -15) Absolute Value FROM
DUAL;
Output: - Absolute Value

15
POWER Function: -
Syntax: -POWER (M, N)
Purpose: - It returns M raised N
th
power. Must be N is
integer else the error will return.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 36 of 54
Example: - SELECT POWER (3,2) 3 Raised to 2 FROM
DUAL;
Output: - 3 Raised to 2

9
ROUND Function: -
Syntax: - ROUND (N [M])
Purpose: -It returns N rounded to the M places right side
of the decimal point. If M is omitted then N is
rounded to ZERO places. M can be a negative
number to round the digit left of the decimal
point. M must be an integer.
Example: - SELECT ROUND (123.55,1) Rounded Value
FROM DUAL;
Output: - Rounded Value

123.6
Example: -SELECT ROUND (123.55,2) Rounded Value
FROM DUAL;
Output: - Rounded Value

123.55
Example: - SELECT ROUND (123.55,0) Rounded Value
FROM DUAL;
Output: - Rounded Value

124
Example: - SELECT ROUND (0,1) Rounded Value FROM
DUAL;
Output: - Rounded Value

0
Example: - SELECT ROUND (123.55,-2) Rounded Value
FROM DUAL;
Output: - Rounded Value

100
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 37 of 54
Example: - SELECT ROUND (123, -2) Rounded Value
FROM DUAL;
Output: - Rounded Value

100
SQRT Function: -
Syntax: - SQRT (N)
Purpose: - It returns square root of N. If N is less than 0 or
NULL than the square root function returns real
result.
Example: - SELECT SQRT (25) SQRT Value FROM
DUAL;
Output: - SQRT Value

5
Example: - SELECT SQRT (0) SQRT Value FROM DUAL;
Output: - SQRT Value

0
Example: - SELECT SQRT (NULL) SQRT Value FROM
DUAL;
Output: - SQRT Value

Example: - SELECT SQRT (-25) SQRT Value FROM


DUAL;
Output: - ERROR at line 1:
ORA-01428: argument '-25' is out of range
TRUNC Function: -
Syntax: - TRUNC (N [, M])
Purpose It returns and truncated to N places right of the
decimal point. If M is omitted N is truncated
ZERO places. If M can be a negative number to
trunk the digits left of the decimal point. M must
be an integer number.
Example: - SELECT TRUNC (123.55) Truncated Value
FROM DUAL;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 38 of 54
Output: - Truncated Value

123
Example: - SELECT TRUNC (123.55,1) Truncated Value
FROM DUAL;
Output: - Truncated Value

123.5
Example: - SELECT TRUNC (123, -2) Truncated Value
FROM DUAL;
Output: - Truncated Value

100
Example: - SELECT TRUNC (123, -3) Truncated Value
FROM DUAL;
Output: - Truncated Value

0
Example: - SELECT TRUNC (123, -4) Truncated Value
FROM DUAL;
Output: - Truncated Value

0
Example: - SELECT TRUNC (123, 0) Truncated Value
FROM DUAL;
Output: - Truncated Value

123
CEIL Function: -
Syntax: - CEIL (N)
Purpose: - It returns ceiling value of the given number N.
Example: - SELECT CEIL (44.778) CEIL Value FROM
DUAL;
Output: - CEIL Value

45
Example SELECT CEIL (44.228) CEIL Value FROM
DUAL;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 39 of 54
Output CEIL Value

45
FLOOR Function: -
Syntax: - FLOOR (N)
Purpose: - It returns flooring value of the given number N.
Example: - SELECT FLOOR (44.778) FLOOR Value
FROM DUAL;
Output: - FLOOR Value

44
Example: - SELECT FLOOR (44.228) FLOOR Value
FROM DUAL;
Output: - FLOOR Value

44
MOD Function: -
Syntax: - MOD (D, d)
Purpose: - It gives modulo or reminder of two expression.
Example: - SELECT MOD (10,3) MOD Value FROM
DUAL;
Output: - MOD Value

1
Example: - SELECT MOD (10,4) MOD Value FROM
DUAL;
Output: - MOD Value

2
3. Conversion Function: -
This type of function works for conversion of one data
type value to another data type value. Following are varies
Conversion Functions.
TO_NUMBER Function: -
Syntax: - TO_NUMBER (Char)
Purpose: - It converts character value to the number data-
type format or in numeric format.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 40 of 54
Example: - SELECT TO_NUMBER (SUBSTR ($100, 2, 3))
NUM FROM DUAL;
Output: - NUM

100
TO_CHAR Function (For Number): -
Syntax: - TO_CHAR (N, [Format])
Purpose: - It converts a value of number data-type to a
value of char data-type using the optional
format string.
Example: - SELECT TO_CHAR (17145, $099999.99)
CHAR FROM DUAL;
Output: - CHAR

$017145.00
TO_CHAR Function (For Date): -
Syntax: - TO_CHAR (Date, [Format])
Purpose It converts a value of date data-type to character
data-type using the optional format string.
Example SELECT TO_CHAR (SYSDATE, MONTH-DD-
YYYY) Format FROM DUAL;
Output: - Format

AUGUST-30-2006
4. Date Function: -
This type of function works on date data type.
Following are varies Date Functions.
TO_DATE Function: -
Syntax: - TO_DATE (char, [Format])
Purpose: - It converts characters data fields to date data
fields in specified format.
Example: - SELECT TO_DATE (30/JUN/06,DD MM YY)
FROM DUAL;
Output: - TO_DATE

30-JUN-06
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 41 of 54
ADD_MONTHS Function: -
Syntax: - ADD_MONTHS (Date, N)
Purpose: - This function adds number of months to a
specific date and it returns the date after adding
number of months specified with the function.
Example: - SELECT ADD_MONTHS (SYSDATE, 2) FROM
DUAL;
Output: - ADD_MONTH

29-OCT-06
LAST_DAY Function: -
Syntax: - LAST_DAY (Date)
Purpose: - It returns the last date of the month specified
with function.
Example: - SELECT SYSDATE, LAST_DAY (SYSDATE)
FROM DUAL;
Output: - SYSDATE LAST_DAY
-------------- ----------------
29-AUG-06 31-AUG-06
MONTHS_BETWEEN Function: -
Syntax: - MONTHS_BETWEEN (Date-1, Date-2)
Purpose: - It returns the numbers of months between Date-
1 and Date-2.
Example: - SELECT MONTHS_BETWEEN (2-FEB-04, 2-
JAN-04) MONTH FROM DUAL;
Output: - MONTH

1
NEXT_DAY Function: -
Syntax: - NEXT_DAY (Date, Char Day)
Purpose: - It returns the date of first weekday named by
character day. The Char Day must be a day of
the week.
Example: - SELECT NEXT_DAY (sysdate, Sunday)
NEXT_DAY FROM DUAL;
Output: - NEXT_DAY

03-SEP-06
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 42 of 54
(1) VIEWS: -
View is a restricted-right of a table.
It is nothing but the mirror image of a original table.
Views are logical table of data that are extracted from the existing tables.
Why views are created?
1. After a table is created and populated with data, It is necessary to prevent
all the users from accessing all the columns of a table for the data security
region.
2. One solution of the above problem is to create several duplicate tables
having number of columns and assign specific rights to the users.
3. Due to the above solution the redundant data increases in the oracle.
4. We are reducing the redundant data and provide the data security with the
use of object views. Because to prevent the unauthorized access without
redundancy is the prime objective of views.
5. Views can be building up with the use of select statement to select number
of columns in the specified view.
6. View is stored as a definition in the oracle system catalogue.
7. When reference is made to the view its definition is scanned from a
catalogue, based table is open and view is created on the top of the based
table.
8. View cannot hold data until specific call is made to the view.
9. When view is used to manipulate the table data based table is completely
invisible and provides the security.
Types of views
1. A view that is used to look at the table data and nothing else that view is
called READ ONLY VIEW.
2. A view that is used to look at the table data as well as To Insert, Update
and Delete the data is called UPDATABLE VIEW.
Syntax: -
CREATE OR [REPLACE] [FORCE/NOFORCE] VIEW <View-name>
AS [SELECT Statement] [WHERE Condition] [WITH CHECK OPTION]
[CONSTRAINT Constraint-name] [WITH READ ONLY] [GROUP BY]
[HAVING Clause];
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 43 of 54
Replace View already exists than it recreates the existing view.
Force It allows the creation of view even when the base table does not
exist and user does not have privileges to create it.
NO Force It allows the creation of view only when the based table is exists.
With Check Option
The check option apply to the WHERE Clause condition in sub
query. It allows the Insertion and Updating of rows based on the
condition that satisfies the view.
Views that is define from a single table: -
CREATE VIEW EMP_VIEW AS SELECT * FROM EMP;
CREATE VIEW EMP_VIEW1 AS SELECT * FROM EMP WHERE
ENO=200;
CREATE OR REPLACE VIEW EMP_VIEW2 AS SELECT * FROM
EMP;
To display the column data: -
SELECT * FROM EMP_VIEW;
SELECT * FROM EMP_VIEW1;
SELECT * FROM EMP_VIEW2;
To see the structure of the view: -
DESCIBE EMP_VIEW;
DESCIBE EMP_VIEW1;
DESCIBE EMP_VIEW2;
To remove the view: -
DROP VIEW EMP_VIEW;
DROP VIEW EMP_VIEW1;
DROP VIEW EMP_VIEW2;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 44 of 54
UPDATABLE VIEW
View cannot be UPDATABLE, if it contains SET Operators,
GROUP Function, GROUP BY Clause and DISTINCT Clause.
Rules for updating a view define on a single table: -
If user wants to inserts the records in the view then PRIMARY KEY
and NOT NU LL columns must be included in the view.
The user can update and delete the records with the help of a view
even if PRIMARY KEY and NOT NULL columns are not included in
the view.
Examples of views that is define from a single table: -
CREATE VIEW CLIENT_VIEWAS SELECT CLIENT_NO, NAME, BAL_DUE
FROM CLIENT_MASTER;
To Insert Operation: -
INSERT INTO CLIENT_VIEW VALUES (C001,RAMESH, 2500);
To Update Operation: -
UPDATE CLIENT_VIEW SET BAL_DUE =500 WHERE NAME=RAMESH;
To Delete Operation: -
DELETE FROM CLIENT_VIEW WHERE NAME=RAMESH;
Creation of view with CHECK OPTION: -
CREATE OR REPLACE VIEW CUST_VIEW AS SELECT * FROM CUST
WHERE CITY=UDP WITH CHECK OPTION;
NOTE: The CHECK OPTION will validate the data during the insert or update based on
the CHECK condition.
For Example: - If CITY=UDP
When a row is inserted into the view the CITY has to be UDP, similarly
when view is updated the value in the column CITY has to be UDP.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 45 of 54
Creation of view with Read Only Option: -
CREATE OR REPLACE VIEW CUST1_VIEW AS SELECT * FROM CUST
WITH READ ONLY;
NOTE: The READ ONLY OPTION does not allow the insert, update and delete
operation on the view. We can only see the data of the view.
Views that is define from multiple tables (The table which have no referential
clause): -
If view is created from multiple tables which were not created using
referential integrity constraints (No logical relationship between the tables) than
all though Primary key and Not Null columns included in the view definition, the
view reacts in the following way.
1. The INSERT, UPDATE and DELETE operation is not allow.
Views that is define from multiple tables (The table which has no referential
clause): -
If view is created from multiple tables which were created using
referential integrity constraints (Logical relationship between the tables) than all
though Primary key and Not Null columns included in the view definition, the
view reacts in the following way.
1. The INSERT, UPDATE and DELETE operation is not allow.
2. An INSERT operation is not allowed.
3. The DELETE or UPDATE operation do not effect the master table.
4. The view can be used UPDATE the columns of the detail table included in
the view.
5. If a DELETE operation is executed on the view the corresponding records
from the detail table will be deleted.
Examples of views that is define from a multiple tables: -
CREATE VIEW VIEW_SALES AS SELECT ORDER_NO, ORDER_DATE,
DELY_ADDR, PRODUCT_NO, QTY_ORDERED, QTY_DISP FROM
SALES_ORDER, SALES_ORDER_DETAIL WHERE SALES_ORDER.ORDER_NO =
SALES_ORDER_DETAIL.D_ORDER_NO;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 46 of 54
To Insert Operation: -
Not allowed in both table.
To Update Operation: -
UPDATE VIEW_SALES SET QTY_DISP = 100 WHERE
D_ORDER_NO = O002;
To Delete Operation: -
DELETE FROM VIEW_SALES WHERE PRODUCT_NO = P001
AND D_ORDER_NO = O003;
(1!) INDEXES: -
Definition: -
An IDEX is an ordered list of constants of a column or a group of columns
of a table.
When user fires a SELECT statement to search for a particular record the
oracle engine must first locate the table on the HDD. The oracle engine reads the
system information and locates the starting location of table's record on the current
storage media. Then performs sequential search to locate the records that match the
user criteria.
For Example To locates the Client no = C004 in Sales order table; the
oracle engine must first locate the Sales order table and then performs a sequential
search on the Client no column to find the value C004.
So, Oracle engine has to search entire table to find column that contain the
value C004.
So, An Indexing a table is an access strategy that is a way to sort and
search the records in the tables. Index is essential to improve the speed with which the
records can be located and retrieve from a table.
Index is a two dimensional matrix that contains: -
A column, which holds the sorted data.
An address field, which identified the record, which is called ROWID.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 47 of 54
RowID: -
RowID is an internal generated and maintained binary value, which
identified a record. It provides the location of the particular record in oracle
database.
Example: - SELECT RowID, EMP_NAME FROM EMP;
Output: -
ROWID EMP_NAME

AAAGE1AABAAAIUsAAA RAM
AAAGE1AABAAAIUsAAB SITA
AAAGE1AABAAAIUsAAC LAXMAN
AAAGE1AABAAAIUsAAD BHARAT
AAAGE1AABAAAIUsAAE RAHUL
AAAGE1AABAAAIUsAAF RAVI
AAAGE1AABAAAIUsAAG RAHUL
7 rows selected.
Creation of Index: -
An Index can be created on one or more then one columns. So, it is
divided in two categories.
There are two types of Index.
Simple Index: -
An Index, which is created on single column of a table, is called
Simple Index.
Syntax: -
CREATE INDEX <INDEX-NAME> ON <TABLE-NAME>
(COLUMN-NAME);
Example: -
CREATE INDEX Idx_Client_No ON Client_master (Client_no);
CREATE INDEX Idx_Emp_Name ON Emp (Emp_no);
Composite Index: -
An Index, which is created on more then one column of a table,
is called Composite Index.
Syntax: -
CREATE INDEX <INDEX-NAME> ON <TABLE-NAME>
(COLUMN1, , COLUMNN);
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 48 of 54
Example:
CREATE INDEX Idx_Client ON Client_master (Client_no,
Client_name);
CREATE INDEX Idx_Emp ON Emp (Emp_no, Emp_name);
Creation of unique Index: -
There are two types of Index.
Simple Unique Index: -
If the Index is created on only one column and the values of the
column is not repeated then this type of Index is called Simple Unique
Index.
Syntax: -
CREATE UNIQUE INDEX <INDEX-NAME> ON <TABLE-NAME>
(COLUMN-NAME);
Example:
CREATE UNIQUE INDEX Idx_Client_No ON Client_master
(Client_no);
CREATE UNIQUE INDEX Idx_Emp_Name ON Emp (Emp_no);
Composite Unique Index: -
If the Index is created on more then one column and the values
in this column are not repeated then this type of Index is called
Composite Unique Index.
Syntax: -
CREATE UNIQUE INDEX <INDEX-NAME> ON <TABLE-NAME>
(COLUMN1,,COLUMNN);
Example:
CREATE UNIQUE INDEX Idx_Client ON Client_master (Client_no,
Client_name);
CREATE UNIQUE INDEX Idx_Emp ON Emp (Emp_no, Emp_name);
To see the Index record: -
SELECT * FROM Client_master;
SELECT * FROM Emp;
To see the list of Indexes: -
SELECT * FROM User_Indexes;
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 49 of 54
To see the structure of Indexes: -
DESCRIBE User_Indexes;
Name Null? Type

INDEX_NAME NOT NULL VARCHAR2 (30)


INDEX_TYPE VARCHAR2 (27)
TABLE_OWNER NOT NULL VARCHAR2 (30)
TABLE_NAME NOT NULL VARCHAR2 (30)
TABLE_TYPE VARCHAR2 (11)
UNIQUENESS VARCHAR2 (9)
COMPRESSION VARCHAR2 (8)
PREFIX_LENGTH NUMBER
TABLESPACE_NAME VARCHAR2 (30)
INI_TRANS NUMBER
MAX_TRANS NUMBER
INITIAL_EXTENT NUMBER
NEXT_EXTENT NUMBER
MIN_EXTENTS NUMBER
MAX_EXTENTS NUMBER
PCT_INCREASE NUMBER
PCT_THRESHOLD NUMBER
INCLUDE_COLUMN NUMBER
FREELISTS NUMBER
FREELIST_GROUPS NUMBER
PCT_FREE NUMBER
LOGGING VARCHAR2 (3)
BLEVEL NUMBER
LEAF_BLOCKS NUMBER
DISTINCT_KEYS NUMBER
AVG_LEAF_BLOCKS_PER_KEY NUMBER
AVG_DATA_BLOCKS_PER_KEY NUMBER
CLUSTERING_FACTOR NUMBER
STATUS VARCHAR2 (8)
NUM_ROWS NUMBER
SAMPLE_SIZE NUMBER
LAST_ANALYZED DATE
DEGREE VARCHAR2 (40)
INSTANCES VARCHAR2 (40)
PARTITIONED VARCHAR2 (3)
TEMPORARY VARCHAR2 (1)
GENERATED VARCHAR2 (1)
SECONDARY VARCHAR2 (1)
BUFFER_POOL VARCHAR2 (7)
USER_STATS VARCHAR2 (3)
DURATION VARCHAR2 (15)
PCT_DIRECT_ACCESS NUMBER
ITYP_OWNER VARCHAR2 (30)
ITYP_NAME VARCHAR2 (30)
PARAMETERS VARCHAR2 (1000)
GLOBAL_STATS VARCHAR2 (3)
DOMIDX_STATUS VARCHAR2 (12)
DOMIDX_OPSTATUS VARCHAR2 (6)
FUNCIDX_STATUS VARCHAR2 (8)
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 50 of 54
To Drop the Indexes: -
Syntax: -
DROP INDEX <INDEX-NAME>;
Example: -
DROP INDEX Idx_Emp;
SELECT Index_name, Table_name, UNIQUENESS FROM User_Indexes;
(1) SEQUENCES: -
Definition: -
A Sequence is a simply an automatic counter, which enabled whenever it
is accessed. The number generated by it can be used to update a column
containing. For Example - A product code or employee code. These guaranties
that there are no two rows with the same code number.
A sequence is an independent object and can be used with any table that
requires its output.
Why the sequence is needed? : -
The fastest way to retrieve the data from the table is to have a column
in the table which uniquely identifies a row. By this column a specific value in
the WHERE Clause of the SELECT Statement. The oracle engine will be able
to identify and retrieve the row very easily and this method is fastest method.
For the above process the constraints is attached to a specific column
in the table that ensure that the column is never left empty and the data values
in the column are unique.
Since, The human being is engaged with the data entry operation it is
quite tightly that duplicate value will be entered, which violets the constraints
and entire row is rejected and not to be entered in to the table although all
other values are right and consistent.
But if the value to be entered in to their column is machine generated
than it will always fulfill the constraints and row will always be entered in to
the table.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 51 of 54
A sequence can be define to: -
a. Generate the number in ascending or in descending order.
b. Provides the interval between the numbers.
c. Caching of sequence number in to the memory.
The minimum information required for generating numbers using
sequence is: -
a. The Starting number of the sequence.
b. The Maximum number that can be generated by the sequence.
c. The Increment value for generating the next number.
Syntax:
CREATE SEQUENCE <Sequence-name> [INCREMENT BY Integer-
value
START WITH Integer-value [MINVALUE / NO MINVALUE]
[MAXVALUE / NO MAXVALUE] [CYCLE / NO CYCLE] [CATCH /
NO CATCH] [ORDER / NO ORDER]];
Keywords and parameters in syntax: -
Keyword Descriptions
Start With
It indicates the Starting value of the sequence. For ascending
sequence Minvalue is 1 and ascending sequence is a default sequence.
For descending sequence Minvalue is -1.
Increment By
It specifies the interval between the sequence numbers. It can be
positive or negative numbers but not ZERO. Default is 1.
Minvalue It specifies a minimum value for the sequence.
No Minvalue
It specifies a minimum value of 1 for ascending sequence and
(10)
26
for descending sequence.
Maxvalue
It specifies a maximum value for the sequence.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 52 of 54
No Maxvalue
It specifies the maximum value of (10)
27
for ascending sequence and
-1 for descending sequence.
Cycle
It specifies that the sequence continue to generate the repeated value
after reaching its maximum value.
No Cycle
It specifies that the sequence cannot generate more value after
reaching its maximum value.
Catch
It indicates the number of sequences that should be created and stored
direct in the memory for faster access.
No Catch It specifies the values of sequences are not pre-allocated in memory.
Order / No
Order
When we are working on the multi-user system many users
simultaneously tries to access the sequence number are generating in
the prescribe order or not. We have to give order clause in the
sequence definition. No order clause does not maintain order of
sequence for the values to be inserted by the users at the same time.
Pseudo Columns: -
Oracle has several Pseudo Columns that behave as a extra column,
When a new table is created. We have seen two types of Pseudo Columns
ROWID and ROWNUM.
To access the value of sequence we can use two Pseudo Columns
CURRVAL and NEXTVAL.
CURRVAL: - It returns the current value of the sequence.
NEXTVAL: - The increase value of the sequence and returns the next value of the
sequence.
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 53 of 54
Examples of Sequences: -
CREATE SEQUENCE Seq_Emp INCREMENT BY 1
START WITH 501 MINVALUE 501 MAXVALUE 9999;
CREATE SEQUENCE SEQ_Item INCREMENT BY 1
START WITH 501 MINVALUE 501 NO MAXVALUE;
CREATE SEQUENCE Seq_Order INCREMENT BY 1
START WITH 101 MINVALUE 101 MAXVALUE 599 CYCLE;
To see the current value and next value of the Sequences: -
SELECT Seq_Emp CURRVAL FROM DUAL;
Output: - CURRVAL

505
SELECT Seq_Emp.NEXTVAL FROM DUAL;
Output: - NEXTVAL

506
To Insert the record in the Sequences: -
INSERT INTO EMP VALUES (TOCHAR
(SEQ_EMP.NEXTVAL),GAJOO,COMPUTER, 10000);
To See the list of Sequences: -
SELECT * FROM USER_SEQUENCES;
SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE LAST_NUMBER

SEQ_EMP 501 9999 1 N N 20 501


DESCRIBE USER_SEQUENCES;
Name Null? Type

SEQUENCE_NAME NOT NULL VARCHAR2 (30)


MIN_VALUE NUMBER
MAX_VALUE NUMBER
INCREMENT_BY NOT NULL NUMBER
CYCLE_FLAG VARCHAR2 (1)
ORDER_FLAG VARCHAR2 (1)
CACHE_SIZE NOT NULL NUMBER
LAST_NUMBER NOT NULL NUMBER
RDBMS SQL * Plus CCMCA-Wadhwan
Developed By: Jaypalsinh A. Gohil Page 54 of 54
To Alter or Modify the Sequences: -
ALTER SEQUENCE Seq_Emp INCREMENT BY 5 MAXVALUE 10000;
Sequence altered.
SELECT * FROM USER_SEQUENCES;
SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE LAST_NUMBER

SEQ_EMP 501 10000 5 N N 20 505


To Drop a Sequences: -
DROP SEQUENCE Seq_Emp;
(1) SYNONYMS: -
Synonym is used to give alternative name to the table.
Syntax: -
CREATE SYNONYM <SYNONYM-NAME> FOR <TABLE-NAME>;
Example: -
CREATE SYNONYM E FOR EMP;
Output: -
Synonym created.
To see the list of Synonym define by user: -
SELECT Table_name, Synonym_name FROM USER_SYNONYMS;
Output: -
TABLE_NAME SYNONYM_NAME

EMP E

You might also like