Top Banner
Data Storage Data Storage For any business to be successful , fast access to information is critical . Information is extracted from the existing data . Important decisions are taken on the information .To get the right information at the right time ; we store data on a Computer System.This aids in fast and easy access to information. To store and manage data on a
116
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Oracle

Data StorageData StorageFor any business to be successful , fast access to information is critical . Information is extracted from the existing data . Important decisions are taken on the information .To get the right information at the right time ; we store data on a Computer System.This aids in fast and easy access to information.

To store and manage data on a computer we need a specialized computer program known as Database Management System(DBMS).A DBMS stores , process and retrieves data .

Page 2: Oracle

Database:Database:A Database is a collection i.e; tables,views,indexes,stored procedure and triggers.The data stored in a database may be related to any process such as Inventory / Payroll System

RDBMS:A collection of related data. Some popular RDBMS are:

• OracleOracle Oracle CorporationOracle Corporation• MS SQL 7.0 Microsoft Corporation• Sybase Sybase Inc.• Informix Informix Inc.• Ingress Ingress Inc.• DB/2

A Database which supports at least 6 Rules of 12 Rules of A Database which supports at least 6 Rules of 12 Rules of Boyce-Codd called RDBMS otherwise DBMSBoyce-Codd called RDBMS otherwise DBMS

Page 3: Oracle

Entity Relationship DiagramEntity Relationship Diagram• It’s a technique which is used to represent the logical

structure of the database of a system.Its nothing but the diagrammatic representation of database design.

• What happens in real world ,when you want to construct a house according to your specifications, you would approach to a construction company .The architect would typically interview you to understand your requirements.He draws “blue print” according to your specifications, and, then construction of the building starts.

• Similarly , in a “Software development environment” , a System Analyst will interview the client for all the project specifications , draw the ER Diagram , and get it verified by the client .If the diagram is as per requirements and fulfills all the needs of client ,creation of the database and table will follows.

Page 4: Oracle

An ER Diagram is like a blue print for the databases.It consists of following 3 elements:Entities Relationships AttributesSequence is:Identify Entities->Attributes->RelationshipIdentify Entities->Attributes->Relationship

It was introduced by It was introduced by Peter Chen in 1976.Peter Chen in 1976.

Page 5: Oracle

Entity:Entity:• An Entity is an object with distinct set of easily

identifiable properties.They are building blocks of a database .An Entity can be any object,item,place, concept or activity about which data can be stored .In a diagramming technique entities are named and represented by a BOX.

STUDENT GRADECOURSEEntity Type: Entity Type: A set of things which share common properties .For eg; STUDENT , COURSE,GRADE.Usually denoted in UpperCaseEntity Instance(Example):Entity Instance(Example):Is a specific individual , thing/objects.For eg; Deepu,Science .Usually denoted in lower/mixed case.

Page 6: Oracle

Attributes:Attributes:• An Attribute is a properties of the Entity.An

attribute instance is a particular property of an individual entity instance.An attribute type is property of an Entity type .For eg; ‘male’ is an attribute instance while SEX is an attribute type.Attributes are depicted as ellipses,labeled with name of the property.

STUDENT

REG_NO

SEMESTER

ADDRESS

NAME

Page 7: Oracle

TABLE:TABLE:Entities are represented as table in a database .A table is a arrangement of Rows and Columns.Attributes are represented as column heading in a table and actual data about the entity in rows .

RollNo Name Address Phone Reg_Date

R001 Arti Dhanbad NULL 10/02/2002

R002 Vivek Kolkata 5619944 21/03/1990

R003 Preeti Kolkata 5619944 05/10/1980

R004 Deepu Lucknow 213456 05/05/1989

R005 Rani Delhi 7639129 14/08/1997

Page 8: Oracle

RELATIONSHIPSRELATIONSHIPS

• It is an association among entities .For eg: there is a relationship between you and me (Student and Instructor ).This relationship represents the fact that an Instructor teaches several students.The name of the relationship is “Teaches”.Relationship depicted by a diamond ,with the name of the relationship type.

INSRUCTOR STUDENTTEACHESTEACHES

Page 9: Oracle

Types of RelationshipsTypes of Relationships

• One to One:– One instance of an Entity can relate to only one instance

of related instance.For one Department ,there can be only one Department Head.One Faculty cannot head more than one Department.

RAJ

RAJA

SIMRAN

DEEPU

RANI

COMPUTER

SALES

FINANCE

MARKETING

PRODUCTION

Page 10: Oracle

DEPARTMENT ONE FACULTY MEMHEADED BYHEADED BY

CITY SALESMANSALESALE

ONE ONE

ONEONE

Page 11: Oracle

One to ManyOne to Many

• One instance of an Entity can relate more than one instance of related Entity.For eg; One Salesman can sell in many cities.

RAJ

SIMRAN

RANI

Kolkata

Mumbay

Dhanbad

Chennai

Ranchi

Orissa

Delhi

SALESMAN CITYSALESALE MANYONE

Page 12: Oracle

Many to ManyMany to Many• More than one instance of an Entity can relate more

than one instance of its related Entity.For eg;Many Salesman can sale in many city.

RAJ

SIMRAN

RANI

Kolkata

Mumbay

Dhanbad

Chennai

Ranchi

Orissa

Delhi

SALESMAN CITYSALESALE MANYMANY

Page 13: Oracle

• After ER Diagram Entities are mapped to tables and they are related using common Attribute

CITYCITY SALESMANSALESMAN

CityCode SCode

CName Sname

SCode Address

• Attribute Naming Conventions:Attribute Naming Conventions:– Starts with Characters– Can use lower/uppercase– Can be upto 256 Characters– Embedded space not allowed

Page 14: Oracle

KeysKeys

• Candidate Key(Surrogate):An attribute or set attribute that uniquely identifies a row.(If a column contain unique values).

To ensure data integrity (Validation) so that the data in the database is valid and correct,Keys play important role .The various types of keys are:

StudId Name City FeesS001 Rajan Lucknow 56000S002 Deepu Lucknow 40000S003 Ajeet Mujaffarpur 67000S004 Deepu Delhi 12000S005 Vivek Kolkata 25000

These columns contains unique values , so these are Candidate Keys.

Page 15: Oracle

Primary KeyPrimary Key• The candidate key which is used to uniquely

identify each row is called Primary Key.Here StudId is Primary Key ,choosing Fees as a Primary Key is meaningless as there is no sequence.

Alternate KeyAlternate Key

• The candidate key which is not chosen as Primary Key is called Alternate Key.Here, Fees is a Alternate Key.

Page 16: Oracle

Composite KeyComposite Key

