Sie sind auf Seite 1von 165

SQL Structured Query Language

Data Definition Language (DDL)


1. Create
2. Alter
3. Drop
4. Truncate
5. Rename

To create a Table
Ex:
Create Table cig_emp(empno number,name varchar2(25),doj date,job varchar2(25),sal number,deptno
number);

To View the Structure of the Table.


SQL>Describe cig_emp;
Or
SQL>Desc cig_emp;

To Alter the Table Structure?


SQL> Alter Table Cig_Emp modify(job varchar2(20));
Note: To resize the column width of Job

To add one more column in the existing table.


SQL> Alter Table Cig_emp Add(Blood_Group varchar2(10));

To Delete the unwanted Column.


SQL> Alter Table Cig_emp Drop(Blood_Group);

To Rename the Column Name


SQL> ALter Table Dept1 Rename column Deptno To Dno;

To Delete the Table.


SQL>Drop Table CIG_EMP;

To remove the data from the table.


SQL> Truncate Table CIG_Emp;

To rename the Table Name


SQL>Rename CIG_EMP To CIG_EMP1;

2. Data Manipulation Language


INSERT
UPDATE
DELETE
MERGE

Ex:
SQL>Insert into CIG_EMP Values(1000, Raghu, 02-Apr-2008, Tech_Consult, 20000, 40);

For Continuous Input


SQL> insert into cig_emp values(&empno,'&name','&doj','&job',&sal,&dno);
Note: Use /

For insert in desired field only


SQL > Insert into CIG_EMP(empno,name) Values (100,Seenu);
For insert all rows to a new table
Sql> Insert into Dept1 ( Select * from dept )

5 rows created.

Data Retrieval - Select


To View the Data
SQL> Select * From CIG_EMP;

To view Selected Columns


SQL> Select Empno, Name from CIG_EMP;

How to view the Desired Record?


To view the Record of Raghu
SQL> select * from CIg_EMP Where empno=1001;
or
SQL> select * from CIg_EMP Where name='Raghu';

To view the records of name starts with r?


SQL> select * from cig_emp where name like 'r%';
Note: % - For Multicharacters.
_ For Single Character.
SQL> select * from cig_emp where name like '_a%';

To view the records Last character as r?


SQL> select * from cig_emp where name like '%r';

To view the records : empno >=1002


SQL> select * from cig_emp where empno>=1002;

Using In to extract Data?


SQL> select * from cig_emp where empno in (1000,1003);
SQL> select * from cig_emp where name in ('Raghu','raja');

Using AND
SQL> Select * from emp where job='CLERK' AND SAL > 1000;
SQL> SELECT * FROM EMP WHERE SAL >=1000 AND SAL <=2000;

Using OR
SQL> select * from emp where job = 'CLERK' OR job = 'MANAGER';
SQL> SELECT * FROM EMP WHERE JOB IN ('MANAGER','CLERK');

Between and
SQL> select * from emp where sal between 1000 and 2000;

Not (except 1000 to 2000)


SQL> select * from emp where sal not between 1000 and 2000;
SQL> select * from emp where not job='MANAGER';
SQL> SELECT * FROM EMP WHERE JOB NOT IN ('MANAGER','CLERK');

SQL> Select name from trial where name like '%\_%' ESCAPE '\';
NAME
--------------------
st_thomas
sri_ramajayam
lathika_saran
abi_nayaa
a_rvinthan

Note: Search for special characters : By using ESCAPE

24.09.2008
To Insert Data in particular fields.
SQL> Insert into cig_emp (Empno,Name) values(2000,'Vignesh');

Update : To made Changes in Existing Records.


Ex:
SQL> Update Cig_Emp1 Set DOJ='02-May-2008' where empno=2000;
Note: Update in a Single Field.

SQL> Update Cig_Emp1 Set Job='DBA',sal=5000,deptno=30 where name='Vignesh';


Note: To update in multiple Fields.

SQL> Update CIG_EMP1 set sal=sal*1.20;


Note: To increase 20% of sal to all employees.

CONSTRAINTS
1. NOT NULL
2. UNIQUE
3. CHECK
4. PRIMARY KEY (UNIQUE + NOT NULL)
5. FOREIGN KEY

To create the table with Primary Key & Not Null


SQL> CREATE TABLE CIG_EMP2(ENO NUMBER PRIMARY KEY,NAME VARCHAR2(30) NOT
NULL,DEPTNO NUMBER,SAL NUMBER);
Note: We cant enter duplicate values in ENO & with out leaving the NAME Field.

How to set Default Value.


SQL> CREATE TABLE CIG_EMP2(ENO NUMBER PRIMARY KEY,NAME VARCHAR2(30) NOT
NULL,DOJ DATE DEFAULT SYSDATE,DEPTNO NUMBER);

Ex:
SQL> INSERT INTO CIG_EMP2(ENO,NAME,DEPTNO) VALUES (&ENO,'&NAME',&DNO);
Or
SQL> INSERT INTO CIG_EMP2 (ENO,NAME,DEPTNO) VALUES (1000,'ASHOK',40);

SQL> Insert into CIG_EMP2 values (1004,'Raghu','02-May-2008',40);


Note: If we give value then take that value otherwise take the default value.

CHECK
SQL> Create table cig_emp3 (eno number primary key,name varchar2(30) not null,deptno number
check(deptno<50));
Note: Allows deptno is less than 50

How to Add Not Null in existing Column?


SQL> Alter table cig modify(name varchar2(20) NOT NULL);

How To add constraint?


SQL> Alter table cig add constraint cons1 PRIMARY KEY(no);

Add Primary Key for Column Sets


SQL>CREATE TABLE TR_TAB1(ID NUMBER,NAME VARCHAR2(20),SAL NUMBER, CONSTRAINT TR_CONS
PRIMARY KEY(ID,NAME))

