You are on page 1of 133

Oracle is a relational database product which is used to store data permanently in secondary

storage devices.
If any user wants to communicate with oracle database then user must use SQL language.
Before user using SQL language that user must connect to the database. If that user wants to
connect to the database then user should use tools like SQL-Plus tool, Toad tool, SQL
navigator, SQL developer.
In oracle each version having two editions these are
1. Express Edition
2. Enterprise Edition
In these two editions default username is SYSTEM and password is MANAGER and SYS
AS SYSDBA and password is SYS.
Oracle provided another user SCOTT along with system user within enterprise edition. This
user having predefined tables.
CONNECT, CONN are the two keywords used for connecting oracle database.
For Connecting to Database:
SQL> CONN
Enter user-name: sys as sysdba
Enter password: sys
Connected.
SQL> CONNECT
Enter user-name: system
Enter password: manager
Connected.

Lock & Unlock the users:


Locking and unlocking the users is performed only when we connected to DBA users. This
can be performed by alter command.
Syntax: alter user username account lock/unlock;
For Locking the user:
Syntax: alter user username account lock;
SQL> conn
Enter user-name: system/manager;
Connected.
SQL> alter user scott account lock;
User altered.
Testing: SQL> conn
Enter user-name: scott/tiger;
ERROR: ORA-28000: the account is locked
Warning: You are no longer connected to ORACLE.
For Unlocking the user:
Syntax: alter user username account unlock;
SQL> conn
Enter user-name: system/manager;
Connected.
SQL> alter user scott account unlock;
User altered.
Testing: SQL> conn
Enter user-name: scott/tiger;
Connected.

To clear the screen:


SQL> cl scr; (or) shift+delete
To show the username:
SQL> show user;
USER is "SCOTT"
To disconnect:
SQL>exit;
To execute previous command:
SQL> / forward slash

For creating spool:


Syntax: spool on;
spool drivename: foldername.type of file
spool off; (or) exit;

SQL>spool on;
SQL> spool F:uma_sql.doc
SQL>spool off; (or) exit;
For appending data into file:
Syntax: spool on;
spool foldername.type of file append;
spool off;

SQL>spool on;
SQL>spool uma_sql.doc append;
SQL>spool off;

To view all tables available in the user:


SQL> select * from tab;

TNAME TABTYPE CLUSTERID

EMP TABLE

DEPT TABLE

BONUS TABLE

SALGRADE TABLE

DUMMY TABLE

To view particular table data:

Syntax: select columnname1, columnname2...(or) *(for all rows) from tablename;

SQL> select * from dept;


DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

To set environment:

When we are try to display EMP table in SQL Plus tool in that table automatically some
gapes are generated because by default in SQL Plus every line having 80 characters. when we
are changing this line size by using SQL-Plus command then automatically gapes are
avoided in EMP table.

Syntax: set line number; (or) set linesize number;

SQL>set line 100; (or) set linesize 100;

When we are try to display EMP table in SQL Plus tool in that table for every 14 rows
the table data definitions are comes because for one page there are 14 rows only. when we are
changing this pagesize by using SQL-Plus command then automatically data definitions are
avoided.

Syntax: set pagesize number;

SQL>set pagesize 50;

SQL: (Structured Query Language)

SQL is a non-procedural language which is used to operate relational database products. (or)
a language that used to communicate with the oracle server.

User communicates with oracle server by sending commands/instructions are called queries.

A query is a question/command/instruction submitted to oracle server to perform some


operation over database.

In 1970 E.F.CODD introduced DSL/ALPHA language for operating relational database


products.

Later IBM company SYSTEM/R team developed modified version of DSL/ALPHA language
and named it as SQUARE. Again IBM company modified SQUARE into SEQUEL
(Structured English Query Language). Again IBM modified it into SQL (Structured Query
Language).

SQL is a structured query language having ANSI Standards from this ANSI-SQL. oracle
creating Oracle SQL.
SQL Sub Languages:

Based on operations over database SQL is categorized into following sub languages. These
are DDL, DML, DQL, TCL, DCL.

1. DDL: (Data Definition Language)

Set of commands used to perform operations over data definitions are called DDL
commands. These are CREATE, ALTER, DROP, TRUNCATE and RENAME (9i).

From oracle 10g onwards 2 more commands were introduced they are FLASHBACK,
PURGE.

2. DML: (Data Manipulation Language)

Set of commands used to perform operations over data are called DML commands. These are
INSERT, UPDATE, DELETE, MERGE (9i) and INSERT ALL (9i).

3. DQL: (Data Query Language)

The command which used to retrieve data from database is called DQL command. It is also
called as DRL (Data Retrieval Language) command. It is SELECT.

4. TCL: (Transaction Control Language)

Set of commands used to control transactions over DML operations are called TCL
commands. These are COMMIT, ROLLBACK and SAVEPOINT.

5. DCL: (Data Control Language)

Set of commands used to control data between users of oracle are called DCL commands.
These are GRANT and REVOKE.

DATA TYPES:

Data type specifies type of data within a table column and amount of memory allocated for
that column. Oracle having following data types. These are 1. number (P)

2. number (P,S)

3. char

4. varchar

5. varchar2

6. long

7. date

number (P): It is used to store fixed number of digits only i.e., this data type does not store
floating point numbers. Maximum limit of precision is up to 38 digits. (P-precision)
Syntax: column name number (precision size);

SQL> create table test (sno number (7));

Table created.

SQL> desc test;

Name Null? Type

SNO NUMBER(7)

SQL> insert into test values (99.9);

1 row created.

SQL> insert into test values (99.3);

1 row created.

SQL> insert into test values (99.9999);

1 row created.

SQL> insert into test values (99.99999);

1 row created.

SQL> select * from test;

SNO

100

99

100

100

SQL> insert into test values (999999999);

ERROR: ORA-01438: value larger than specified precision allowed for this column

number (P, S): It is used to store fixed, floating point numbers.

P-precision total no. of digits

S- scale No. of digits allowed after decimal


Syntax: column name number (P,S);

SQL> create table test (sno number (7,2));

Table created.

SQL> desc test;

Name Null? Type

SNO NUMBER(7,2)

SQL> insert into test values (12345.67);

1 row created.

SQL> insert into test values (5000);

1 row created.

SQL> insert into test values (5000.507);

1 row created.

SQL> insert into test values (5000.503);

1 row created.

SQL> select * from test;

SNO

12345.67

5000

5000.51

5000.5

NOTE-1: Whenever we are using number (P, S) then if you are try to specify more than P-S
number of digits in before decimal point then oracle server returns an error.

SQL> insert into test values (123456.7);

ERROR: ORA-01438: value larger than specified precision allowed for this column

NOTE-2: Oracle server does not return any error when we are specifying more number of
digits than the specified scale after decimal point. In this case oracle server internally
automatically round that scale based on the maximum size specified in number (P, S).
SQL> insert into test values (12345.678);

1 row created.

SQL> select * from test;

SNO

12345.68

char: It is used to store fixed length of alpha numeric data in bytes. Maximum size is up to
2000 bytes. By default character data type having 1 byte.

Syntax: column name char (size);

SQL> create table test (name char (6));

Table created.

SQL> desc test;

Name Null? Type

SNO CHAR(6)

SQL> insert into test values ('UMESH');

1 row created.

SQL> insert into test values ('RAMSAI');

1 row created.

SQL> insert into test values ('RITHVIK');

ERROR: ORA-12899: value too large for column "SCOTT"."TEST"."NAME" (actual: 7,


maximum: 6)

SQL> select * from test;


NAME

UMESH

RAMSAI

NOTE: Whenever we are using character data type if you are try to store less number of bytes
than the maximum size specified in character data type then oracle server internally
automatically add blank spaces at the end of the string in place of remaining bytes. This is
called “Blank Padded Mechanism”.
Blank padded space
U M E S H

varchar2: Oracle 7.0 introduced varchar2 data type. It is used to store variable length alpha
numeric data in bytes. Maximum size is up to 4000 bytes.

Syntax: column name varchar2 (maxsize);

SQL> create table test (name varchar2 (6));

Table created.

SQL> desc test;

Name Null? Type

SNO VARCHAR2(6)

SQL> insert

1 row created.

SQL> insert into test values ('RAMSAI');

1 row created.

SQL> insert into test values ('RITHVIK');

ERROR: ORA-12899: value too large for column "SCOTT"."TEST"."NAME" (actual: 7,


maximum: 6)

SQL> select * from test;


NAME

UMESH

RAMSAI
NOTE: Whenever we are try to store less number of bytes than the
maximum size then oracle server does not add blank spaces at the end of the string that’s way
here disk space is not wasted.

U M E S H

varchar: Prior to oracle 7.0 if you want to store variable length alpha numeric data then we
are using varchar data type. It is also same as varchar2 data type. This data type stores up to
2000 bytes.

Syntax: column name varchar (maxsize)


NOTE: Basically varchar data type is an ANSI standard that’s way this data type is used in
all relational database products where as varchar is an oracle standard.

long: If you want to store more than 4000 bytes of alpha numeric data then we are using long
data type. This data type stores up to 2GB data but their can be only one long column per a
table.

Syntax: column name long;

SQL> create table test (col1 long);

Table created.

SQL> insert into test values ('UMESH');

1 row created.

SQL> insert into test values (852852);

1 row created.

SQL> select * from test;


COL1

UMESH

852852

SQL> create table test1 (col1 long,col2 long);

ERROR: ORA-01754: a table may contain only one column of type LONG

date: It is used to store dates and time in oracle date format. But time is optional if not
mention oracle stores 12:00 AM

Syntax: column name date;

Input DD-MON-YY
By default oracle date format is
Oracl DD-MON-YYYY HH MI SS DD-MON-YY. Date occupies 7
e bytes of memory.
Bytes 1 1 2 1 1 1

DDL Commands: These commands are used to define structure of the table.
1. CREATE

2. ALTER

3. DROP

4. TRUNCATE

5. RENAME

CRETAE: It is used to create database objects like tables, indexes, clusters, etc.,

Syntax: create table tablename ( column1 data type(size),

column2 datatype(size),

........

........

columnN datatype(size));

SQL> create table test (sno number(10),country_code char(3),

ename varchar2(10),hiredate date);

Table created.

To show table definition:

Syntax: desc tablename;

SQL> desc test;

Name Null? Type

SNO NUMBER(10)

COUNTRY_CODE CHAR(3)

ENAME VARCHAR2(10)

HIREDATE DATE

ALTER: It is used to change structure of the existing table. ADD, MODIFY,DROP are these
actions performed on a table by using alter command.

(i).ADD: It is used to add columns to exiting tables.


Syntax: alter table tablename add (col1 datatype(size),col2 datatype(size),..);

SQL> alter table test add (sal number (10));

Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

COUNTRY_CODE CHAR(3)

ENAME VARCHAR2(10)

HIREDATE DATE

SAL NUMBER(10)

(ii).MODIFY: It is used to change column data type or column data type size only.

Syntax: alter table tablename modify (col1 datatype(size),col2 datatype(size),...);

SQL> alter table test modify ename varchar2 (20);

Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

COUNTRY_CODE CHAR(3)

ENAME VARCHAR2(20)

HIREDATE DATE

SAL NUMBER(10)

SQL> alter table test modify (country_code number (3));

Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)
COUNTRY_CODE NUMBER(3)

ENAME VARCHAR2(10)

HIREDATE DATE

SAL NUMBER(10)

(iii).DROP: It is used to drop columns in a table.

Method-1: Syntax: (for single column)

alter table tablename drop column columnname; (or)

alter table tablename drop(columnname);

SQL> alter table test drop column country_code;

Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

ENAME VARCHAR2(20)

HIREDATE DATE

SAL NUMBER(10)

SQL> alter table test drop (sal);

Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

ENAME VARCHAR2(20)

HIREDATE DATE

Method-2: Syntax: (for multiple columns)

alter table tablename drop(colname1,colname2,...);

SQL> alter table test drop (hiredate,ename);


Table altered.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

NOTE: In all database systems we can't drop all columns in a table.

SQL> alter table test drop (sno);

ERROR: ORA-12983: cannot drop all columns in a table.

DROP: It is used to drop database objects from database. In all databases at a time we are
allowed to drop on database object only.

Syntax: drop databaseobject objectname;

SQL> drop table test;

Table dropped.

Testing: SQL> desc test;

ERROR: ORA-04043: object test does not exist

Before oracle 10g: After oracle 10g in enterprise editions:

Table Table
oracle oracle

Recycle bin
Table

To Get Back: Before oracle 10g if we drop the database objects those are permanently
dropped we can't get it back. But after oracle 10g it is possible to get back database objects by
using flashback command. In this if we drop database objects those are stored in
RECYCLEBIN. It is possible in Enterprise Editions only.

Syntax: flashback object objectname to before drop;

SQL> flashback table test to before drop;


Table Get backed.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

To Drop Permanently:

Syntax: drop object objectname purge;

SQL> drop table test purge;

Table dropped.

Testing: SQL> flashback table test to before drop;

ERROR: ORA-38305: object not in RECYCLE BIN

RECYCLE BIN:

Recycle bin is a read only table. This table stores dropped objects. Whenever we are
installing oracle server then automatically so many read-only tables are created. These read-
only tables are also called as Data Dictionaries. These tables automatically stores specific
information related to database objects.

Recycle bin
oracle

Object_name Original_name

Test

NOTE: We can also drop particular object or all objects from recycle in by using purge
command.

To drop particular object from recyclebin:

Syntax: purge object objectname;

SQL> purge table test;


To drop all objects from recyclebin:

Syntax: purge recyclebin;

SQL> create table test (sno number (10));

SQL> drop table test;

SQL> desc recyclebin;

Name Null? Type

OBJECT_NAME NOT NULL VARCHAR2 (30)

ORIGINAL_NAME VARCHAR2 (32)

SQL> select ORIGINAL_NAME from recyclebin;

ORIGINAL_NAME

TEST

SQL> purge recyclebin;

Recyclebin purged.

Testing: SQL> select ORIGINAL_NAME from recyclebin;

no rows selected.

TRUNCATE: It is used to delete total data perminantely from a table but table definition
remains. Oracle 7.0 introduced this command.

