Professional Documents
Culture Documents
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.
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;
EMP TABLE
DEPT TABLE
BONUS TABLE
SALGRADE TABLE
DUMMY TABLE
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.
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.
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.
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.
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.
Set of commands used to perform operations over data are called DML commands. These are
INSERT, UPDATE, DELETE, MERGE (9i) and INSERT ALL (9i).
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.
Set of commands used to control transactions over DML operations are called TCL
commands. These are COMMIT, ROLLBACK and SAVEPOINT.
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);
Table created.
SNO NUMBER(7)
1 row created.
1 row created.
1 row created.
1 row created.
SNO
100
99
100
100
ERROR: ORA-01438: value larger than specified precision allowed for this column
Table created.
SNO NUMBER(7,2)
1 row created.
1 row created.
1 row created.
1 row created.
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.
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.
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.
Table created.
SNO CHAR(6)
1 row created.
1 row created.
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.
Table created.
SNO VARCHAR2(6)
SQL> insert
1 row created.
1 row created.
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.
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.
Table created.
1 row created.
1 row created.
UMESH
852852
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
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.,
column2 datatype(size),
........
........
columnN datatype(size));
Table created.
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.
Table altered.
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.
Table altered.
SNO NUMBER(10)
COUNTRY_CODE CHAR(3)
ENAME VARCHAR2(20)
HIREDATE DATE
SAL NUMBER(10)
Table altered.
SNO NUMBER(10)
COUNTRY_CODE NUMBER(3)
ENAME VARCHAR2(10)
HIREDATE DATE
SAL NUMBER(10)
Table altered.
SNO NUMBER(10)
ENAME VARCHAR2(20)
HIREDATE DATE
SAL NUMBER(10)
Table altered.
SNO NUMBER(10)
ENAME VARCHAR2(20)
HIREDATE DATE
SNO NUMBER(10)
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.
Table dropped.
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.
SNO NUMBER(10)
To Drop Permanently:
Table dropped.
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.
ORIGINAL_NAME
TEST
Recyclebin purged.
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.
Table created.
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Table truncated.
no rows selected
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
Renaming a Table:
Table renamed.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Table altered.
DNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
NOTE: In all Databases by default all DDL commands are automatically committed (saved).
Table created.
SNO NUMBER(10)
NAME VARCHAR2(10)
Table altered.
SNO NUMBER(10)
ENAME VARCHAR2(10)
SQL> rollback;
Rollback complete.
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
INSERT: It is used to insert data into table. There are 3 methods are there to insert data.
Method-1:
Table created.
1 row created.
1 row created.
SNO NAME
1 UMESH
2 RAJU
1 row created.
SQL> /
1 row created.
SNO NAME
1 UMESH
2 RAJU
3 RUKKU
4 SATHI
Method-3:(Skipping columns)
1 row created.
1 row created.
SNO NAME
1 UMESH
2 RAJU
3 RUKKU
4 SATHI
5
SANTHU
1 row updated.
1 row updated.
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.
6 rows deleted.
no rows selected
Rollback complete.
SQL> select * from test;
SNO NAME
1 UMESH
2 RAJU
3 RUKKU
4 SATHI
5 LANKE
6 SANTHU
1 row deleted.
SNO NAME
1 UMESH
2 RAJU
3 RUKKU
4 SATHI
5 LANKE
Rollback complete.
SNO NAME
1 UMESH
2 RAJU
3 RUKKU
4 SATHI
5 LANKE
6 SANTHU
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.
Table created.
1 row created.
SQL> /
1 row created.
SQL> commit;
Commit complete.
SNO
2 rows deleted.
SQL> rollback;
Rollback complete.
SNO
Table truncated.
no rows selected
SQL> rollback;
Rollback complete.
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.
from tablename
where condition
group by clause
having condition
order by clause[asc/desc];
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
DEPTNO
10
20
30
40
DEPTNO
Selecting all columns and particular rows:
20
SQL> select * from dept where deptno=10;
Table created.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
Syntax: create table newtablename as select * from existing tablename where false condition;
Table created.
no rows selected
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
2. Relational (or) Comparison Operators [=, <, <=, >, >=, <> (or) !=]
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;
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?
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?
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?
Q) Write a query to display the employees those who are working under job as clerk or
salesman from emp table?
Q) Write a query to display the employees who are getting more than 2000 salary and less
than 5000 salary from emp table?
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?
Q) Write a query to display the employee whose ename is blake from emp table?
Q) Write a query to display the employee whose ename is blake from emp table?
no rows selected
Q) Write a query to display the employees whose are joined after 1981 from emp table?
Q) Write a query to display the employees whose are joined in the year 1981 from emp
table?
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;
Q) Write a query to display the employees whose job as clerk or manager and salary more
than 2000 from emp table?
EXP: Here, output is wrong because AND operator has got more priority than OR operator
1. In, not in
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.
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);
Q) Write a query to display the employees whose job is either clerk or manager from emp
table by using In operator?
Q) Write a query to display the employees who are working other than deptno 10,20 from
emp table by using NOT IN operator?
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.
no rows selected.
Q) Write a query to display ename, sal comm, sal+comm of the employee SMITH from emp
table?
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.
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.
nvl (10,20)10
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;
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';
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?
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 not null;for is not null
Q) Write a query to display employees whose commission is null from emp table?
no rows selected
Q) Write a query to display employees whose commission is not a null from emp table?
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 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?
Q) Write a query to display the employee whose ename having any letter ‘M’ from emp
table by using like operator?
Q) Write a query to display the employees whose are joined in the month of FEB from emp
table by using like operator?
Q) Write a query to display the employees whose are joined in the year of 81 from emp table
by using like operator?
Q) Write a query to display the employees whose ename second letter is capital letter ‘A’
from emp table by using like operator?
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?
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.
Q) Write a query to display the employees whose ename start with ‘S_’ from emp table by
using like operator?
1 row created.
1 S_MITH
1 S_MITH
Concatenation Operator: (||) If you want to display column data along with literal strings
then we must use concatenation operator. (||)
'MYEMPLOYEENAMESARE'||ENAME
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
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 (-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.
SQL> select sign (70), sign (-70), sign (0) from dual;
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.
DUMMY VARCHAR2(1)
Testing:
90
30+50
80
MOD (10, 2)
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.
NOTE: It always checks’ remaining number if remaining number is above 50% ten
automatically one added to the rounded number
ROUND (1.7)
2
SQL> select round (1.23456, 3) from dual;
ROUND (1.23456, 3)
1.235
1280
1280
Q) Write a query to display ename, sal and round (sall,-3) from emp table?
TRUNC (1,8)
TRUNC (1.8)
TRUNC (1.23456, 3)
1.234
SQRT (16)
ceil (), floor (): These functions always returns integers ceil function returns nearest greatest
integer where as floor function returns nearest lowest integer.
CEIL (1.3)
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.
50
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.
UMESH
LOWER
umesh
UPPER (ENAM
SMITH
ALLEN
WARD
LOWER(ENAM
Smith
Allen
Ward
initcap (): It returns initial letter is capital and all remaining letters are small.
INITCAP('UMESHISAGO
Length (): It returns total length of the string or expression including spaces.
LENGTH ('UMESH')
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
Substr (): It will extract portion of the string within given string or expression or column
name based on last two parameters.
NOTE: The last two parameters must be a numbers and second parameter may be positive or
negative number and last parameter is optional.
SUB
BCD
SUBSTR
CDEFGH
SUB
GH
SUBST
DEFGH
Q) Write a query to display the employees whose ename second letter would be ‘AR’ from
emp table by using substr function?
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.
NOTE: Here, the last two parameters must be numbers and third parameter may be positive
or negative number and these are optional.
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.
INSTR ('ABCDEFGHGEFJKEFKM','EF',9,2)
14
INSTR ('ABCDEFGHGEFJKEFKM','EF',-9,2)
INSTR ('ABCDEFGHGEFJKEFKM','EF',-8)
10
INSTR ('CORPORATEFLOOR','OR',3,2)
14
INSTR ('CORPORATEFLOOR','OR',-3,2)
INSTR ('ABCD','Z')
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’);
LPAD('ABCD
######ABCD
LPAD(“,10
**********
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######
RPAD(“,10
**********
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.
LP
AB
RP
AB
Ltrim (): It removes specified characters on the left side of the given string.
LTRIM ('S
MISSTHSS
Rtrim (): It removes specified characters on the right side of the given string.
RTRIM ('S
SSMISSTH
Trim (): Oracle 8i introduced trim function. It is used remove left and right side specified
characters from a given string.
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.
TRIM(LEA
MISSTHSS
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;
9 8 11
SQL> select length (rtrim('umesh ',' ')),length (ltrim(' raju',' ')),length (trim(' rukku '))
from dual;
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.
TRANS
XYdia
TRANS
SQL> select translate ('A B C','','XYZ') from dual;
Vijay
T
TRANS
AXBXC
TRANS
@$#
REPLACE
XYdia
REPLACE
SQL> select replace ('A B C','','XYZ') from dual;
Vijayawada
REPLACE
ABC
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.
REPLACE
MITH
Q) Write a query which counts number of occurrences of ‘E’ within given string SLEEP by
using replace, length functions?
LENGTH('SLEEP')-LENGTH(REPLACE('SLEEP','E'))
ASCII(‘A’
)
65
Date functions: In oracle by default date format is DD-MON-YY. Oracle having following
date functions. These are
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.
ADD_MONTH
15-SEP-05
ADD_MONTH
15-MAR-05
ADD_MONTH
15-JUL-17
ADD_MONTH
15-MAY-17
Last_day (): It returns last date of the specified month within given date.
LAST_DAY(
30-JUN-17
LAST_DAY(
31-JUL-05
Next_day (): It returns next occurrence day from the specified date based on the second
parameter.
NEXT_DAY (
18-JUN-17
NEXT_DAY (
16-JUN-17
NEXT_DAY (
16-JUN-17
NEXT_DAY (
22-JUN-17
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.
MONTHS_BETWEEN ('23-JAN-17',SYSDATE)
-4.7538336
MONTHS_BETWEEN ('23-JAN-17',SYSDATE)
4.7538336
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.
SYSDATE +1
16-JUN-17
SYSDATE -1
14-JUN-17
SYSDATE-SYSDATE
Q) Write a query to display first date of the current month by using predefined functions
sysdate, add_months, last_day()?
ADD_MONTH
01-JUN-17
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.
TO_CHAR (SY
15/06/2017
SQL> select to_char (sysdate, 'D') from dual; DDay of the week
SQL> select to_char (sysdate, 'DD') from dual; DDDay of the month
TO
15
SQL> select to_char (sysdate, 'DDD') from dual; DDDDay of the year
TO
166
TO_C
15TH
TO_CHAR (SYSDAT
FIFTEENTH
06
TO
17
TO_C
2017
TO_CHAR (
07:33:31
TO_CHAR (
19:33:46
TO_CHAR (SYSDATE,’DAY’)
THURSDAY
TO_CHAR (SYSD
THU
TO_CHAR (SYSDATE,’MONTH’
JUNE
TO_CHAR (SYSD
JUN
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.
To_date (): It is used to convert date string into oracle date type. (Oracle date format)
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.
TO_DATE (‘
23-JUN-17
Q) Write a query which is used to add 5 days to the given date string ’10-AUG-05’?
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;
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?
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.
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?
no rows selected
SQL> select * from emp where to_char ( hiredate, 'FMMONTH')='DECEMBER';
Q) Write a query to display the employees who are joining in the year of 81 from emp table
by using to_char function?
Q) Write a query to display the employees who are before 15th of every month from emp
table by using to_char function?
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.
LAST_DAY (
30-JUN-05
LAST_DAY (
30-JUN-05
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
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.
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.
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
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?
1 row created.
no rows selected
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.
ROUND (SYS
01-JAN-18
ROUND (SYS
01-JUN-17
ROUND (SYS
18-JUN-17
SQL> select trunc (sysdate,'day') from dual;
TRUNC (SYS
11-JUN-17
TRUNC (SYS
01-JUN-17
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.
MAX (SAL)
5000
SQL> select max (hiredate) from emp; (checks from year onwards)
MAX (HIRED
12-JAN-83
MAX (ENAME)
WARD
Min (): It return minimum value from a table column.
MIN (SAL)
800
SQL> select min (hiredate) from emp; (checks from year onwards)
MIN (HIRED
17-DEC-80
MIN (ENAME)
ADAMS
NOTE: In all databases we are not allowed to use group functions in where clause.
AVG (SAL)
2073.21429
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.
AVG (NVL(COMM,0))
157.142857
SUM (SAL)
29025
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.
COUNT (COMM)
COUNT (NVL(COMM,0))
14
COUNT (DEPTNO)
14
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.
Q) Write a query to display number of employees in each department from emp table by
using group by clause?
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?
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;
30 2850 950
20 3000 800
10 5000 1300
NOTE: In all databases we can also use group by clause without using group functions.
DEPTNO
30
20
10
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;
SQL> select deptno, job, sum (sal) from emp group by deptno,job;
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
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.
SUM (SAL)
29025
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.
Deptno Deptno
Deptno
10 10 10
10
20 10 20 20
20
30 20 30 30
30
10 30
30
Q) Write a query to display the departments having more than 3 employees from emp table
by using group by clause?
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.
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;
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.
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;
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
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?
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.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
40 OPERATIONS BOSTON
30 SALES CHICAGO
20 RESEARCH DALLAS
NOTE: In oracle we can also use column number within order by clause this number
specifies column position.
40 OPERATIONS BOSTON
30 SALES CHICAGO
20 RESEARCH DALLAS
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.
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
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.
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
Where condition
Group by clause
Having condition
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
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.
SQL> select deptno, job, sum (sal) from emp group by rollup (deptno, job);
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);
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,
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.
1. Inner joins
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.
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.
SQL> select ename, sal, deptno, dname, loc from emp, dept
where emp.deptno=dept.deptno;
NOTE: For avoiding ambiguity error we must specify table name in front of the common
column name by using .(dot) operator.
where emp.deptno=dept.deptno;
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.
where e.deptno=d.deptno;
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?
where e.deptno=d.deptno
and loc='CHICAGO';
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?
where e.deptno=d.deptno
group by dname;
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?
where e.deptno=d.deptno
group by d.deptno,dname;
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?
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?
where e.deptno=d.deptno
group by dname
having sum(sal)>9000;
RESEARCH 10875
SALES 9400
Non equi join: Based on other than equality operator (<>,<=,>=,>,<,between, etc.,) we are
retrieving data from multiple tables.
Where table1.common column name (other equal to{=} operator) table2.common column
name;
Table created.
1 row created.
SQL> /
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
SNO
10
20
30
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.
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
from emp,salgrade
from emp,salgrade
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.
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?
where e1.ename='SCOTT'
and e1.sal=e2.sal;
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;
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?
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?
where e1.mgr=e2.empno
and e1.sal>e2.sal;
Q) Write a query to display employees who are joining before their managers from emp table
by using self join?
where e1.mgr=e2.empno
and e1.hiredate<e2.hiredate;
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.
NOTE: Here, join operator can be used only one side at a time within joining condition.
40 OPERATIONS BOSTON
where e.deptno=(+)d.deptno;
where e.deptno=d.deptno(+);
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
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
where e.deptno=d.deptno;
Q) Write a query to display the employees who are working in the location CHICAGO from
emp, dept tables by using 9i inner join?
on e.deptno=d.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.
1 row created.
1 row created.
1 row created.
1 row created.
A B C
X Y Z
P Q R
A B
X Y
S T
A B C A B
X Y Z X Y
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.
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
A B C A B
X Y Z X Y
P Q R
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
X Y Z X Y
S T
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
A B C A B
X Y Z X Y
S T
P Q R
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.
NOTE: whenever we are using natural join internally database servers uses “using clause”
that’s way this join return common columns one time only.
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;
SQL> select ename, sal, d.deptno, dname, loc from emp e join dept d
Using (deptno);
SQL> select ename, sal, deptno, loc from emp e natural join dept d;
using (deptno);
On table1.key=table2.key
On table1.key=table2.key
On table1.key=table2.key
Or table2.key is null;
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
Table created.
SQL> insert into test2 values (&sno);
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
30
SNO
10
20
40
on test1.sno=test2.sno
SNO SNO
30
on test1.sno=test2.sno
40
on test1.sno=test2.sno
SNO SNO
30
40
Syntax for 8i joins: select col1, col2, .. from table1, table2, table3
Syntax for 9i joins: select col1, col2, .. from table1 join table2
join table3
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.
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),....
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:
SQL> create table test (sno number (10) not null, name varchar2 (10));
Table created.
1 row created.
SQL> /
1 row created.
SNO NAME
10 UMESH
10 UMESH
Table level:
Syntax: create table tablename (col1 datatype (size), col2 datatype (size),....
SQL> create table test (sno number (10), name varchar2 (10) not null (sno, name));
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:
SQL> create table test (sno number (10) unique, name varchar2 (10));
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SNO NAME
10 UMESH
10 UMESH
RAJU
SQL> create table test (sno number (10) unique, name varchar2 (10) unique);
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> insert into test values (&sno, '&name');
SQL> /
SNO NAME
10 UMESH
ABC
20
Table level:
Syntax: create table tablename (col1 datatype (size), col2 datatype (size),.... ,
SQL> create table test (sno number (10), name varchar2 (10) ,unique (sno, name));
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
1 row created.
SQL> /
1 row created.
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:
SQL> create table test (sno number (10) primary key, name varchar2 (10));
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SQL> /
10 UMESH
20 NULL
30 UMESH
Table level:
Syntax: create table tablename (col1 datatype (size), col2 datatype (size),.... ,
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.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SQL> /
Enter value for sno: 10
1 row created.
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:
SQL> create table test (sno number (10) primary key, name varchar2 (10));
Table created.
1 row created.
SQL> /
Enter value for sno: 20
1 row created.
SQL> /
1 row created
SQL> /
1 row created.
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.
1 row created.
SQL> /
1 row created.
SQL> /
Enter value for sno: 10
1 row created.
SQL> /
1 row created.
SQL> /
SNO
10
20
10
20
Table level:
Foreign key (col1, col2, ....) mastertablename (primary key column values));
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
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> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SQL> /
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,
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,....);
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
30
SQL> create table child (sno number (10) references mas (sno));
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SQL> /
SNO
10
10
20
20
30
2 rows deleted.
SNO
20
20
30
1 row deleted.
SNO
20
30
SQL> drop table mas;
Table dropped.
Table dropped.
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
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);
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SNO
10
10
20
20
30
SNO
20
30
SNO
20
20
30
Table dropped.
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,.....);
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
30
SQL> create table child (sno number (10) references mas (sno) on delete set null);
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
Enter value for sno: 30
1 row created.
SQL> /
SNO
10
10
20
20
30
Testing:
1 row deleted.
SNO
20
30
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.
0 rows updated.
1 row updated.
1 row updated.
SNO
20
20
20
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.
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
30
Testing: SQL> create table child (sno number (10) references mas (sno) on delete set null);
Table created.
1 row created.
SQL> /
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
SNO
10
10
20
20
30
1 row created.
1 row created.
10
20
30
40
SNO
10
10
20
20
30
40
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.
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SNO
10
20
30
SQL> create table child (sno number (10) references mas (sno) on delete set null);
Table created.
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
Enter value for sno: 40
SNO
10
10
20
20
30
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.
1 row created.
SQL> /
1 row created.
SQL> /
NAME
ABC
UMESH
Table level:
Syntax: create table tablename (col1 datatype (size), col2 datatype (size),...
SQL> create table test (sno number (10), name varchar2 (10), check (name=upper (name)
and sno>2000));
Table created.
1 row created.
SQL> /
SQL> /
1 row created.
SQL> /
1 row created.
SQL>/
1 row created.
SNO NAME
3000 UMESH
3000 UMESH
NULL
2500
Table created.
SQL> insert into test values (1);
1 row created.
SQL> create table test1 (sno number (10) constraint pk_sno primary key);
Table created.
1 row created.
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.
NOTE: In all oracle all constraints information stored under “user_constraints” data
dictionary.
SEARCH_CONDITION LONG
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.
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.
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.
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.
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.
where table_name='TEST';
SEARCH_CONDITION
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.
POSITION NUMBER
CONSTRAINT_NAM COLUMN_NAME
E
SYS_C007697 EMPNO
SYS_C007698 SAL
SYS_C007699 DEPTNO
SYS_C007700 ENAME
where table_name='TEST1';
CONSTRAINT_NAME COLUMN_NAME
SYS_C007701 DEPTNO
where table_name='TEST3';
FK_DEPTNO DEPTNO 1
NOTE: In oracle all columns information stored under “user_tab_columns” data dictionary.
where table_name='TEST';
EMPNO NUMBER 22
ENAME VARCHAR2 10
SAL NUMBER 22
DEPTNO NUMBER 22
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”.
SQL> create table test (sno number (10), sal number (10) default 2000, name varchar2(10)
default ‘UMESH’;
Table created.
1 row created.
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.
where table_name='TEST';
DATA_DEFAULT
2000
‘UMESH’
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
Primary key:
Table altered.
Not null:
Unique:
Table altered.
1 row created.
Check:
Table altered.
Foreign key:
Table created.
SQL> alter table test1 add foreign key (name) references test (name);
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;
Table created.
Not null:
SQL> alter table test add name varchar2 (10) not null;
Table altered.
Unique:
Table altered.
1 row created.
Check:
SQL> alter table test add sal number (10) check (sal>2000);
Table altered.
Primary key:
Table created.
SQL> alter table test add name varchar2 (10) primary key;
Table altered.
Foreign key:
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.
1 row created.
1 row created.
NOTE: here, not null constraint is does not working table level and column level adding
constraints.
Table altered.
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.
Table created.
Dropping constraints:
Table created.
CONSTRAINT_NAME
SYS_C005486
Table altered.
SNO NUMBER(10)
SQL> create table test (sno number (10) primary key, name varchar2 (10) unique, sal number
(10) unique);
Table created.
Table altered.
Table altered.
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.
Table created.
Table created.
Table altered.