• When the key that uniquely identifies the rows of table made up of more than one attribute .

CustId ProdId Qty SaleDate

C122 P002 12 14/08/76

C134 P002 13 14/08/76

C122 P005 12 10/02/75

None of the columns contains unique values . However , if we combine CustId and ProdId we get unique value.So CustId+ProdId is Composite Primary Key.

Page 17: Oracle

Foreign KeyForeign Key

• When primary key of one table is also available as an attribute in another table,it is called Foreign Key. It is used to relate tables.

• Referential Integrity:Ensuring that all the values in Foreign key match with the Primary Key.

PRODUCTSProdId(PK)DescriptionQohPrice

CUSTOMER

CustIdProdId(FK)QtyOrderValue

Page 18: Oracle

SQLSQL• It is the language used to access data within

Oracle databases.

• Developed by IBM in mid –1970s.

• Oracle Corporation introduced the first the commercially available implementation of SQL.

• Abbreviation of Structured Query Language, pronounced as “see” – “quell” is made of three sub-languages such as:

Page 19: Oracle

• Data Definition language (DDL):– Consists of commands to create the objects like

CREATE,ALTER,DROP such as tables,views , indexes etc.

• Data Manipulation Language(DML):– Used for query , Insertion,Deletion and

Updation of information stored in the databases.

• Data Control Language(DCL):– Used for controlling data and access to the

databases Example:Commit , Rollback

Page 20: Oracle

SQL *PlusSQL *Plus

• SQL *Plus is a software product from Oracle Corporation that allows users to interactively use the SQL commands , produce formatted reports and support written command-procedures to access Oracle databases.Through SQL * Plus user can:

– Enter,edit,store,retrieve and run SQL commands

– Format ,perform calculations on , store , and print query results in the form of reports.

– List column definition of any table.

– Access and copy data between SQL databases.

– Send messages to and accept responses from an end user.

Page 21: Oracle

Starting SQL *PlusStarting SQL *PlusPrograms

Oracle-OraHome81

Application Development

SQL Plus

Page 22: Oracle
Page 23: Oracle

Data Type:Data Type:Type of data that is stored in a column. These are:1)Char(size):Fixed-length character data ,size character long.Maximum size is 2000.2)Varchar2(size):Variable length character string having maximum of size bytes(upto 4000)3)Number(size): Stores fixed and floating point nos.4)Date: Stores date and time.5)Long: Can store up to 2 GB of characters.6)Raw: Used to store graphics & sound etc.

Page 24: Oracle

Creating TableCreating Table• Table is a Row and Column arrangement of data.• Tables are owned by the user who creates them • Name of table must be unique• Column names in a table must be unique• Column names can be duplicated across the tables• Table name must begin with a letter A-Z or a-z• It may contain letters, numbers and special characters• It may upto 30 characters long.• Must not be SQL reserved word• Names are not case-sensitive• Syntax:

– Create table <table name>(– Column-name <datatype(size)>,– ….);

Page 25: Oracle

Create table ItemMast(ITNO number(4),Name varchar2(20),QOH number(5),Class char(1),ROD date,Rate number(8,2));To see the structure of a table:

Desc[ribe] <table-name>

Page 26: Oracle

Inserting Values into a TableInserting Values into a Table

• Insert command is used to insert rows in a table

• Values can be inserted for all columns or for selected columns

• At a time single can be inserted• Syntax:Insert into <table-name> (cols list)

values(…..);

Page 27: Oracle

Inserting through Parameter SubstitutionInserting through Parameter Substitution• Parameter substitution provides an easier way to

enter data into a table .The ‘&’ symbol is used as the substitution operator.When a substitution operator is used ,SQL *Plus prompts for the value of the variable , accepts it and then substitutes it in place of the variable.