Syntax: truncate table tablename;

SQL> create table test as select * from dept;

Table created.

SQL> desc test;

Name Null? Type

DEPTNO NUMBER(2)

DNAME VARCHAR2(14)
LOC VARCHAR2(13)

SQL> select * from test;

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

SQL> truncate table test;

Table truncated.

Testing: SQL> select * from test;

no rows selected

SQL> desc test;

Name Null? Type

DEPTNO NUMBER(2)

DNAME VARCHAR2(14)

LOC VARCHAR2(13)

RENAME: It is used to rename a table and renaming a column also.

Renaming a Table:

Syntax: rename oldtablename to newtablename;

SQL> rename test to test_new;

Table renamed.

Testing: SQL> select * from test;

ERROR: ORA-00942: table or view does not exist

SQL> select * from test_new;

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS
30 SALES CHICAGO

40 OPERATIONS BOSTON

Renaming a Column: It is introduced in the Oracle 9i version.

Syntax: alter table tablename rename column oldcolumnname to newcolumnname;

SQL> alter table test_new rename column deptno to dno;

Table altered.

Testing: SQL> desc test_new;

Name Null? Type

DNO NUMBER(2)

DNAME VARCHAR2(14)

LOC VARCHAR2(13)

NOTE: In all Databases by default all DDL commands are automatically committed (saved).

SQL> create table test (sno number (10),name varchar2(10));

Table created.

SQL> desc test;

Name Null? Type

SNO NUMBER(10)

NAME VARCHAR2(10)

SQL> alter table test rename column name to ename;

Table altered.

SQL> desc test;

Name Null? Type

SNO NUMBER(10)

ENAME VARCHAR2(10)
SQL> rollback;

Rollback complete.

Testing: SQL> desc test;

Name Null? Type

SNO NUMBER(10)

ENAME VARCHAR2(10)

DML Commands:DML commands are used to manipulate data within a table. Oracle
having following DML commands.

1. INSERT

2. UPDATE

3. DELETE

4. MERGE (Oracle 9i)

INSERT: It is used to insert data into table. There are 3 methods are there to insert data.

Method-1:

Syntax: insert into tablename values (value1, value2,..);

SQL> create table test (sno number (10),name varchar2(10));

Table created.

SQL> insert into test values (1,'UMESH');

1 row created.

SQL> insert into test values (2,'RAJU');

1 row created.

Testing: SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

Method-2:(Using Substitutional operator(&))


Syntax: insert into tablename values (&col1,&col2,...);

SQL> insert into test values(&sno,'&name');

Enter value for sno: 3

Enter value for name: RUKKU

1 row created.

SQL> /

Enter value for sno: 4

Enter value for name: SATHI

1 row created.

Testing: SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI

Method-3:(Skipping columns)

Syntax: insert into tablename (col1, col2,..) values (value1,value2,..);

SQL> insert into test (sno) values (5);

1 row created.

SQL> insert into test (name) values ('SANTHU');

1 row created.

Testing: SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI
5

SANTHU

UPDATE: It is used to modify data in a table.

Syntax: update tablename set columnname=new value where columnname=old value;

SQL> update test set name='LANKE' where sno=5;

1 row updated.

SQL> update test set sno=6 where name='SANTHU';

1 row updated.

Testing: SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI

5 LANKE

6 SANTHU

DELETE: It is used to delete particular rows or all rows from a table data.

To Delete all rows:

Syntax: delete from tablename;

SQL> delete from test;

6 rows deleted.

Testing: SQL> select * from test;

no rows selected

To get back: SQL> rollback;

Rollback complete.
SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI

5 LANKE

6 SANTHU

To delete particular rows:

Syntax: delete from test where condition;

SQL> delete from test where sno=6;

1 row deleted.

Testing: SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI

5 LANKE

To get back: SQL> rollback;

Rollback complete.

Testing:SQL> select * from test;

SNO NAME

1 UMESH

2 RAJU

3 RUKKU

4 SATHI

5 LANKE
6 SANTHU

Difference between TRUNCATE and DELETE:

Whenever we are using DELETE from table then deleted data is temporarily stored in
a buffer. We can get it back this data by using ROLLBACK (without using COMMIT
command).

Whenever we are using TRUNCATE from table then deleted data is permanently
deleted. Because TRUNCATE is an DDL command and also by default all DDL commands
are automatically committed. That’s way we can't get it back this data if we are using
ROLLBACK also.

SQL> create table test (sno number (10));

Table created.

SQL> insert into test values (&sno);

Enter value for sno: 1

1 row created.

SQL> /

Enter value for sno: 2

1 row created.

SQL> commit;

Commit complete.

SQL> select * from test;

SNO

SQL> delete from test;

2 rows deleted.

Testing: SQL> select * from test;


no rows selected

SQL> rollback;

Rollback complete.

SQL> select * from test;

SNO

SQL> truncate table test;

Table truncated.

Testing: SQL> select * from test;

no rows selected

SQL> rollback;

Rollback complete.

SQL> select * from test;

no rows selected

DQL [or] DRL Commands: This commands is used to retrieve the data from database.
SELECT is the only on command in DQL commands.

SELECT: It is used to fetching data from table.

Syntax: select col1,col2,..(or) *(all columns)

from tablename

where condition

group by clause

having condition

order by clause[asc/desc];

Selecting all columns and rows:

SQL> select * from dept;


DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

Selecting all rows and particular columns:

SQL> select deptno from dept;

DEPTNO

10

20

30

40

Selecting particular rows and particular columns:

SQL> select deptno from dept where loc='DALLAS';

DEPTNO
Selecting all columns and particular rows:
20
SQL> select * from dept where deptno=10;

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

Creating a New table from Existing table:

Syntax: create table Newtablename as select * from existing tablename;

SQL> create table test as select * from dept;

Table created.

Testing: SQL> select * from test;

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> desc test;

Name Null? Type

DEPTNO NUMBER(2)

DNAME VARCHAR2(14)

LOC VARCHAR2(13)

Creating a New table from existing table without copying data:

Syntax: create table newtablename as select * from existing tablename where false condition;

SQL> create table test1 as select * from dept where 1=2;

Table created.

Testing: SQL> select * from test1;

no rows selected

SQL> desc test1;

Name Null? Type

DEPTNO NUMBER(2)

DNAME VARCHAR2(14)

LOC VARCHAR2(13)

Operators used in select statement:

1. Arithmetic Operators [*, /, +, -]

2. Relational (or) Comparison Operators [=, <, <=, >, >=, <> (or) !=]

3. Logical Operators [AND, OR]

4. Special Operators [IN, NOTIN, BETWEEN, IS NULL, LIKE]

NOTE: We are going to use relational, logical and special operators only after where
condition whereas arithmetic operators can be used after select statement.

Q) Write a query to display ename, salary, annual salary of the employees from emp table by
using arithmetic operators?
ANS> select ename, sal, sal*12 "annualsal" from emp;

ENAME SAL annualsal

SMITH 800 9600

ALLEN 1600 19200

WARD 1250 15000

JONES 2975 35700

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7499 ALLEN SALESMA 7698 20-FEB-81 1600 300 30


N

7566 JONES MANAGER 7839 02-APR-81 2975 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

Q) Write query to display the employees except job as clerk from emp table?
ANS> select * from emp where job<>'CLERK';

Q) Write a query to display the employees who are getting more than 2000 salary from emp
table?

ANS> select * from emp where sal>2000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7566 JONES MANAGER 7839 02-APR-81 2975 20

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7782 CLARK MANAGER 7839 09-JUN-81 2450 10

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7902 FORD ANALYST 7566 03-DEC-81 3000 20

Logical operators: In all databases if you want to specify more than one condition in where
clause then we are using logical operators AND, OR.

AND: Whenever we are using logical operator AND then database servers filter data from
where clause first condition.
Emp
table

AND
Result set Sal>3000

Job<>’CLERK’
Q) Write a query to display the employees who are getting more than 3000 salary and except
job as clerk?

SQL> select * from emp where job<>'CLERK' and sal>3000;

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7839 KING PRESIDENT 17-NOV-81 5000 10

OR: Whenever we are using logical operator OR then database servers retrieve data from
table based on the individual conditions specified in where clause.

Emp
table

OR
Result set Sal>3000

Job=’CLERK’
Q) Write a query to display the employees who are getting more than 3000 salary and job as
clerk?

SQL> select * from emp where job='CLERK' and sal>3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-DEC-80 800 20

7839 KING PRESIDEN 17-NOV-81 5000 10


T

7876 ADAMS CLERK 7788 12-JAN-83 1100 20


7900 JAMES CLERK 7698 03-DEC-81 950 30

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employees those who are working under job as clerk or
salesman from emp table?

ANS> select * from emp where job='CLERK' or job='SALESMAN';

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7369 SMITH CLERK 7902 17-DEC-80 800 20

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Q) Write a query to display the employees who are getting more than 2000 salary and less
than 5000 salary from emp table?

ANS> select * from emp where sal>2000 and sal<5000;

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7566 JONES MANAGER 7839 02-APR-81 2978 20

NOTE: In all databases if you want to retrieve multiple values from a same column by using
equality operator then we must use OR operator.

Q) Write a query to display the employees who are working under the department of 10, 30,
50, 70, 90 from emp table?

ANS> select * from emp where deptno=10 or deptno=30 or deptno=50 or deptno=70 or


deptno=90;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employee whose ename is blake from emp table?

ANS> select * from emp where ename='BLAKE';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

NOTE: In oracle, string comparison is case sensitive.

Q) Write a query to display the employee whose ename is blake from emp table?

ANS> select * from emp where ename='blake';

no rows selected

Q) Write a query to display the employees whose are joined after 1981 from emp table?

ANS> select * from emp where hiredate>1981;

ERROR: ORA-00932: inconsistent datatypes: expected DATE got NUMBER

SOL> select * from emp where hiredate>'31-DEC-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7876 ADAMS CLERK 7788 12-JAN-83 1100 20

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employees whose are joined in the year 1981 from emp
table?

ANS> select * from emp where hiredate>='01-JAN-1981' and hiredate<='31-DEC-1981';

EMPN ENAME JOB MG HIREDATE SAL COMM DEPTNO


O R

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7900 JAMES CLERK 7698 03-DEC-81 950 30

7902 FORD ANALYST 7566 03-DEC-81 3000 20

Q) Write a query to display the employees who are working under deptno=30 and job as
salesman and salary more than 1500 from emp table?

ANS> select * from emp where deptno=30 and job='SALESMAN' and sal>1500;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Q) Write a query to display the employees whose job as clerk or manager and salary more
than 2000 from emp table?

ANS> select * from emp where job='CLERK' or job='MANAGER' and sal>2000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-DEC-80 800 20

7566 JONES MANAGER 7839 02-APR-81 2975 20

EXP: Here, output is wrong because AND operator has got more priority than OR operator

SOL> select * from emp where (job='CLERK' or job='MANAGER') and sal>2000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

Special Operators: Oracle having following special operators. These are,

1. In, not in

2. Between, not between

3. Is null, is not null

4. Like, not like

IN, NOT IN Operators: In operator is used to pick the values one by one from list of values.
Generally we can use IN operator in place of OR operator because IN operator performance
is very high compared to OR operator.

NOT IN operator operation is completely opposite to IN operator.

Syntax: select * from tablename where columnname in (list of values);for in

Syntax: select * from tablename where columnname not in (list of values);for not in

Q) Write a query to display the employees who are working under departments 10, 30, 50,
70, 90 from emp table by using IN operator?
ANS> select * from emp where deptno in (10, 30, 50, 70, 90);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employees whose job is either clerk or manager from emp
table by using In operator?

ANS> select * from emp where job in ('CLERK','MANAGER');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employees who are working other than deptno 10,20 from
emp table by using NOT IN operator?

ANS> select * from emp where deptno not in (10, 20);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7900 JAMES CLERK 7698 03-DEC-81 950 30

NOTE: In all database systems NOT IN operator does not work with null values. NULL is a
undefined, unknown value. It is not same as zero. Any arithmetic operation performed with
NULL values then result will be NULL.

For example, null+50=>null

SQL> select * from emp where deptno not in (10,20,null);

no rows selected.

Q) Write a query to display ename, sal comm, sal+comm of the employee SMITH from emp
table?

ANS> select empno,ename,sal,comm,sal+comm from emp where ename='SMITH';


EMPNO ENAME SAL COMM SAL+COMM

7369 SMITH 800

EXP: Wrong result. To overcome this problem oracle provided NVL() function.

NVL ():

NVL is an free-defined function which is used to replace (or) substitute user-defined value in
place of NULL.

Syntax: nvl (expression1, expression2);

This function accepts two expressions. These two expressions must belong to same datatype.
If expression1 is null then it returns expression2 otherwise it will returns expression1.

For example, =>nvl (null, 30)30

nvl (10,20)10

SOL> select empno,ename,sal,comm,sal+nvl(comm,0) from emp where ename='SMITH';

EMPNO ENAME SAL COMM SAL+NVL (COMM,0)

7369 SMITH 800 800

BETWEEN, NOT BETWEEN Operators: Between operator is used to retrieve range of


values where as not between operator is completely opposite to between operator. Between
operator is also called as “between...and” operator.

Syntax: select * from tablename where columnname

between lowvalue and highvalue;for between

Syntax: select * from tablename where columnname

not between lowvalue and highvalue;for not between

Q) Write a query to display employees whose salary more than 2000 and less than 5000 from
emp table by using between operator?

ANS> select * from emp where sal between 5000 and 2000;

no rows selected

EXP: Here, between operators does not works on higher value to lower value because
between internally uses equal to operator.

SOL> select * from emp where sal between 2000 and 5000;

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7782 CLARK MANAGEER 7839 09-JUN-81 2450 10

Q) Write a query to display employees who are not joined in the year 1981 from emp table by
using between operators?

ANS> select * from emp where hiredate not between '01-JAn-1981' and '31-DEC-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7876 ADAMS CLERK 7788 12-JAN-83 1100 20

7369 SMITH CLERK 7902 17-DEC-80 800 20

