Beruflich Dokumente
Kultur Dokumente
TABLE OF CONTENTS
2) ALTER statement for changing the structure of the database tables, views, indexes, etc...........4
b) UNIQUE CONSTRAINT....................................................................................................................................... 6
e) CHECK CONSTRAINT.......................................................................................................................................... 9
f) DEFAULT................................................................................................................................................................. 9
g) INDEX........................................................................................................................................................................ 9
i) WHERE [condition]...................................................................................................................................... 10
v) SQL FUNCTIONS............................................................................................................................................ 14
2) NVL FUNCTION............................................................................................................................................. 19
vi) DISTINCT..................................................................................................................................................... 19
(2) SELF-JOIN............................................................................................................................................... 20
1) VIEW............................................................................................................................................................................ 26
2) SEQUENCE................................................................................................................................................................ 27
1) GRANT statement................................................................................................................................................... 27
2) REVOKE statement................................................................................................................................................ 28
PL/SQL...................................................................................................................................................................................... 28
1) PL/SQL block........................................................................................................................................................... 28
2) CURSOR...................................................................................................................................................................... 31
4
3) STORED PROCEDURE........................................................................................................................................... 33
4) TRIGGER.................................................................................................................................................................... 37
Syntax-
);
Data types –
NUMBER
CHAR
VARCHAR
DATE
BLOB
CLOB
INTEGER
E.g. –
Syntax-
DROP (<column-name>);
Examples –
Syntax-
The NOT NULL modifier prevents NULL (a token (non-zero) that designates a column as being
empty) values from appearing in the column.
Syntax-
B) UNIQUE CONSTRAINT
To avoid duplicate values to be added to a table, UNIQUE constraint is used on the column.
According to the ANSI standards SQL:92, SQL:1999, and SQL:2003, a UNIQUE constraint should
disallow duplicate non-NULL values, but allow multiple NULL values.
OR
PRIMARY KEY enforces both NOT NULL & UNIQUE constraints. On top of that, it helps to relate with
other tables.
Syntax-
Usually it is a convention to add constraints after creating the table by using ALTER
statement.
This helps to give a custom name to the PRIMARY KEY; through this name the KEY can be
modified/deleted. Otherwise the SQL engine gives an internal name like – “SYS_C000308”.
OR
When there are multiple tables in a database the tables must be related to each other. For a table,
where a PRIMARY KEY of another table is used to relate data it is referred as FOREIGN KEY.
Syntax-
E.g.-
E) CHECK CONSTRAINT
OR
F) DEFAULT
The ANSI/ISO standard allows defining default values that columns should have. Usually, if no value
is supplied for a column, then it is assigned a NULL value. The DEFAULT modifier overrides this.
G) INDEX
Index is an object which contains ordered list of elements from one or multiple columns. Index can
be created on single or multiple columns. An index is a performance-tuning method of allowing
faster retrieval of records
Syntax –
E.g.,
10
Whenever index is created on the table then all the values of the specified column will be sorted and
the sorted values will be placed under specified index name.
Syntax-
I) WHERE [CONDITION]
ENAME SAL
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
FORD 3000
ENAME SAL
SMITH 800
ALLEN 1600
WARD 1250
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000
MILLER 1300
ENAME
SMITH
12
JAMES
SELECT EMPNO, ENAME, JOB, MGR FROM EMP WHERE JOB='SALESMAN' AND MGR = 7698
OR
SELECT EMPNO, ENAME, JOB, MGR FROM EMP WHERE JOB='SALESMAN' OR MGR = 7698
NOT
JOB AVG(SAL)
ANALYST 3000
CLERK 1037.5
MANAGER 2758.333333
PRESIDENT 5000
SALESMAN 1400
JOB AVG(SAL)
ANALYST 3000
MANAGER 2758.333333
PRESIDENT 5000
V) SQL FUNCTIONS
SELECT ENAME, SAL FROM SCOTT.EMP WHERE SAL = (SELECT MAX (SAL) FROM SCOTT.EMP
WHERE JOB='CLERK')
ENAME SAL
MILLER 1300
(B) MIN ()
SELECT ENAME, SAL FROM SCOTT.EMP WHERE SAL = (SELECT MIN(SAL) FROM SCOTT.EMP
WHERE JOB='CLERK')
ENAME SAL
SMITH 800
(C) SUM ()
SELECT SUM (SAL) AS CLERKS_SALARY FROM SCOTT.EMP WHERE JOB='CLERK'
CLERKS_SALARY
4150
(D) COUNT ()
SELECT COUNT (JOB) AS NO_OF_MANAGERS FROM SCOTT.EMP WHERE JOB='MANAGER'
NO_OF_MANAGERS
3
(E) AVG ()
SELECT AVG (SAL) AS AVERAGE_SALARY_FOR_CLERK FROM SCOTT.EMP WHERE JOB='CLERK'
AVERAGE_SALARY_FOR_CLERK
1037.5
LENGTH('CLUSTER')
7
(B) SUBSTR ()
SELECT SUBSTR ('CLUSTER', 2, 5) FROM DUAL
16
SUBSTR('CLUSTER',2,5)
LUSTE
(C) UPPER ()
SELECT UPPER ('cluster') FROM DUAL
UPPER('CLUSTER')
CLUSTER
(D) LOWER ()
SELECT LOWER ('CLUSTER') FROM DUAL
LOWER('CLUSTER')
Cluster
(E) INITCAP ()
SELECT INITCAP ('hello world') FROM DUAL
INITCAP('HELLOWORLD')
Hello World
(F) LTRIM ()
SELECT LENGTH (' cluster') FROM DUAL
LENGTH('CLUSTER')
9
LENGTH(LTRIM('CLUSTER'))
7
(G) RTRIM ()
SELECT LENGTH(RTRIM('cluster ')) FROM DUAL
LENGTH(RTRIM('CLUSTER'))
7
(H)LPAD ()
17
LPAD('CLUSTER',10,'*')
***CLUSTER
(I) RPAD ()
SELECT RPAD ('CLUSTER', 10,'*') FROM DUAL
RPAD('CLUSTER',10,'*')
CLUSTER***
ABS(-23.65)
23.65
(B) SIN ()
SELECT SIN (3) FROM DUAL
SIN(3)
0.141120008
(C) COS ()
COS(30)
-0.989992497
(D) TAN ()
(E) SQRT ()
SELECT SQRT (9) FROM DUAL
SQRT(9)
3
18
(F) CEIL ()
SELECT CEIL (32.35) FROM DUAL
CEIL(32.35)
33
CEIL(32.35)
32
(G) FLOOR ()
SELECT FLOOR (5.9) FROM DUAL
FLOOR(5.9)
5
FLOOR(-5.9)
-6
(H)ROUND ()
SELECT ROUND (5.5) FROM DUAL
ROUND(5.5)
6
ROUND(5.5555,2)
5.56
Would always store the value of date in MM/DD/YYYY format in the database
(B) TO_CHAR ()
The to_char function converts a NUMBER or DATE to STRING
NUMBER to STRING
DATE to STRING
(C) TO_NUMBER ()
The to_number function converts a STRING to NUMBER
2) NVL FUNCTION
In Oracle/PLSQL, the NVL function lets you substitute a value when a null value is encountered.
VI) DISTINCT
The DISTINCT clause allows you to remove duplicates from the result set. The DISTINCT clause can
only be used with select statements.
(2) SELF-JOIN
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 11/12/2008 800 NULL 20
7499 ALLEN SALESMAN 7698 2/20/1981 1600 300 30
7521 WARD SALESMAN 7698 2/22/1981 1250 500 30
7566 JONES MANAGER 7839 4/2/1981 2975 NULL 20
7654 MARTIN SALESMAN 7698 9/28/1981 1250 1400 30
7698 BLAKE MANAGER 7839 5/1/1981 2850 NULL 30
7782 CLARK MANAGER 7839 6/9/1981 2450 NULL 10
7788 SCOTT ANALYST 7566 4/19/1987 3000 NULL 20
7839 KING PRESIDENT NULL 11/17/1981 5000 NULL 10
7844 TURNER SALESMAN 7698 9/8/1981 1500 0 30
7876 ADAMS CLERK 7788 5/23/1987 1100 NULL 20
7900 JAMES CLERK 7698 12/3/1981 950 NULL 30
7902 FORD ANALYST 7566 12/3/1981 3000 NULL 20
7934 MILLER CLERK 7782 1/23/1982 1300 NULL 10
EMP TABLE
SYNTAX -
ON EMP.DEPTNO = DEPT.DEPTNO
OR
ON EMP.DEPTNO = DEPT.DEPTNO
OR
CARTESIAN PRODUCT - If two tables in a join query have no join condition, Oracle returns their
Cartesian product. Oracle combines each row of one table with each row of the other. A Cartesian
product always generates many rows and is rarely useful. For example, the Cartesian product of
two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you
specifically need a Cartesian product.
Example 2 – IN OPERATOR
SELECT ENAME, JOB, SAL FROM EMP WHERE SAL > ALL (SELECT SAL FROM EMP WHERE DEPTNO
= 20)
SELECT ENAME, JOB, SAL FROM EMP WHERE SAL > ANY (SELECT SAL FROM EMP WHERE
DEPTNO = 20) AND DEPTNO <> 20
25
Example 5 –
Syntax-
Syntax-
Anything specified in [ ] is optional. If WHERE condition is not specified then all the records will be
updated.
If WHERE condition is not specified then all the records of the table will be deleted.
1) VIEW
A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query
joining one or more tables. Advantages - Restrict access, Eases the "complicated" joins, present
different views of the same data according to their particular criteria. You can use views instead of
creating temporary tables and dropping them daily.
SELECT <columns>
FROM table
WHERE predicates;
DROPPING A VIEW
i) Simple view
A Simple view selects from one table. A Complex view selects from one or more tables.
You can perform DML through Simple views but you cannot always perform DML through
Complex views.
Example –
2) SEQUENCE
In Oracle, you can create an auto number field by using sequences. A sequence is an object in Oracle
that is used to generate a number sequence. This can be useful when you need to create a unique
number to act as a primary key.
MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
NOCACHE
CYCLE;
Eg-
1) GRANT STATEMENT
GRANT statement is used to give various permissions to the user on various database objects.
Syntax
ON <object-name>
TO <user-name>
28
Example -
2) REVOKE STATEMENT
REVOKE statement is used to withdraw permissions to the user on the database objects.
Syntax-
ON<object-name>
FROM<user-name>
Example-
PL/SQL
1) PL/SQL BLOCK
A PL/SQL block contains 1 or more PL/SQL statements. Such a block must at least have the two
keywords BEGIN and END. However, such a block cannot declare any (local) variables. In order to
have local variables, the BEGIND...END block must be preceded with a DECLARE followed by the
variable declarations.
DECLARE
A INTEGER;
B INTEGER;
S INTEGER;
BEGIN
A:= 10;
B:= 20;
S:=A+B;
DBMS_OUTPUT.PUT_LINE (S);
END;
DECLARE
ENAM SCOTT.EMP.ENAME%TYPE;
ESAL SCOTT.EMP.SAL%TYPE;
BEGIN
SELECT ENAME, SAL INTO ENAM, ESAL FROM SCOTT.EMP WHERE EMPNO = &EMPNO;
DBMS_OUTPUT.PUT_LINE ('NAME : ' || ENAM);
DBMS_OUTPUT.PUT_LINE ('SAL : ' || ESAL);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('EMPLOYEE DOES NOT EXIST');
END;
DECLARE
A1 NUMBER;
B1 NUMBER;
S INTEGER;
N NUMBER;
I NUMBER;
BEGIN
SELECT COUNT (*) INTO N FROM SCOTT.T_SUM;
DBMS_OUTPUT.PUT_LINE (N);
I:= 1;
WHILE (I<=N)
LOOP
SELECT A, B INTO A1, B1 FROM SCOTT.T_SUM WHERE CID = I;
S:= A1 + B1;
UPDATE SCOTT.T_SUM SET C = S WHERE CID = I;
DBMS_OUTPUT.PUT_LINE (S);
I:= I+1;
END LOOP;
END;
DECLARE
M NUMBER;
N NUMBER;
I NUMBER;
BEGIN
SELECT COUNT (*) INTO N FROM SCOTT.T_MARKS;
DBMS_OUTPUT.PUT_LINE (N);
I:= 1;
WHILE (I<=N)
LOOP
SELECT MARKS INTO M FROM SCOTT.T_MARKS WHERE SID = I;
30
IF (M>=90) THEN
DBMS_OUTPUT.PUT_LINE ('EXCELLENT');
UPDATE SCOTT.T_MARKS SET REMARKS = 'EXCELLENT' WHERE SID=I;
ELSIF (M>=60 AND M <90) THEN
DBMS_OUTPUT.PUT_LINE ('GOOD');
UPDATE SCOTT.T_MARKS SET REMARKS = 'GOOD' WHERE SID = I;
ELSIF (M>=35 AND M <60) THEN
DBMS_OUTPUT.PUT_LINE ('AVERAGE');
UPDATE SCOTT.T_MARKS SET REMARKS = 'AVERAGE' WHERE SID = I;
ELSIF (M <35) THEN
DBMS_OUTPUT.PUT_LINE ('FAIL');
UPDATE SCOTT.T_MARKS SET REMARKS = 'FAIL' WHERE SID = I;
END IF;
I:= I+1;
END LOOP;
END;
DECLARE
N NUMBER;
I NUMBER;
BEGIN
N:=10;
FOR I IN 1..N
LOOP
DBMS_OUTPUT.PUT_LINE (I);
END LOOP;
END;
DECLARE
N NUMBER;
I NUMBER;
BEGIN
N:=10;
FOR I IN REVERSE 1..N
LOOP
DBMS_OUTPUT.PUT_LINE (I);
END LOOP;
END;
2) CURSOR
A cursor is a mechanism by which you can assign a name to a "SELECT STATEMENT" and
manipulate the information within that SQL statement.
31
For every SQL statement execution, certain area in memory is allocated. PL/SQL allows you to name
this area. This private SQL area is called context area or cursor. A cursor acts as a handle or pointer
into the context area. A PL/SQL program controls the context area using the cursor. Cursor
represents a structure in memory and is different from cursor variable.
Cursors allow the programmer to retrieve data from a table and perform actions on that data one
row at a time. There are two types of cursors implicit cursors and explicit cursors.
IMPLICIT CURSOR
For SQL queries returning single row PL/SQL declares implicit cursors. Implicit cursors are simple
SELECT statements and are written in the BEGIN block (executable section) of the PL/SQL. Implicit
cursors are easy to code, and they retrieve exactly one row. PL/SQL implicitly declares cursors for
all DML statements. The most commonly raised exceptions here are NO_DATA_FOUND or
TOO_MANY_ROWS.
Syntax:
SELECT ename, sal INTO enam, esal FROM EMP WHERE EMPNO = 7844;
DECLARE
ENAM SCOTT.EMP.ENAME%TYPE;
ESAL SCOTT.EMP.SAL%TYPE;
BEGIN
SELECT ENAME, SAL INTO ENAM, ESAL FROM SCOTT.EMP WHERE EMPNO = &EMPNO;
DBMS_OUTPUT.PUT_LINE ('NAME : ' || ENAM);
DBMS_OUTPUT.PUT_LINE ('SAL : ' || ESAL);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('EMPLOYEE DOES NOT EXIST');
END;
EXPLICIT CURSOR
Explicit cursors are used in queries that return multiple rows. The set of rows fetched by a query is
called active set. The size of the active set meets the search criteria in the select statement. Explicit
cursor is declared in the DECLARE section of PL/SQL program.
Syntax:
Sample Code:
DECLARE
CURSOR emp_cur IS SELECT ename FROM EMP;
BEGIN
----
32
---
END;
Opening Cursor:
When a cursor is opened the active set is determined, the rows satisfying the where clause in the
select statement are added to the active set. A pointer is established and points to the first row in
the active set.
To get the next row from the cursor we need to use fetch statement.
FETCH statement retrieves one row at a time. Bulk collect clause need to be used to fetch more than
one row at a time.
After retrieving all the rows from active set the cursor should be closed. Resources allocated for the
cursor are now freed. Once the cursor is closed the execution of fetch statement will lead to errors.
CLOSE <cursor-name>;
Example 1
DECLARE
ENAM SCOTT.EMP.ENAME%TYPE;
ESAL SCOTT.EMP.SAL%TYPE;
CURSOR C1 IS
SELECT ENAME, SAL INTO ENAM, ESAL FROM SCOTT.EMP;
BEGIN
OPEN C1;
FETCH C1 INTO ENAM, ESAL;
DBMS_OUTPUT.PUT_LINE (ENAM || ' SALARY IS $ ' || ESAL);
FETCH C1 INTO ENAM, ESAL;
DBMS_OUTPUT.PUT_LINE (ENAM || ' SALARY IS $ ' || ESAL);
FETCH C1 INTO ENAM, ESAL;
DBMS_OUTPUT.PUT_LINE (ENAM || ' SALARY IS $ ' || ESAL);
FETCH C1 INTO ENAM, ESAL;
DBMS_OUTPUT.PUT_LINE (ENAM || ' SALARY IS $ ' || ESAL);
CLOSE C1;
END;
33
Every cursor defined by the user has 4 attributes. When appended to the cursor name these
attributes let the user access useful information about the execution of a multirow query.
%NOTFOUND: It is a Boolean attribute, which evaluates to true, if the last fetch failed. i.e. when
there are no rows left in the cursor to fetch.
%FOUND: Boolean variable, which evaluates to true if the last fetch, succeeded.
%ROWCOUNT: It’s a numeric attribute, which returns number of rows fetched by the cursor so far.
%ISOPEN: A Boolean variable, which evaluates to true if the cursor is opened otherwise to false.
DECLARE
ENAM SCOTT.EMP.ENAME%TYPE;
ESAL SCOTT.EMP.SAL%TYPE;
CURSOR C1 IS
SELECT ENAME, SAL INTO ENAM, ESAL FROM SCOTT.EMP ORDER BY SAL DESC;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
LOOP
FETCH C1 INTO ENAM, ESAL;
DBMS_OUTPUT.PUT_LINE (ENAM || ' SALARY IS $ ' || ESAL);
EXIT WHEN C1%NOTFOUND;
END LOOP;
END IF;
CLOSE C1;
END;
3) STORED PROCEDURE
Syntax –
CREATING A PROCEDURE
EXECUTING A PROCEDURE
1) IN type parameter: These types of parameters are used to send values to stored
procedures.
2) OUT type parameter: These types of parameters are used to get values from stored
procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values from
stored procedures.
NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN type
parameter.
IN PARAMETER
This is similar to passing parameters in programming languages. We can pass values to the stored
procedure through these parameters or variables. This type of parameter is a read only parameter.
We can assign the value of IN type parameter to a variable or use it in a query, but we cannot
change its value inside the procedure.
Example -
CREATE OR REPLACE PROCEDURE SCOTT.IN_PARAM (MESG VARCHAR2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE (MESG);
END IN_PARAM;
/
OUT PARAMETER
The OUT parameters are used to send the OUTPUT from a procedure or a function. This is a write-
only parameter i.e, we cannot pass values to OUT parameters while executing the stored procedure,
but we can assign values to OUT parameter inside the stored procedure and the calling program
can receive this output value.
Example -
CREATE OR REPLACE PROCEDURE SCOTT.OUT_PARAM (MESG OUT VARCHAR2) IS
BEGIN
MESG := 'SINGLE OUT PARAMETER';
END OUT_PARAM;
/
DECLARE
S VARCHAR2 (50);
BEGIN
OUT_PARAM (S);
DBMS_OUTPUT.PUT_LINE (S);
END;
IN OUT PARAMETER
The IN OUT parameter allows us to pass values into a procedure and get output values from the
procedure. This parameter is used if the value of the IN parameter can be changed in the calling
program.
By using IN OUT parameter we can pass values into a parameter and return a value to the calling
program using the same parameter. But this is possible only if the value passed to the procedure
and output value have a same datatype. This parameter is used if the value of the parameter will be
changed in the procedure.
Example -
CREATE OR REPLACE PROCEDURE SCOTT.INOUT_PARAM (MESG IN OUT VARCHAR2) IS
36
BEGIN
MESG := MESG || ' AN IN OUT PARAMETER';
END INOUT_PARAM;
/
DECLARE
S VARCHAR2 (50) := 'THIS PROCEDURE USES';
BEGIN
SCOTT.INOUT_PARAM(S);
DBMS_OUTPUT.PUT_LINE(S);
END;
EXECUTION
DECLARE
S VARCHAR2 (50);
BEGIN
PKG_OUT_PARAM.PROC_OUT_PARAM (S);
DBMS_OUTPUT.PUT_LINE (S);
END;
/* First create a package and specify the content of the package. Here we are declaring 2
procedures*/
CREATE OR REPLACE PACKAGE SCOTT.PKG_WITH_MULTIPLE_PROCS AS
PROCEDURE PROC_OUT_PARAM (MESG OUT VARCHAR2);
PROCEDURE MARKS_PROCEDURE (ID NUMBER);
END PKG_WITH_MULTIPLE_PROCS;
37
4) TRIGGER
DBMS_OUTPUT.PUT_LINE (OPERATION);
DBMS_OUTPUT.PUT_LINE (CD);
END;
DROPPING A TRIGGER
OTHER INFORMATION
Logging in as a DBA
SYS/AS SYSDBDA