• insert into ItemMast values (&ITNO, '&Name', &Qoh,‘&class','&ROD','&Rate')

• Enter value for itno: 2• Enter value for name: Cinthol Int.• Enter value for qoh: 15• Enter value for class: B

Page 28: Oracle

• Enter value for rod: 19-May-2002

• Enter value for rate: 15.76old 1: insert into ItemMast values (&ITNO, '&Name‘, &Qoh, '&class','&ROD','&Rate')

New 1: insert into ItemMast values(2,'Cinthol Int.', 15 , 'B', '19-May-2002','15.76')

1 row created.

Page 29: Oracle

Alternatively we can use like:insert into ItemMast values(&1,'&2',&3,'&4','&5',&6)

Enter value for 1: 4

Enter value for 2: XXX

Enter value for 3: 100

Enter value for 4: D

Enter value for 5: 02-Feb-2002

Enter value for 6: 100

Statement: insert into ItemMast values (&1, '&2', &3,‘ &4',‘ &5',&6)

Read As : insert into ItemMast values(4,'XXX',100,'D','02-Feb 2002',100)

1 row created.

Page 30: Oracle

Retrieve Information from TableRetrieve Information from Table

• Select statement instruct the database to retrieve information from a table.

• Syntax:

Select <column list> from <table-name>

[where <condition>]

Select * from ItemMast;

To see list of tables created by the user:To see list of tables created by the user:

Select * from TAB;Select * from TAB;

Page 31: Oracle

Alter TableAlter Table • Tables can be altered in one of the three ways:

– By adding a column to an existing table– By changing a column’s definition– By droping column

• Adding column to a table:– Alter table <table name> add(<col-name>

<datatype>);– alter table Employee add(Salary Number);– Any No. of columns can be added in single alter

command.

• Changing Column Definition:– Alter table Employee modify(Salary Number(5) NOT

NULL);

Page 32: Oracle

Dropping Column of a table :

To drop a column use :

Syntex:

Alter table <tab-name> drop column <col-name>;

eg.

Alter table Employee drop column EmpAddress;

Page 33: Oracle

Creating table with Rows from Another Creating table with Rows from Another TableTable

Create table MyTable

As

Select * from ItemMast;

Creating with different Column Creating with different Column Headings:Headings:

Create table myTable(Name,Salary)

As

Select ename, sal from Employee;

Page 34: Oracle

Creating Temporary TableCreating Temporary TableTemporary tables are only for current

session , after session only structure of table left in the database.

Create global temporary table MyTable

(

EmpId char(4),

EmpName varchar2(10)

);

Page 35: Oracle

Updating Column(s) of a TableUpdating Column(s) of a Table• UPDATE command is used to update the

columns in the table.• Values of a single column or group of columns .• Updation can be carried out for all the rows in

the table or selected rows.• Syntax:Update <Table-Name> SET <column-name> = <value>[where <condition>] Update emp set comm=500;Update emp set sal=sal+(sal*0.1);Update emp set sal=sal+500 where EmpId=‘E005’;

Page 36: Oracle

Deleting Rows from TableDeleting Rows from Table

• DELETE command is used to delete rows from a table.

• The entire row is deleted from the table.

• Specific column cannot be deleted from table

• Syntax:

Delete from <Table-Name>

[where <condition>]

Delete from emp;

Delete from emp where job=‘Clerk’;

Page 37: Oracle

Deleting Structure of a TableDeleting Structure of a Table

• To delete structure of table DROP command is used.

• Syntax:

DROP TABLE <Table-Name>;

Drop table emp;

Page 38: Oracle

Data Integrity

Enforcing data integrity ensures the quality of the data in the database. For example, if an employee is entered with an employee_id value of “123”, the database should not allow another employee to have an ID with the same value. If you have an employee_rating column intended to have values ranging from 1 to 5, the database should not accept a value of 6. If the table has a dept_id column that stores the department number for the employee, the database should allow only values that are valid for the department numbers in the company.

Two important steps in planning tables are to identify valid values for a column and to decide how to enforce the integrity of the data in the column. Data integrity falls into four categories:

Page 39: Oracle

• Entity integrity

• Domain integrity

• Referential integrity

• User-defined integrity

There are several ways of enforcing each type of integrity.• Entity: PRIMARY KEY constraint

UNIQUE constraint

• Domain DEFAULT definitionFOREIGN KEY constraintCHECK constraintNOT NULL

• Referential FOREIGN KEY constraintCHECK constraint

• User-defined All column- and table-level constraints in CREATE TABLEStored ProceduresTriggers

Page 40: Oracle

• Entity Integrity:Entity integrity defines a row as a unique entity for a particular table. Entity integrity enforces the integrity of the identifier column(s) or the primary key of a table (through indexes, UNIQUE constraints or PRIMARY KEY constraints).

• Domain Integrity:Domain integrity is the validity of entries for a given column. You can enforce domain integrity by restricting the type (through data types), the format (through CHECK constraints ), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL definitions).

Page 41: Oracle

• Referential Integrity:Referential integrity preserves the defined relationships between tables when records are entered or deleted. It is based on relationships between foreign keys and primary keys or between foreign keys and unique keys. Referential integrity ensures that key values are consistent across tables. Such consistency requires that there be no references to nonexistent values and that if a key value changes, all references to it change consistently throughout the database.When you enforce referential integrity, SQL Server prevents users from:

• Adding records to a related table if there is no associated record in the primary table.

• Changing values in a primary table that result in orphaned records in a related table.

Page 42: Oracle

Applying ConstraintsApplying ConstraintsThey are part of table definition that are used to limit the

values entered into its columns

NOT NULL:Prevents column from accepting NULL values

UNIQUE:Ensures uniqueness of the values in a column

Primary Key:Same as Unique , but only one column allowed per table

Check:Controls the value of a column(s) being inserted

Default:Assigns a default value for the column(s),at the time of insertion when no value is given for that column

References:Used to relate two tables,maintains “Referential Integrity”

Page 43: Oracle

• The constraints are declared at the time of creating creating a table with CREATE Table command.

• Constraint can be added to a table after its creation .

• All the the details of constraints are stored in Data Dictionary.

• Each constraint is assigned a name.It is easier if we give user defined names so that it is easily referenced ,otherwise the name is automatically generated of the form :

SYS_Cn Where n is unique numberWhere n is unique number• The keyword CONSTRAINT allows us to name a

new constraint .All constraint names must be unique.

Page 44: Oracle

• NOT NULL:NOT NULL:This constraint is placed immediately after

the datatype of a column .Any attempts to put NULL values in that column will be rejected .Columns without NOT NULL constraint allow NULL values.

Create table ItemMast(ITNO number(4) NOT NULL ,Name varchar2(20),QOH number(5));

Page 45: Oracle

• UNIQUE:UNIQUE:This constraint ensures that the values entered into

the column are UNIQUE..Create table ItemMast(Create table ItemMast(ITNO number(4) UNIQUE ,ITNO number(4) UNIQUE ,Name varchar2(20),Name varchar2(20),QOH number(5));QOH number(5));

Columns with Unique constraint allows NULL ,but if we want to restrict the same , use NOT NULL along with UNIQUE constraint

Create table ItemMast(Create table ItemMast(ITNO number(4) NOT NULL UNIQUE ,ITNO number(4) NOT NULL UNIQUE ,Name varchar2(20),Name varchar2(20),QOH number(5));QOH number(5));

Page 46: Oracle

We can also define a group of columns as UNIQUE table constraint.Declaring a group of column as UNIQUE , differs from declaring the individual columns as unique

Create table ItemMast(Create table ItemMast(ITNO number(4) NOT NULL,ITNO number(4) NOT NULL,

Name varchar2(20) NOT NULL,Name varchar2(20) NOT NULL,

QOH number(5),QOH number(5),

UNIQUE(ITNO,Name));UNIQUE(ITNO,Name));

Applying constraint Name:Create table ItemMast(Create table ItemMast(

ITNO number(4) NOT NULL constraint MYCons UNIQUE ,ITNO number(4) NOT NULL constraint MYCons UNIQUE ,

Name varchar2(20),Name varchar2(20),

QOH number(5));QOH number(5));

Page 47: Oracle

• PRIMARY KEY:PRIMARY KEY:

This key also ensures unique values , but it differs from UNIQUE as – it does not allow NULL – Only one Primary Key can be declared in a table.– It can also apply to multiple columns , forcing a

unique combination of values.Create table ItemMast(Create table ItemMast(ITNO number(4) Primary Key,ITNO number(4) Primary Key,Name varchar2(20) NOT NULL,Name varchar2(20) NOT NULL,QOH number(5));QOH number(5));

Create table ItemMast(Create table ItemMast(ITNO number(4),ITNO number(4),Name varchar2(20),Name varchar2(20),QOH number(5),QOH number(5),PRIMARY KEY(ITNO,Name));PRIMARY KEY(ITNO,Name));

Page 48: Oracle

• CHECK:CHECK:

This allows the user to define a condition ,that a value entered into the table ,has to satisfy,before it can be accepted.The CHECK Constraint consists of the keyword CHECK followed by parenthesized conditions.Any attempt to update or insert column values that will make the condition false , will give an error.Create table ItemMast(Create table ItemMast(ITNO number(4) Primary Key,ITNO number(4) Primary Key,Name varchar2(20) NOT NULL,Name varchar2(20) NOT NULL,QOH number(5) CHECK (QOH >10));QOH number(5) CHECK (QOH >10));

Create table ItemMast(Create table ItemMast(ITNO number(4),ITNO number(4),Name varchar2(20) Check (Name in (‘Lux’,’Cinthol’,’Denim’)),Name varchar2(20) Check (Name in (‘Lux’,’Cinthol’,’Denim’)),QOH number(5));QOH number(5));

Page 49: Oracle

Create table ItemMastCreate table ItemMast((

ITNO number(4) Primary Key,ITNO number(4) Primary Key,Name varchar2(20) NOT NULL,Name varchar2(20) NOT NULL,QOH number(5) ,QOH number(5) ,Check ((Name=‘Lux’ and QOH Check ((Name=‘Lux’ and QOH >=10) OR (Name=‘Cinthol’ and >=10) OR (Name=‘Cinthol’ and QOH >=20))QOH >=20))

););

Page 50: Oracle

• DEFAULT:– This is used insert a value in the column when

user is not entering any value for that column.

Create table ItemMastCreate table ItemMast((

ITNO number(4) Primary Key,ITNO number(4) Primary Key,Name varchar2(20) Default ‘Lux’,Name varchar2(20) Default ‘Lux’,QOH number(5) ,QOH number(5) ,Check ((Name=‘Lux’ and QOH >=10) Check ((Name=‘Lux’ and QOH >=10) OR (Name=‘Cinthol’ and QOH >=20))OR (Name=‘Cinthol’ and QOH >=20))

););

Page 51: Oracle

REFERENCES:REFERENCES:A foreign key is a combination of columns with values with values

based on the primary key values from another table.A foreign key constraint, also known as Referential Integrity Constraint , specifies that the values of the foreign key correspond to actual values of the primary key in another table .

Create table ItemTran(Create table ItemTran(

ITNO number(4) references ITEMMAST(ITNO),ITNO number(4) references ITEMMAST(ITNO),

TranType char(1) check (trantype in(‘I’,’R’)),TranType char(1) check (trantype in(‘I’,’R’)),

TranDate date,TranDate date,

Qty number(5));Qty number(5));

Create table ItemTran(Create table ItemTran(

ITNO number(4),ITNO number(4),

TranType char(1) check (trantype in(‘I’,’R’)),TranType char(1) check (trantype in(‘I’,’R’)),

TranDate date,TranDate date,

Qty number(5),Qty number(5),

Foreign key(ITNO) references ITEMMAST(ITNO));Foreign key(ITNO) references ITEMMAST(ITNO));

Page 52: Oracle

• ON DELETE CASCADE OPTION:– Using this option whenever a parent row is deleted then

all the corresponding child rows are deleted from the detail table.This option is always used with FOREIGN KEY.

Create table ItemTran(Create table ItemTran(

ITNO number(4) references ITEMMAST(ITNO) ITNO number(4) references ITEMMAST(ITNO) ON DELETE CASCADE,ON DELETE CASCADE,

TranType char(1) check (trantype in(‘I’,’R’)),TranType char(1) check (trantype in(‘I’,’R’)),

TranDate date,TranDate date,

Qty number(5));Qty number(5));

Page 53: Oracle

Querying Database TablesQuerying Database Tables

• The Select statement instructs the database to retrieve information from table.

• Syntax:Select <column list> from <table-name>[Where Condition>[Group By Column Name(s)>][Having <condition>][Order by <expression>]• Examples:• Select * from emp;• Select EmpName,Salary from Emp;

Page 54: Oracle

Conditional Retrieval of Rows:• The Where clause is used along with the SELECT

statement to specify the condition ,based on which the rows will be extracted from the table with SELECT

• The where clause is case-sensitive• Operators are used to specify conditions:

– Relational Operators:=,>,>=,<,<=,<>,!=

– Logical Operators:AND, OR ,NOT

– Special Operators:IN,BETWEEN,LIKE

Page 55: Oracle

• Examples:• Select * from emp where deptno=20;• Select ename,sal from emp where sal>20;• Select empno,ename from emp where job= ‘MANAGER’

• Select ename from emp where job=‘CLERK’ and deptno=20;

• Select ename from emp where job=‘CLERK’ or job=‘ANALYST’;

• Select * from emp where hiredate <= ’30-SEP-81’;• Select ename from emp where job <> ‘MANAGER’• Select ename from emp where enpno in(7369,7521,7839);• Select * from emp where deptno NOT IN (10,20,30);• Select enam,sal from emp where sal between 1000 and 2000 • Select ename from emp where hiredate not between ’30-

JUN-81’ and ’31-DEC-81’;

Page 56: Oracle

DISTINCT ClauseDISTINCT Clause :

• DISTINCT clause is used with select to suppress duplicate values if any in a column.

• SELECT DISTINCT job from emp;

Page 57: Oracle

NULL values:NULL values:

• NULL values are not 0 or a blank.

• It represents an unknown or inapplicable value.

• It cannot be compared using the relational and /or logical operators.

• The special operator ‘IS’ is used with the keyword ‘NULL’ to locate NULL values

• Select ename from emp where deptno IS NULL;

• Select ename from emp where deptno IS NOT NULL;

• Select * from emp where sal > 2000 and comm is NULL;

Page 58: Oracle

Matching a pattern with a columnMatching a pattern with a column

• The LIKE operator is used.

• It can only used with CHAR and VARCHAR2

• ‘%’ represents a sequence of zero or more characters

• ‘_’ stands for single character

• Examples:

• Select ename from emp where ename like ‘S%’

• Select ename from emp where ename like ‘%S’

• Select ename from emp where ename like ‘_____’

• Select ename from emp where ename like ‘_I%’

Page 59: Oracle

User friendly Column User friendly Column HeadingsHeadings

• We can change the names of columns at the time of select statement

• Syntax:Select <actual col-name> “<user-def

name>” from <table-name>Select id “EMPID” from EmployeeSelect id as “EMPID” from EmployeeSelect ename, sal,sal*0.1 “PF” from emp

Page 60: Oracle

Ordering Results of a QueryOrdering Results of a Query• SQL uses the ORDER BY clause to impose an order

on the result of a query.• ORDER BY clause is used with SELECT statement.• Syntax:

Select <col-list> from <table-name>[Where condition][ORDER BY <columns>][ASC|DESC]

The order by clause orders(sorts) the query output according to the values in one or more selected columns.By default it orders in Ascending order.

ORDER BY must always be the last clause in the SELECT statement.

Page 61: Oracle

Order BY contd…Order BY contd…• List the empno,ename, sal in ascending

order of salarySelect empno, ename, sal from emp order by sal;Select empno, ename, sal from emp order by sal;

• List the Employee Name , salary,Job and Dept No. is ascending order of Department and then on descending order of salary:Select deptno, job, ename, sal from emp order by Select deptno, job, ename, sal from emp order by DeptNo, Sal DESC;DeptNo, Sal DESC;

Page 62: Oracle

Ordering output by Column NumberOrdering output by Column Number

• In place of column names,we can use numbers to indicate the fields being used to order the output.These numbers will refer, not to the order of the columns in the table, but to their orders in the output.

• Example:Select empno, ename, sal from emp order by 3;

Page 63: Oracle

Aggregate FunctionsAggregate FunctionsAggregate functions are used to

produce summarized results. They operate on set of rows. They return results based on groups . By default all rows in a table are treated as one group . The aggregate functions produce a single value for an entire group or table.

Page 64: Oracle

• COUNT:–It determines the number of rows/ no-

NULL column values.If * is passed , then the total number of rows is returned.

List the no. of employees working with the company:

SELECT COUNT(*) FROM emp;List no. of jobs available in the emp t

able:SELECT COUNT(DISTINCT job) from

emp;

Page 65: Oracle

• SUM:The sum function returns the sum of values for the select list of columns.

Select Sum(sal) from emp;• MAX:This returns the maximum value of the

selected list of item.Select MAX(sal) from emp where

job=‘Salesman’;• MIN:This returns the minimum value of the

selected list of item.Select MIN(sal) from emp where

job=‘Salesman’;• AVG:Returns the average of column values.Select AVG(sal) from emp;

Page 66: Oracle

Grouping the Result of a QueryGrouping the Result of a Query• The Group By clause is used to divide the rows in a table

into smaller groups.• The Group By clause is used with SELECT clause• SQL groups the result after it retrieves the rows from

the table.• Conditional retrieval of rows from grouped result is

possible with the HAVING clause• Syntax:

Select <col-list> from <table>

[where condition]

GROUP BY <col>

[HAVING <condition>]

Page 67: Oracle

• List the department numbers and the number of employees in each department

Select deptno,count(*) from emp GROUP BY deptno;• List the dep no. and the total salary payable in each

dept:Select deptno,sum(sal) from emp group by deptno;• List the jobs and the number of employees in each

job.The result should be in descending order of the number of employees:

Select job,count(*) from emp group by jobOrder by 2 desc;• List the total salary maximum & minimum salary and

average salary of employees job wise:Select job,sum(sal),avg(sal),max(sal),min(sal) from emp

group by job.

Page 68: Oracle

• List the average salary from each job excluding managers:

Select job,AVG(sal) from empWhere job!=‘MANAGER’ group by job• Groups within groups:Group by clause can be used to provide

results for groups within groups.• List the average monthly salary for

each job type within departmentSelect deptno,job,avg(sal) from emp

group by deptno,job;

Page 69: Oracle

The HAVING ClauseThe HAVING Clause• HAVING clause is used to specify the condition on

Group By clause like Where Clause select is used with SELECT.

• List average salary for all departments employing more than five people:

• SELECT deptno,AVG(sal) from emp GROUP BY deptno HAVING count(*) >= 5;

Page 70: Oracle

JOINSJOINS• Joins are used to combine

columns from different tables.• The connection between tables is

established through the where clause.

• Types of Joins:Equi Joins, Cartesian Joins,Outer Joins, Self Joins.

Page 71: Oracle

One of the most important features of SQL is the ability to define relationships between multiple tables and draw the information from them in terms of these relationships , along within a single command.With joins , the information from any number of tables can be accessed.

To join two tables, the retrieval criteria will typically specify the condition that a column in the first table (which is defined as foreign key) is equal to a column in the second table (which is primary key referenced by the foreign key)A join’s where clause may contain additional conditions.In a join , the table names are listed in the from clause separated by commas.

Page 72: Oracle

SyntaxSyntaxSELECT SELECT <select-list> from table1> , <table2> ,…., <tableN><select-list> from table1> , <table2> ,…., <tableN>

Where <table1.col1>= <table2.col2> and…………Where <table1.col1>= <table2.col2> and…………

<table2.col3>= <tableN.colN>………….<table2.col3>= <tableN.colN>………….

Additional –conditionsAdditional –conditions

<select-list>:<select-list>:set of cols and expressions from <table1> through <tableN>

<table1> through <tableN>:<table1> through <tableN>: tables from which column values are retrieved

<col1>through <colN>:<col1>through <colN>:the columns in <table1> through <tableN> that are related

Addition conditionsAddition conditions are optional query criteria

Page 73: Oracle

EQUI JOINS:When two tables are joined together using equality

of values in one or more columns ,they make an Equi Join.Table prefixes are utilized to prevent ambiguity and the where clause specifies the columns being joined.

Example:

List the employee numbers,names , department numbers and the department name:

SELECT empno,ename,emp.deptno ,dname from emp , dept

where emp.deptno=dept.deptno

EQUI JOINS:When two tables are joined together using equality

of values in one or more columns ,they make an Equi Join.Table prefixes are utilized to prevent ambiguity and the where clause specifies the columns being joined.

Example:

List the employee numbers,names , department numbers and the department name:

SELECT empno,ename,emp.deptno ,dname from emp , dept

where emp.deptno=dept.deptno

Page 74: Oracle

Table AliasesTable Aliases• It can be very tedious to type the table names

repeatedly.Temporary labels(or aliases) can be used in the FROM clause .These temporary names are valid only for the current select statement.Table aliases should also be specified in the select clause.Table aliases should can be up to 30 character in length , but the shorter they are better.

The advantage of using table aliases is that it The advantage of using table aliases is that it effectively speeds up the queryeffectively speeds up the query

SELECT e.empno,e.ename,e.deptno ,d.dname from emp e, dept d

Where e.deptno=d.deptno

Page 75: Oracle

Cartesian JoinsCartesian Joins• When no join condition clause is specified in

WHERE clause, each row of one table matches every row of the other table.This results in a Cartesian product.

SELECT empno, ename, dname, loc from emp, dept;

If the number of rows are 14 and 4 in emp and If the number of rows are 14 and 4 in emp and dept tables respectively ,then the total number dept tables respectively ,then the total number of rows produced is 56.of rows produced is 56.

Cartesian product is useful in finding out all the possible combination of columns from different tables.

Page 76: Oracle

Consider following tables and data present:• Tab1:Holds principal amount.• Tab2:Holds year and rate of interest .

• Finding the possible combinations of calculation of amount, a Cartesian join of Tab1 and Tab2 is required.The formula for calculation of Amount is Pricipal*(1+(rate/100))year

• Select Principal, Year, Rate, Principal* POWER(1+(rate/100),year) from TAB1,TAB2

Tab1PRICIPAL

1000

2000

3000

Tab2YEAR RATE

1 10

2 11

3 11.5

4 12

Page 77: Oracle

Outer JoinsOuter JoinsIf there are any values in one table that do not have

corresponding value(s) in the other , in an equi join that row will not be selected.Such rows can be forcefully selected by using the outer join symbol(+) . The corresponding columns for that row will have NULLs.

Example:Display the list of employees working in each department .Display the department information even if no employee belongs to that department:

SELECT empno, ename, emp.deptno, dname, loc from emp, dept where emp.deptno(+) = dept.deptno;

Page 78: Oracle

Rules to place(+) operatorRules to place(+) operator

•The outer join symbol(+) can not be on both the sides

•It is possible between only two tables

Page 79: Oracle

Self Join:Self Join:• To join a table to itself means that each row of the table

is combined with itself and with every other row of the table.The self join can be viewed as a join of two copies of the same table .The table is not actually copied , but SQL performs the command as though it were.

• The syntax of the command for joining table to itself as almost same as that for joining two different tables.To distinguish the column names from one another , aliases for the actual table name are used , since both the tables have the same name .

• Example:To list out the names of the manger with the employee record one will have to join EMP with itself

Select Worker.ename,Manager.ename "Manager"from emp Worker , emp Managerwhere Worker.mgr=Manager.empno;

Page 80: Oracle

• List all employees who joined the company before their manager

Select e.ename,e.hiredate,m.ename manager , m.hiredate

From emp e, emp m

WHERE e.mgr=m.empno

and e.hiredate< m.hiredate

Page 81: Oracle

• SET OperatorsSET Operators :SET Operators are used to combine information of similar type from one or more than one table.

• Datatype of corresponding columns must be the same• The types of SET Operators are:

– UNION:Rows of the first query plus rows of the second query, less duplicate rows

– INTERSECT:Common rows from all the queries– MINUS :Rows unique to the first query

• SET operator combine two or more queries into one result.

• Suppose we want following three details from dept table– List of all the different designations in department 20 and 30– List the jobs common to department 20 and 30– List the jobs unique to department 20

• To get these combination of information the SET operators UNION, INTERSECT and MINUS are used.

Page 82: Oracle

UNION:UNION:• The union clause merges the outputs of two or

more queries into single set of rows and columns.• Syntax:

Select <stmt1>UNIONSelect <stmt2>[Order BY clause]

Display the different designations in department 20 and 30

Select job from emp where deptno=20UNION Select job from emp where deptno=30

Page 83: Oracle

Points to kept in mind:Points to kept in mind:• The two select statement may not contain an

ORDER BY clause,however the final result of the entire UNION operator can be ordered

• The no. of columns retrieved by the first select must be equal to no. of cols. retrieved by the second statement.

• The data types of cols retrieved by the select statement must be same

Select empno,ename from emp where deptno=20UNION Select empno,ename from emp where deptno=30Order by 1

Page 84: Oracle

INTERSECTINTERSECT• The INTERSECT operator returns the rows that

are common between two sets of rows.• Syntax:

Select <stmt1>INTERSECTSelect <stmt2>[Order BY clause]

Display the jobs common to department 20 and 30

Select job from emp where deptno=20INTERSECT Select job from emp where deptno=30

Page 85: Oracle

MINUS:MINUS:• The MINUS returns the rows unique to first query.• Syntax:

Select <stmt1>MINUSSelect <stmt2>[Order BY clause]

Display the jobs unique to department 20Select job from emp where deptno=20MINUS Select job from emp where deptno=10MINUSSelect job from emp where deptno=30

Page 86: Oracle

NESTED QUERIESNESTED QUERIES• If we want List Employees belonging to department

of MILLER:– We have to use two query statements,first of all we

have to do determine the department number of MILLER like:

SELECT deptno from emp where ename=‘MILLER’;– Then we will use the the deptno to find out the other

Employees something like:SELECT ename from emp where deptno=10;– We can combine the above two query statements into

single something like:– SELECT ename from emp where deptno=(SELECT

deptno from emp where ename=‘MILLER’);THIS IS NESTED QUERY i.e; Query inside another QUERY THIS IS NESTED QUERY i.e; Query inside another QUERY

Page 87: Oracle

SQL has an ability to nest queries within one another.A subquery is a SELECT statement that is nested within another SELECT statement and which returns intermediate results .SQL first evaluates the inner query (subquery) within the WHERE clause .The inner query generates values that are tested in the predict of the outer query ,determining when it will be true.The return value of inner query is then substituted in the condition of the outer query.

Advantages:Advantages:– Subqueries allows a developers to build powerful

commands out the simple one.– The nested queries is very useful when you need

to select rows from a table with a condition that depends on the data in the table itself.

Page 88: Oracle

• List the names of the employee drawing the highest salary:

Select ename from emp where sal=(select max(sal) from emp);

• List all employee details whose salary is greater than average salary of employees whose hiredate is before ’01-APR-1981’:

Select * from emp where sal > (select avg(sal) from emp where hiredate <’01-APR-1981’);

Page 89: Oracle

DISTINCT clause:DISTINCT clause:It use to force the query to return single

value.Select * from dept where deptno=(select

distinct deptno from emp where mgr=‘7698’);

Subqueries that return more than one row:Subqueries that return more than one row:List of employees, who earn lowest salary in

each department:SELECT ename,sal,deptno from emp where

sal IN(SELECT MIN(sal) from emp group by deptno);

Page 90: Oracle

Points to be kept in MINDPoints to be kept in MIND• The inner query must enclosed in

parenthesis• The inner query must be on the right hand

side of the condition.• The subquery may not have an order by

clause .• The ORDER BY clause appears at the end

of the main SELECT statement.• Subqueries are always executed from the

most deeply nested to the least deeply nested.

Page 91: Oracle

Correlated SubQuery:Correlated SubQuery: A correlated subquery is a nested subquery which is executed for each ‘candidate row’ considered by the main query and which on execution uses a value from the column of the outer query.

• In a correlated subquery , the column value used in inner sub query refers to the column value present in the outer query forming a correlated query .The subquery is executed repeatedly , one for each row of the main (outer) query table.

• Employees earn salary greater than the average salary for their dept:SELECT empno,ename,sal,deptno from emp e where sal >(select AVG(sal)

from emp where deptno=e.deptno);

Correlated subquery is used to answer multi-part questions whose answer depends on the value of each row of the parent query.The inner select is normally executed once for each candidate row.

Page 92: Oracle

Special Operators in SubqueriesSpecial Operators in Subqueries

EXISTS:EXISTS:

• Used to check the existence of values

• Produces Boolean result

ANY,SOME and ALL:ANY,SOME and ALL:

• Used along with relational operators

• Similar to IN ,but only used in subqueries

• The SOME and ANY can be used interchangeably

Page 93: Oracle

EXISTS:EXISTS:• List all employees who have at least one person List all employees who have at least one person

reporting to them:reporting to them:

SELECT empno,ename,job,deptno from emp e where EXISTS (select empno from emp where emp.mgr=e.empno);

• List the employee detail if any and only if more than 2 List the employee detail if any and only if more than 2 employees are present in department number 10: employees are present in department number 10:

Select * from emp where deptno= 10 and EXISTS ( select count(*) from emp where deptno=10 GROUP BY deptno HAVING COUNT(*) > 2);

• List all employees details who do not manage any one:List all employees details who do not manage any one:

SELECT ename,job from emp e WHERE NOT EXISTS (Select mgr from emp where mgr=e.empno);

Page 94: Oracle

• ANY OperatorANY Operator:It compares the lowest value from the set

• List the employee names whose salary is greater than the lowest salary of an employee belonging to department number 20:

SELECT ename from emp where sal > ANY(select sal from emp where deptno=20);

• List the employee details of those employee whose salary is greater than any of the managers:

SELECT empno,ename,sal from emp where sal > ANY(select sal from emp where JOB=‘manager’);

Page 95: Oracle

• ALL Operator:ALL Operator: In case of ALL operator the predicate is true if every value selected by the subquery satisfies the condition in the predicate of the outer query.

• Example:

List the employee names whose salary is greater than the highest salary of all employee belonging to department number 20:

Select ename from emp where sal > ALL (select sal from emp where deptno=20);

Page 96: Oracle

FUNCTIONSFUNCTIONSThey are used to manipulate data items.Advantages:Advantages:

• Perform complex calculations on data

• Can modify individual data items

• Can very easily manipulate output for group of rows.

• Can alter date format for display

Types:Types:

• Single Row Function(Column Function)

• Group Function

Page 97: Oracle

DUAL TABLEDUAL TABLE• DUAL table is a table with only one

row and column in it.It is owned by ‘SYS’ and can be accessed by all users.It contains one column, DUMMY and one row with value X.The DUAL table is useful to return a value only once-for instance , the value of a constant , psuedo_column or expression that is not derived from a table with ‘user’ data.

• Desc DUAL;

Page 98: Oracle

• Column Functions:As they work on columns. They are:

• Arithmetic Functions:Arithmetic Functions:

• ABS(n):Returns absolute value of the column or values passed

• SELECT ABS(-65) from dual;

• CEIL(n):Finds the smallest integer greater than or equal to n.

• Select CEIL(89.9) from dual;

• FLOOR(n):Finds the largest integer less than or equal to n.

• Select FlOOR(89.9),CEIL(89.9) from DUAL;

Page 99: Oracle

• MOD(m,n):Returns the remainder of m divided by n ; or m if n=0

SELECT MOD(200,30) from dual;• POWER(m,n):Returns m raised to power nSelect power(2,2) from DUAL;• SIGN(n): Returns –1 if n is negative, it returns 1 if n is

positive and it returns 0 if n is 0.Select sign(-1) from dual;• SQRT(n):Returns square root of n.Select sqrt(81) from dual;• trunc(m,[n]):This truncates the m or column to n

decimal places .If n is omitted then it is truncated to no decimal places.If n is negative then numbers left of decimal places are truncated to 0;

Select trunc(90.723,1), trunc(90.723,-1), trunc(90.723) from dual

Page 100: Oracle

• ROUND(m,[n]):This rounds the m or column to n decimal places .If n is omitted then it is rounded to no decimal places.If n is negative then numbers left of decimal places are rounded to 0;

Select round(90.723,1), round(90.723,-1), round(90.723) from dual;

• EXP(n):This returns e raised to the nth power.

Select exp(4) from DUAL;

Page 101: Oracle

Character FunctionsCharacter FunctionsWorking with charactersWorking with characters

• CHR(x):Returns the character given to character number

Select chr(65) from DUAL;• ASCII(x):Returns the ASCII value of given character Select ASCII(‘A’) from DUAL;• CONCAT(str1,str2):Returns str1 concatenated with

str2.Select concat(‘Anu’,’Rag’) from DUAL;• INITCAP(string):Capitalize the first character of each

word in the string.Select initcap(‘anurag’) from dual;• LOWER(string):Converts string to lower case.SELECt lower(‘ANU’) from DUAL;

Page 102: Oracle

• UPPER(string):Converts string to upper case.Select upper(‘anu’) from DUAL;• LPAD(char1,n[,char2]):This fills(pads) the column

value from left , to a total width of n characters positions.The leading spaces are filled with char2.If string is omitted value is padded with spaces.

Select lpad(dname,15,’$’),lpad(dname,15,’ ‘) , dname from dept;

• RPAD(char1,n[,char2]):This fills(pads) the column value to the right , to a total width of n characters positions.The trailing spaces are filled with char2.If string is omitted value is padded with spaces.

Select rpad(dname,15,’$’),rpad(dname,15,’ ‘) , dname from dept;

Page 103: Oracle

• LTRIM(string,’char/s’):Removes all blank spaces from the left .If char/s is specified it removes from the left leading occurrences of char.

Select dname,LTRIM(dname),LTRIM(dname,’R’) from DEPT;

• RTRIM(string,’char/s’):Removes trailing occurrence(s) of all blank spaces .If char/s is specified it removes from the right trailing occurrences of char.

Select dname,RTRIM(dname),RTRIM(dname,’S’) from DEPT;

REPLACE(string,search_str[,replace_str]):This returns string with every occurrence of search_str replaced with replace_str.If replace_str is not specified, all occurrences of search_str are removed.

Select replace(‘This and That’,’Th’,’B’) from dual;Select replace('This and That','Th') from dual;

Page 104: Oracle

• SUBSTR(string,m[,n]):Returns substring, n characters long from the string specified, starting at position number m .If n is not specified the string is extracted from position m to end.

Select dname , SUBSTR(dname,2,4) , SUBSTR(dname,4) from dept;

• TRANSLATE(string,from_str,to_str):This returns string with all occurrences of each character in from_str replaced by corresponding character in to_str.

select translate(‘abcdefghij’,’abcdef’,’123456’) from dual;

select translate('abcdefghij','abcdefghij','123456') from dual;

Page 105: Oracle

• INSTR(string,char):Returns position of first occurrence of ‘char’ in ‘string’.

Select dname,instr(dname,e) from dept;

• LENGTH(string):Returns length of string.

Select length(‘Anu’) from dual;

Page 106: Oracle

Date FunctionsDate Functions• They are used to manipulate date.All date

function returns a value of DATE data type except MONTHS_BETWEEN which returns a numeric value.

• SYSDATE:It is a psuedo-column that returns the current date and time of type DATE.The SYSDATE can be used just as any other column name.

SELECT SYSDATE from DUAL;• ADD_MONTHS(d,n):Adds or subtracts to or

from a date.Returns date as resultSelect hiredate , add_months(hiredate,4) ,

add_months(hiredate,-4) from emp;

Page 107: Oracle

Click Me for Date FormatSelect to_char(’14-AUG-96’,’RM’) from DUAL;Select to_char(’14-AUG-96’,’RM’) from DUAL;

SELECT TO_CHAR(TO_DATE('12-APR-71 13:21:00‘ , SELECT TO_CHAR(TO_DATE('12-APR-71 13:21:00‘ , 'DD-MON-YY HH24:MI:SS'),'HH:MI') FROM DUAL'DD-MON-YY HH24:MI:SS'),'HH:MI') FROM DUAL