Q) Write a query to display employees working as clerk or manager and earing between 2000
and 5000 and joined in 1981 year and not working for department 10 or 20 from emp table?

ANS> select * from emp

where job in('CLERK','MANAGER') and

sal between 2000 and 5000 and

hiredate between '01-JAN-1981' and '31-DEC-1981'

and deptno not in(10,20);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

IS NULL, IS NOT NULL Operators: These two operators are used to test whether a
column having null values or not.

Syntax: select * from tablename where columnname is null;for is null

Syntax: select * from tablename where columnname is not null;for is not null
Q) Write a query to display employees whose commission is null from emp table?

SQL> select * from emp where comm=NULL;

no rows selected

SQL> select * from emp where comm is null;

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7782 CLARK MANAGEER 7839 09-JUN-81 2450 10

Q) Write a query to display employees whose commission is not a null from emp table?

SQL> select * from emp where comm is not null;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

LIKE, NOT LIKE Operators: Like operator is used to retrieve data based on character
pattern. This operator performance is very high compared to pre-defined searching functions.

Along with like operator we must use following special characters. These are also called as
Wild card characters. (%, _) Not like operator operation is completely opposite to like
operator.

(%) --> for string or group of characters (_) -->for single character

Syntax:select * from tablename where columnname like ‘character pattern’;for like

Syntax:select * from tablename where columnname not like ‘character pattern’;for not like
Q) Write a query to display the employee whose ename start with capital letter ‘M’ from emp
table by using like operator?

ANS> SQL> select * from emp where ename like 'M%';

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7654 MARTI SALESMAN 7698 28-SEP-81 1250 1400 30


N

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Q) Write a query to display the employee whose ename having any letter ‘M’ from emp
table by using like operator?

ANS> SQL> select * from emp where ename like '%M%';

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7654 MARTI SALESMAN 7698 28-SEP-81 1250 1400 30


N

7934 MILLER CLERK 7782 23-JAN-82 1300 10

7876 ADAMS CLERK 7788 12-JAN-83 1100 20

Q) Write a query to display the employees whose are joined in the month of FEB from emp
table by using like operator?

ANS> select * from emp where hiredate like '%FEB%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7499 ALLEN SALESMAN 7698 20-FEB-81 160 300 30


0

7521 WARD SALESMAN 7698 22-FEB-81 125 500 30


0

Q) Write a query to display the employees whose are joined in the year of 81 from emp table
by using like operator?

ANS> select * from emp where hiredate like '%81';

EMPN ENAME JOB MG HIREDATE SAL COMM DEPTNO


O R
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7900 JAMES CLERK 7698 03-DEC-81 950 30

7902 FORD ANALYST 7566 03-DEC-81 3000 20

Q) Write a query to display the employees whose ename second letter is capital letter ‘A’
from emp table by using like operator?

ANS> select * from emp where ename like '_A%';

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

7521 WARD SALESMAN 7698 22-FEB-81 125 500 30


0

Q) Write a query to display the employees whose are joined in first 9 days of any month from
emp table by using like operator?

ANS> select * from emp where hiredate like '0%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7900 JAMES CLERK 7698 03-DEC-81 950 30

7902 FORD ANALYST 7566 03-DEC-81 3000 20

NOTE: Whenever resource table column data having wildcard characters and also if we are
requesting data based on wildcard characters then database servers returns wrong results.
Because here (_) underscore treated as special character and also % treated as special
character.

To overcome this problem for avoiding special meanings ANSI/ISO SQL provided escape
function along with like operator. Whenever we are using escape function database servers
escapes special meaning of the wildcard character. i.e., here (_) treated as underscore and %
sign is treated as %sign.

Syntax: select * from tablename where columnname

like ‘character pattern’ escape ‘escape character’;


Here, escape character length must be one character. And it is used in before the wildcard
character only.

Q) Write a query to display the employees whose ename start with ‘S_’ from emp table by
using like operator?

SQL> insert into emp (empno, ename) values(1,'S_MITH');

1 row created.

ANS> select * from emp where ename like 'S_%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7369 SMITH CLERK 7902 17-DEC-80 800 20

1 S_MITH

SOL>select * from emp where ename like ‘S!_%’ escape ‘!’;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

1 S_MITH

Concatenation Operator: (||) If you want to display column data along with literal strings
then we must use concatenation operator. (||)

Syntax: select ‘text’ || columnnam from tablename;

SQL> select 'My Employee Names are'||ename from emp;

'MYEMPLOYEENAMESARE'||ENAME

My Employee Names areSMITH

My Employee Names areALLEN

My Employee Names areWARD

Functions:

Functions are used to solve particular tasks and also functions must return a value. Oracle
having two types of functions. These are 1.Predefined functions

2. User defined functions


Predefined functions: Oracle having following types of predefined functions.

1. Number functions
2. Character functions
3. Date functions
4. Group (or) Aggregate functions

Number functions: The functions which are operated on number data are called number
functions.

abs (): It is used to convert negative sign(-) into positive sign(+).

Syntax: abs (number);

SQL> select abs (-70) from dual;

ABS (-70)

70

sign (): It is used to represent sign of a number. i.e., it tells whether the given number is
positive or negative. It gives 1 for positive, -1 for negative and 0 for zero.

Syntax: sign (number);

SQL> select sign (70), sign (-70), sign (0) from dual;

SIGN(70) SIGN(-70) SIGN(0)

1 -1 0

Dual Table: Dual is a predefined virtual table which contains only one row and one column.

This table is used to test predefined and user defined functions functionality.

NOTE: By default dual table column data type is varchar2.

SQL> select * from dual;

SQL> desc dual;

Name Null? Type

DUMMY VARCHAR2(1)

Testing:

SQL> select nvl (null, 90) from dual;


NVL (NULL,90)

90

SQL> select 30+50 from dual;

30+50

80

mod ( n, m): It returns the remainder of n divided by m.

Syntax: mod (n, m); where n, m are numbers

SQL> select mod (10, 2) from dual;

MOD (10, 2)

power (m, n): returns m raised to the nth power.

Syntax: power (m, n); where m, n are numbers

SQL> select power (2) from dual;

ERROR: ORA-00909: invalid number of arguments

SQL> select power (2, 2) from dual;

POWER (2, 2)

round (m, n): It returns a number rounded off value of the number ‘m’ up to the number ‘n’
number of decimal places.

Syntax: round (m, n); where m, n is a integer

NOTE: It always checks’ remaining number if remaining number is above 50% ten
automatically one added to the rounded number

SQL> select round (1.7) from dual;

ROUND (1.7)

2
SQL> select round (1.23456, 3) from dual;

ROUND (1.23456, 3)

1.235

SQL> select round (1278.689,-1) from dual;

ROUND (1278.689, -1)

1280

SQL> select round (1278,-2) from dual;

ROUND (1278, -1)

1280

Q) Write a query to display ename, sal and round (sall,-3) from emp table?

ANS> select ename, sal, round (sal,-3) from emp;

ENAME SAL ROUND (SAL,-3)


trunc (m, n): It truncates given
SMITH 800 1000
floated value number ‘m’ based
on ‘n’. ALLEN 1600 2000

Syntax: trunc (m, WARD 1250 1000 n); where m, n are


integers

SQL> select trunc (1, 8) from dual;

TRUNC (1,8)

SQL> select trunc(1.8) from dual;

TRUNC (1.8)

SQL> select trunc (1.23456, 3) from dual;

TRUNC (1.23456, 3)

1.234

sqrt (m): It returns a square root of a number.

Syntax: sqrt (m); where m is an integer


SQL> select sqrt (16) from dual;

SQRT (16)

ceil (), floor (): These functions always returns integers ceil function returns nearest greatest
integer where as floor function returns nearest lowest integer.

Syntax: ceil (n); floor (n); here, n is a number

SQL> select ceil (1.3) from dual;

CEIL (1.3)

SQL> select floor (1.9) from dual;

FLOOR (1.9)

greatest (), least (): These functions always returns a number. Greatest function returns
maximum value among given expressions where as least function returns minimum value
among given expressions.

Syntax: greatest (exp1, exp2, ..);

least (exp1, exp2, ..);

SQL> select greatest (10, 50, 30) from dual;

GREATEST (10, 50, 30)

50

SQL> select least (10, 50, 30) from dual;

LEAST (10, 50, 30)

50

Character functions:

upper (), lower (): upper function is used to convert a string or column values into upper
case where as lower is used to convert a string or column values into lower case.

Syntax: upper (string or column name);

lower (string or column name);

SQL> select upper ('umesh') from dual;


UPPER

UMESH

SQL> select lower ('UMESH') from dual;

LOWER

umesh

SQL> select upper (ename) from emp;