Note: If we create as like above then it check for 2 columns not a single column.

Ex: SQL> select * from tr_tab1;

ID NAME SAL
---------- -------------------- ----------
1000 Saran 2500
1000 Seenu 2500
2000 Seenu 2500

How to Handle More than one Table?


1. List EmpNo, Name, DepartmentNo, Department Name,JOB
SQL> select cig_emp2.eno,cig_emp2.name,cig_emp2.deptno,cig_dept.dname from cig_emp2,cig_dept
where cig_emp2.deptno = cig_dept.deptno;

By using ALIAS Name to the Table


SQL> Select e.eno,e.name,d.dname from cig_emp2 e,cig_dept d where e.deptno=d.deptno;

Sorting
SQL> select * from cig_emp2 order by name;
Note: In Default : Ascending

Descending
SQL> select * from cig_emp2 order by name desc;

Functions
Single Row Function

General functions:
NVL
NVL2
NULLIF
COALESCE
CASE
DECODE

Function Description
NVL Converts a null value to an actual value
NVL2 If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The
argument expr1can have any data type.

NULLIF Compares two expressions and returns null if they are equal, or the first
expression if they are not equal

COALESCE Returns the first non-null expression in the expression list

Ex: NVL
SQL> select empno,ename,nvl(comm,100) from emp;
Note: Substitute the value 100 for null value.

SQL> select ename,sal*nvl(comm,1) from emp;

SQL> select empno,ename,nvl(hiredate,sysdate) from emp;


Note: Show system date for null of hiredate

SQL> select empno,nvl(ename,'Prasanth') from emp;

NVL2
SQL> Select empno,ename,comm,nvl2(comm,'YES','NO') "Commision Status" from emp;

Ex:
EMPNO ENAME COMM Com
---------- ---------- ---------- ---
7369 SMITH NO
7499 ALLEN 300 YES
7521 WARD 500 YES
7566 JONES NO

NULLIF
Syntax
NULLIF (expr1, expr2)
In the syntax:
expr1 is the source value compared to expr2
expr2 is the source value compared with expr1. (If it is not equal to expr1, expr1
is returned.)

Note: The NULLIF function is logically equivalent to the following CASE expression. The CASE
expression is discussed in a subsequent page:
CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END

Ex:
SQL> select ename,job,NULLIF(EMPNO,MGR) "NULLIF" FROM EMP;

ENAME JOB NULLIF


---------- --------- ----------
SMITH CLERK 7369
ALLEN SALESMAN 7499
WARD SALESMAN 7521
JONES MANAGER 7566
XX Sales 1321
the manager 1121
Saran 100
ASHOK TECH
The COALESCE Function
The COALESCE function returns the first non-null expression in the list.
Syntax
COALESCE (expr1, expr2, ... exprn)
In the syntax:
expr1 returns this expression if it is not null
expr2 returns this expression if the first expression is null and this expression is not
null
exprn returns this expression if the preceding expressions are null

SQL> Select ename,coalesce(comm,sal,1000) "COALESCE" From emp;

ENAME COALESCE
---------- ----------
SMITH 800
ALLEN 300
WARD 500
JONES 2975
MARTIN 1400
the 5000
Saran 1000
ASHOK 25

Conditional Expressions
Provide the use of IF-THEN-ELSE logic within a
SQL statement
Use two methods:
CASE expression
DECODE function

SQL> Select ename,job,sal "Current Salary", CASE JOB


When 'CLERK' THEN 1.10 * SAL
2 When 'SALESMAN' Then 1.15 * sal
3 When 'MANAGER' Then 1.20 * Sal
4 ELSE
5 Sal
6 End "Revised Salary" From Emp;

ENAME JOB Current Salary Revised Salary


---------- --------- -------------- --------------
SMITH CLERK 800 880
ALLEN SALESMAN 1600 1840
WARD SALESMAN 1250 1437.5
JONES MANAGER 2975 3570
MARTIN SALESMAN 1250 1437.5
BLAKE MANAGER 2850 3420
kannan SALESMAN 850 977.5
SCOTT ANALYST 300 300

SQL> Select Ename,Job,Sal "Current Salary", DECODE(Job, 'CLERK', 1.10 * Sal, 'SALESMAN',1.15 *
Sal, 'MANAGER', 1.20 * Sal, sal) "Revised Sal" From Emp;

ENAME JOB Current Salary Revised Sal


---------- --------- -------------- -----------
SMITH CLERK 800 880
ALLEN SALESMAN 1600 1840
WARD SALESMAN 1250 1437.5
JONES MANAGER 2975 3570
MARTIN SALESMAN 1250 1437.5
BLAKE MANAGER 2850 3420

Try it Yourself

1. Find a Grade for the Employees Depends upon the Salary:


A > 3000
B > 2000 & <=3000
C Others
27-09-2008
Character-Manipulation Functions
These functions manipulate character strings:

CONCAT To Add more than one text.


Ex:1
SQL> select concat('Hello',' World') from Dual;