Page 108: Oracle

• ROUND(d[,format]):Rounds date d to the unit specified by format.If format is not specified, it defaults to ‘DD’,which rounds d to the nearest day.

Select round(to_date(’14-AUG-76’),’MM’) from Dual;• TRUNC(d[,format]):This function returns the date d

truncated to the unit specified by format.If format is not specified, it defaults to ‘DD’,which truncates to the nearest day.

Select trunc(to_date(’14-AUG-76’),’MM’) from Dual;• MONTHS_BETWEEN(d1,d2):Returns number of

months between two dates,d1 and d2.If d1 is later than d2,the result is positive,if d1 is earlier than d2 ,the result is negative.The output will be a number.

Select months_between(’02-FEB-02’,’02-AUG-02’), months_between(’02-AUG-02’,’02-FEB-02’) from dual;

Page 109: Oracle

• LAST_DAY(d):Returns the date of the last day of the month specified.The result will be a date.

SELECT sysdate,last_day(sysdate) from dual;

• NEXT_DAY(date,day):Returns the date of next specified day of the week after the ‘date’.

SELECT sysdate,next_day(sysdate) from dual;

TO_CHAR(d,f):this function converts the date ‘d’ to character format ‘f’.

SELECT sysdate,TO_CHAR(sysdate,’DAY’) from dual