UPPER (ENAM

SMITH

ALLEN

WARD

SQL> select lower (ename) from emp;

LOWER(ENAM

Smith

Allen

Ward

initcap (): It returns initial letter is capital and all remaining letters are small.

Syntax: initcap (string or expression or column name);

SQL> select initcap ('umesh is a good boy') from dual;

INITCAP('UMESHISAGO

Umesh Is A Good Boy

Length (): It returns total length of the string or expression including spaces.

Syntax: length (string or expression);

SQL> select length ('umesh') from dual;

LENGTH ('UMESH')

SQL> select length ('umesh is a good boy') from dual;


LENGTH ('UMESHISAGOODBOY')

19

SQL> select length (12345) from dual; here 12345 is taken as string

LENGTH (12345)

SQL> select length ('31-dec-1986') from dual; here date is taken as string

LENGTH ('31-DEC-1986')

11

SQL> select length (31-dec-1986) from dual;

ERROR: ORA-00904: "DEC": invalid identifier

Substr (): It will extract portion of the string within given string or expression or column
name based on last two parameters.

Syntax: substr (column name or string, starting position,

number of characters from position);

NOTE: The last two parameters must be a numbers and second parameter may be positive or
negative number and last parameter is optional.

SQL> select substr ('ABCDEFGH', 2, 3) from dual;

SUB

BCD

SQL> select substr ('ABCDEFGH', 3) from dual;

SUBSTR

CDEFGH

SQL> select substr ('ABCDEFGH',-2, 3) from dual;

SUB

GH

SQL> select substr ('ABCDEFGH', -5) from dual;

SUBST

DEFGH
Q) Write a query to display the employees whose ename second letter would be ‘AR’ from
emp table by using substr function?

ANS> select ename from emp where substr (ename, 2, 2) = 'AR';

ENAME

WARD

MARTIN

Instr (): This function always returns number data type i.e., it returns position of the
delimiter, position of the character or position of the string within a given string or column.

Syntax: instr (columnname or string, ‘str’, searching position,

number of occurrences from position);

NOTE: Here, the last two parameters must be numbers and third parameter may be positive
or negative number and these are optional.

SQL> select instr ('ABC#D','#') from dual;

INSTR ('ABC#D','#')

NOTE: Always instr function returns position based on last two parameters but oracle server
always counts number of characters left side 1st position onwards.

SQL> select instr ('ABCDEFGHGEFJKEFKM','EF', 9, 2) from dual;

INSTR ('ABCDEFGHGEFJKEFKM','EF',9,2)

14

SQL> select instr ('ABCDEFGHGEFJKEFKM','EF',-9,2) from dual;

INSTR ('ABCDEFGHGEFJKEFKM','EF',-9,2)

SQL> select instr ('ABCDEFGHGEFJKEFKM','EF',-8) from dual;

INSTR ('ABCDEFGHGEFJKEFKM','EF',-8)

10

SQL> select instr ('CORPORATE FLOOR','OR', 3, 2) from dual;

INSTR ('CORPORATEFLOOR','OR',3,2)
14

SQL> select instr ('CORPORATE FLOOR','OR',-3, 2) from dual;

INSTR ('CORPORATEFLOOR','OR',-3,2)

SQL> select instr('ABCD','Z') from dual;

INSTR ('ABCD','Z')

Concat (): It is used to concatenate given two strings.

Syntax: concat (str1, str2);

SQL> select concat ('WEL','COME') from dual;

CONCAT (

WELCOME

Lpad (): It will fill remaining spaces with specified characters on the left side of the given
string. Always here second parameter returns total length of the string.

Syntax: lpad (column name or string name, total length, ‘filled character’);

SQL> select lpad ('ABCD', 10, '#') from dual;

LPAD('ABCD

######ABCD

SQL> select lpad(' ',10,'*') from dual;

LPAD(“,10

**********

SQL> select lpad('',10,'*') from dual;

Rpad (): It will fill remaining spaces with specified characters on the right side of the given
string. Always here second parameter returns total length of the string.

Syntax: rpad (column name or string name, total length, ‘filled character’);
SQL> select rpad ('ABCD', 10,'#') from dual;

RPAD('ABCD

ABCD######

SQL> select rpad(' ',10,'*') from dual;

RPAD(“,10

**********

SQL> select rpad('',10,'*') from dual;

NOTE: Whenever we are submitting lpad(), rpad() functions then oracle server always
fetching data from left side first character from first parameter. That’s way lpad(),rpad()
functions returns same result. When we are specifying more number of characters in first
parameter then the total length of second parameter.

SQL> select lpad ('ABC', 2,'*') from dual;

LP

AB

SQL> select rpad ('ABC', 2,'*') from dual;

RP

AB

Ltrim (): It removes specified characters on the left side of the given string.

Syntax: ltrim (column name, ‘set of characters’);

SQL> select ltrim ('SSMISSTHSS','S') from dual;

LTRIM ('S

MISSTHSS

Rtrim (): It removes specified characters on the right side of the given string.

Syntax: rtrim (column name, ‘set of characters’);

SQL> select rtrim ('SSMISSTHSS','S') from dual;

RTRIM ('S
SSMISSTH

Trim (): Oracle 8i introduced trim function. It is used remove left and right side specified
characters from a given string.

Syntax: trim (‘character’ from ‘string name or column name’);

SQL> select trim ('SSMISSTHSS','S') from dual;

TRIM('S

MISSTH

NOTE: We can also convert trim function into ltrim by using leading clause and also convert
into rtrim function by using trailing clause.

SQL> select trim (leading 'S' from 'SSMISSTHSS') from dual;

TRIM(LEA

MISSTHSS

SQL> select trim (trailing 'S' from 'SSMISSTHSS') from dual;

TRIM(TRA

SSMISSTH

NOTE: By using trim functions we can also remove leading and trailing spaces.

SQL> select length ('umesh '), length (' raju'), length (' rukku ') from dual;

LENGTH('UMESH') LENGTH('RAJU') LENGTH('RUKKU')

9 8 11

SQL> select length (rtrim('umesh ',' ')),length (ltrim(' raju',' ')),length (trim(' rukku '))
from dual;

LENGTH('UMESH') LENGTH('RAJU') LENGTH('RUKKU')

5 4 5

Translate (), Replace (): Translate is used to replace character by character whereas replace
is used to replaces character by string or string by string.

Syntax: translate (‘str1’, ‘str2’, ‘str3’);

Replace (‘str1’, ‘str2’, ‘str3’);


SQL> select translate ('India', 'In', 'XY') from dual;

TRANS

XYdia

SQL> select translate ('India', 'India', 'Vijayawada') from dual;

TRANS
SQL> select translate ('A B C','','XYZ') from dual;
Vijay
T

SQL> select translate ('A B C',’ ','XYZ') from dual;

TRANS

AXBXC

SQL> select translate ('ABC','BCA','$#@') from dual;

TRANS

@$#

SQL> select replace ('India', 'In', 'XY') from dual;

REPLACE

XYdia

SQL> select replace ('India', 'India', 'Vijayawada') from dual;

REPLACE
SQL> select replace ('A B C','','XYZ') from dual;
Vijayawada
REPLACE

ABC

SQL> select replace ('A B C',’ ','XYZ') from dual;

REPLACE

AXYZBXYZC
NOTE: In oracle whenever we are not specifying 3rd parameter within replace function then
automatically specified second parameter character or string permanently removed from the
given string within first parameter.

SQL> select replace ('SSMISSTHSS','S') from dual;

REPLACE

MITH

Q) Write a query which counts number of occurrences of ‘E’ within given string SLEEP by
using replace, length functions?

ANS> select length ('SLEEP’)-length (replace ('SLEEP','E')) from dual;

LENGTH('SLEEP')-LENGTH(REPLACE('SLEEP','E'))

ASCII (): It returns ASCII value of the given character.

SQL> select ascii('A') from dual;

ASCII(‘A’
)

65

Chr (): It returns character for the ASCII value.

SQL> select chr(65) from dual;

Date functions: In oracle by default date format is DD-MON-YY. Oracle having following
date functions. These are

Sysdate: It returns current date of the system in oracle date format.

SQL> select sysdate from dual;

SYSDATE

15-JUN-17
Add_months (): It is used to add or subtract number of months to the specified date based on
the second parameter.

Syntax: add_months (date,number);

NOTE: here number may be positive or negative number.

SQL> select add_months('15-AUG-05',1) from dual;

ADD_MONTH

15-SEP-05

SQL> select add_months('15-AUG-05',-5) from dual;

ADD_MONTH

15-MAR-05

SQL> select add_months(sysdate,1) from dual;

ADD_MONTH

15-JUL-17

SQL> select add_months(sysdate,-1) from dual;

ADD_MONTH

15-MAY-17

Last_day (): It returns last date of the specified month within given date.

Syntax: last_day (date);

SQL> select last_day (sysdate) from dual;

LAST_DAY(

30-JUN-17

SQL> select last_day('23-jul-2005') from dual;

LAST_DAY(

31-JUL-05
Next_day (): It returns next occurrence day from the specified date based on the second
parameter.

Syntax: next_day (date, ‘day’);

SQL> select next_day (sysdate, 'SUN') from dual;

NEXT_DAY (

18-JUN-17

SQL> select next_day (sysdate, 'FRI') from dual;

NEXT_DAY (

16-JUN-17

SQL> select next_day (sysdate, 'FRIDAy') from dual;

NEXT_DAY (

16-JUN-17

SQL> select next_day (sysdate, 5) from dual;

NEXT_DAY (

22-JUN-17

SQL> select next_day (sysdate, 1) from dual;

NEXT_DAY (

18-JUN-17

Months_between (): It returns number data type i.e., it returns number of months between
two specified dates. Hence date1 is always greater than date2 otherwise this function returns
negative value.

Syntax: months_between (date, date2);

SQL> select months_between ('23-jan-17', sysdate) from dual;

MONTHS_BETWEEN ('23-JAN-17',SYSDATE)

-4.7538336

SQL> select months_between (sysdate,'23-jan-17') from dual;

MONTHS_BETWEEN ('23-JAN-17',SYSDATE)
4.7538336

SQL> select round (months_between (sysdate,'23-jan-17')) from dual;

ROUND(MONTHS_BETWEEN(SYSDATE,'23-JAN-17')

10

Date Arithmetic: Date arithmetic means performing arithmetic operations on date. The
following are the arithmetic’s performed on dates.

1. Date + Number (P)

2. Date – Number (P)

3. Date1 + Date2 (NP)

4. Date1 – Date2 (P)

SQL> select sysdate+1 from dual;

SYSDATE +1

16-JUN-17

SQL> select sysdate-1 from dual;

SYSDATE -1

14-JUN-17

SQL> select sysdate+sysdate from dual;

ERROR: ORA-00975: date + date not allowed

SQL> select sysdate-sysdate from dual;

SYSDATE-SYSDATE

Q) Write a query to display first date of the current month by using predefined functions
sysdate, add_months, last_day()?

SQL> select add_months (last_day (sysdate),-1) + 1 from dual;

select last_day (add_months (sysdate,-1)) + 1 from dual;

ADD_MONTH
01-JUN-17

Date Conversion Functions: Oracle having following date conversion functions.

1. To_char ()

2. To _date ()

To_char (): It is used to convert oracle data type into character type. i.e., It converts data type
into date string.

Syntax: to_char (date, ‘character format pattern’);

NOTE: Basically to_char character formats are case sensitive formats.

For example, DAYMONDAY, dayMonday

SQL> select to_char (sysdate, 'DD/MM/YYYY') from dual;

TO_CHAR (SY

15/06/2017

SQL> select to_char (sysdate, 'D') from dual; DDay of the week

SQL> select to_char (sysdate, 'DD') from dual; DDDay of the month

TO

15

SQL> select to_char (sysdate, 'DDD') from dual; DDDDay of the year

TO

166

SQL> select to_char (sysdate, 'DDTH') from dual;

TO_C

15TH

SQL> select to_char (sysdate, 'DDSPTH') from dual; SPspell out

TO_CHAR (SYSDAT

FIFTEENTH

SQL> select to_char (sysdate, 'MM') from dual;


TO

06

SQL> select to_char (sysdate, 'YY') from dual;

TO

17

SQL> select to_char (sysdate, 'YYYY') from dual;

TO_C

2017

SQL> select to_char (sysdate, 'HH: MI: SS') from dual;

TO_CHAR (

07:33:31

SQL> select to_char (sysdate, 'HH24: MI: SS') from dual;

TO_CHAR (

19:33:46

SQL> select to_char (sysdate, 'DAY') from dual;

TO_CHAR (SYSDATE,’DAY’)

THURSDAY

SQL> select to_char (sysdate, 'DY') from dual;

TO_CHAR (SYSD

THU

SQL> select to_char (sysdate, 'MONTH') from dual;

TO_CHAR (SYSDATE,’MONTH’

JUNE

SQL> select to_char (sysdate, 'MON') from dual;

TO_CHAR (SYSD

JUN

SQL> select to_char (sysdate, 'year') from dual;

TO_CHAR(SYSDATE,'YEAR')
twenty seventeen

NOTE: Whenever we are using to_char function always first parameter must be oracle data
type otherwise oracle server returns an error.

SQL> select to_char ('23-jun-17', 'dd/mon/yy') from dual;

ERROR: ORA-01722: invalid number

SQL> select to_char ('23-JUN-17','DD-MON-YY') from dual;

ERROR: ORA-01722: invalid number

To_date (): It is used to convert date string into oracle date type. (Oracle date format)

Syntax: to_date (‘date string or character format pattern’)

SQL> select to_date('23/JUN/17') from dual;

TO_DATE (‘

23-JUN-17

NOTE: In oracle whenever we are using to_date function passed parameter return values
always matched with default date format return value otherwise oracle server returns an error.
To overcome this problem use a second parameter as same as first parameter format then
only oracle server internally automatically converts date string into date type.

SQL> select to_date('23/06/17') from dual;

ERROR: ORA-01843: not a valid month

SQL> select to_date ('23/06/17', 'dd/mm/yy') from dual;

TO_DATE (‘

23-JUN-17

Q) Write a query which is used to add 5 days to the given date string ’10-AUG-05’?

SQL> select '10-aug-05'+5 from dual;

ERROR: ORA-01722: invalid number

SQL> select to_date('10-aug-05')+5 from dual;

TO_DATE (‘

15-AUG-05

Q) Write a query which is used to add 5 days to the given date string ’10-08-05’?
SQL> select '10-08-05'+5 from dual;

ERROR: ORA-01722: invalid number

SQL> select to_date('10-08-05')+5 from dual;

ERROR: ORA-01843: not a valid month

SQL> select to_date('10-08-05','dd-mm-yy')+5 from dual;

TO_DATE (‘

15-AUG-05

Q) Write a query to display given date into client requirement format by using to_char
function. Given date string is: 15-JUNE-05 and display format is: 15/JUNE/05?

SQL> select to_char('15-JUNE-05','DD/MONTH/YY') from dual;

ERROR: ORA-01722: invalid number

SQL> select to_char(to_date('15-JUNE-05'),'DD/MONTH/YY') from dual;

TO_CHAR(TO_DATE('15-JUNE05'),'DD/MONTH/YY

15/JUNE /05

NOTE: Whenever we are using ‘MONTH’ format in to_char function then oracle server
return gaps in final output. Because oracle server internally allocates 9 bytes when we are
using month format that why whenever any month having less than 9 bytes then
automatically generates gaps. To overcome this problem oracle provided “fill mode”{FM}
format within to_char function. This mode automatically fills gaps and also automatically
suppresses leading zeros.

SQL> select to_char(to_date('15-JUNE-05'),'DD/FMMONTH/YY') from dual;

TO_CHAR(TO_DATE('15-JUNE05'),'DD/FMMONTH/YY

15/JUNE/05

Q) Write a query to display the employees who are joining in the month of December from
emp table by using to_char function?

SQL> select * from emp where to_char ( hiredate, 'MM')=12;

SQL> select * from emp where to_char ( hiredate, 'MONTH')='DECEMBER';

no rows selected
SQL> select * from emp where to_char ( hiredate, 'FMMONTH')='DECEMBER';

SQL> select * from emp where to_char ( hiredate, 'MON')='DEC';

EMPN ENAME JOB MGR HIREDATE SAL COMM DEPTNO


O

7369 SMITH CLERK 7902 17-DEC-80 800 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7900 JAMES CLERK 7698 03-DEC-81 950 30

7902 FORD ANALYST 7566 03-DEC-81 3000 20

Q) Write a query to display the employees who are joining in the year of 81 from emp table
by using to_char function?

SQL> select * from emp where to_char ( hiredate, 'yy')='81';

EMPNO ENAME JOB MG HIREDATE SAL COMM DEPTNO


R

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7566 JONES MANAGER 7839 02-APR-81 2975 20

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7900 JAMES CLERK 7698 03-DEC-81 950 30

7782 CLARK MANAGEER 7839 09-JUN-81 2450 10

Q) Write a query to display the employees who are before 15th of every month from emp
table by using to_char function?

SQL> select * from emp where to_char (hiredate, 'dd')<15;

EMPN ENAME JOB MG HIREDATE SAL COMM DEPTNO


O R

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7900 JAMES CLERK 7698 03-DEC-81 950 30


7782 CLARK MANAGEE 7839 09-JUN-81 2450 10
R

NOTE: In oracle whenever we are passing date string into oracle predefined date functions
(add_months (), nxt_day (), etc.,) then we are not required to use to_date function because in
this case oracle server only internally automatically converts date string into date type but
here passed parameter must be in default date format. Otherwise oracle server returns an
error.

SQL> select last_day('23-jun-05') from dual;

LAST_DAY (

30-JUN-05

SQL> select last_day('23-05-05') from dual;

ERROR: ORA-01843: not a valid month

SQL> select last_day(to_date('23-05-05','dd-mm-yy')) from dual;

LAST_DAY (

30-JUN-05

Inserting dates into oracle date data type column:

SQL> create table test (col1 date);

Table created.

SQL> insert into test values (sysdate);

1 row created.

SQL> insert into test values ('23-JUN-05');

1 row created.

SQL> insert into test values ('23-JUNE-05');

1 row created.

SQL> insert into test values ('23-06-05');

ERROR: ORA-01843: not a valid month

SQL> insert into test values (to_date ('23-06-05') );

ERROR: ORA-01843: not a valid month


SQL> insert into test values (to_date ('23-06-05','DD-MM-YY'));

1 row created.

SQL> select * from test;

COL1

15-JUN-17

23-JUN-05

23-JUN-05

23-JUN-05

Round (), trunc () functions are used in dates: Oracle date data type contains both date and
time. For example, 27-jul-16 07:52:34

Whenever we are using round (), trunc () functions then automatically date part can be
changed based on time portion and also internally time portion is automatically set to zeros.

SQL> select to_char(sysdate, 'DD-MM-YYYY HH24:MI:SS') from dual;

TO_CHAR (SYSDATE,'DD

15-06-2017 20:12:21

Whenever we are using round () function then oracle server automatically adds one day to the
given date if time portion is greater than or equal to 12 noon and also internally time portion
is automatically set to zeros.

SQL> select to_char(round(sysdate),'DD-MM-YYYY HH24:MI:SS') from dual;

TO_CHAR (ROUND(SYSDA

16-06-2017 00:00:00

Whenever we are using trunc () function then oracle server returns same date if time portion
is greater than or equal to 12 noon and also internally time portion is automatically set to
zeros

SQL> select to_char (trunc(sysdate),'DD-MM-YYYY HH24:MI:SS') from dual;

TO_CHAR (TRUNC(SYSDA

15-06-2017 00:00:00

NOTE: In all databases whenever we are comparing dates then database servers not only
compares date part but also compares time part that’s why when we are comparing dates by
using where clause database servers does not retrieve data from the tables. To overcome this
problem we must use trunc function because trunc function internally automatically time
portion is set to zeros.

Q) Write a query to display the employees who are joining today from emp table?

SQL> insert into emp(empno,ename,hiredate) values(1,'umesh',sysdate);

1 row created.

SQL> select * from emp where hiredate=sysdate;

no rows selected

SQL> select * from emp where round(hiredate)=round(sysdate);

SQL> select * from emp where trunc(hiredate)=trunc(sysdate);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

1 umesh 15-JUN-17

NOTE: In oracle using round (), trunc () functions we can also display first date of the year,
first date of the month by using following syntax.

Syntax: round (date, ‘year’);

round (date, ‘month’);

round (date, ‘day’);

Syntax: trunc (date, ‘year’);

trunc (date, ‘month’);

trunc (date, ‘day’);

SQL> select round (sysdate,'year') from dual

ROUND (SYS

01-JAN-18

SQL> select round (sysdate,'month') from dual;

ROUND (SYS

01-JUN-17

SQL> select round (sysdate,'day') from dual;

ROUND (SYS

18-JUN-17
SQL> select trunc (sysdate,'day') from dual;

TRUNC (SYS

11-JUN-17

SQL> select trunc (sysdate,'month') from dual;

TRUNC (SYS

01-JUN-17

SQL> select trunc (sysdate,'year') from dual;

TRUNC (SYS

01-JAN-17

NOTE: round function displays next year first date when if the current date is above 50% of
the year(>31-JUN) otherwise it displays current year first date of the year only whereas trunc
function always displays same year first date if the current date is above 50% or below 50%.
Similarly for first date of the month and first date of the week also.

Group functions: In all databases by default all group functions return single value and
operate over set of values in a table column.

Oracle having following group functions. They are

Max(): It return maximum value from a table column.

Syntax: max (column name);

SQL> select max (sal) from emp;

MAX (SAL)

5000

SQL> select max (hiredate) from emp; (checks from year onwards)

MAX (HIRED

12-JAN-83

SQL> select max (ename) from emp; (Z is big and A is small)

MAX (ENAME)

WARD
Min (): It return minimum value from a table column.

Syntax: min (column name);

SQL> select min (sal) from emp;

MIN (SAL)

800

SQL> select min (hiredate) from emp; (checks from year onwards)

MIN (HIRED

17-DEC-80

SQL> select min (ename) from emp; (Z is big and A is small)

MIN (ENAME)

ADAMS

NOTE: In all databases we are not allowed to use group functions in where clause.

SQL> select * from emp where sal=max (sal);

ERROR: ORA-00934: group function is not allowed here

Avg (): It returns average from number of data type column.

Syntax: avg (column name);

SQL> select avg (sal) from emp;

AVG (SAL)

2073.21429

SQL> select avg (comm) from emp;

AVG (COMM)

550

NOTE: By default all group functions ignores null values except count (*) function. If you
want to count null values then we are using nvl function.

SQL> select avg(nvl(comm,0)) from emp;

AVG (NVL(COMM,0))
157.142857

Sum (): It returns total from number data type column.

Syntax: sum (column name);

SQL> select sum (sal) from emp;

SUM (SAL)

29025

Count (*): It counts number of rows in a table.

Syntax: count (*);

SQL> select count (*) from emp;

COUNT (*)

14

Count (column): It counts number of not null values in a column. If we want to count
number of distinct values from a table column then we are using distinct class within count
function.

Syntax: count (column name);-for count column

Count (distinct (column name));for distinct column

SQL> select count (comm) from emp;

COUNT (COMM)

SQL> select count (nvl (comm,0)) from emp;

COUNT (NVL(COMM,0))

14

SQL> select count (deptno) from emp;

COUNT (DEPTNO)

14

SQL> select count (distinct (deptno)) from emp;


COUNT (DISTINCT(DEPTNO))

Group by clause: Group by clause is used to arrange similar data items into set of logical
groups. This clause is used in select statement.

Syntax: select column name,...

From table name

Group by column name;

Q) Write a query to display number of employees in each department from emp table by
using group by clause?

SQL> select deptno, count (*) from emp;

ERROR: ORA-00937: not a single-group group function

SQL> select deptno, count (*) from emp group by deptno;

DEPTNO COUNT (*)

30 6

20 5

10 3

Q) Write a query to display number of employees in each job from emp table by using group
by clause?

SQL> select job, count (*) from emp group by job;

JOB COUNT (*)

CLERK 4

SALESMAN 4

PRESIDENT 1

MANAGER 3

ANALYST 2
Q) Write a query to display minimum and maximum salary in each department from emp
table by using group by clause?

SQL> select deptno, max (sal), min (sal) from emp group by deptno;

DEPTN MAX (SAL) MIN (SAL)


O

30 2850 950

20 3000 800

10 5000 1300

NOTE: In all databases we can also use group by clause without using group functions.

SQL> select deptno from emp group by deptno;

DEPTNO

30

20

10

SQL> select job from emp group by job;

JOB

CLERK

SALESMAN

PRESIDENT

MANAGER

ANALYST

RULE: Other than group function columns specified after select statement those all columns
must be specified after group by clause. Otherwise oracle server returns an error.

SQL> select deptno, job, sum (sal) from emp group by deptno;

ERROR: ORA-00979: not a GROUP BY expression

SQL> select deptno, job, sum (sal) from emp group by deptno,job;

DEPTNO JOB SUM (SAL)

20 CLERK 1900

30 SALESMAN 5600
20 MANAGER 2975

30 CLERK 950

10 PRESIDENT 5000

30 MANAGER 2850

10 CLERK 1300

10 MANAGER 2450

20 ANALYST 6000

SQL> select deptno,job from emp group by deptno,job;

DEPTNO JOB

20 CLERK

30 SALESMAN

20 MANAGER

30 CLERK

10 PRESIDENT

30 MANAGER

10 CLERK

10 MANAGER

20 ANALYST

NOTE: In all databases when we are try to display normal columns along with group function
columns then oracle server returns an error. To overcome this problem we must use group by
clause.

SQL> select sum (sal) from emp;

SUM (SAL)

29025

SQL> select deptno, sum (sal) from emp;

ERROR: ORA-00937: not a single-group group function

SQL> select deptno, sum(sal) from emp group by deptno;


DEPTNO SUM (SAL)

30 9400

20 10875

10 8750

Execution: whenever we are submitting group by clause into the oracle server then oracle
server first executes group by clause column i.e., it selects similar data items from group by
clause column and then suppress number of rows in each group and then only that result is
stored in result set table internally. Then only oracle server selects specified columns from
the result set table based on the select list.

For example, SQL>select deptno from emp group by deptno;

Step-1: group by deptno; Step-2: select deptno

Deptno Deptno
Deptno
10 10 10
10
20 10 20 20
20
30 20 30 30
30
10 30

20 Result set table

30

Q) Write a query to display the departments having more than 3 employees from emp table
by using group by clause?

SQL> select deptno,count(*) from emp group by deptno where count(*)>3;

ERROR: ORA-00933: SQL command not properly ended

Having clause: After group clause we are not allowed to use where clause in place of this
ANSI/ISO SAL provided another clause “HAVING”.

Generally if you want to restrict rows in a table then we are using where clause
whereas if you want to restrict groups after group by clause then we must use having clause.

Syntax: select columnname...

From table name

Group by column name

Having condition;
Q) Write a query to display the departments having more than 3 employees from emp table
by using group by clause?

SQL> select deptno, count (*) from emp group by deptno having count (*)>3;

DEPTNO COUNT (*)

30 6

20 5

NOTE: Generally we are not allowed to use group functions in where clause where as we are
allowed to use group functions in having clause.

SQL> select * from emp where sal=max (sal);

ERROR: ORA-00934: group function is not allowed here

Q) Write a query to display the departments sum of salary having more than 10000 from emp
table by using group by clause?

SQL> select deptno, sum (sal) from emp group by deptno having sum (sal)>10000;

DEPTNO SUM (SAL)

20 10875

Q) Write a query to display year and number of employees per year in which more than one
employee was hired from emp table by using group by clause?

SQL> select to_char (hiredate, 'YYYY') "Year", count (*) from emp

group by to_char (hiredate ,'YYYY') having count(*)>1;

Year COUNT (*)

1892 2

1981 10

NOTE: In all databases we can also restrict groups by using invisible group functions in
having clause because whenever we are try t display group function values within group by
clause then database servers internally uses all group functions.

Q) Write a query to display each department sum of salary those departments having more
than 3 employees from emp table by using group by clause?

SQL> select deptno,sum(sal) from emp

group by deptno

having count(*)>3;
DEPTNO SUM (SAL)

30 9400

20 10875

Order by clause: This clause is used to arrange data either in ascending order (or) in
descending order. Along with order by clause we are using two key words. These are “asc”
and “desc” By default order by clause having ascending order.

Syntax: slect * from emp

Order by column name [asc/desc];

SQL> select * from dept order by deptno;

DEPTN DNAME LOC


O

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

SQL> select * from dept order by deptno asc;

DEPTN DNAME LOC


O

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

SQL> select * from dept order by deptno desc;

DEPTN DNAME LOC


O

40 OPERATIONS BOSTON
30 SALES CHICAGO

20 RESEARCH DALLAS

10 ACCOUNTING NEW YORK

NOTE: In oracle we can also use column number within order by clause this number
specifies column position.

SQL> select * from dept order by 1 desc;

DEPTN DNAME LOC


O

40 OPERATIONS BOSTON

30 SALES CHICAGO

20 RESEARCH DALLAS

10 ACCOUNTING NEW YORK

NOTE: Whenever we are using number in order by clause then oracle server checks that
number column is available in within slect list or not. If that column is not available then
oracle server returns an error.

SQL> select deptno, dname from dept order by 3 desc;

ERROR: ORA-01785: ORDER BY item must be the number of a SELECT-list expression

SQL> select deptno, dname from dept order by 1 desc;

DEPTNO DNAME

40 OPERATIONS

30 SALES

20 RESEARCH

10 ACCOUNTING

NOTE: Whenever we are using order by clause in null value columns then oracle server
returns null values last in ascending order and first in descending order. If you want to change
this default order then we can also use “nulls first” (or) “nulls last” clauses along with order
by clause.
SQL> select comm from emp order by comm asc;

COMM

300

SQL> select comm from emp order by comm desc;

COMM

300

SQL> select comm from emp order by comm asc nulls first;

COMM

300

SQL> select comm from emp order by comm desc nulls last;

COMM

300
NOTE: In all databases we can also use multiple columns within order by clause but in this
case database servers sorting data based on 1st column and also when 1st column data having
same data items then only database servers sorting data in second column based on the each
and every sub group of the first column.

SQL> select deptno, sal from emp order by deptno, sal;

DEPTN SAL
O

10 1300

10 2450

20 800

20 1100

30 950

30 1250

SQL> select deptno, sal from emp order by deptno asc, sal desc;

DEPTN SAL
O

10 5000

10 2450

20 3000

20 2975

30 2850

30 1600

Complete select statement syntax:

Syntax: select col1,col... from table name

Where condition

Group by clause

Having condition

Order by column name [asc/desc];

Q) Write a query to display those departments having more than 1000 salary and having more
than 3 employees and display in ascending order from emp table?
SQL> select deptno,count(*) from emp

where sal>1000

group by deptno

having count(*)>3

order by deptno asc;

DEPTNO COUNT(*)

20 4

30 5

Rollup and Cube: Oracle 8i introduced rollup, cube clauses these clauses are used along
with group by clause only. These clauses are optional clauses. If you want to calculate
subtotal, grand total automatically then we are using rollup, cube clauses in group by clause.

Syntax: select col1, col2...

From table name

Group by rollup (col1, col2,..);

Syntax: select col1, col2...

From table name

Group by cube (col1, col2,..);

Generally rollup is used to calculate subtotal values based on a single column at a


time whereas if you want to calculate subtotal values based on number of columns at a time
then we are using cube.

SQL> select deptno, job, sum (sal) from emp group by rollup (deptno, job);

DEPTN JOB SUM (SAL)


O

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

10 8750

20 CLERK 1900
20 ANALYST 6000

20 MANAGER 2975

20 10875

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

30 9400

29025

SQL> select deptno, job, sum (sal) from emp group by cube (deptno, job);

DEPTNO JOB SUM (SAL)

29025

CLERK 4150

ANALYST 6000

MANAGER 8275

SALESMAN 5600

PRESIDENT 5000

10 8750

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

20 10875

20 CLERK 1900

20 ANALYST 6000

20 MANAGER 2975

30 9400

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

SQL> select ename, sum (sal) from emp group by rollup (ename);
ENAME SUM (SAL)

DAMS 1100

ALLEN 1600

BLAKE 2850

CLARK 2450

10000

JOINS:

Joins are used to retrieve data from multiple tables. In all databases when we are
joining ‘n’ tables then we are using ‘(n-1)’ joining conditions. Oracle having following types
of joins. These are,

1. Equi join (or) Inner join

2. Non equi join

3. Self join

4. Outer join

These joins are also called as oracle 8i joins. Along with these joins oracle 9i onwards
oracle supports ANSI/ISO joins. These joins are also called as ANSI joins (or) 9i joins.

ANSI joins (or) 9i joins:

1. Inner joins

2. Left outer join

3. Right outer join

4. Full outer join

5. Natural join

In oracle we can also retrieve data from multiple tables without using joining
condition i.e., whenever we are specifying number of tables in from clause then oracle server
internally uses default join. In oracle default join is “cross join”. It returns more duplicate
data because cross join is implemented based on Cartesian product.

Syntax: select col1, col2, .. from tab1, tab2;

SQL> select empno, ename, dname, loc from emp, dept;

EMPNO ENAME DNAME LOC


7369 SMITH ACCOUNTING NEW YORK

7499 ALLEN ACCOUNTING NEW YORK

7369 SMITH RESEARCH DALLAS

7499 ALLEN RESEARCH DALLAS

7369 SMITH SALES CHICAGO

7499 ALLEN SALES CHICAGO

7369 SMITH OPERATIONS BOSTON

Equi join: Based on equality operator we are retrieving data from multiple tables. Here
joining conditional columns must belong to same data type.

Whenever tables having common columns then only we are allowed to use equi join. Here
these common columns must belong to same data type.

Syntax: select col1, col2, ..

From tablenam1, tablename2

Where table1.common column name= table2.common column name;

SQL> select ename, sal, deptno, dname, loc from emp, dept

where emp.deptno=dept.deptno;

ERROR: ORA-00918: column ambiguously defined

NOTE: For avoiding ambiguity error we must specify table name in front of the common
column name by using .(dot) operator.

SOL> select ename, sal, dept.deptno, dname, loc

from emp, dept

where emp.deptno=dept.deptno;

ENAME SAL DEPTNO DNAME LOC

SMITH 800 20 RESEARCH DALLAS

ALLEN 1600 30 SALES CHICAGO

WARD 1250 30 SALES CHICAGO


JONES 2975 20 RESEARCH DALLAS

NOTE: Generally for avoiding feature ambiguity we can also specify table name in each and
every column before with in select list.

Using aliasname: In oracle joins we can also create alias names for the tables within from
clause these alias names are also called as reference names. Once we are creating these alias
names in from clause then we are using these alias names in place of table names within
select list, within joining condition. These alias names must be different names.

Syntax: from tablename1aliasname1, tablename2 aliasname2,...

SOL> select ename, sal, d.deptno, dname, loc

from emp e, deptd

where e.deptno=d.deptno;

ENAME SAL DEPTNO DNAME LOC

SMITH 800 20 RESEARCH DALLAS

ALLEN 1600 30 SALES CHICAGO

WARD 1250 30 SALES CHICAGO

JONES 2975 20 RESEARCH DALLAS

NOTE: In all databases always equi joins returns matching rows only. [Here, deptno 40 does
not display when we are using d.deptno also]

Q) Write a query to display the employees who are working in the location CHICAGO from
emp, dept tables by using equi join?

SQL> select ename,loc,d.deptno

from emp e,dept d

where e.deptno=d.deptno

and loc='CHICAGO';

ENAME LOC DEPTNO

ALLEN CHICAGO 30
WARD CHICAGO 30

MARTI CHICAGO 30
N

NOTE: If you want to filter data after joining condition then we are using ‘AND’ operator in
8i joins whereas in 9i joins we are using either ‘AND’ operator or where clause.

Q) Write a query to display dname, sum (sal) from emp, dept tables by using equi join?

SQL> select dname, sum (sal)

from emp e,dept d

where e.deptno=d.deptno

group by dname;

DNAME SUM (SAL)

ACCOUNTIN 8750
G

RESEARCH 10875

SALES 9400

Q) Write a query to display deptno, dname, sum (sal) from emp, dept tables by using equi
join?

SQL> select d.deptno,dname,sum(sal)

from emp e,dept d

where e.deptno=d.deptno

group by d.deptno,dname;

DEPTNO DNAME SUM (SAL)

10 ACCOUNTING 8750

20 RESEARCH 10875

30 SALES 9400

Q) Write a query to display loc, count(*) from emp, dept tables by using equi join?

SQL> select loc,count(*) from emp e,dept d

where e.deptno=d.deptno

group by loc;
LOC COUNT (*)

NEWYORK 3

CHICAGO 6

DALLAS 5

Q) Write a query to display the employees having more than 9000 salary from emp, dept
tables by using equi join?

SQL> select dname,sum(sal) from emp e,dept d

where e.deptno=d.deptno

group by dname

having sum(sal)>9000;

DNAME SUM (SAL)

RESEARCH 10875

SALES 9400

Non equi join: Based on other than equality operator (<>,<=,>=,>,<,between, etc.,) we are
retrieving data from multiple tables.

Syntax: select col1, col2, ..

From tablenam1, tablename2

Where table1.common column name (other equal to{=} operator) table2.common column
name;

SQL> create table test1 (sno number (10));

Table created.

SQL> insert into test1 values (&no);

Enter value for no: 10

1 row created.

SQL> /

Enter value for no: 20


1 row created.

SQL> create table test2 (sno number (10));

Table created.

SQL> insert into test2 values (&no);

Enter value for no: 10

1 row created.

SQL> /

Enter value for no: 20

1 row created.

SQL> /

Enter value for no: 30

1 row created.

SQL> select * from test1;

SNO

10

20

SQL> select * from test2;

SNO

10

20

30

SQL> select * from test1, test2

where test1.sno>test2.sno;

SNO SNO

20 10
NOTE: In oracle by using non equi join we are retrieving data from multiple tables when a
table does not have common columns. In this case any one table one column values lies
between another table two columns that’s way this join is also called as “between..And” join.

SQL> select * from emp;

EMPN ENAME JOB MG HIREDATE SAL COMM DEPTNO


O R

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7900 JAMES CLERK 7698 03-DEC-81 950 30

7782 CLARK MANAGEE 7839 09-JUN-81 2450 10


R
..... .... .... ..... .... .... ....
.....

SQL> select * from salgrade;

GRADE LOSAL HISAL

1 700 1200

2 1201 1400

3 1401 2000

4 2001 3000

5 3001 9999

SQL> select ename,sal,losal,hisal

from emp,salgrade

where sal between losal and hisal;

SQL> select ename,sal,losal,hisal

from emp,salgrade

where sal>=losal and sal<=hisal;

ENAME SAL LOSAL HISAL

SMITH 800 700 1200

ADAMS 1100 700 1200

JAMES 950 700 1200


WARD 1250 1201 1400

Execution of join queries:

Sno Sno

10 10

20 20

30

Self join: Joining a table to itself is called self join. Here joining conditional columns must
belong to same data type.

Generally self join is used in following two scenarios.

1) When we are try to compare one column one value with all other values in same column
within same table.

2) When we are comparing two different column values from a same table in this case thes
two columns belong to same data type.

In all databases when we are using self join then we must create alias names for the
table in from clause. These alias names are also called as reference names. These alias names
must be different names. These alias names internally behaves like a exact tables when query
execution time.

Syntax: from table name alias name1, table name alias name2, ...

Comparing one column one value with all other values in a same column:

Q) Write a query to display the employees who are getting same salary as a scott salary from
emp table by using self join?

SQL> select e2.* from emp e1, emp e2

where e1.ename='SCOTT'

and e1.sal=e2.sal;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7902 FORD ANALYST 7566 03-DEC-81 3000 20

NOTE: When we are try to compare one value with all other values in a same column by
using self join then we must display data from second alias table. Otherwise oracle server
display wrong results.
SQL> select e1.* from emp e1, emp e2

where e1.ename='SCOTT'

and e1.sal=e2.sal;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

Comparing two different column values in a same table:

Generally if you want to compare two different table same columns then we are using
equi join whereas if you want to compare two different column values in a same table then
we must use self join but here these two columns must belong to same data type and also
having related data.

Q) Write a query to display employee names and their manager names from emp table by
using self join?

SQL> select e1.ename "EMPLOYEES", e2.ename "MANAGERS"

from emp e1,emp e2

where e1.mgr=e2.empno;

EMPLOYEE MANAGERS
S

FORD JONES

SCOTT JONES

JAMES BLAKE

TURNER BLAKE

MILLER CLERK

ADAMS SCOTT

CLARK KING

SMITH FORD

Q) Write a query to display employees who are getting more salary than their manager salary
from emp table by using self join?

SQL> select e1.ename "EMPLOYEES",e1.sal,e2.ename "MANAGERS",e2.sal


from emp e1,emp e2

where e1.mgr=e2.empno

and e1.sal>e2.sal;

EMPLOYEE SAL MANAGERS SAL


S

FORD 3000 JONES 2975

SCOTT 3000 JONES 2975

Q) Write a query to display employees who are joining before their managers from emp table
by using self join?

SQL> select e1.ename "EMPLOYEES", e1.hiredate, e2.ename "MANAGERS", e2.hiredate

from emp e1,emp e2

where e1.mgr=e2.empno

and e1.hiredate<e2.hiredate;

EMPLOYEE HIREDATE MANAGERS HIREDATE


S

WARD 22-FEB-81 BLAKE 01-MAY-81

BLAKE 09-JUN-81 KING 17-NOV-81

SMITH 17-DEC-80 FORD 3-DEC-81

Outer join: This join returns all rows from one table and matching rows from another table.

Generally equi join returns matching rows only if you want to retrieve non matching
rows also then we are using join operate (+) within joining condition of the equi join. This
join is also called as oracle 8i outer join.

Syntax: select col1, col2, ..

from table name1 alias name1, tablename2 aliasname2,...

where aliasname1.commmon columnname(+)= aliasname2.common column name2;

NOTE: Here, join operator can be used only one side at a time within joining condition.

SQL> select e.ename,d.deptno,sal,dname,loc

from emp e,dept d


where e.deptno(+)=d.deptno;

ENAME DEPTN SAL DNAME LOC


O

SMITH 20 800 RESEARCH DALLAS

WARD 30 1250 SALES CHICAGO

CLARK 10 2450 ACCOUNTING NEW YORK

40 OPERATIONS BOSTON

SQL> select e.ename,d.deptno,sal,dname,loc

from emp e,dept d

where e.deptno=(+)d.deptno;

ERROR: ORA-00936: missing expression

SQL> select e.ename,d.deptno,sal,dname,loc

from emp e,dept d

where e.deptno=d.deptno(+);

OUTPUT: wrong result it does not displays non matching rows.

ANSI joins (or) 9i joins: Along with oracle 8i joins oracle 9i introduced following joins.
These joins are called as ANSI joins because these joins are available in all databases. These
are,

1. Inner join

2. Left outer join

3. Right outer join

4. Full outer join

5. Natural join

Inner join: This join also returns matching rows only. whenever tables having common
columns then only we are allowed to use inner join. Here also joining conditional columns
must belong to same data type. Inner join performance is very high compared to equi join.

Syntax: select col1, col2, .. from tablename1 aliasname1 join tablename2 aliasname2

On aliasname1.common column name=aliasname2.common column name;


SOL> select ename, sal, d.deptno, dname, loc

from emp e, deptd

where e.deptno=d.deptno;

ENAME SAL DEPTNO DNAME LOC

SMITH 800 20 RESEARCH DALLAS

ALLEN 1600 30 SALES CHICAGO

WARD 1250 30 SALES CHICAGO

JONES 2975 20 RESEARCH DALLAS

Q) Write a query to display the employees who are working in the location CHICAGO from
emp, dept tables by using 9i inner join?

SQL> select ename,d.deptno,dname,loc

from emp e join dept d

on e.deptno=d.deptno

and (or) where d.loc=’CHICAGO’;

ENAME LOC DEPTNO

ALLEN CHICAGO 30

WARD CHICAGO 30

MARTI CHICAGO 30
N

SQL> create table test1 (a varchar2 (10), b varchar2 (10), c varchar2 (10));

Table created.

SQL> insert into test1 values ('X','Y','Z');

1 row created.

SQL> insert into test1 values ('P','Q','R');

1 row created.

SQL> create table test2 (a varchar2 (10), b varchar2 (10));


Table created.

SQL> insert into test2 values ('X','Y');

1 row created.

SQL> insert into test2 values ('S','T');

1 row created.

SQL> select * from test1;

A B C

X Y Z

P Q R

SQL> select * from test2;

A B

X Y

S T

SQL> select * from test1, test2

where test1.a=test2.a and test1.b=test2.b;

A B C A B

X Y Z X Y

SQL> select * from test1 join test2

on test1.a=test2.a and test1.b=test2.b;

A B C A B

X Y Z X Y

Using clause: Oracle 9i introduced using clause in place of ON clause. Using clause
performance is very high compared to on clause and also using clause returns common
columns one time only.

Syntax: select * from tablename1 join tablename2

using (common columnname1, common columnname2);


SQL> select * from test1 join test2

using (a, b);

A B C

X Y Z

Left outer join: This join returns all rows from left side table and matching rows from right
side table and also returns null values in place of non matching rows in another table.

Syntax: select col1, col2, .. from tablename1 aliasname1 left outer join tablename2
aliasname2

On aliasname1.common column name=aliasname2.common column name;

SQL> select * from test1 left outer join test2

on test1.a=test2.a and test1.b=test2.b;

A B C A B

X Y Z X Y

P Q R

SQL> select * from test1 left outer join test2

Using (a, b);

A B C

X Y Z

P Q R

Right outer join: This join returns all rows from right side table and matching rows from left
side table and also returns null values in place of non matching rows in another table.

Syntax: select col1, col2, .. from tablename1 aliasname1 right outer join tablename2
aliasname2

On aliasname1.common column name=aliasname2.common column name;

SQL> select * from test1 right outer join test2

on test1.a=test2.a and test1.b=test2.b;


A B C A B

X Y Z X Y

S T

SQL> select * from test1 right outer join test2

Using (a, b);

A B C

X Y Z

S T

Full outer join: This join returns all rows from all tables because it is a combination of both
left and right outer joins. This join also returns null values in place of non matching rows.

Syntax: select col1, col2, .. from tablename1 aliasname1 full outer join tablename2
aliasname2

On aliasname1.common column name=aliasname2.common column name;

SQL> select * from test1 full outer join test2

on test1.a=test2.a and test1.b=test2.b;

A B C A B

X Y Z X Y

S T

P Q R

SQL> select * from test1 full outer join test2

Using (a, b);

A B C

X Y Z

P Q R

S T
Natural join: This join also returns matching rows only. whenever tables having common
columns then only we are allowed to use this join.

When we are using natural join we are not allowed to use any joining condition in this
case database servers only internally automatically establishes joining condition based on the
common column names. This join performance is very high compared to inner join.

Syntax: select * from tablename1 natural join tablename2;

NOTE: whenever we are using natural join internally database servers uses “using clause”
that’s way this join return common columns one time only.

SQL> select * from test1 natural join test2;

A B C

X Y Z

NOTE: whenever we are using natural join (or) using clause then we are not allowed to use
alias name on joining conditional column within select list otherwise oracle server returns an
error.

SQL> select ename, sal, d.deptno, loc from emp e natural join dept d;

ERROR: ORA-25155: column used in NATURAL join cannot have qualifier

SQL> select ename, sal, d.deptno, dname, loc from emp e join dept d

Using (deptno);

ERROR: ORA-25154: column part of USING clause cannot have qualifier

SQL> select ename, sal, deptno, loc from emp e natural join dept d;

SQL> select ename,sal,deptno,dname,loc

from emp e join dept d

using (deptno);

ENAME SAL DEPTNO LOC

SMITH 800 20 DALLAS

ALLEN 1600 30 CHICAGO

WARD 1250 30 CHICAGO

JONES 2975 20 DALLAS


Join Subtraction:

Syntax: select * from table1 left outer join table2

On table1.key=table2.key

Where table2.key is null;

Syntax: select * from table1 right outer join table2

On table1.key=table2.key

Where table1.key is null;

Syntax: select * from table1 full outer join table2

On table1.key=table2.key

Where table1.key is null

Or table2.key is null;

SQL> create table test1 (sno number (10));

Table created.

SQL> insert into test1 values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> create table test2 (sno number (10));

Table created.
SQL> insert into test2 values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 40

1 row created.

SQL> select * from test1;

SNO

10

20

30

SQL> select * from test2;

SNO

10

20

40

SQL> select * from test1 left outer join test2

on test1.sno=test2.sno

where test2.sno is null;

SNO SNO

30

SQL> select * from test1 right outer join test2

on test1.sno=test2.sno

where test1.sno is null;


SNO SNO

40

SQL> select * from test1 full outer join test2

on test1.sno=test2.sno

where test2.sno is null or test1.sno is null;

SNO SNO

30

40

Joining more than two tables:

Syntax for 8i joins: select col1, col2, .. from table1, table2, table3

Where table1.common column name=table2.common column name

And table2.common column name=table3.common column name;

Syntax for 9i joins: select col1, col2, .. from table1 join table2

on table1.common column name=table2.common column name

join table3

on table2.common column name=table3.common column name;

CONSTRAINTS:

Constraints are used to prevent invalid data entry into our tables. Generally
constraints are created on table columns. oracle having following constraints. These are,

1. Not null

2. Unique

3. Primary key

4. Foreign key

5. Check
In all databases all above constraints are defined in two ways. They are

1. Column level

2. Table level

Column level: In this method we are defining constraints on individual columns i.e.,
whenever we are defining the column then only immediately we can specify constraint type.

Syntax: create table tablename (col1 datatype (size) constraint type,

col2 datatype (size) constraint type,...);

Table level: In this method we are defining constraints on group of columns i.ee., first we are
defining all columns and then only we are specifying constraint type along with group of
columns.

Syntax: create table tablename (col1 datatype (size), col2 datatype (size),....

Constraint type (col1, col2, ...));

Not null: Not null constraint does not support table level. This constraint does not accepts
null values but it will accept duplicate values.

Column level:

Syntax: create table tablename (col1 datatype (size) not null,

col2 datatype (size) not null,....);

SQL> create table test (sno number (10) not null, name varchar2 (10));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: null

Enter value for name: UMESH

ERROR: ORA-01400: cannot insert NULL into ("SCOTT"."TEST"."SNO")

SQL> insert into test values (&sno, '&name');


Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> select * from test;

SNO NAME

10 UMESH

10 UMESH

Table level:

Syntax: create table tablename (col1 datatype (size), col2 datatype (size),....

Not null (col1, col2,...));

SQL> create table test (sno number (10), name varchar2 (10) not null (sno, name));

ERROR: ORA-00907: missing right parenthesis

Unique: It does not accept duplicate data but it can accept null values. This constraint is
defined in both column level and table level.

Column level:

Syntax: create table tablename (col1 datatype (size) unique,

col2 datatype (size) unique,....);

SQL> create table test (sno number (10) unique, name varchar2 (10));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: UMESH

1 row created.
SQL> /

Enter value for sno: NULL

Enter value for name: RAJU

1 row created.

SQL> /

Enter value for sno: 10

Enter value for name: ABC

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007197) violated

SQL> select * from test;

SNO NAME

10 UMESH

10 UMESH

RAJU

SQL> create table test (sno number (10) unique, name varchar2 (10) unique);

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: NULL

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: NULL

1 row created.
SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: SSS

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007198) violated

SQL> /

Enter value for sno: 30

Enter value for name: ABC

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007199) violated

SNO NAME

10 UMESH

ABC

20

Table level:

Syntax: create table tablename (col1 datatype (size), col2 datatype (size),.... ,

unique (col1, col2,...));

SQL> create table test (sno number (10), name varchar2 (10) ,unique (sno, name));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: NULL

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 20


Enter value for name: NULL

1 row created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: SSS

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: UMESH

1 row created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007200) violated

SQL> select * from test;

SNO NAME

10 UMESH

ABC

20 NULL

10 SSS

20 UMESH

Primary key: Primary key is used to identifying a record in a table uniquely. There can be
only one primary keyin a table and also primary does not accept null values and duplicate
data.

Column level:

Syntax: create table tablename (col1 datatype (size) primary key,

col2 datatype (size) primary key,....);


SQL> create table test (sno number (10) primary key, name varchar2 (10) primary key);

ERROR: ORA-02260: table can have only one primary key

SQL> create table test (sno number (10) primary key, name varchar2 (10));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: NULL

1 row created.

SQL> /

Enter value for sno: 30

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 10

Enter value for name: UMESH

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007202) violated

SQL> /

Enter value for sno: NULL

Enter value for name: UMESH

ERROR: ORA-01400: cannot insert NULL into ("SCOTT"."TEST"."SNO")

SQL> select * from test;


SNO NAME

10 UMESH

20 NULL

30 UMESH

Table level:

Syntax: create table tablename (col1 datatype (size), col2 datatype (size),.... ,

Primary key (col1, col2,...));

NOTE: This is also called as “composite primary key” because it is the combination of
columns as a single primary key.

SQL> create table test (sno number (10), name varchar2 (10), primary key (sno, name));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 10

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: NULL

Enter value for name: ABC

ERROR: ORA-01400: cannot insert NULL into ("SCOTT"."TEST"."SNO")

SQL> /
Enter value for sno: 10

Enter value for name: NULL (because it takes as string)

1 row created.

SQL> select * from test;

SNO NAME

10 UMESH

10 ABC

20 ABC

10 NULL

NOTE: In all databases whenever we are creating unique constraint or primary key then
database servers internally automatically creates “Btree indexes” on those columns.

Foreign key: If you want to establish relationship between tables then we must use
referential integrity constraint foreign key. One table foreign key must belong to another table
primary key. In all databases always foreign key values based on primary key values only.

Generally primary key does not accept duplicate, null values wheras foreign ky accpts
duplicate, null values and also primary key column and related foreign key column must
belong to same data type.

Column level:

Syntax: create table tablename (col1 datatype (size) references

mastertablename (primary key column name),....);

SQL> create table test (sno number (10) primary key, name varchar2 (10));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /
Enter value for sno: 20

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 30

Enter value for name: PQR

1 row created

SQL> /

Enter value for sno: 40

Enter value for name: XYZ

1 row created.

SQL> select * from test;

SNO NAME

10 UMESH

20 ABC

30 PQR

40 XYZ

SQL> create table test1 (sno number (10) references test); (or)

SQL> create table test1 (sno number (10) references test (sno));

Table created.

SQL> insert into test1 values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /
Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 50

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007219) violated - parent key not


found

SQL> select * from test1;

SNO

10

20

10

20

SQL> create table test2 (sno number (10), references test2);

ERROR: ORA-00902: invalid datatype

SQL> create table test2 (sno number (10), references test);

ERROR: ORA-00902: invalid datatype

Table level:

Syntax: create table tablename (col1 datatype(size), col2 datatype(size),....,

Foreign key (col1, col2, ....) mastertablename (primary key column values));

SQL> create table test(sno number(10),name varchar2(10),primary key(sno,name));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 10

Enter value for name: UMESH

1 row created.
SQL> /

Enter value for sno: 20

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 30

Enter value for name: PQR

1 row created.

SQL> /

Enter value for sno: 30

Enter value for name: NULL

1 row created.

SQL> /

Enter value for sno: 40

Enter value for name: ABC

1 row created.

SQL> select * from test;

SNO NAME

10 UMESH

20 ABC

30 PQR

30 NULL

40 ABC

SQL> create table test1 (sno number (10), name varchar2 (10), foreign key (sno, name)
references test);

Table created.

SQL> insert into test1 values (&sno, '&name');


Enter value for sno: 10

Enter value for name: ABC

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007222) violated - parent key not


found

SQL> /

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 10

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: NULL

Enter value for name: 30

1 row created.

SQL> /

Enter value for sno: 20

Enter value for name: ABC

1 row created.

SQL> /

Enter value for sno: 70

Enter value for name: ABC

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007222) violated - parent key not


found

SQL> /

Enter value for sno: NULL

Enter value for name: NULL


1 row created.

SQL> select * from test1;

SNO NAME

10 UMESH

10 UMESH

30

20 ABC

NULL

Whenever we are establishing relationship between tables then oracle server violates
following two rules. These are,

1. Deletion in master table

2. Insertion in child table

Deletion in master table:

Whenever we are tried to delete master table record in master table if those records
are available in child table then oracle server returns an error ORA-2292. To overcome this
problem first we are deleting those records in child table then only we are allowed to delete
those records in master table otherwise using “on delete cascade”. This is an optional clause
used along with foreign key only.

On delete cascade clause: whenever child table having on delete cascade clause along with
foreign key then we are deleting master table record within master table then automatically
those records are deleted in master table as well as child table also.

Syntax: create table tablename (col1 datatype (size) referencs mastertablename (primary key
columnname) on delete cascade,....);

SQL> create table mas (sno number (10) primary key);

Table created.

SQL> insert into mas values (&sno);

Enter value for sno: 10

1 row created.
SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> select * from mas;

SNO

10

20

30

SQL> create table child (sno number (10) references mas (sno));

Table created.

SQL> insert into child values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30


1 row created.

SQL> /

Enter value for sno: 40

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007224) violated - parent key not


found

SQL> select * from child;

SNO

10

10

20

20

30

Testing: SQL> delete from mas where sno=10;

ERROR: ORA-02292: integrity constraint (SCOTT.SYS_C007224) violated - child record


found

SQL> delete from child where sno=10;

2 rows deleted.

SQL> select * from child;

SNO

20

20

30

SQL> delete from mas where sno=10;

1 row deleted.

SQL> select * from mas;

SNO

20

30
SQL> drop table mas;

ERROR: ORA-02449: unique/primary keys in table referenced by foreign keys

SQL> drop table child;

Table dropped.

SQL> drop table mas;

Table dropped.

SQL> create table mas (sno number (10) primary key);

Table created.

SQL> insert into mas values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> select * from mas;

SNO

10

20

30

SQL> create table child (sno number (10) references mas (sno) on delete cascade);

Table created.
SQL> insert into child values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> /

Enter value for sno: 40

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007224) violated - parent key not


found

SQL> select * from child;

SNO

10

10

20

20

30

Testing: SQL> delete from mas where sno=10;


1 row deleted.

SQL> select * from mas;

SNO

20

30

SQL> select * from child;

SNO

20

20

30

SQL> drop table mas;

ERROR: ORA-02449: unique/primary keys in table referenced by foreign keys

SQL> drop table child;

Table dropped.

SQL> drop table mas;

Table dropped.

Oracle also supports another clause “on delete set null” along with foreign key.

On delete set null: whenever foreign key having on delete set null clause then we are
deleting primary key values within master table then that primary key values are deleted in
master table and also those values are also deleted in child table and set to null values.

Syntax: create table tablename (col1 datatype (size) references mastertablename (primary
key column name) on delete set null,.....);

SQL> create table mas (sno number (10) primary key);

Table created.

SQL> insert into mas values (&sno);

Enter value for sno: 10

1 row created.
SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> select * from mas;

SNO

10

20

30

SQL> create table child (sno number (10) references mas (sno) on delete set null);

Table created.

SQL> insert into child values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /
Enter value for sno: 30

1 row created.

SQL> /

Enter value for sno: 40

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007224) violated - parent key not


found

SQL> select * from child;

SNO

10

10

20

20

30

Testing:

SQL> delete from mas where sno=10;

1 row deleted.

SQL> select * from mas;

SNO

20

30

SQL> select * from child;

SNO

20

20

30
NOTE: Modifying (or) updating data in master table is not possible in oracle SQL server
because there are no on update set clauses in oracle SQL server but this will be achieved by
using triggers in PL/SQL.

SQL> update mas set sno=20 where sno=10;

0 rows updated.

SQL> update mas set sno=10 where sno=30;

ERROR: ORA-02292: integrity constraint (SCOTT.SYS_C007229) violated - child record


found

SQL> update child set sno=10 where sno=30;

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007229) violated - parent key not


found

SQL> update child set sno=20 where sno=30;

1 row updated.

SQL> update mas set sno=10 where sno=30;

1 row updated.

SQL> select * from child;

SNO

20

20

20

SQL> select * from mas;

SNO

20

30
Insertion in child table:

When we are try to insert other than primary key values into foreign keythen oracle
server returns an error ORA-2291 because in all databases always foreign key values are
based on primary key values only.

SQL> create table mas (sno number (10) primary key);

Table created.

SQL> insert into mas values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> select * from mas;

SNO

10

20

30

Testing: SQL> create table child (sno number (10) references mas (sno) on delete set null);

Table created.

SQL> insert into child values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 10


1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> /

Enter value for sno: 40

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007224) violated - parent key not


found

SQL> select * from child;

SNO

10

10

20

20

30

Solution: SQL> insert into mas values (&sno);

Enter value for sno: 40

1 row created.

SQL> insert into child values (&sno);

Enter value for sno: 40

1 row created.

SQL> select * from mas;


SNO

10

20

30

40

SQL> select * from child;

SNO

10

10

20

20

30

40

Truncate table cascade: (12C)

Generally in all databases we cannot truncate master tables if those records are available in
child table. To overcome this problem oracle 12c introduced “truncate table cascade” clause
which truncates master table if those records are there in child table also before we are using
this cascade clause then we must use on delete cascade clause along with foreign key with in
child table.

Syntax: truncate table tablename cascade;

SQL> create table mas (sno number (10) primary key);

Table created.

SQL> insert into mas values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.
SQL> /

Enter value for sno: 30

1 row created.

SQL> select * from mas;

SNO

10

20

30

SQL> create table child (sno number (10) references mas (sno) on delete set null);

Table created.

SQL> insert into child values (&sno);

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 10

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 20

1 row created.

SQL> /

Enter value for sno: 30

1 row created.

SQL> /
Enter value for sno: 40

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C007224) violated - parent key not


found

SQL> select * from child;

SNO

10

10

20

20

30

Testing: SQL> truncate table mas;

ERROR: ORA-02266: unique/primary keys in table referenced by enabled foreign keys

Solution: (12c) SQL> truncate table mas cascade;

SQL> select * from mas;

SQL> select * from child;

Check: This constraint is used to define logical conditions according to our business rules. In
oracle check constraint does not work with “sysdate” function.

Column level:

Syntax: create table tablename (col1 datatype (size) check (logical condition),...);

SQL> create table test (name varchar2 (10) check (name=upper (name)));

Table created.

SQL> insert into test values ('&name');

Enter value for name: ABC

1 row created.
SQL> /

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for name: umesh

ERROR: ORA-02290: check constraint (SCOTT.SYS_C007693) violated

SQL> select * from test;

NAME

ABC

UMESH

Table level:

Syntax: create table tablename (col1 datatype (size), col2 datatype (size),...

,check (logical condition1 and logical condition2,...));

SQL> create table test (sno number (10), name varchar2 (10), check (name=upper (name)
and sno>2000));

Table created.

SQL> insert into test values (&sno, '&name');

Enter value for sno: 3000

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: 2500

Enter value for name: umesh

ERROR: ORA-02290: check constraint (SCOTT.SYS_C007694) violated

SQL> /

Enter value for sno: 1000

Enter value for name: UMESH

ERROR: ORA-02290: check constraint (SCOTT.SYS_C007694) violated


SQL> /

Enter value for sno: 3000

Enter value for name: UMESH

1 row created.

SQL> /

Enter value for sno: NULL

Enter value for name: NULL

1 row created.

SQL>/

Enter value for sno: 2500

Enter value for name:

1 row created.

SQL> select * from test;

SNO NAME

3000 UMESH

3000 UMESH

NULL

2500

Assign user defined names to constraints (or) constraint names:

Whenever w are creating constraints then database servers internally automatically


generates an unique identification a constraint uniquely. oracle server also automatically
generates an unique identification number in the format of “SYS_CN” for identifying a
constraint uniquely. This is called pre-defined constraint name. In place of this we can also
create user defined name by using “constraint” keyword.

Syntax: constraint user defined name constraint type

Pre-defined constraint name:

SQL> create table test (sno number (10) primary key);

Table created.
SQL> insert into test values (1);

1 row created.

SQL> insert into test values (1);

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C007695) violated

User defined constraint name:

SQL> create table test1 (sno number (10) constraint pk_sno primary key);

Table created.

SQL> insert into test1 values (1);

1 row created.

SQL> insert into test1 values (1);

ERROR: ORA-00001: unique constraint (SCOTT.PK_SNO) violated

Data dictionaries (or) Read only tables:

Whenever we are installing oracle server then automatically oracle server creates read
only tables which stores specific information related to data base objects. These read only
tables are also called as data dictionaries. In oracle if you want to view these data dictionaries
then we are using following select statement syntax.

Syntax: select * from dict;

NOTE: In all oracle all constraints information stored under “user_constraints” data
dictionary.

SQL> desc user_constraints;

Name Null? Type

OWNER VARCHAR2 (120)

CONSTRAINT_NAME NOT NULL VARCHAR2 (30)

CONSTRAINT_TYPE VARCHAR2 (1)

TABLE_NAME NOT NULL VARCHAR2 (30)

SEARCH_CONDITION LONG

SQL> select CONSTRAINT_NAME, CONSTRAINT_TYPE from user_constraints


where TABLE_NAME='EMP';

CONSTRAINT_NAME C

SYS_C007026 C

SQL> create table test (empno number (10) not null, ename varchar2 (10) unique, sal number
(10) check (sal>2000), deptno number (10) primary key);

Table created.

SQL> select constraint_name, constraint_type from user_constraints

where table_name='TEST';

CONSTRAINT_NAM C
E

SYS_C007697 C

SYS_C007698 C

SYS_C007699 P

SYS_C007700 U

SQL> create table test1 (deptno number (10) references test (deptno));

Table created.

SQL> select constraint_name, constraint_type from user_constraints

where table_name='TEST1';

CONSTRAINT_NAME C

SYS_C007701 R

SQL> create table test2 (empno number (10) constraint nn_empno not null, ename varchar2
(10) constraint u_name unique, sal number (10) constraint c_sal check (sal>2000), deptno
number (10) constraint pk_deptno primary key);

Table created.

SQL> select constraint_name, constraint_type from user_constraints

where table_name='TEST2';
CONSTRAINT_NAM C
E

NN_EMPNO C

C_SAL C

PK_DEPTNO P

U_NAME U

SQL> create table test3 (deptno number (10) constraint fk_deptno references test (deptno));

Table created.

SQL> select constraint_name, constraint_type, owner from user_constraints

where table_name='TEST3';

CONSTRAINT_NAME C OWNER

FK_DEPTNO R SCOTT

NOTE: In oracle if you want to view logical condition of the check constraint then we are
using “search_condition” property from user_constraints data dictionary.

SQL> select search_condition from user_constraints

where table_name='TEST';

SEARCH_CONDITION

"EMPNO" IS NOT NULL

sal>2000

NOTE: In oracle if you want to view column names along with constraint names then we are
using “user_cons_columns” data dictionary.

SQL> desc user_cons_columns;

Name Null? Type

OWNER NOT NULL VARCHAR2 (30)

CONSTRAINT_NAME NOT NULL VARCHAR2 (30)

COLUMN_NAME VARCHAR2 (4000)

TABLE_NAME NOT NULL VARCHAR2 (30)

POSITION NUMBER

SQL> select constraint_name, column_name from user_cons_columns


where table_name='TEST';

CONSTRAINT_NAM COLUMN_NAME
E

SYS_C007697 EMPNO

SYS_C007698 SAL

SYS_C007699 DEPTNO

SYS_C007700 ENAME

SQL> select constraint_name,column_name from user_cons_columns

where table_name='TEST1';

CONSTRAINT_NAME COLUMN_NAME

SYS_C007701 DEPTNO

SQL> select constraint_name, column_name, position from user_cons_columns

where table_name='TEST3';

CONSTRAINT_NAME COLUMN_NAME POSITION

FK_DEPTNO DEPTNO 1

NOTE: In oracle all columns information stored under “user_tab_columns” data dictionary.

SQL> desc user_tab_columns;

SQL> select column_name, data_type, data_length from user_tab_columns

where table_name='TEST';

COLUMN_NAME DATA_TYPE DATA_LENGTH

EMPNO NUMBER 22

ENAME VARCHAR2 10

SAL NUMBER 22

DEPTNO NUMBER 22

Q) Write a query which counts number of columns from emp table?

SQL> select count (*) from user_tab_columns where table_name='EMP';

COUNT(*)

8
Default clause:

In oracle we can also pass default values for a column by specifying default clause
along with column name. This is also called as “default constraint”.

Syntax: column name datatype (size) default defaultvalue;

SQL> create table test (sno number (10), sal number (10) default 2000, name varchar2(10)
default ‘UMESH’;

Table created.

SQL> insert into test (sno) values (10);

1 row created.

SQL> select * from test;

SNO SAL NAME

10 2000 UMESH

NOTE: In oracle if you want to view default values for a column then we are using
“data_default” property from “user_tab_columns” data dictionary.

SQL> select data_default from user_tab_columns

where table_name='TEST';

DATA_DEFAULT

2000

‘UMESH’

Adding (or) Dropping constraints on existing table:

By using alter command we can also add (or) drop constraints on existing table.

NOTE-1: If you want to add constraints on existing table and existing column then we are
using table level syntax methods.

Syntax: alter table tablename add constraint type (existing column name);

SQL> create table test (sno number (10), name varchar2 (10), sal number (10));

Table created.
Name Null? Type

SNO NUMBER (10)

NAME VARCHAR2 (10)

SAL NUMBER (10)

SQL> alter table test add sno primary key;

ERROR: ORA-02263: need to specify the datatype for this column

Primary key:

SQL> alter table test add primary key (name);

Table altered.

SQL> desc test;

Name Null? Type

SNO NUMBER (10)

NAME NOT NULL VARCHAR2 (10)

Not null:

SQL> alter table test add not null (sno);

ERROR: ORA-00904: : invalid identifier

Unique:

SQL> alter table test add unique (sno);

Table altered.

SQL> insert into test values (10, 'UMESH', 2500);

1 row created.

SQL> insert into test values (10, 'RAJU', 2500);

ERROR: ORA-00001: unique constraint (SCOTT.SYS_C005466) violated

Check:

SQL> alter table test add check sal>2000;

Table altered.

SQL> insert into test values (20, ‘RAJU’, 1500);


ERROR: ORA-02290: check constraint (SCOTT.SYS_C005467) violated

Foreign key:

SQL> create table test1 (name varchar2 (10));

Table created.

SQL> alter table test1 add foreign key (name) references test (name);

SQL> insert into test1 values (‘RAJU’);

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C005469) violated - parent key not


found

NOTE-2: If you want to add a new column along with constraint then we are using column
level syntax method.

Syntax: alter table tablename add column name datatype (size) constraint type;

SQL> create table test (sno number (10));

Table created.

Not null:

SQL> alter table test add name varchar2 (10) not null;

Table altered.

SQL> desc test;

Name Null? Type

SNO NUMBER (10)

NAME NOT NULL VARCHAR2 (10)

Unique:

SQL> alter table test add dname varchar2 (10) unique;

Table altered.

SQL> insert into test values (10, 'UMESH', 'SALES');

1 row created.

SQL> insert into test values (20, 'ABC', 'SALES');


ERROR: ORA-00001: unique constraint (SCOTT.SYS_C005473) violated

Check:

SQL> alter table test add sal number (10) check (sal>2000);

Table altered.

SQL> insert into test values (10, 'UMESH', 'SALES', 1500);

ERROR: ORA-02290: check constraint (SCOTT.SYS_C005474) violated

Primary key:

SQL> create table test (sno number (10));

Table created.

SQL> alter table test add name varchar2 (10) primary key;

Table altered.

SQL> desc test;

Name Null? Type

SNO NUMBER (10)

NAME NOT NULL VARCHAR2 (10)

Foreign key:

SQL> create table test1 (sno number (10));

Table created.

SQL> alter table test1 add name varchar2 (10) references test (name); (or)

SQL> alter table test1 add name varchar2 (10) references test;

Table altered.

SQL> insert into test values (10, 'UMESH');

1 row created.

SQL> insert into test1 values (20, 'UMESH');

1 row created.

SQL> insert into test1 values (20, 'ABC');

ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C005476) violated - parent key not


found
NOTE-3: If you want to add not null constraint on existing column and existing table then we
are using following syntax. This syntax is also working for other constraint types also.

NOTE: here, not null constraint is does not working table level and column level adding
constraints.

Syntax: alter table tablename modify column name not null

SQL> alter table test modify sno not null;

Table altered.

SQL> desc test;

Name Null? Type

SNO NOT NULL NUMBER(10)

NOTE-4: If all databases whenever we are copying a table from another table constraints are
never copied except not null constraints.

SQL> create table test (sno number (10) not null, name varchar2 (10) primary key, sal
number (10) unique);

Table created.

SQL> desc test;

Name Null? Type

SNO NOT NULL NUMBER (10)

NAME NOT NULL VARCHAR2 (10)

SAL NUMBER (10)

SQL> create table test1 as select * from test;

Table created.

SQL> desc test1;

Name Null? Type

SNO NOT NULL NUMBER (10)

NAME VARCHAR2 (10)


SAL NUMBER (10)

Dropping constraints:

Method-1: In this dropping constraint is done by using “constraint_name” property from


“user_constraints” (or) “user_cons_columns” data dictionary.

Syntax: alter table tablename drop constraint constraint_name;

SQL> create table test (sno number (10) not null);

Table created.

Name Null? Type

SNO NOT NULL NUMBER(10)

SQL> select constraint_name from user_constraints where table_name='TEST'; (or)

SQL> select constraint_name from user_cons_columns where table_name='TEST';

CONSTRAINT_NAME

SYS_C005486

SQL> alter table test drop constraint SYS_C005486;

Table altered.

SQL> desc test;

Name Null? Type

SNO NUMBER(10)

Method-2: In this method dropping constraint is done by using constraint_type.

Syntax: alter table tablename drop primary key;

Alter table tablename drop unique (column name);

SQL> create table test (sno number (10) primary key, name varchar2 (10) unique, sal number
(10) unique);

Table created.

SQL> desc test;


Name Null? Type

SNO NOT NULL NUMBER (10)

NAME VARCHAR2 (10)

SAL NUMBER (10)

SQL> alter table test drop primary key;

Table altered.

SQL> alter table test drop unique(name,sal);

ERROR: ORA-02442: Cannot drop nonexistent unique key

SQL> alter table test drop unique (name);

Table altered.

SQL> alter table test drop unique (sal);

Table altered.

NOTE: In oracle if you want to drop primary key along with referenced foreign keys then we
are using “cascade clause” along with alter..drop.

Syntax: alter table tablename drop primary key cascade;

SQL> create table test (sno number (10) primary key);

Table created.

SQL> create table test1 (sno number (10) references test);

Table created.

SQL> alter table test drop primary key;

ERROR: ORA-02273: this unique/primary key is referenced by some foreign keys

SQL> alter table test drop primary key cascade;

Table altered.

You might also like