CONCAT('HEL
-----------
Hello World

SQL> Select Concat(Ename,Job) from Emp;


CONCAT(ENAME,JOB)
-------------------
SMITHCLERK
ALLENSALESMAN
WARDSALESMAN
JONESMANAGER

In Real Time Example.


SQL> Select ename || ' is a ' || job "Ename with Job" From Emp;

Ename with Job


-------------------------
SMITH is a CLERK
ALLEN is a SALESMAN
WARD is a SALESMAN
JONES is a MANAGER

SUBSTR To extract a particular character(s) from the existing text.


Syntax: SubStr(text,startpos,no.of Char)
SQL> Select SubStr('Murshidh',4,5) from dual;

SUBST
-----
Shidh

SQL> Select SubStr('Ashok',3) from Dual;


SUB
---
Hok

To extract from Right of the Text.


SQL> Select Substr(ename,-3) from emp;

SUB
---
ITH
LEN

LENGTH

SQL> Select Length('Ashok') from Dual;


LENGTH('ASHOK')
---------------
5

SQL> Select Ename, Length(Ename) "Length" from Emp;

ENAME Length
---------- ----------
SMITH 5
ALLEN 5

SQL> Select * from Emp where Length(Ename)=5;

EMPNO ENAME JOB MGR HIREDATE


---------- ---------- --------- ---------- ---------
7369 SMITH CLERK 7902 17-DEC-80
7499 ALLEN SALESMAN 7698 20-FEB-81
7566 JONES MANAGER 7839 02-APR-81

Or
SQL> Select * from emp Where Ename Like '_____';

EMPNO ENAME JOB MGR HIREDATE


---------- ---------- --------- ---------- ---------
7369 SMITH CLERK 7902 17-DEC-80
7499 ALLEN SALESMAN 7698 20-FEB-81
7566 JONES MANAGER 7839 02-APR-81

INSTR To find the Position of the Character in the Text.

SQL> Select Instr('Ashok','o') From Dual;

INSTR('ASHOK','O')
------------------
4

SQL> Select Instr('Murshidh','o') From Dual;


INSTR('MURSHIDH','O')
---------------------
0

SQL> Select Instr('amirtha','a') From Dual;

INSTR('AMIRTHA','A')
--------------------
1

SQL> Select Instr('amirtha','a',2) From Dual;

INSTR('AMIRTHA','A',2)
----------------------
7

Exercise:
Extract the Characters upto second - in a column
SQL> select * from ex1;

COL1
------------------------------
5676-2345-6572-5672
56-57-565
567-676-752-110
5-7865-656-756

Result
Select Substr(col1,1,Instr(col1,'-',instr(col1,'-')+1)-1) from ex1
/
SUBSTR(COL1,1,INSTR(COL1,'-',I
------------------------------
5676-2345
56-57
567-676
5-7865

LPAD To Add Given Character in Left Side (For filling the Empty Space)
SQL> Select LPAD('Saranya',20,'#') From Dual;

LPAD('SARANYA',20,'#
--------------------
#############Saranya

SQL> Select Lpad(Ename,25,'*') From Emp;

LPAD(ENAME,25,'*')
-------------------------
********************SMITH
********************ALLEN
*********************WARD

RPAD To Add Given Character in Right Side (For filling the Empty Space)
SQL> Select Rpad('Kiran',20,'$') From Dual;

RPAD('KIRAN',20,'$')
--------------------
Kiran$$$$$$$$$$$$$$$

SQL> Select Rpad(sal,15,'%') From emp;

RPAD(SAL,15,'%'
---------------
800%%%%%%%%%%%%
1600%%%%%%%%%%%
1250%%%%%%%%%%%

TRIM To remove the blank space or first character of a text.


SQL> Select Trim('a' From 'aaaalagi') from dual;
TRIM
----
Lagi
SQL> select trim(ename) from emp;

TRIM(ENAME
----------
SMITH
ALLEN

29.09.2008
Replace :
Syntax: Replace(Text,Searching Text, Replacing Text);

Ex:
SQL> Select Replace('saravanan','a','z') from dual;

REPLACE('
---------
szrzvznzn
SQL> Select Replace ('This is sample','is','was') from dual;

REPLACE('THISISS
----------------
Thwas was sample

SQL> select ename,replace(ename,'a','x') from emp;

ENAME REPLACE(EN
---------- ----------
kannan kxnnxn
SCOTT SCOTT
kannan kxnnxn
the the
kumar kumxr
nithya1 nithyx1
To remove all a in a Given Text
SQL>select replace('aaaalagi','a') from dual

REP
---
lgi

Case Manipulation Functions


These functions convert case for character strings.
LOWER(SQL Course)
UPPER(SQL Course)
INITCAP(SQL Course)

SQL> Select Lower('AShok') From dual;

LOWER
-----
ashok
SQL> Select Lower(ename),Upper(Ename),Initcap(Ename) From emp;

LOWER(ENAM UPPER(ENAM INITCAP(EN


---------- ---------- ----------
smith SMITH Smith
allen ALLEN Allen
ward WARD Ward
jones JONES Jones
martin MARTIN Martin

Number Functions
ROUND: Rounds value to specified decimal
ROUND(45.926, 2) 45.93
SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),
2 ROUND(45.923,-1)
3 FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)


-------------- --------------- ----------------
45.92 46 50

TRUNC: Truncates value to specified decimal


TRUNC(45.926, 2) 45.92

SQL> select round(2000.3589,2),Trunc(2000.3589,2) From Dual;

ROUND(2000.3589,2) TRUNC(2000.3589,2)
------------------ ------------------
2000.36 2000.35

SQL> Select Round(3564.25,-2) from Dual;

ROUND(3564.25,-2)
-----------------
3600

TRUNC(3554.25,-3)
-----------------
3000
MOD: Returns remainder of division
MOD(1600, 300) 100

SQL> Select Mod(26,5) from dual;

MOD(26,5)
----------
1
Calculate the remainder of a salary after it is divided
by 5000 for all employees whose job title is sales
representative.
SELECT last_name, salary, MOD(salary, 5000)
FROM employees WHERE job_id = 'SA_REP'
/

LAST_NAME SALARY MOD(SALARY,5000)


-------------------- ---------- ----------------
Abel 11000 1000
Grant 7000 2000

Date Functions
To view the System Date
SQL> select sysdate from dual;

SYSDATE
---------
29-SEP-08

Arithmetic with Dates


Add or subtract a number to or from a date for a
resultant date value.
Subtract two dates to find the number of days
between those dates.
Add hours to a date by dividing the number of
hours by 24.

SQL> SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM employees WHERE


department_id = 90;

LAST_NAME WEEKS
-------------------- ----------
King 1110.78507
Kochhar 992.642216
De Haan 818.92793

For example, display the employee number, hire date, number of months employed, six-month review
date, first Friday after hire date, and last day of the hire month for all employees employed for fewer
than 36 months.

SQL> SELECT employee_id, hire_date,


2 MONTHS_BETWEEN (SYSDATE, hire_date) TENURE,
3 ADD_MONTHS (hire_date, 6) REVIEW,
4 NEXT_DAY (hire_date, 'FRIDAY'), LAST_DAY(hire_date)
5* FROM employees
EMPLOYEE_ID HIRE_DATE TENURE REVIEW NEXT_DAY( LAST_DAY(
---------- --------- ---------- --------- --------- ---------
100 17-JUN-87 255.403214 17-DEC-87 19-JUN-87 30-JUN-87
101 21-SEP-89 228.274182 21-MAR-90 22-SEP-89 30-SEP-89
102 19-JAN-93 188.338698 19-JUL-93 22-JAN-93 31-JAN-93
103 03-JAN-90 224.854827 03-JUL-90 05-JAN-90 31-JAN-90
104 21-MAY-91 208.274182 21-NOV-91 24-MAY-91 31-MAY-91

Using Date Functions


MONTHS_BETWEEN (01-SEP-95,11-JAN-94)
SQL> Select Round(Months_Between(Sysdate, To_Date('15-Jan-1975'))/12) From Dual;

ADD_MONTHS (11-JAN-94,6)
SQL> Select Sysdate,ADD_MONTHS(SYSDATE,6) From Dual;

SYSDATE ADD_MONTH
--------- ---------
29-SEP-08 29-MAR-09

NEXT_DAY (01-SEP-95,FRIDAY)
SQL> Select Sysdate,Next_Day(SYSDATE,'WEDNESDAY') From Dual;

SYSDATE NEXT_DAY(
--------- ---------
29-SEP-08 01-OCT-08

LAST_DAY(01-FEB-95)
SQL> Select Last_Day(Sysdate) From Dual;

LAST_DAY(
---------
30-SEP-08

Explicit Data Type Conversion

To_Char
SQL> Select sysdate,To_Char(sysdate,'MM/YY') From Dual;

SYSDATE TO_CH
--------- -----
29-SEP-08 09/08

AS Like We use the Below Terms


YYYY
YEAR
MM
MONTH
DY
DAY
MON
DD

To Spelled the Year


SQL> Select To_Char(sysdate,'YEAR') From Dual;
TO_CHAR(SYSDATE,'YEAR')
------------------------------------------
TWO THOUSAND EIGHT

To Spelled the day


SQL> Select To_Char(To_Date('15-Jan-75'),'ddspth') from dual;

TO_CHAR(TO_DAT
--------------
Fifteenth

To Spelled the Day of the Date


SQL> Select To_Char(sysdate,'DAY') From Dual;

TO_CHAR(S
---------
MONDAY
Note: For MON Use DY

To Spelled the Month of the Date


SQL> Select To_Char(sysdate,'MONTH') From Dual;

TO_CHAR(S
---------
SEPTEMBER
Note: For JAN Use MON

To Show in Roman Letter


SQL> Select To_Char(sysdate,'RM') From Dual;

TO_C
----
IX

SQL> Select To_Char(sysdate,'DD "of" Month') From Dual;

TO_CHAR(SYSDATE
---------------
29 of September

SQL> Select To_char(sysdate,'DD') || ' of ' || To_Char(sysdate,'Month') from dual;

TO_CHAR(SYSDATE
---------------
29 of September

SQL> SELECT last_name,


2 TO_CHAR(hire_date, 'fmDD Month YYYY')
3 AS HIREDATE
4* FROM employees;

LAST_NAME HIREDATE
-------------------- -----------------
King 17 June 1987
Kochhar 21 September 1989
De Haan 19 January 1993
Hunold 3 January 1990
Ernst 21 May 1991

9 Represents a number

0 Forces a zero to be displayed

$ Places a floating dollar sign

L Uses the floating local currency symbol

. Prints a decimal point

, Prints a thousand indicator

SQL> Select To_Char(sal,'9,99,999.99') from emp;

TO_CHAR(SAL,
------------
800.00
1,600.00
1,250.00
2,975.00
1,250.00
2,850.00
SQL>Select To_Char(sal,'0,99,999.99') from emp
TO_CHAR(SAL,
------------
0,00,800.00
0,01,600.00
0,01,250.00

SQL > Select To_Char(sal,'$9,99,999.99') from emp;

TO_CHAR(SAL,'
-------------
$800.00
$1,600.00
$1,250.00
$2,975.00

SQL > Select To_Char(sal,'L9,99,999.99') from emp;


TO_CHAR(SAL,'L9,99,999
----------------------
800.00
1,600.00
1,250.00
2,975.00
For Negative values only
SQL > select To_Char(-4500,'999999MI') from dual;

TO_CHAR
-------
4500-

SQL>select To_Char(-4500,'999999PR') from dual;

TO_CHAR(
--------
<4500>

SQL> Select To_Char(4578456874,'9999EEEE') from dual;

TO_CHAR
-------
5E+09

V Multiply by 10 n times (n = number of 9s after V) 9999V99 123400


SQL> Select To_Char(1234,'9999V99') from Dual;

TO_CHAR
-------
123400

B - Display zero values as blank, not 0 B9999.99 1234.00


SQL> select To_Char(0,'9B') from dual;

TO
--

To_Number
SQL> Select To_Number('145') from dual;

TO_NUMBER('145')
----------------
145

To_Date
SQL> Select To_Date('19-Sep-2008') from dual;

TO_DATE('
---------
19-SEP-08

SQL> Select To_Date('25-Jul-1973') + 7 From dual;

TO_DATE('
---------
01-AUG-73

30-09-2008
Displaying Data From Multiple Tables
Cartesian Products
When a join condition is invalid or omitted completely, the result is a Cartesian product, in which all
combinations of rows are displayed. All rows in the first table are joined to all rows in the second table.
A Cartesian product tends to generate a large number of rows, and the result is rarely useful. You should
always include a valid join condition in a WHERE clause, unless you have a specific need to combine all
rows from all tables.
Cartesian products are useful for some tests when you need to generate a large number of rows to simulate
a reasonable amount of data.

Ex:
Sql>Select Ename,Dname From Emp,Dept;

135 Rows Selected.. (27 x 5 Records)

Note: Cartesian Product occurs


SQL> Set Pause On;
SQL> Set Pause Press any key to Continue..
(Wait for each page)

To Avoid Cartesian Product..

SQL > Select Ename,emp.deptno,Dname from emp,dept where emp.deptno=dept.deptno;

ENAME DEPTNO DNAME


---------- ---------- --------------
SMITH 20 RESEARCH
ALLEN 30 SALES
WARD 30 SALES
JONES 20 RESEARCH
MARTIN 30 SALES
BLAKE 30 SALES

Note: If we use the common named columns then we use the table name also as prefix. (emp.deptno)
Note: Equijoins are also called simple joins or inner joins.
Using AND condition.
SQL>Select Ename,emp.deptno,Dname from emp,dept where emp.deptno=dept.deptno AND
dept.deptno=20;

ENAME DEPTNO DNAME


---------- ---------- --------------
SMITH 20 RESEARCH
JONES 20 RESEARCH
SCOTT 20 RESEARCH
ADAMS 20 RESEARCH

Using Table Alias


Qualifying Ambiguous Column Names
You need to qualify the names of the columns in the WHERE clause with the table name to avoid
ambiguity. Without the table prefixes, the DEPARTMENT_ID column could be from either the
DEPARTMENTS table or the EMPLOYEES table. It is necessary to add the table prefix to execute your
query.

SQL> Select e.ename,e.job,e.sal,e.deptno,d.dname, d.loc from emp e,dept d where e.deptno=d.deptno;


ENAME JOB SAL DEPTNO DNAME LOC
---------- --------- ---------- ---------- -------------- -------------
SMITH CLERK 800 20 RESEARCH DALLAS
ALLEN SALESMAN 1600 30 SALES CHICAGO
WARD SALESMAN 1250 30 SALES CHICAGO
JONES MANAGER 2975 20 RESEARCH DALLAS
MARTIN SALESMAN 1250 30 SALES CHICAGO
SQL > Select e.ename,d.dname,l.name From emp e,dept d,location l where e.deptno=d.deptno and
d.loc_id=l.loc_id

ENAME DNAME NAME


---------- -------------- --------------------
kannan ACCOUNTING EAST
kannan ACCOUNTING EAST
Raman ACCOUNTING EAST
XX ACCOUNTING EAST
SMITH RESEARCH WEST
ADAMS RESEARCH WEST
FORD RESEARCH WEST

SQL >Select Distinct e.ename,d.dname,l.name From emp e,dept d,location l where e.deptno=d.deptno
and d.loc_id=l.loc_id;

ENAME DNAME NAME


---------- -------------- --------------------
ADAMS RESEARCH WEST
ALLEN SALES SOUTH
ASHOK RESEARCH WEST
BLAKE SALES SOUTH
FORD RESEARCH WEST
JAMES SALES SOUTH
JONES RESEARCH WEST

Non-Equijoins
A non-equijoin is a join condition containing something other than an equality operator.
The relationship between the EMPLOYEES table and the JOB_GRADES table has an
example of a non-equijoin. A relationship between the two tables is that the SALARY
column in the EMPLOYEES table must be between the values in the LOWEST_SALARY
and HIGHEST_SALARY columns of the JOB_GRADES table. The relationship is
obtained using an operator other than equals (=).

SQL> SELECT e.last_name, e.salary, j.grade_level


2 FROM employees e, job_grades j
3 WHERE e.salary
4 BETWEEN j.lowest_sal AND j.highest_sal;

LAST_NAME SALARY GRA


-------------------- ---------- ---
Matos 2600 A
Vargas 2500 A
Lorentz 4200 B
Rajs 3500 B
Davies 3100 B
Whalen 4400 B
Hunold 9000 C

The slide example creates a non-equijoin to evaluate an employees salary grade. The salary must be
between any pair of the low and high salary ranges.
It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
None of the rows in the job grade table contain grades that overlap. That is, the salary value for
an employee can lie only between the low salary and high salary values of one of the rows in the
salary grade table.
All of the employees salaries lie within the limits provided by the job grade table. That is, no
employee earns less than the lowest value contained in the LOWEST_SAL column or more than
the highest value contained in the HIGHEST_SAL column.
Note: Other conditions, such as <= and >= can be used, but BETWEEN is the simplest. Remember to
specify the low value first and the high value last when using BETWEEN.
Table aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.
SQL> SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j WHERE e.salary >=
j.lowest_sal AND e.salary <= j.highest_sal

LAST_NAME SALARY GRA


-------------------- ---------- ---
Matos 2600 A
Vargas 2500 A
Lorentz 4200 B
Rajs 3500 B
SQL > select ename,dept.deptno,dept.dname from emp,dept where emp.deptno(+)=dept.deptno

ENAME DEPTNO DNAME


---------- ---------- --------------
kannan 10 ACCOUNTING
kannan 10 ACCOUNTING
BLAKE 30 SALES
MARTIN 30 SALES
JAMES 30 SALES
TURNER 30 SALES
WARD 30 SALES
PRIYA 40 OPERATIONS
65 ADMIN
SQL>select ename,dept.deptno,dept.dname from emp,dept where emp.deptno=dept.deptno(+)

ENAME DEPTNO DNAME


---------- ---------- --------------
SMITH 20 RESEARCH
ADAMS 20 RESEARCH
JAMES 30 SALES
FORD 20 RESEARCH
10 ACCOUNTING
the
kumar
nithya1

Raman 20 RESEARCH
Raman 10 ACCOUNTING
PRIYA 40 OPERATIONS
ENAME DEPTNO DNAME
---------- ---------- --------------
XX 10 ACCOUNTING
the 20 RESEARCH
Saran
ASHOK 20 RESEARCH
Ashok

SQL> ed
Wrote file afiedt.buf

SQL > SELECT worker.last_name || ' works for '


|| manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id
WORKER.LAST_NAME||'WORKSFOR'||MANAGER.LAST_NAME
---------------------------------------------------
Kochhar works for King
De Haan works for King
Haritstein works for King
Zlotkey works for King
Whalen works for Kochhar
Higgins works for Kochhar
Hunold works for De Haan
Lorentz works for Hunold
Abel works for Zlotkey
Grant works for Zlotkey
Fay works for Haritstein
Gietz works for Higgins

12 rows selected.
03-Oct-2008

CROSS JOIN
SQL> Select Empno,Dept.deptno,Dname From Emp CROSS JOIN Dept;

EMPNO DEPTNO DNAME


---------- ---------- --------------
7369 10 ACCOUNTING
7499 10 ACCOUNTING
---- --
100 65 ADMIN
5000 65 ADMIN
145 65 ADMIN

135 rows selected.

OR
SQL> Select Empno,Dept.Deptno,Dname From Emp,Dept;

NATURAL JOIN
SQL>Select Empno,Deptno,Ename,Dname From Emp NATURAL JOIN Dept

EMPNO DEPTNO ENAME DNAME


---------- ---------- ------------------------- --------------
7369 20 SMITH RESEARCH
7499 30 ALLEN SALES
7521 30 WARD SALES
7566 20 JONES RESEARCH
7654 30 MARTIN SALES
7698 30 BLAKE SALES
4567 10 kannan ACCOUNTING
7788 20 SCOTT RESEARCH
4568 10 kannan ACCOUNTING
7844 30 TURNER SALES
7876 20 ADAMS RESEARCH
7900 30 JAMES SALES
7902 20 FORD RESEARCH

Using Where Clause in NATURAL JOIN


SQL>Select Empno,Deptno,Ename,Dname From Emp NATURAL JOIN Dept Where Deptno in (20,40)
EMPNO DEPTNO ENAME DNAME
--------- ---------- ------------------------------ ----------
7512 40 PRIYA OPERATIONS
7369 20 SMITH RESEARCH
7566 20 JONES RESEARCH
7788 20 SCOTT RESEARCH

JOIN & USING (As like EQUI JOIN)


SQL> Select e.ename,d.dname from emp e join dept d using (deptno);

ENAME DNAME
------------------------------ --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
kannan ACCOUNTING
SCOTT RESEARCH
LEFT OUTER JOIN
Instructor Note
It was not possible to complete this in earlier releases using outer joins. However, you could
accomplish the same results using the UNION operator.
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id (+) = d.department_id
UNION
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id (+);

Aggregating Data
Using Group Functions
Group Functions
Unlike single-row functions, group functions operate on sets of rows to give one result per group.
These sets may be the whole table or the table split into groups.
Groups of Data
Until now, all group functions have treated the table as one large group of information. At times, you need
to divide the table of information into smaller groups. This can be done by using the GROUP BY clause.
Standard Deviation

SQL> select stddev(sal) from emp;

STDDEV(SAL)
-----------
14044.1804

1 row selected.

SQL> select variance(sal) from emp;

VARIANCE(SAL)
-------------
197239002

1 row selected.

04-Oct-2008
Subqueries
In this lesson, you learn about more advanced features of the SELECT statement. You can write
subqueries in the WHERE clause of another SQL statement to obtain values based on an unknown
conditional value. This lesson covers single-row subqueries and multiple-row subqueries.
Note: The outer and inner queries can get data from different tables.
Multiple-Row Subqueries (continued)
The ANY operator (and its synonym, the SOME operator) compares a value to each value returned by a
subquery. The slide example displays employees who are not IT programmers and whose salary is less than
that of any IT programmer. The maximum salary that a programmer earns is $9,000.
<ANY means less than the maximum. >ANY means more than the minimum. =ANY is equivalent to
IN.
<ALL means less than the maximum. >ALL means more than the minimum
Multiple-Row Subqueries (continued)
The ALL operator compares a value to every value returned by a subquery. The slide example displays
employees whose salary is less than the salary of all employees with a job ID of IT_PROG and whose job
is not IT_PROG.
>ALL means more than the maximum, and <ALL means less than the minimum.
The NOT operator can be used with IN, ANY, and ALL operators.
Manipulating Data
To create a Table from existing with record
SQL> Create Table Dept_Dupe As Select * from Dept;

Table created.

To create a Table from existing with out record


SQL> Create Table Dept_Dupe1 As Select * from Dept Where 0=1;

To insert Records
SQL> Insert into Dept_Dupe1 Select * From Dept;

To a Particular Column
SQL> Insert into Dept_Dupe1(Dname) Select Loc_Id from Dept;

6-Oct-2008
To change a name in the existing record?
SQL> Update emp SET ENAME = 'ABISHEIK' where ename='kannan';

To Change in 2 columns
SQL> UPDATE EMP SET ENAME='THIRU',JOB='TECH' WHERE EMPNO=4569;

Update for 2 Emp numbers


SQL> UPDATE EMP SET ENAME='PRASANTH',JOB='CONSULT' WHERE EMPNO=1254 OR
EMPNO=1245;

To Change the salary as 1000 those who get Less than 1000
SQL> Update emp set sal=1000 Where SAL < 1000;
Ex:
SQL> Update Emp set Job = (Select Job from emp where ename='PRIYA'),Sal = (Select Sal from Emp
Where Ename='PRIYA') Where Ename='ABISHEIK';
Ex:
SQL> UPDATE EMP2 SET ENAME=(Select Ename From Emp Where Empno=4569) Where
empno=4569;
EX:
SQL> Truncate Table Departments;
Truncate Table Departments
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
Ex:
To delete a particular row
SQL>Delete From Emp2 Where Empno=1000;

To Delete all Rows


SQL>Delete From Emp2;

Note: Rollback the Deleted Rows

Using IN
SQL>Delete From Emp Where Empno IN (145,100,1321,11111)
Ex:
SQL> Delete From Emp Where Deptno = (Select deptno from dept where dname='OPERATIONS');
7-Oct-08

Ex:
SQL> UPDATE CIG_STAFF SET DEPTNO=DEFAULT WHERE ID=3000;

1 row updated.

SQL> SELECT * FROM CIG_STAFF;


ID NAME DEPTNO
---------- ------------------------- ----------
1000 PRASANTH 20
2000 ASHOK 20
3000 20

SQL> UPDATE CIG_STAFF SET NAME=DEFAULT WHERE ID=1000;

1 row updated.

SQL> SELECT * FROM CIG_STAFF;

ID NAME DEPTNO
---------- ------------------------- ----------
1000 20
2000 ASHOK 20
3000 20
Ex:
SQL> Merge into copy_staff cs using cig_staff ot
2 on (cs.id = ot.id)
3 When Matched then
4 Update set cs.name = ot.name
5 , cs.deptno=ot.deptno
6 When Not Matched Then
7 Insert values (ot.id,ot.name,ot.deptno);

5 rows merged.
Ex:
SQL> commit;

Commit complete.

SQL> insert into copy_staff values(8000,'Saro',65);

1 row created.

SQL> SavePoint A;

Savepoint created.

SQL> insert into copy_staff values(9000,'Seenu',75);

1 row created.

SQL> SavePoint B;

Savepoint created.

SQL> insert into copy_staff values(7500,'raja',85);

1 row created.

SQL> rollback to savepoint A;

Rollback complete.

SQL> select * from copy_staff;

ID NAME DEPTNO
---------- ------------------------- ----------
1000 Saran 20
2000 ASHOK 20
3000 Saran 20
5000 Abishiek 60
4000 Thiru 50
8000 Saro 65

6 rows selected.

SQL> rollback;

Rollback complete.

SQL> select * from copy_staff;

ID NAME DEPTNO
---------- ------------------------- ----------
1000 Saran 20
2000 ASHOK 20
3000 Saran 20
5000 Abishiek 60
4000 Thiru 50

SQL> delete from copy_staff;


5 rows deleted.

SQL> rollback;

Rollback complete.

SQL> select * from copy_staff;

ID NAME DEPTNO
---------- ------------------------- ----------
1000 Saran 20
2000 ASHOK 20
3000 Saran 20
5000 Abishiek 60
4000 Thiru 50
11-Oct-08
Creating and Managing Tables
Ex:
SQL>Select * From SCOTT.EMP;
Ex:
SQL>CREATE TABLE STAFF(ENO NUMBER,ENAME VARCHAR2(25),DOJ DATE DEFAULT
SYSDATE);
Ex:
SQL> SELECT * FROM USER_TABLES;
SQL> SELECT * FROM USER_VIEWS;
SQL> SELECT * FROM USER_SYNONYMS;
SQL> SELECT * FROM USER_SEQUENCES;

USE ALL_
SQL> SELECT * FROM ALL_TABLES;
SQL> SELECT * FROM ALL_VIEWS;
Ex:
SQL>Create Table Emp2 As Select * from emp;
Ex:
SQL> SELECT * FROM ALL_TAB_COMMENTS WHERE TABLE_NAME = 'EMPLOYEES';

Including Constraints
Ex:
Sql>CREATE TABLE CIG_CONS1(ID NUMBER,NAME VARCHAR2(15),NICK VARCHAR2(10),
CONSTRAINT CONS_1 UNIQUE(name,nick));
ISQLPLUS
Note:
If we give the value by Define then take that value otherwise it asking for a value.

SQL>DEFINE TN=DEPT;
SQL>SELECT * FROM &TN;
Note: SQL>SET VERIFY OFF;
Now old & new are skipped.
Ex:
SQL>BREAK ON JOB;
SQL> select * from emp order by job;

EMPNO ENAME JOB MGR HIREDATE


---------- ------------------------------ --------- ---------- ---------
7788 SCOTT ANALYST 7566 19-APR-87
7902 FORD 7566 03-DEC-81
7369 SMITH CLERK 7902 17-DEC-80
4567 ABISHEIK 7698 11-JUN-08
7900 JAMES 7698 03-DEC-81
7876 ADAMS 7788 23-MAY-87
7512 PRIYA 7902 17-JAN-08
4568 ABISHEIK 7698 11-JUN-08
1254 PRASANTH CONSULT 7698 11-JUN-08
1245 PRASANTH
7566 JONES MANAGER 7839 02-APR-81

Compute
SQL> COMPUTE SUM LABEL 'TOTAL' OF SAL ON JOB;
SQL> SELECT * FROM EMP ORDER BY JOB;

EMPLOYEE_NUMBER ENAME JOB MGR HIREDATE SAL


--------------- ------------------------------ --------- ---------- --------- ---------- -----
7788 SCOTT ANALYST 7566 19-APR-87 1000
7902 FORD 7566 03-DEC-81 3300
********* ----------
TOTAL 4300
7369 SMITH CLERK 7902 17-DEC-80 1000
4567 ABISHEIK 7698 11-JUN-08 2200
7900 JAMES 7698 03-DEC-81 1045
7876 ADAMS 7788 23-MAY-87 1210
7512 PRIYA 7902 17-JAN-08 2200
4568 ABISHEIK 7698 11-JUN-08 2200
********* ----------
TOTAL 9855
How to remove the Compute?
SQL>Clear Computes;
TTITLE

TTI[TLE] [printspec [text|variable] ...] [ON|OFF]

where printspec represents one or more of the following clauses used to place and format the text:

COL n
S[KIP] [n]
TAB n
LE[FT]
CE[NTER]
R[IGHT]
BOLD
FORMAT text

Places and formats a specified title at the top of each report page or lists the current TTITLE definition. The
old form of TTITLE is used if only a single word or string in quotes follows the TTITLE command.

Examples

To define "Monthly Analysis" as the top title and to left-align it, to center the date, to right-align the page
number with a three-digit format, and to display "Data in Thousands" in the center of the next line, enter

TTITLE LEFT 'Monthly Analysis' CENTER '01 Jan 2001' -


RIGHT 'Page:' FORMAT 999 SQL.PNO SKIP CENTER -
'Data in Thousands'

Monthly Analysis 01 Jan 2001 Page: 1


Data in Thousands
To suppress the top title display without changing its definition, enter

TTITLE OFF

Ex:
SQL>REPHEADER WELCOME
SQL>REPFOOTER GOOD BYE

15-Oct-08

Creating Views

Ex:
SQL>create or replace view emp_view AS Select employee_number,ename,sal from emp;
Ex:
SQL>CREATE OR REPLACE VIEW CVIEW AS SELECT D.DEPTNO,MIN(E.SAL)
MINSAL,MAX(E.SAL) MAXSAL,AVG(E.SAL) AVGSAL FROM EMP E,DEPT D WHERE
E.DEPTNO=D.DEPTNO GROUP BY D.DEPTNO;
SQL> SELECT * FROM CVIEW;

DEPTNO MINSAL MAXSAL AVGSAL


---------- ---------- ---------- ----------
10 1000 3740 2290
20 1000 71500 11315.3125
30 1045 3135 1723.33333
40 2200 2200 2200
Ex:
Sql>select rownum Rank,ename,sal from (select ename,sal from emp where sal is not null order by sal
desc) where rownum < 5;

Other Database Objects


16-Oct-08
Ex:
SQL>ALTER SEQUENCE CIG_SEQ1 INCREMENT BY 5;

Ex:
SQL> ALTER SEQUENCE CIG_SEQ1 MAXVALUE 50;
ALTER SEQUENCE CIG_SEQ1 MAXVALUE 50
*
ERROR at line 1:
ORA-04009: MAXVALUE cannot be made to be less than the current value
Ex:
SQL> DROP SEQUENCE CIG_SEQ1;

Sequence dropped.
Ex:
SQL> CREATE INDEX CIG_INDEX1 ON CIG_TAB1(NAME);

Index created.
Let students know that to create a function-based index in your own schema on your own table, you must
have the CREATE INDEX and QUERY REWRITE system privileges. To create the index in another
schema or on another schemas table, you must have the CREATE ANY INDEX and GLOBAL QUERY
REWRITE privileges. The table owner must also have the EXECUTE object privilege on the functions
used in the function-based index.
Ex:
SQL>CREATE SYNONYM EM FOR EMPLOYEES;
SYNONYM CREATED.

Controlling User Access


Using SET Operators

Ex:
SQL> SELECT ID,NAME FROM CIG_SET1
2 UNION
3 SELECT ID,NAME FROM CIG_SET2;
SQL> SELECT ID,NAME FROM CIG_SET1
2 UNION ALL
3 SELECT ID,NAME FROM CIG_SET2;

SQL> SELECT ID,NAME FROM CIG_SET1


2 INTERSECT
3 SELECT ID,NAME FROM CIG_SET2;

SQL> SELECT ID,NAME FROM CIG_SET1


2 MINUS
3 SELECT ID,NAME FROM CIG_SET2;
Ex:
SQL>select id,name,remarks from cig_set2
2 union
3* select id,name,'BETTER' from cig_set1;

NOPRINT
To hide a column upto the current session
SQL>COLUMN ENAME NOPRINT;

Note: The column Ename is hidden;


17-Oct-08
Oracle9i Datetime Functions

To view all zones


SQL>Select * From V$TIMEZONE_NAMES;
Enhancements to the GROUP BY Clause
SQL> SELECT department_id, job_id, SUM(salary)
2 FROM employees
3 WHERE department_id < 60
4 GROUP BY ROLLUP(department_id, job_id);

DEPARTMENT_ID JOB_ID SUM(SALARY)


------------- ---------- -----------
10 AD_ASST 4400
10 4400
20 MK_MAN 13000
20 MK_REP 6000
20 19000
30 PU_MAN 11000
Note:
If we use as like above , just eliminate the subtotals of jobid wise.
Advanced Subqueries
Ex:
SQL> select deptno from dept d where Not Exists (Select 'X' from Emp where deptno = d.deptno);

DEPTNO
----------
65
Ex:
SQL> Update cor_emp e set dname = (Select dname from dept where e.deptno=deptno);

29 rows updated.
Hierarchical Retrieval
Oracle9i Extensions to
DML and DDL Statements

Das könnte Ihnen auch gefallen