Page 1 of 79
Wipro Confidential
Preface.................................................................................................................................4
Audience..........................................................................................................................4
Organization.....................................................................................................................4
Introduction..........................................................................................................................4
SQL - Structured Query Language......................................................................................4
General Information.........................................................................................................4
Types of SQL:..................................................................................................................5
Data Types in Oracle........................................................................................................5
Oracle Operators:.............................................................................................................5
SQL*PLUS......................................................................................................................6
How to open SQL * PLUS?.........................................................................................6
How to edit the last executed query?...........................................................................6
How to create a table?......................................................................................................6
How to view the structure of the table?...........................................................................6
How to view the tables present in the logged in user area?.............................................7
How to insert the values to the table?..............................................................................7
How to view the records present in the table?...............................................................10
How to select only the records that we need?................................................................11
How to copy a table?.....................................................................................................13
How to copy the structure of a table alone?..................................................................14
Wild Cards.....................................................................................................................14
Built In Functions in SQL..............................................................................................15
Types..........................................................................................................................15
1. Number Function...............................................................................................17
2. Character Functions...........................................................................................20
3. Date Functions:..................................................................................................25
4. Conversion Function..........................................................................................25
5. Group Function..................................................................................................27
6. Environmental Function....................................................................................31
7. Special Functions...............................................................................................33
How to modify a record?...............................................................................................33
How to revert the changes?............................................................................................34
How to save the transactions?........................................................................................34
How to remove a record from the table?.......................................................................34
How to remove a particular record?..............................................................................35
How to modify the table structure?...............................................................................35
How to add a new field to the existing table?............................................................35
How to change the data type of an existing field?.....................................................36
How to increase or decrease the field size?...............................................................37
How to rename a table?.................................................................................................38
How to flush off the records in the table?......................................................................39
How to remove the table structure from the DB?..........................................................40
Constraints:....................................................................................................................40
How do I add a new constrain to an existing table?..................................................47
How do I remove an existing constraint?..................................................................49
Page 2 of 79
Wipro Confidential
Page 3 of 79
Wipro Confidential
Preface
This tutor contains a description of the Structured Query Language (SQL) used to
manage information in an Oracle database. Oracle SQL is a superset of the American
National Standards Institute (ANSI) and the International Standards Organization (ISO)
SQL99 standard.
Audience
The SQL tutor is intended for beginners and intermediate users of Oracle SQL.
Intermediate users can skip the elementary initial sections.
Organization
This SQL Tutor contains a lot of examples and important notes and I would
suggest the users of this guide to try out these examples as and when they go through the
sections.
Introduction
In 1979, Relational Software, Inc. (now Oracle Corporation) introduced the first
commercially available implementation of SQL. Today, SQL is accepted as the standard
RDBMS language. Structured Query Language (SQL) is the set of statements with which
all programs and users access data in an Oracle database.
General Information
Users in the database
Tables in the user
Records in the table
Columns in the table 7.x
Columns in the table 8.x
Default DATE FORMAT
No limit
No limit
No limit
256
1000
DD-MON-YY
Page 4 of 79
Wipro Confidential
Types of SQL:
Types
DDL (Data Definition Language)
DML (Data Manipulation Language)
DQL (Data Query Language)
TCL (Transaction Control Language)
DCL (Data Control Language)
Example
CREATE, ALTER, DROP, TRUNCATE,
RENAME
INSERT, UPDATE, DELETE
SELECT
COMMIT, ROLLBACK, SAVE POINT
GRANT, REVOKE
Oracle Operators:
Type
Arithmetic
Logical
Relational
Set
Special
Address
Concatenation
Page 5 of 79
Operators
+
*
/
AND OR
NOT
<
<=
>
>=
=
<>
!=
UNION, UNION ALL, INTERSECT, MINUS
IS, IN, LIKE, BETWEEN
&
||
^=
Wipro Confidential
SQL*PLUS
Type
------------Wipro Confidential
NO
NA
DOB
NUMBER(3)
VARCHAR2(20)
DATE
Example
>INSERT INTO DUMP1 VALUES(1,'OCEAN','05-FEB-03');
>1 Row Created.
Note 1
If the fields data type is Char, Varchar2 or Date then we should specify the values
with in quotes.
Note 2
What if we change the order of the values say
>INSERT INTO DUMP1 VALUES('OCEAN',2,'05-FEB-03');
>Error: invalid number.
Note 3
What if we miss some values say
>INSERT INTO DUMP1 VALUES(2,'OCEAN');
>Error : not enough values
Note 4
Page 7 of 79
Wipro Confidential
Note 5
What if we dont have a value for the DOB field?
We have to use the NULL Keyword.
How to put the Null value to a Field?
>INSERT INTO DUMP1 VALUES(2,'MADHU',NULL);
>1 Row Created.
Specific Insert
We can change the order of the fields.
We can also specify the columns for which we want to insert data.and the
remaining fields will be filled by the NULL value automatically.
Syntax
>INSERT INTO <tname>(fn1,..) VALUES(v1,...);
Example
>INSERT INTO DUMP1(NO,NA) VALUES(3,'SIVA');
>1 Row Created.
In this case the DOB field automatically filled with NULL value.
Note
The order of the selected fields must match exactly with the order of the values
provided and its data type.
o Example
INSERT INTO DUMP1(NO,NA) VALUES('HA',4);
*
Error: invalid number
o More values:
INSERT INTO DUMP1(NO,NA) VALUES(4,'DEMO',20);
*
Error : too many values
o Not enough values
INSERT INTO DUMP1(NO,NA) VALUES(4);
Error : not enough values.
Macros:
This is used to get input from the user. Address operator is used to accomplish it.
Types
1. Direct Macros
Page 8 of 79
Wipro Confidential
2. Specific Macros
Address Operator (&)
Used to get the value from the user and substitute it in the query.
1. Direct Macros:
We must give the values for all fields without changing the Order.
Syntax:
>INSERT INTO <tname> VALUES(&var1,...);
>Enter the value for var1 : val1
Output
old : INSERT INTO <tname> VALUES(&var1,...);
new : INSERT INTO <tname> VALUES(val1,...);
1 Row Created.
Example:
INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
Enter the value for v1 : 4
Enter the value for v2 : 'MATHEW'
Enter the value for v3 : '10-DEC-71'
old : INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
new : INSERT INTO DUMP1 VALUES(4,'MATHEW','10-DEC-71');
1 Row Created.
NOTE: To run the last executed query type / in the prompt.
SQL> /
Enter the value for v1 : 5
Enter the value for v2 : 'BADHU'
Enter the value for v3 : '10-DEC-91'
old : INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
new : INSERT INTO DUMP1 VALUES(5,'BADHU','10-DEC-81');
1 Row Created.
By this way we can insert n number of records easily. You can notice that
when we enter values for date and varchar fields (v3 and v2) we enter the
values within single quote each time but this can be avoided if we give the
single quote in the insert statement itself as follows.
INSERT INTO DUMP1 VALUES(&V1,'&V2','&V3');
SQL>/
Enter the value for v1 : 6
Enter the value for v2 : RAVI
Enter the value for v3 : 10-DEC-81
old : INSERT INTO DUMP1 VALUES(6,'RAVI','10-DEC-81');
Page 9 of 79
Wipro Confidential
1 Row Created.
2. Specific Macros
We can select the fields for which we are going to insert values and the
other fields will be inserted with NULL value automatically (If the omitted
field is not a NOTNULL field).
Syntax:
INSERT INTO <tname>(fn1,...) VALUES(&v1,..);
Enter the value for V1 : val1
old : INSERT INTO <tname>(fn1,...) VALUES(&v1,..);
new : INSERT INTO <tname>(fn1,...) VALUES(val1,..);
1 Row Created.
Example
>INSERT INTO DUMP1(NO,NA) VALUES(&V1,'&V2');
Enter the value for v1 : 6
Enter the value for v2 : RAVI
>1 Row Created.
Wipro Confidential
Null?
Type
Wipro Confidential
------------------------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
-------NOT NULL
-----NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)
Page 12 of 79
Condition
Operation
Example
NOT
SELECT *
FROM employees
WHERE NOT (job_id IS
NULL);
SELECT *
FROM employees
WHERE NOT
(salary BETWEEN 1000
AND 2000);
AND
SELECT *
FROM employees
WHERE job_id =
PU_CLERK
AND department_id = 30;
OR
SELECT *
Wipro Confidential
component condition is
TRUE.
Returns FALSE if both are
FALSE. Otherwise returns
UNKNOWN.
FROM employees
WHERE job_id =
PU_CLERK
OR department_id = 10;
List all employees working in department number 10,20 and his salary is
less than his commission.
SELECT * FROM EMP WHERE DEPTNO = 10 OR DEPTNO=20 AND
SAL < COMM;
List all employees who are not getting any commission.
SELECT * FROM EMP WHERE COMM = NULL;
No Rows Selected.
The above query will return No Rows Selected even if the value for
commission is null. This is because we cannot use equal-to operator to
check for null values. We need to use IS which is a special relational
operator to check for null values.
Correct Query
SELECT * FROM EMP WHERE COMM IS NULL;
List all employees who are getting commission.
SELECT * FROM EMP WHERE COMM IS NOT NULL;
List all employees in department number 10,20,30 and whose job is either
CLERK or MANAGER..
SELECT * FROM EMP WHERE (DEPTNO = 10 OR DEPTNO = 20 OR
DEPTNO = 30) AND (JOB = 'CLERK' OR JOB = 'MANAGER');
We can simplify the above query by using IN operator.
Syntax:
Fieldname IN(v1,...)
SELECT * FROM EMP WHERE DEPTNO IN (10,20,30) AND
JOB IN ('MANAGER','CLERK');
List all employees who are getting Salary greater than 2000 and less than
3000
SELECT * FROM EMP WHERE SAL>2000 and SAL<3000;
(OR)
SELECT * FROM EMP WHERE SAL BETWEEN 2001 AND 2999;
Wipro Confidential
Wild Cards
In DOS:
DIR
Select all Dir / Files in current directory.
Dir *.txt
Select all .txt extension file from the current directory.
Dir p*.txt
Select the all .txt files starting with letter P.
Dir *p.txt
Select the all .txt files ending with letter P.
Dir ?p*.txt
Select the all .txt files with second letter as P.
Dir *p*.txt
Select the all .txt files containing letter P.
*
?
Page 14 of 79
Examples:
List all employees whose name starts with A.
SELECT * FROM EMP WHERE ENAME = 'A%';
No Rows Selected.
The above query will return No Rows Selected even if the there are
employees whose name starts with A. This is because we cannot use
equal-to operator when we are using wild card characters. We need to use
LIKE which is a special relational operator.
Correct Query
SELECT * FROM EMP WHERE ENAME LIKE 'A%';
List all employees whose name ends with N.
SELECT * FROM EMP WHERE ENAME LIKE '%N';
List all employees whose name has A as the second letter.
SELECT * FROM EMP WHERE ENAME LIKE '_A%';
List all employees whose name contains letter A.
SELECT * FROM EMP WHERE ENAME LIKE '%A%';
Exercise:
List all employees whose name contains letter A only once. (Eg. If there is
a employee called ADAMS then it should not be listed).
Answer:
SELECT * FROM EMP WHERE ENAME LIKE '%A%' AND ENAME
NOT LIKE '%A%A%';
Wipro Confidential
1. Number Function
abs
trunc
sign sin
cosh atan
ceil
mod
ln
cos
tanh
floor
sqrt
log
tan
asin
sinh acos
2. Char Function
2 Types
A) Character function returning character value.
B) Character function returning numeric value.
1. Character function returning character value.
chr
ltrim initcap
soundex
lpad
replace
upper
rpad
translate
Wipro Confidential
next_day
last_day
months_between
4. Conversion Function
to_char
to_number
to_date
5. Group Function
count
sum
avg
min
max
stddev
variance
6. Environmental Function
user
uid
userenv
least
greatest
nvl
7. Special Function
decode
vsize
Selecting from the DUAL Table
DUAL is a table automatically created by Oracle along with the data dictionary.
DUAL is in the schema of the user SYS, but is accessible by the name DUAL to
all users. It has one column, DUMMY, defined to be VARCHAR2(1), and
contains one row with a value X. Selecting from the DUAL table is useful for
computing a constant expression with the SELECT statement. Because DUAL has
only one row, the constant is returned only once. Alternatively, you can select a
constant, pseudo column, or expression from any table, but the value will be
returned as many times as there are rows in the table.
1.
Number Function
abs(x)
ABS returns the absolute value of n.
Page 17 of 79
Wipro Confidential
Wipro Confidential
Return Value
1
-1
0
Wipro Confidential
exp(n)
EXP returns e raised to the nth power, where e = 2.71828183 ...
SELECT EXP(0) FROM DUAL;
1
ln(n)
LN returns the natural logarithm of n, where n is greater than 0.
SELECT LN(10) FROM DUAL;
2.30258509
log(m,n)
LOG returns the logarithm, base m, of n. The base m can be any positive number
other than 0 or 1 and n can be any positive number.
SELECT LOG(10,1000) FROM DUAL;
3
2.
Character Functions
I. Character function returning character value.
chr('number')
Chr returns the character value for the ASCII number entered.
SELECT CHR('65') FROM DUAL;
A
SELECT CHR('97') FROM DUAL;
a
SELECT CHR('3') FROM DUAL;
"
SELECT CHR('39') FROM DUAL;
'
concat(String1,String2)
This is used to concatenate strings.
SELECT CONCAT('Wipro','Technologies') FROM DUAL;
WiproTechnologies
SELECT CONCAT(ENAME,JOB) FROM EMP;
Concatenation Operator ( || )
Page 20 of 79
Wipro Confidential
Wipro Confidential
WIPRO
SELECT RTRIM('WIPRO
WIPRO
lpad(char1,n,char2)
This is used for reporting purpose to format the values.
LPAD returns char1, left-padded to length n with the sequence of
characters in char2; char2 defaults to a single blank. If char1 is longer than
n, this function returns the portion of char1 that fits in n. Both char1 and
char2 can be any of the datatypes CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2
datatype and is in the same character set as char1. The argument n is the
total length of the return value as it is displayed on your terminal screen.
In most character sets, this is also the number of characters in the return
value. However, in some multibyte character sets, the display length of a
character string can differ from the number of characters in the string.
SELECT LPAD('ABCDE',10,'*') FROM DUAL;
*****ABCDE
SELECT LPAD(Page 1,15,*.) "LPAD example"
FROM DUAL;
LPAD example
--------------*.*.*.*.*Page 1
rpad(char1,n,char2)
RPAD returns char1, right-padded to length n with char2, replicated as
many times as necessary; char2 defaults to a single blank. If char1 is
longer than n, this function returns the portion of char1 that fits in n. Both
char1 and char2 can be any of the data types CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of
VARCHAR2 data type and is in the same character set as char1. The
argument n is the total length of the return value as it is displayed on your
terminal screen. In most character sets, this is also the number of
characters in the return value. However, in some multi byte character sets,
the display length of a character string can differ from the number of
characters in the string.
SELECT RPAD('ABCDE',10,'*') FROM DUAL;
ABCDE*****
Exercise:
***ABCDE***
Answer:
Page 22 of 79
Wipro Confidential
Page 23 of 79
Wipro Confidential
Wipro Confidential
3.
Date Functions:
Sysdate:
This function returns the current system date.
SELECT SYSDATE FROM DUAL;
23-JUL-03
last_day(date)
This function returns the last date of that month.
SELECT LAST_DAY(SYSDATE) FROM DUAL;
31-JUL-03
add_months(date,number)
This function adds the number of months specified to the given date.
SELECT ADD_MONTHS(SYSDATE,3) FROM DUAL;
10-FEB-06
next_day(Date,DayOfTheWeek)
This function returns the date of the first weekday named by DayOfTheWeek
that is later than the date Date.
SELECT NEXT_DAY(SYSDATE,'FRIDAY') FROM DUAL;
months_between(date1, date2)
MONTHS_BETWEEN returns number of months between dates date1 and date2.
If date1 is later than date2, result is positive; if earlier, negative. If date1 and date2
are either the same days of the month or both last days of months, the result is
always an integer. Otherwise Oracle calculates the fractional portion of the result
based on a 31-day month and considers the difference in time components date1
and date2.
SELECT MONTHS_BETWEEN(SYSDATE,'23-JAN-03') FROM DUAL;
4.
Conversion Function
To_Char()
It is a conversion function used to convert the date into the desired format.
Syntax:
Page 25 of 79
Wipro Confidential
TO_CHAR(DATE,'Format')
Format:
DD-MON-YY
DD
D
Day
DDTH
DDSP
MM
MONTH
MMSP
YYY
YYYY
HH:MI:SS
Example:
SELECT TO_CHAR(SYSDATE,'DD-MON-YY') FROM DUAL;
10-NOV-05
SELECT TO_CHAR(SYSDATE,'DD-MONTH-YY') FROM DUAL;
10-NOVEMBER -05
SELECT TO_CHAR(SYSDATE,'DD-MONTH-YYYY') FROM DUAL;
10-NOVEMBER -2005
SELECT TO_CHAR(SYSDATE,'DD') FROM DUAL;
10
SELECT TO_CHAR(SYSDATE,'D') FROM DUAL;
5
SELECT TO_CHAR(SYSDATE,'DAY') FROM DUAL;
THURSDAY
SELECT TO_CHAR(SYSDATE,'DDSP-MONTH-YYYY') FROM
DUAL;
TEN-NOVEMBER -2005
SELECT TO_CHAR(SYSDATE,'HH:MI:SS') FROM DUAL;
02:48:59
SELECT TO_CHAR(SYSDATE,'MM') FROM DUAL;
11
SELECT TO_CHAR( HIREDATE,'MONTH') FROM EMP;
Page 26 of 79
Wipro Confidential
Exercise:
List all employees hired in the month of april.
Answer:
SELECT * from emp where
trim(TO_CHAR( HIREDATE,'MONTH')) = 'APRIL'
(OR)
SELECT * from emp where TO_CHAR( HIREDATE,'MM')=4
5.
Group Function
count()
COUNT returns the number of rows in the query.
Example:
SELECT COUNT (EMPNO) FROM EMP;
14
SELECT COUNT (COMM) FROM EMP;
4
Note:
As shown above COUNT () does not take into account NULL values.
SELECT COUNT (*) FROM EMP;
14
sum()
This function returns the summation for that group.
SELECT SUM (SAL) FROM EMP;
29025
avg()
This function returns the average for that group.
SELECT AVG (SAL) FROM EMP;
min()
This function returns the minimum value in that group.
SELECT MIN (SAL) FROM EMP;
800
max()
This function returns the maximum value in that group.
SELECT MAX (SAL) FROM EMP;
5000
stddev()
This function returns the Standard Deviation.
SELECT STDDEV (SAL) FROM EMP;
Page 27 of 79
Wipro Confidential
variance()
This function returns the variance value.
SELECT VARIANCE(SAL) FROM EMP;
SELECT SQRT(VARIANCE(SAL)) FROM EMP;
Group by caluse:
This clause is used to show repeated values only once.
Syntax:
GROUP BY <fieldname>
SELECT { fn1,gf(fn),.. } FROM <tname> [WHERE clause]
[GROUP BY clause[HAVING clause]] [ORDER BY clause];
SELECT DEPTNO FROM EMP GROUP BY DEPTNO;
Note:
The column in the group by clause is ordered by ascending automatically.
SELECT COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT COUNT(*),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT SUM(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT MIN(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT JOB FROM EMP;
14 Rows Selected.
SELECT JOB FROM EMP GROUP BY JOB;
5 Rows Selected.
Exercise:
Group the employees by their nature of job and display Job, Sum (Sal),
Avg (Sal), Min (Sal)
Answer:
SELECT JOB, SUM (SAL), AVG (SAL), MIN(SAL) FROM EMP
GROUP BY JOB;
Exercise:
Page 28 of 79
Wipro Confidential
Wipro Confidential
Step 2:
SELECT MAX (SAL) FROM EMP WHERE SAL < 5000;
3000
Final Query:
SELECT MAX(SAL) FROM EMP WHERE SAL < (SELECT
MAX(SAL) FROM EMP);
3000
Exercise:
Fetch the employee details for the employee who is getting the second
minimum salary.
Answer:
SELECT * FROM EMP WHERE SAL=(SELECT MIN(SAL) FROM
EMP WHERE SAL > (SELECT MIN(SAL) FROM EMP));
950
Exercise:
Fetch the employee details for the employees having the longest name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME) = (SELECT
MAX(LENGTH(ENAME)) FROM EMP);
Exercise:
Fetch the employee details for the employees having the second longest
name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME)=(SELECT
MAX(LENGTH(ENAME)) FROM EMP WHERE LENGTH(ENAME) <
(SELECT MAX(LENGTH(ENAME)) FROM EMP));
Exercise:
Fetch the employee details for the employees having the second shortest
name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME)=(SELECT
MIN(LENGTH(ENAME)) FROM EMP WHERE LENGTH(ENAME) >
(SELECT MIN(LENGTH(ENAME)) FROM EMP));
Exercise:
Fetch the third minimum salary paid to the employees.
Answer:
SELECT MIN(SAL) FROM EMP WHERE SAL > (SELECT MIN(SAL)
FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP))
Page 30 of 79
Wipro Confidential
Note:
Maximum number of sub queries in a query is 255.
Using Where clause and Group By clause in a query
Example:
Fetch the total amount of salary paid to the employees in department 10
SELECT SUM(SAL),DEPTNO FROM EMP WHERE DEPTNO = 10
GROUP BY DEPTNO;
List the department number and total salary paid to the employees of that
department only if the total salary paid to that department is greater than
9000.
SELECT SUM(SAL),DEPTNO FROM EMP WHERE SUM(SAL) > 9000
GROUP BY DEPTNO
*
ERROR at line 1:
ORA-00934: group function is not allowed here
Note:
We cannot use group functions in the where clause of the query and hence
we have to use having clause as shown below.
Having Clause:
Syntax:
SELECT fn,gf(fn),... FROM <tname> [WHERE clause]
[GROUP BY clause[HAVING clause]] [ORDER BY clause];
SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO
HAVING SUM(SAL) > 9000;
Exercise
List the total salary paid to employees based on their designation (i.e.
Job) only if the total salary is less than 5500.
Answer
SELECT SUM(SAL),JOB FROM EMP GROUP BY JOB HAVING
Sum(sal) < 5500;
Exercise
Select the department number which is having least number of employees.
Hint
Select the department number whose count (*) is the minimum.
Answer
SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO
HAVING COUNT(*)=(SELECT MIN(COUNT(*)) FROM EMP GROUP
BY DEPTNO)
Page 31 of 79
Wipro Confidential
6.
Environmental Function
User
This gives the logged in user name.
SELECT USER FROM DUAL;
scott
uid
This returns the User ID of the logged in user.
SELECT UID FROM DUAL;
20
userenv:
This retuns the Environment details of the user area.
SELECT USERENV('LANG') FROM DUAL;
US
SELECT USERENV('LANGUAGE') FROM DUAL;
USERENV('LANGUAGE')
---------------------------------------------------AMERICAN_AMERICA.UTF8
SELECT USERENV('SESSIONID') FROM DUAL;
USERENV('SESSIONID')
-------------------177495
least(v1,v2,v3...)
This returns the least value in the list.
SELECT LEAST(10,2,100,1,20) FROM DUAL;
1
greatest(v1,v2,...)
This returns the greatest value in the list.
SELECT GREATEST(10,2,100,1,20) FROM DUAL;
100
nvl(field,TreateValue)
This function is used to represent null value in the way we desire.
SELECT COMM FROM EMP;
If you execute the above query you can see some blanks in commission field, these
blanks are nulls in the data base.
Page 32 of 79
Wipro Confidential
7.
Special Functions
decode
This is similar to Like if-else-if in programming languages.
Syntax:
DECODE(fieldname,V1,treatvalue,V2,treatvalue,...,DEFAULT)
Example:
SELECT DECODE ( DEPTNO ,10,'ACCOUNTING' ,20, 'RESEARCH',
'DEMO') , DEPTNO FROM EMP;
vsize
This returns the size of the field.
Syntax:
VSIZE(fieldname)
Example:
SELECT VSIZE(HIREDATE) FROM EMP;
DD-MON-YY
7
N Rows Updated.
Note:
If we are not specifying any condition in the where clause of the update query
then all the records in the table are updated.
UPDATE EMP SET COMM = 100;
14 Rows Updated
SELECT * FROM EMP;
All the records will have commission as 100 now.
Update a specific record:
UPDATE EMP SET COMM = 100 WHERE EMPNO = 7839;
1 Row Updated.
Update values in 2 or more fields in a record
UPDATE EMP SET COMM = 100,SAL = SAL + 100 WHERE EMPNO = 7839;
Wipro Confidential
Example:
DELETE EMP;
14 Rows Deleted.
SELECT * FROM EMP;
No Rows Selected.
ROLLBACK;
SELECT * FROM EMP;
14 Rows Selected.
Wipro Confidential
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
DOB
DATE
If the table has some records already the newly added field will have NULL
values for those records.
Wipro Confidential
Null?
-----------
Type
----------VARCHAR2(1)
Wipro Confidential
Example:
DESC DEMO_EX
RENAME DEMO_EX TO DEMO_EX1;
Table Renamed.
Now let us try to access DEMO_EX.
DESC DEMO_EX
Error : Object Demo_Ex does not exists
DESC DEMO_EX1
Wipro Confidential
No Rows Selected.
Constraints:
This is a way to restrict data that goes into a table.
2 Types
1. Column Level Constraints
2. Table Level Constraints.
Column Level Constraints
Types:
1. NOT NULL
2. CHECK
3. UNIQUE
4. PRIMARY KEY
5. REFERENCES
NULL:
It is a keyword used to represent the field in a record which does not have any
value. In a storage space perspective Null does not occupy any space as such.
Note:
In oracle all the table fields default constraint is NULL.
NOT NULL:
If a field has a not null constraint specified then it cannot hold null values.
DROP TABLE DEMO_EX;
Page 40 of 79
Wipro Confidential
Wipro Confidential
DESC DEMO_EX
Name
-----------NO
NA
Null?
Type
-------- -----------NUNBER (3)
VARCHAR2 (20)
Wipro Confidential
Page 43 of 79
Wipro Confidential
Wipro Confidential
Classifications
CHECK
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM (
NO NUMBER(3),
NA VARCHAR2(20),
CHECK(NO < 101)
);
Table Level Constraint:
The functionality is the same as that of column level constrain but the way we
define them is different.
Column Level Constraint:
CREATE TABLE EX_DEM1(
NO NUMBER (3) CHECK (NO<101),
NA VARCHAR2 (20)
);
INSERT INTO EX_DEM VALUES (1,'OCEAN');
INSERT INTO EX_DEM (NO) VALUES (2);
INSERT INTO EX_DEM (NA) VALUES ('DEMO');
INSERT INTO EX_DEM (No) VALUES (101);
Error: Check Constraint (Scott.Name) Violated.
Table Level Constraint:
Unique:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM (
NO NUMBER(3),
NA VARCHAR2(20),
UNIQUE(NO)
);
Primary Key:
DROP TABLE EX_DEM;
Page 45 of 79
Wipro Confidential
Wipro Confidential
Wipro Confidential
Usage:
ALTER TABLE EX_DEM MODIFY(NO NOT NULL);
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NOT NULL NUMBER(3)
NA
VARCHAR2(20)
Wipro Confidential
Note 1:
Since table EX_DEM1 is referring to EX_DEM we will not be able to drop
EX_DEM.
Example:
DROP TABLE EX_DEM;
Error : unique/primary keys in table referenced by foreign keys
Note 2:
We can add or modify the constraint to an existing table field as long as the field
has no values in it or if the field has already some values those values must satisfy
the new constraint that we are trying to add or modify.
Type
---VARCHAR2(30)
VARCHAR2(30)
VARCHAR2(1)
VARCHAR2(30)
LONG
VARCHAR2(30)
VARCHAR2(30)
VARCHAR2(9)
VARCHAR2(8)
VARCHAR2(14)
VARCHAR2(9)
VARCHAR2(13)
VARCHAR2(14)
VARCHAR2(3)
DATE
Wipro Confidential
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME
FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
CONSTRAINT_TYPE
MEANING
P
Primary Key
R
References
C
Not null & Check
U
Unique.
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME
FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM1';
Example:
DROP TABLE EX_DEM1;
DROP TABLE EX_DEM;
Create a table with NOT NULL constraint to NO field.
CREATE TABLE EX_DEM(NO NUMBER(3) NOT NULL,NA
VARCHAR2(20));
Find the name of the constraint
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NOT NULL NUMBER(3)
NA
VARCHAR2(20)
Remove the constraint
ALTER TABLE EX_DEM DROP CONSTRAINT SYS_C00740;
Table Altered.
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
Example:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3) NOT NULL,NA VARCHAR2(20)
UNIQUE);
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
INSERT INTO EX_DEM(NA) VALUES('DEMO');
Error: Cannot Insert Null into "Scott"."Ex_Dem"."No"
INSERT INTO EX_DEM VALUES(1,'OCEAN');
1 Row Created.
INSERT INTO EX_DEM VALUES(1,'OCEAN');
Error : Unique Constraint(Scott.Sys_C00742) Violated.
ALTER TABLE EX_DEM DISABLE CONSTRAINTS SYS_C00742;
Table Altered.
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
Since we have disabled the unique constraint now we can insert duplicate values..
INSERT INTO EX_DEM VALUES(1,'OCEAN');
1 Row Created.
Wipro Confidential
Set Operators:
The four set operators union, union all, intersect and minus allow to serially
combine more than one select statement. Although more than one select statement
will then be present, only one result set is then returned.
If the select statements vary in their numbers of returned columns, Oracle reportS
an ORA-01789: query block has incorrect number of result columns.
For the demonstration of set operators, the following test tables are created:
CREATE TABLE U1(NO NUMBER(3));
CREATE TABLE U2(NO NUMBER(3));
INSERT INTO U1 VALUES(1);
INSERT INTO U1 VALUES(4);
INSERT INTO U1 VALUES(2);
INSERT INTO U2 VALUES(3);
INSERT INTO U2 VALUES(4);
INSERT INTO U2 VALUES(5);
COMMIT;
SELECT * FROM U1;
SELECT * FROM U2;
1. UNION ALL:
Union all selects all rows from all select statements:
Example:
SELECT * FROM U1
UNION ALL
SELECT * FROM U2;
1
4
2
3
4
5
Page 52 of 79
Wipro Confidential
2. UNION:
Union is very similar to union all, however, it dismisses duplicate rows
found across different select statements:
Note :
The selected values automatically displayed in ascending order.
Example:
SELECT * FROM U1 UNION SELECT * FROM U2;
1
2
3
4
5
3. INTERSECT
Intersect only returns the rows that are found in all select statements:
Example:
SELECT * FROM U1 INTERSECT SELECT * FROM U2;
4
4. MINUS:
Minus returns all rows from the first select statements except those who
are duplicated in a following select statement:
Example:
SELECT * FROM U1 MINUS SELECT * FROM U2;
1
2
SELECT * FROM U2 MINUS SELECT * FROM U1;
3
5
1. ROWID:
For each row in the database, the ROWID pseudo column returns a rows
address. Usually, a rowid value uniquely identifies a row in the database.
However, rows in different tables that are stored together in the same
cluster can have the same rowid. Values of the ROWID pseudo column
have the data type ROWID or UROWID.
Important uses of ROWID:
a. They are the fastest way to access a single row.
Page 53 of 79
Wipro Confidential
2. ROWNUM:
For each row returned by a query, the ROWNUM pseudo column returns a
number indicating the order in which Oracle selects the row from a table
or set of joined rows. The first row selected has a ROWNUM of 1, the
second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query,
as in this example
Example:
SELECT * FROM employees WHERE ROWNUM < 10;
If an ORDER BY clause follows ROWNUM in the same query, the rows
will be reordered by the ORDER BY clause. The results can vary
depending on the way the rows are accessed. For example, if the ORDER
BY clause causes Oracle to use an index to access the data, Oracle may
retrieve the rows in a different order than without the index. Therefore, the
following statement will not have the same effect as the preceding
example:
Example:
SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY
last_name;
If you embed the ORDER BY clause in a sub query and place the
ROWNUM condition in the top-level query, you can force the ROWNUM
condition to be applied after the ordering of the rows. For example, the
following query returns the 10 smallest employee numbers. This is
sometimes referred to as a "top-N query":
Example:
Page 54 of 79
Wipro Confidential
3. LEVEL:
For each row returned by a hierarchical query, the LEVEL pseudo column
returns 1 for a root row, 2 for a child of a root, and so on.
A root row is the highest row within an inverted tree.
A child row is any non root row.
A parent row is any row that has children.
A leaf row is any row without children.
Figure below shows the nodes of an inverted tree with their LEVEL
values.
Page 55 of 79
Wipro Confidential
Wipro Confidential
Page 57 of 79
Wipro Confidential
Tree View:
SELECT LPAD(LEVEL,LEVEL,' '),ENO,JOB,MNO FROM DEMO_EX
CONNECT BY PRIOR ENO = MNO
START WITH JOB = 'MD';
Joins:
Joins are used to select fields from many tables using a single select statement.
3 Types
1. Equi Join
2. Non Equi Join
3. Outer Join
Cartesian product:
Page 58 of 79
Wipro Confidential
A{1,2,3}
B{a,b}
A * B = 1a,1b,,2a,2b,3a,3b
Steps to write a query with join:
Identify the fields that you need to view from different tables and add
those field names in the SELECT clause of the query.
Add all table names to the FROM clause of the query.
Identify the common fields between the tables and add them to the join
condition.
Join Condition:
Table1.Fieldname OPERATOR Table2.FieldName
Note:
If there are N number of tables in the FROM clause of the query there should be
N-1 join conditions.
1. Equi Join:
Syntax:
Table1.Fieldname = Table2.FieldName
Example:
SELECT * FROM DEPT;
4 Rows Selected.
SELECT * FROM EMP;
14 Rows Selected.
List the Ename and Dname column values.
SELECT ENAME,DNAME FROM EMP,DEPT;
56 Rows Selected.
The above query will return a Cartesian product of the two tables and
hence we get 56 (14 * 4 =56) rows selected. This happens because there is
no join condition mentioned in the above query.
To Avoid: (Mention a join condition)
SELECT ENAME,DNAME FROM EMP,DEPT WHERE EMP.DEPTNO
= DEPT.DEPTNO;
List Ename,Job,Loc,Dname column values.
SELECT ENAME,JOB,LOC,DNAME FROM EMP,DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Page 59 of 79
Wipro Confidential
Select the employee name and his department who gets a salary greater
than 2000.
SELECT ENAME,DNAME FROM EMP WHERE SAL > 2000;
*
Error: Invalid Column Name
SELECT ENAME, DNAME FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO AND SAL > 2000;
List Ename, Dname, DeptNo column values.
SELECT ENAME, DNAME, DEPTNO FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Error : Column Ambiguously defined
The above query is throwing an error because the column DEPTNO
mentioned in the select clause is present in both EMP and DEPT table.
Hence we should mention the TABLE.FIELD_NAME to avoid confusion.
SELECT ENAME, DNAME, EMP.DEPTNO FROM EMP, DEPT
WHERE
EMP.DEPTNO = DEPT.DEPTNO;
SELECT ENAME, DNAME, DEPT.DEPTNO FROM EMP, DEPT
WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Select Ename, Deptno, and Dname of the employee getting maximum
salary.
SELECT ENAME, DNAME FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO AND
SAL = (SELECT MAX (SAL) FROM EMP);
Select all employees belonging to the department having maximum
number of employees.
Step 1:
SELECT DEPTNO FROM EMP GROUP BY DEPTNO;
Step 2:
SELECT COUNT (*), DEPTNO FROM EMP GROUP BY DEPTNO;
Step 3:
SELECT DEPTNO FROM EMP GROUP BY DEPTNO
HAVING COUNT (*) = (SELECT MAX (COUNT (*)) FROM EMP
GROUP BY DEPTNO);
Step 4:
Page 60 of 79
Wipro Confidential
3. Outer Joins:
A "normal" join finds values of two tables that are in a relation to each
other. In most cases, this relation is equality (=), but it can also be all sorts
of operations that either return true or false. The important thing is that a
"normal" join only returns rows of both tables of which the compared
columns return true. Of course, a row whose column-value is not found in
the other table's joined column is not returned at all. However, sometimes,
there is a requirement to show these rows as well.
Example:
SELECT * FROM DEPT;
Page 61 of 79
Wipro Confidential
(+) =
= (+)
Select employees name his department number and his department name.
Normal Equi Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;
14 Rows Selected.
Left Outer Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO(+) = DEPT.DEPTNO;
Page 62 of 79
Wipro Confidential
15 Rows Selected.
Table1.Field(+) = Table2.Field
This condition selects the matching records plus the additional records in
Table2 which does not have a matching record in Table1.
Right Outer Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO(+);
14 Rows Selected.
In this case we get only 14 records because the EMP table is the child
table and DEPT table is the master table and hence it cannot contain an
employee belonging to a totally new department which is not there in the
department table.
Select all the departments which do not have any employees working in
it.
The result for the above requirement can be obtained in 2 ways
Using Join:
SELECT DEPT.DEPTNO,DNAME,LOC FROM EMP,DEPT
Page 63 of 79
Wipro Confidential
Using Join:
SELECT * FROM DEPT WHERE DEPTNO NOT IN (SELECT
DEPTNO FROM EMP GROUP BY DEPTNO);
Privileges:
A privilege is a right to execute an SQL statement or to access another user's object. In
Oracle, there are two types of privileges: system privileges and object privileges. A
privileges can be assigned to a user or a privilege The set of privileges is fixed, that is,
there is no SQL statement like create privilege xyz.
1. System privileges:
There are quite a few system priviliges: in Oracle 9.2, we count 157 of them,
and 10g has even 173. Those can be displayed with
Select name from system_privilege_map
Executing this statement, we find privileges like create session, drop user,
alter database. System privileges can be audited. Arguably, the most important
system privileges are:
a. create session (A user cannot login without this privilege. If he tries, he
gets an ORA-01045).
b. create table
c. create view
d. create procedure
e. sysdba
f. sysoper
This is basically used for DB related activities live user creation, object
creation etc.
Note:
When we install the Oracle, it automatically creates 5 Users
User
Password
1
Sys
Change_On_Install
2
System
Manager
The above 2 are DBA users
3
Scott
tiger
4
Demo
Demo
5
DBSNMP
DBSNMP
The above 3 are Ordinary Users.
DBA:
Users have System Privileges.
Page 64 of 79
Wipro Confidential
Ordinary User:
Do the operations within their area.
Examples of DBA operations:
User Creation
User Alteration
Grant the Permission
Drop the user.
Note: We must login into the DBA user Area.
Example: System / Manager
How to find your user name in the SQL Prompt?
SHOW USER
Its a SQL * Plus Editor Command.
How to Create a User?
CREATE USER:
Its a DDL command.
Syntax:
CREATE USER <uname> IDENTIFIED BY <pwd>;
User Created.
or
Insufficient Privileges
Example:
Log in as Scott:
CREATE USER MUNI IDENTIFIED BY MUNI;
Insufficient Privileges
Log in as System:
CREATE USER MUNI IDENTIFIED BY MUNI;
User Created.
Now that we have created a user let us try to log in. We will get an error
message as shown below.
error : user MUNI lacks CREATE SESSION privileges : logon denied
This is because the user that we just created is not having the privilege to
connect with the data base.
How to give the permission to the user to connect with the DB?
Page 65 of 79
Wipro Confidential
Grant:
Its a DCL command, which is used to give the permission
Syntax:
GRANT <permission> TO <username>;
Grant Succeeded.(DBA)
or
Insufficient Previleges(Ordinary User)
Permission:
CONNECT
RESOURCE
DBA
Connect With DB
DUAL, User_Constraints,...
Treat like a another DBA
Example:
Scott:
GRANT CONNECT,RESOURCE TO MUNI;
Error : Insufficient Previleges
System:
GRANT CONNECT,RESOURCE TO MUNI;
Grant Succeeded.
Note:
Now the user will be able to connect with the database.
How to change the User Password?
ALTER USER:
Its a DDL command which is used to change the password.
Syntax:
ALTER USER <uname> IDENTIFIED BY <pwd>;
User Altered.
Note:
The Password can be changed by current user or by the DBA.
Example:
Scott:
ALTER USER MUNI IDENTIFIED BY MUNI1;
Error : Insufficient Previleges
System:
ALTER USER MUNI IDENTIFIED BY MUNI2;
Page 66 of 79
Wipro Confidential
User Altered.
Muni:
ALTER USER MUNI IDENTIFIED BY MUNI3;
User Altered.
How to drop the user from the DB?
DROP USER:
Its a DDL command which is used to remove the user from DB.
Syntax:
DROP USER <uname> [CASCADE];
User Dropped.
or
Insufficient Privileges.
Example:
Scott:
DROP USER MUNI;
Error : Insufficient Previleges.
System:
DROP USER MUNI;
User Dropped.
CASCADE:
If the user we are dropping has some objects in his area then he cannot be
dropped unless his objects are dropped first. To accomplish this we use
Cascade key word. On using this the objects are dropped first and the user
is dropped next.
2. Object privileges
Object privileges can be assigned to the following types of objects:
1. Tables
Select, insert, update, delete, alter, debug, flashback, on commit
refresh, query rewrite, references, all
2. Views
Select, insert, update, delete, under, references, flashback, debug
3. Sequence
alter, select
4. Packages, Procedures, Functions (Java classes, sources...)
execute, debug
Page 67 of 79
Wipro Confidential
For a user to be able to access an object in another user's schema, he needs the
according object privilege. Object privileges can be displayed using
all_tab_privs_made or user_tab_privs_made.
This is basically used to enable communication between users.
Grant:
Its a DCL command used to give the permission to the user to access
objects.
Syntax:
GRANT <permission> ON <object> TO <user>;
Grant Succeeded.
Permission
SELECT
INSERT
UPDATE
DELETE
ALL
Object:
Tables, procedures, views etc.
Example:
Scott:
GRANT SELECT ON EMP TO MUNI;
Grant Succeeded.
MUNI:
SELECT * FROM TAB;
No Rows Selected.
SELECT * FROM EMP;
Error : table or view does not exists
SELECT * FROM SCOTT.EMP;
14 Rows Selected.
SELECT * FROM SCOTT.DEPT;
Error: table or view does not exists
Note:
Suppose if user "MUNI" performs other than the select operation he will
get the "Insufficient Privilege" error because scott has granted only select
privilege to MUNI on EMP table
Page 68 of 79
Wipro Confidential
Example:
MUNI:
DELETE FROM SCOTT.EMP;
Error: Insufficient Privileges
How to revoke the granted permission?
REVOKE:
Its a DCL command.
Syntax:
REVOKE <permission> ON <object> FROM <user>;
Revoke Succeeded.
Example:
Scott:
REVOKE SELECT ON EMP FROM MUNI;
Revoke Succeeded.
From now on user MUNI cannot access Scott.Emp.
Muni:
SELECT * FROM SCOTT.EMP;
Error: table or view does not exists
How to grant more than one permission to a user?
GRANT SELECT, DELETE ON EMP TO MUNI;
Grant Succeeded.
1. View:
It is a logical representation of the Table (Object). Table is a physical
representation of data. View does not occupy memory; it is just used to store
the query. A view when called always executes the query associated to fetch
the results.
We can create a view for a Table, View or Synonym.
Page 69 of 79
Wipro Confidential
Syntax:
CREATE [OR REPLACE] VIEW <vname>[(fn1,fn2,..)] AS query;
View Created.
OR REPLACE:
If a view is already having the given "vname" then old query in that view
is replaced by the current query.
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT * FROM EMP;
View Created.
SELECT * FROM VV1;
14 Rows Selected.
Note:
If a View is created from single table with all fields included then we can
manipulate the data using that view.
Manipulation:
Manipulation in this context means Inserting, Deleting and Updating the
data.
INSERT INTO VV1 (EMPNO, DEPTNO) VALUES (1, 20);
1 Row Created.
SELECT * FROM VV1;
15 Rows Selected.
SELECT * FROM EMP;
15 Rows Selected.
Note:
The new values must satisfy the constraints in on that table.
UPDATE VV1 SET ENAME='DEMO' WHERE EMPNO = 1;
1 Row Updated.
SELECT * FROM VV1;
SELECT * FROM EMP;
DELETE FROM VV1 WHERE EMPNO = 1;
SELECT * FROM VV1;
SELECT * FROM EMP;
COMMIT;
Page 70 of 79
Wipro Confidential
Note:
If we are creating a view which has columns from more than one table in
that case we cant modify the data using the view.
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT ENAME, DNAME
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;
View Created.
SELECT * FROM VV1;
14 Rows Selected.
INSERT INTO VV1 (ENAME) VALUES ('DEMO');
Error: cannot modify the multiple table join view.
How to change the field names in the view?
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT * FROM EMP;
SELECT * FROM VV1;
Now the column names are the same as that of EMP table. In order to give
different name the columns we need to create a view as follows.
CREATE OR REPLACE VIEW VV1(ENO,ENA,DNO) AS SELECT
EMPNO,ENAME,DEPTNO FROM EMP;
SELECT * FROM VV1;
2. Synonyms
A synonym is an alias for one of the following objects:
a. table
b. object table
c. view
d. object view
e. sequence
f. stored procedure
g. stored function
h. package
i. materialized view
j. java class
k. used defined object object type
l. another synonym
Page 71 of 79
Wipro Confidential
The object does not need to exist at the time of its creation. Synonyms can't be
used in a drop and truncate statements. If this is tried, it results in a ORA00942: table or view does not exist
Syntax:
create synonym <synonym-name> for <object-name>;
create public synonym <synonym-name> for <object-name>;
Public synonyms:
A public synonym (create public synonym) is owned by public rather than the
one who has created it. Therefore, a public synonym is valid for each schema.
Example:
SQL> create table test_ (a number);
Table created.
SQL> create synonym t for test_;
Synonym created.
SQL> insert into t values(4);
1 row created.
SQL> insert into t values(5);
1 row created.
SQL> update t set a =40 where a =4;
1 row updated.
SQL> delete from t where a = 5;
1 row deleted.
SQL> truncate table t;
truncate table t
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> drop table t;
drop table t
*
ERROR at line 1:
ORA-00942: table or view does not exist
Page 72 of 79
Wipro Confidential
3. Sequence:
It is used to generate unique numbers in a sequential manner. It is a database
object. As we have seen earlier NEXTVAL and CURRVAL are the pseudo
columns which are used to access the value from the sequence
Syntax:
CREATE SEQUENCE <sname>
[INCREMENT BY
NUMBER
START WITH
NUMBER
MINVALUE
NUMBER]
MAXVALUE
NUMBER
[CACHE /*NOCACHE NUMBER
CYCLE /*NOCYCLE;]
Sequence Created
Example:
CREATE SEQUENCE SEQ1
INCREMENT BY1
START WITH
1
MINVALUE
1
MAXVALUE
5;
Sequence Created
SELECT * FROM TAB;
This will not display the sequence objects.
CREATE TABLE U1 (NO NUMBER (3));
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
4
5
Page 73 of 79
Wipro Confidential
Wipro Confidential
/
Sequence Created.
TRUNCATE TABLE U1;
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
1
2
3
Note:
The Start with value must be greater than the Min value.
Example:
DROP SEQUENCE SEQ1;
CREATE SEQUENCE SEQ1
INCREMENT BY1
START WITH
0
MINVALUE
2
MAXVALUE
5;
Error : Start with Cannot Less than Minvalue
How to know the current value of the sequence?
SELECT SEQ1.CURRVAL FROM DUAL;
Page 75 of 79
Wipro Confidential
4. Index:
Index is used to make the selection of records faster. An index is a schema
object that contains an entry for each value that appears in the indexed
column(s) of the table or cluster and provides direct, fast access to rows.
Type1:
CREATE INDEX <iname> ON <tname>(fn1,..);
Type2:
CREATE UNIQUE INDEX <iname> ON <tname>(fn1,..);
Type3:
CREATE INDEX <iname> ON CLUSTER <cname>;
Example:
CREATE INDEX II1 ON EMP(ENAME);
Index Created.
SELECT * FROM EMP;
SELECT * FROM EMP WHERE DEPTNO = 10;
The II1 index is not used in the above queries.
SELECT * FROM EMP WHERE ENAME LIKE 'A%';
The II1 index will be used in the above query and this will make the record
selection in faster.
Note:
We cant create more than one index on a field.
Example:
CREATE INDEX II2 ON EMP(ENAME);
Error: such column list already indexed
How to Drop the Index?
DROP INDEX <iname>;
Index Dropped.
Example:
DROP INDEX II1;
Unique Index:
CREATE UNIQUE INDEX II1 ON EMP(ENAME);
Index Created.
Note:
Page 76 of 79
Wipro Confidential
Specify UNIQUE to indicate that the value of the column (or columns) upon
which the index is based must be unique.
It work like the Unique Constraint once an unique index is created on a
column you cannot insert duplicates.
INSERT INTO EMP(EMPNO,ENAME,DEPTNO) VALUES(1,'KING',20);
Error : Unique Constraint (Scott.II1) Violated.
Note : (OCP)
If a table field contains Primary Key / Unique Constraint we cant create an
Index to those fields because automatically an index will be created on the
primary key / Unique field.
Example:
CREATE TABLE U1(NO NUMBER(3) PRIMARY KEY,NA
VARCHAR2(20) UNIQUE);
CREATE INDEX II2 ON U1 (NO);
Error: such column list already indexed
CREATE INDEX II2 ON U1 (NA);
Error: such column list already indexed
5. Cluster:
A cluster is a schema object that contains data from one or more tables, all of
which have one or more columns in common. Oracle stores together all the
rows (from all the tables) that share the same cluster key.
For information on existing clusters, query the USER_CLUSTERS,
ALL_CLUSTERS, and DBA_CLUSTERS data dictionary views.
Clusters are groups of one or more tables that are physically stored together
because they share common columns and usually are used together. Because
related rows are physically stored together, disk access time improves.
Steps to Create a Cluster:
1. Create a cluster.
2. Create the table and add the table fields to the cluster.
3. Create an index for the cluster.
4. Add records to the Cluster tables.
Example:
If we are not going to use cluster then we would be performing the following
operations.
CREATE TABLE STUD_PER (RNO NUMBER (3), NA VARCHAR2 (20));
Table Created.
Page 77 of 79
Wipro Confidential
Wipro Confidential
Page 79 of 79
Wipro Confidential