Page 110: Oracle

GENERAL FUNCTIONsGENERAL FUNCTIONs• GREATEST(expr1[,expr]…):This returns the greatest

expression of its arguments.• Select greatest(10,7,-1) from dual;• LEAST(expr1[,expr]…): This returns the least

value in the list of expressions.• Select least(10,7,-1) from dual;• NVL(col,value):The columns with NULL values are

ignored in all of the group functions such as SUM,AVG etc.Also in arithmetic expression ,if the column contains NULL ,will not provide any useful information.The NVL function helps in substituting a value in place of a NULL.The data type of the value to substituted must match with col data type

• Select ename,sal,comm,sal+comm GROSS ,sal+NVL(comm,0) “New Gross” from emp;

Page 111: Oracle

• TRANSLATE(char,find,new):This function returns ‘char’ with each ‘find’ changed to ‘new’.All occurrences of find are replaced with corresponding character in new.If corresponding new character is not supplied,then find char is removed.

Select dname,translate(dname,’e’,’l’) from dept;DECODE(C,V1,S1,V2,S2,…,D):This function does a ‘if-

then-else’.A default value can also be specified with DECODE function,which is substituted,in case nothing matches from the set.’C’ which is either column or expression is compared to each ‘V’ and substitutes ‘S’ if ‘C’ equals the search value.If no match is found , the DECODE function returns the ‘D’ which is default value.If default value is omitted ,NULL is returned for unmatched values.

