Beruflich Dokumente
Kultur Dokumente
To create a Table
Ex:
Create Table cig_emp(empno number,name varchar2(25),doj date,job varchar2(25),sal number,deptno
number);
Ex:
SQL>Insert into CIG_EMP Values(1000, Raghu, 02-Apr-2008, Tech_Consult, 20000, 40);
5 rows created.
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;
SQL> Select name from trial where name like '%\_%' ESCAPE '\';
NAME
--------------------
st_thomas
sri_ramajayam
lathika_saran
abi_nayaa
a_rvinthan
24.09.2008
To Insert Data in particular fields.
SQL> Insert into cig_emp (Empno,Name) values(2000,'Vignesh');
CONSTRAINTS
1. NOT NULL
2. UNIQUE
3. CHECK
4. PRIMARY KEY (UNIQUE + NOT NULL)
5. FOREIGN KEY
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);
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
Note: If we create as like above then it check for 2 columns not a single column.
ID NAME SAL
---------- -------------------- ----------
1000 Saran 2500
1000 Seenu 2500
2000 Seenu 2500
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
Ex: NVL
SQL> select empno,ename,nvl(comm,100) from emp;
Note: Substitute the value 100 for null value.
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 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", DECODE(Job, 'CLERK', 1.10 * Sal, 'SALESMAN',1.15 *
Sal, 'MANAGER', 1.20 * Sal, sal) "Revised Sal" From Emp;
Try it Yourself
CONCAT('HEL
-----------
Hello World
SUBST
-----
Shidh
SUB
---
ITH
LEN
LENGTH
ENAME Length
---------- ----------
SMITH 5
ALLEN 5
Or
SQL> Select * from emp Where Ename Like '_____';
INSTR('ASHOK','O')
------------------
4
INSTR('AMIRTHA','A')
--------------------
1
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
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$$$$$$$$$$$$$$$
RPAD(SAL,15,'%'
---------------
800%%%%%%%%%%%%
1600%%%%%%%%%%%
1250%%%%%%%%%%%
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
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
LOWER
-----
ashok
SQL> Select Lower(ename),Upper(Ename),Initcap(Ename) From emp;
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(2000.3589,2) TRUNC(2000.3589,2)
------------------ ------------------
2000.36 2000.35
ROUND(3564.25,-2)
-----------------
3600
TRUNC(3554.25,-3)
-----------------
3000
MOD: Returns remainder of division
MOD(1600, 300) 100
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'
/
Date Functions
To view the System Date
SQL> select sysdate from dual;
SYSDATE
---------
29-SEP-08
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.
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
To_Char
SQL> Select sysdate,To_Char(sysdate,'MM/YY') From Dual;
SYSDATE TO_CH
--------- -----
29-SEP-08 09/08
TO_CHAR(TO_DAT
--------------
Fifteenth
TO_CHAR(S
---------
MONDAY
Note: For MON Use DY
TO_CHAR(S
---------
SEPTEMBER
Note: For JAN Use MON
TO_C
----
IX
TO_CHAR(SYSDATE
---------------
29 of September
TO_CHAR(SYSDATE
---------------
29 of September
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
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
TO_CHAR(SAL,'
-------------
$800.00
$1,600.00
$1,250.00
$2,975.00
TO_CHAR
-------
4500-
TO_CHAR(
--------
<4500>
TO_CHAR
-------
5E+09
TO_CHAR
-------
123400
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
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;
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;
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;
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 (=).
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
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
12 rows selected.
03-Oct-2008
CROSS JOIN
SQL> Select Empno,Dept.deptno,Dname From Emp CROSS JOIN Dept;
OR
SQL> Select Empno,Dept.Deptno,Dname From Emp,Dept;
NATURAL JOIN
SQL>Select Empno,Deptno,Ename,Dname From Emp NATURAL JOIN Dept
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
STDDEV(SAL)
-----------
14044.1804
1 row selected.
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 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;
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;
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.
1 row updated.
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.
1 row created.
SQL> SavePoint A;
Savepoint created.
1 row created.
SQL> SavePoint B;
Savepoint created.
1 row created.
Rollback complete.
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.
ID NAME DEPTNO
---------- ------------------------- ----------
1000 Saran 20
2000 ASHOK 20
3000 Saran 20
5000 Abishiek 60
4000 Thiru 50
SQL> rollback;
Rollback complete.
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;
Compute
SQL> COMPUTE SUM LABEL 'TOTAL' OF SAL ON JOB;
SQL> SELECT * FROM EMP ORDER BY JOB;
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 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;
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.
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;
NOPRINT
To hide a column upto the current session
SQL>COLUMN ENAME NOPRINT;
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