Select ename , job , DECODE(job,’CLERK’,’EXEC’, ’MANAGER’,’RM’,job) from emp;

Page 112: Oracle

• UID:this returns an integer that uniquely identifies the current database user.It takes no arguments.

SELECT UID from dual;

• User:this returns a VARCHAR2 value containing the name of the current Oracle user.USER takes no arguments.

SELECT USER from dual;

Page 113: Oracle

• SEQUENCES A sequence is database object used to generate unique integers for use as primary keys.

• Syntax:

Create SEQUENCE <seq-name> INCREMENT by <n>]Start with <m>]MAXVALUE N|NOMAXVALE]MINVALUE N|NOMINVALUE]Where:<seq-name><seq-name> name of sequence<n><n> increment specified by userStart withStart with number with which the sequence will beginMINVALUEMINVALUE lower boundMAXVALUEMAXVALUE upper bound

Page 114: Oracle

• CREATE SEQUENCE empnumber INCREMENT BY 1 START WITH 1;

• Generating Sequence Numbers:A pseudo column NEXTVAL is used:

– Select empnumber.NEXTVAL from dual;

• Use in table: create table checking (id number(5),name varchar2(10));• insert into checking values( empnumber.NEXTVAL , 'Anu');

• select * from checking;• Output: ID NAME

--------- ---------- 1 Anu

Page 115: Oracle

• insert into checking values( empnumber.NEXTVAL , ‘Dipti');

• select * from checking;Output: ID NAME--------- ---------- 2 Dipti

• Checking Current Value :Checking Current Value :The pseudo column CURRVAL is used for this

purpose.It tells the last value.Select empnumber.CURRVAL from dual;

• To see list of SEQUENCES created by user:To see list of SEQUENCES created by user:• Select * from USER_SEQUENCES;

Page 116: Oracle

• Altering SEQUENCES:Altering SEQUENCES:Alter SEQUENCE <seq-name> INCREMENT by <n>]

MAXVALUE N | NOMAXVALE]

MINVALUE N | NOMINVALUE]• ALTER SEQUENCE empnumber INCREMENT BY 2;ALTER SEQUENCE empnumber INCREMENT BY 2;

NOTENOTE::This alter sequence command will not affect the This alter sequence command will not affect the sequence number created earlier.Only future sequence sequence number created earlier.Only future sequence numbers are affected by the ALTER SEQUENCE numbers are affected by the ALTER SEQUENCE statement.statement.START WITHSTART WITH value cannot be changed using value cannot be changed using ALTER .The sequence must be dropped and recreated in ALTER .The sequence must be dropped and recreated in order to restart a sequence at different number.order to restart a sequence at different number.

Removing SEQUENCES:Removing SEQUENCES:

Drop sequence <seq name>

Drop sequence empnumber;