Vous êtes sur la page 1sur 66

Day 1: SQL/PLSQL Concepts

System Development Life Cycle


A framework that describes the activities performed at
each stage of a software development project.
Benefits of SDLC :-
 High quality system to meet users
expectations,
 Completion of development within time
and cost estimates,
 inexpensive to maintain and cost-effective
to enhance.
Relational Database Management
System (RDBMS)

 Data organised into related tables.


 SQL is used to insert, delete or
manipulate data in the database.
 E.g. Oracle, DB2, MS SQL Server…
Basic SQL Statements
SQL

DDL DML DCL


SELECT - retrieve data
CREATE - to create INSERT - insert data into
•Grant
objects a table •Revoke
ALTER - alters the UPDATE - updates
structure existing data within a
DROP - delete objects table
DELETE - deletes records
from a table
 INSERT INTO <table_name>
(<column_name>) VALUES <value>);

 UPDATE <table_name>
SET <column_name> = <value>
WHERE <column_name> = <value> ;

 DELETE FROM <table_name>


WHERE <condition>;
Restricting and Sorting Data
 Restrict the rows returned by using the
WHERE clause.
SELECT [DISTINCT] {* | column [alias], … }
FROM table
[WHERE condition(s)]

• The WHERE clause follows the FROM


clause.
Using the WHERE Clause

SQL > SELECT ename, job, deptno


FROM emp
WHERE job=‘CLERK’;
ENAME JOB DEPTNO
------------------------------------------------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10
Character Strings and Dates
 Character strings and date values are
enclosed in single quotation marks.
 Character values are case sensitive and
date values are format is DD-MON-YY
SQL> SELECT ename, job, deptno
FROM emp
WHERE ename = ‘JAMES’;
Comparison Operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
Using the Comparison
Operators
SQL > SELECT ename, sal, comm
FROM emp
WHERE sal <= comm;

ENAME SAL COMM


------------------------------------------------
MARTIN 1250 1400
Other comparison Operators
Operator Meaning
BETWEEN
Between two values
…..AND…..
Match any of a list of
IN (list)
values
Match a character
LIKE
pattern
Using the BETWEEN Operator
Use the BETWEEN operator to display
rows based on a range of values.
SQL> SELECT ename, sal
FROM emp
WHERE sal BETWEEN 1000 AND 1500;

ENAME SAL
------------------------------------
MARTIN 1250
TURNER 1500
WARD 1250
Using the IN Operator
Use the IN operator to test for values in
a list
SQL> SELECT empno, ename, sal, mgr
FROM emp
WHERE mgr IN (7902, 7566, 7788);

EMPNO ENAME SAL MGR


--------- ----------------------- ------------ ------------------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788
Using the LIKE Operator
 Use the LIKE operator to perform
wildcard searches of valid search string
values.
 Search conditions can contain either
literal characters or numbers.
 %denote zero or many characters.
 _denote one character

SQL> SELECT ename


FROM emp
WHERE ename LIKE ‘S%’;
Using the LIKE Operator
 You can combine pattern-matching
characters.
SQL> SELECT ename
FROM emp
WHERE ename LIKE ‘_A%’;

ENAME
-------------------------
MARTIN
JAMES
WARD
Using the IS NULL Operator

 Test for null values with the IS


NULL operator.
SQL> SELECT ename, mgr
FROM emp
WHERE mgr IS NULL;

ENAME MGR
---------- ---------
KING
Logical Operators
Operator Meaning
Returns TRUE if both
AND component conditions are
TRUE
Returns TRUE if either
OR component condition is
TRUE
Returns TRUE if the
NOT following condition is
FALSE
Using the AND Operator
AND requires both conditions to be TRUE.

SQL > SELECT empno, ename, job, sal


FROM emp
WHERE sal >= 1100
AND job= ‘CLERK’;

EMPNO ENAME JOB SAL


--------------- ---------------- ----------------- ---------------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300
Using the OR Operator
OR requires either condition to be TRUE

SQL > SELECT empno, ename, job, sal


FROM emp
WHERE sal >= 1100
OR job = ‘CLERK’;

EMPNO ENAME JOB SAL


------- ---------------- ----------------- -------------
7839 KING PRESSIDENT 5000
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
Using the NOT Operator
SQL > SELECT ename, job
FROMemp
WHERE job NOT IN (‘CLERK’, ’MANAGER’, ’ANALYST’);

ENAME JOB
---------------- --------------------------
Ram PRESSIDENT
Shayam SALESMAN
Sohan SALESMAN
Mohan SALESMAN
Rules of Precedence

Order Evaluated Operator

1 All comparison operators

2 NOT

3 AND
4 OR
Rules of Precedence
SQL > SELECT ename, job, sal
FROM emp
WHERE job = ‘SALESMAN’
OR job = ‘PRESSIDENT’
AND SAL > 1500;

ENAME JOB SAL


----------------- ---------------- ------------------
Ram PRESSIDENT 5000
Shayam SALESMAN 1250
Mohan SALESMAN 1600
Sohan SALESMAN 1500
Rohan SALESMAN 1250
Rules of Precedence
SQL > SELECT ename, job, sal
FROM emp
WHERE (job = ‘SALESMAN’
OR job = ‘PRESSIDENT’)
AND sal > 1500;

ENAME JOB SAL


----------------- ----------------- -----------
Ram PRESSIDENT 5000
Shayam SALESMAN 1600
ORDER BY Clause
 Sort rows with the ORDER BY clause
 ASC: ascending order, default
 DESC descending order
 The ORDER BY clause comes last in the SELECT
statement.
SQL > SELECT ename, job, deptno, hiredate
FROM emp
ORDER BY hiredate;

ENAME JOB DEPTNO HIREDATE


-------------- ---------------- ----------------- -----------------
Sohan CLERK 20 17-DEC-80
Seema SALESMAN 30 20-FEB-81
Sorting in Descending Order
SQL > SELECT ename, job, deptno, hiredate
FROM emp
ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIREDATE


----------------- ---------------- ----------------- -----------------
Mohan CLERK 20 12-JAN-83
Sohan ANALYST 20 09-DEC-82
Rahul CLERK 10 23-JAN-82
Rohan CLERK 30 03-DEC-81
Sorting by Column Alias
SQL > SELECT empno, ename, sal*12 annsal
FROM emp
ORDER BY annsal;

EMPNO ENAME ANNSAL


----------------- ------------------ --------------------
7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
Sorting by Multiple Columns
• The order of ORDER BY list is the order of sort.
SQL > SELECT ename, deptno, sal
FROM emp
ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL


---------------- ---------------- ------------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000
Functions (Single and Group
functions)
 Single Row Functions: Single row or Scalar functions
return a value for every row that is processed in a query.

 Group Functions: These functions operate on groups


of rows and return one value for the entire group .
These are used to calculate aggregate values like total or
average.
Single Row Functions
 1) Numeric Functions: These are functions that accept numeric
input and return numeric values. For example,

Function Name Examples Return Value

CEIL (2.83) 3
CEIL (x) CEIL (2.49) 3
CEIL (-1.6) -1
FLOOR (2.83) 2
FLOOR (x) FLOOR (2.49) 2
FLOOR (-1.6) -2
TRUNC (125.456, 1) 125.4
TRUNC (x, y) TRUNC (125.456, 0) 125

ROUND (140.234, 2) 140.23


ROUND (x, y) ROUND (-54, 1) 54
ROUND (5.7) 5
 2) Character or Text Functions: These are functions
that accept character input and can return both
character and number values.

Function Name Examples Return Value

LOWER(string_value) LOWER('Good Morning') good morning

UPPER(string_value) UPPER('Good Morning') GOOD MORNING

INITCAP(string_value) INITCAP('GOOD MORNING') Good Morning

LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good) Morning

TRIM (trim_text FROM


TRIM ('o' FROM 'Good Morning') Gd Mrning
string_value)

SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7) Morning

LENGTH (string_value) LENGTH ('Good Morning') 12


 3) Date Functions: These are functions that take values that are
of datatype DATE as input and return values of datatype DATE,
except for the MONTHS_BETWEEN function, which returns a
number.

Function Name Examples Return Value

ADD_MONTHS ( ) ADD_MONTHS ('16-Sep-10', 3) 16-Dec-10

MONTHS_BETWEEN ('16-Sep-
MONTHS_BETWEEN( ) 3
10', '16-Dec-10')

LAST_DAY( ) LAST_DAY ('01-Jun-10') 30-Jun-10

NEXT_DAY ('06-Jun-10',
NEXT_DAY( ) 09-JUN-10
'Wednesday')
 4) Conversion Functions: These are functions that help us to convert a
value in one form to another form. For Example: a null value into an actual
value, or a value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE etc.

Function Name Examples Return Value

TO_CHAR () TO_CHAR (SYSDATE, Monday, December 2010


'Day, Month YYYY')

TO_DATE () TO_DATE ('01-Jun-10') 01-Jun-10

NVL () NVL (null, 1) 1


Group Functions
 COUNT (): This function returns the number of rows in the table that
satisfies the condition specified in the WHERE condition. If the WHERE
condition is not specified, then the query returns the total number of rows
in the table. E.g.
SELECT COUNT (*) FROM employee
WHERE dept = ‘SAP ABAP’ ;

 DISTINCT(): This function is used to select the distinct rows. E.g.


SELECT DISTINCT dept FROM employee;

 MAX(): This function is used to get the maximum value from a column.
E.g. SELECT MAX (salary) FROM employee;
 MIN(): This function is used to get the
minimum value from a column.
SELECT MIN (salary) FROM employee;

 AVG(): This function is used to get the average value of


a numeric column. E.g.
SELECT AVG (salary) FROM employee;

 SUM(): This function is used to get the sum of a


numeric column. E.g.
SELECT SUM (salary) FROM employee;
Data from multiple tables
 A join is a query that combines rows from
two or more tables and views.

 Equijoins :
SELECT e.last_name, e.job_id, d.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id
ORDER BY last_name, job_id;
 Non-equi Joins :
select e.empno, e.ename, e.sal, s.grade
from emp e, salgrade s
where e.sal between s.lowsal and s.hisal;

 Self Joins :
SELECT e1.last_name||' works for '||e2.last_name "Employees and
Their Managers"
FROM employees e1, employees e2
WHERE e1.manager_id = e2.employee_id
AND e1.last_name LIKE 'R%'
ORDER BY e1.last_name;
 Inner Join :
It is a join of two or more tables that returns
only those rows that satisfy the join condition.

 Outer Joins :
select e.empno, e.ename, e.sal, e.deptno,
d.dname, d.city from emp e, dept d
where e.deptno(+)=d.deptno;
Creating and managing Tables with
constraints
 CREATE TABLE table_name (
column_name datatype [[CONSTRAINT constraint_name]
column_constraint] [default_value],

column_name datatype [[CONSTRAINT constraint_name]


column_constraint] [default_value],
... column_name datatype [[CONSTRAINT constraint_name]
column_constraint] [default_value] [,
list_of_table_constraints] );
Creating and managing Tables with
constraints
 CREATE TABLE hr.admin_emp (
empno NUMBER(5) PRIMARY KEY,
ename VARCHAR2(15) NOT NULL,
job VARCHAR2(10),
mgr NUMBER(5),
hiredate DATE DEFAULT (sysdate),
sal NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(3) NOT NULL
CONSTRAINT admin_dept_fkey REFERENCES
hr.departments (department_id)) ;
Views
 A view is simply a representation of a SQL statement
that is stored in memory so that it can easily be reused.

CREATE VIEW view_emp


AS
SELECT empid FROM emp;
PL/SQL

 PL/SQL stands for Procedural Language


extension of SQL.
 PL/SQL is a combination of SQL along with
the procedural features of programming
languages.
Benefits of subprograms
 Block Structures: PL SQL consists of blocks of code, which can be nested within
each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can
be stored in the database and reused.

 Procedural Language Capability: PL/SQL consists of procedural language


constructs such as conditional statements (if else statements) and loops like (FOR
loops).

 Better Performance: PL/SQL engine processes multiple SQL statements


simultaneously as a single block, thereby reducing network traffic.

 Error Handling: PL/SQL handles errors or exceptions effectively during the


execution of a PL/SQL program. Once an exception is caught, specific actions can be
taken depending upon the type of the exception or it can be displayed to the user
with a message.
Structure of subprograms
[DECLARE
Variable declaration]
BEGIN
Program Execution
[EXCEPTION
Exception handling]
END;
Interactive with Server
Writing Control Structure
 IF THEN ELSE STATEMENT
IF condition 1
THEN statement 1; statement 2;
ELSIF condtion2
THEN statement 3;
ELSE statement 4;
END IF;
 Simple Loop
LOOP
statements;
EXIT; {or EXIT WHEN condition;}
END LOOP;
 While Loop
WHILE <condition>
LOOP
statements;
END LOOP;
 FOR Loop.
FOR counter IN val1..val2
LOOP
statements;
END LOOP;

Please note : val1 - Start integer value.


val2 - End integer value.
Implicit and Explicit Cursor
 Implicit cursors:
 These are created by default when DML statements like,
INSERT, UPDATE, and DELETE statements are executed.
They are also created when a SELECT statement that
returns just one row is executed.
 Oracle provides few attributes called as implicit cursor
attributes to check the status of DML operations. The
cursor attributes available are %FOUND, %NOTFOUND
and %ROWCOUNT.
DECLARE
var_rows number(5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees
are updated');
END IF;
END;
Explicit cursors
They must be created when you are
executing a SELECT statement that
returns more than one row. Even though
the cursor stores multiple records, only
one record can be processed at a time,
which is called as current row.
Steps in using an Explicit Cursor.
 DECLARE the cursor in the declaration
section.
 OPEN the cursor in the Execution Section.
 FETCH the data from cursor into PL/SQL
variables or records in the Execution
Section.
 CLOSE the cursor in the Execution Section
before you end the PL/SQL Block.
DECLARE
variables; records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
DECLARE
emp_rec emp%rowtype;
CURSOR emp_cur IS
SELECT * FROM emp
WHERE salary > 10;
BEGIN
OPEN emp_cur;
LOOP
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.first_name || ' ' ||
emp_rec.last_name);
END LOOP;
CLOSE emp_cur;
END;
Handling Exceptions
DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1
THEN -Error handling statements
WHEN ex_name2
THEN -Error handling statements
WHEN Others
THEN -Error handling statements
END;
For example
BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return
any row.');
END;
Creating Procedure
CREATE [OR REPLACE] PROCEDURE
proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION Exception section
END;
CREATE OR REPLACE PROCEDURE employer_details
IS
CURSOR emp_cur IS SELECT first_name, last_name, salary FROM
emp;
emp_rec emp_cur%rowtype;
BEGIN

OPEN emp_cur;

LOOP
FETCH emp_cur INTO emp_rec;
dbms_output.put_line(emp_rec.first_name || ' ' ||
emp_rec.last_name || ' ' || emp_rec.salary);
END LOOP;
END;
How to execute a Stored Procedure?
1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure –
Creating Functions
CREATE [OR REPLACE] FUNCTION function_name
[parameters] RETURN return_datatype;
IS Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION exception section;
END;
CREATE OR REPLACE FUNCTION
employer_details_func RETURN
VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl
WHERE empID = '100‘;
RETURN emp_name;
END;
How to execute a PL/SQL Function?

 Since a function returns a value we can assign it to a


variable :-
employee_name := employer_details_func;

 As a part of a SELECT statement


SELECT employer_details_func FROM dual;

 In a PL/SQL Statements like,


dbms_output.put_line(employer_details_func);
Creating Packages
 A package is a schema object that groups logically related PL/SQL
types, variables, and subprograms. Packages usually have two
parts, a specification (spec) and a body (which is optional).
Example of creating package
CREATE PACKAGE emp_bonus
AS PROCEDURE calc_bonus (date_hired employees.hire_date%TYPE);
END emp_bonus;
/

CREATE PACKAGE BODY emp_bonus


AS
PROCEDURE calc_bonus (date_hired employees.hire_date%TYPE)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Employees hired on ' || date_hired || ' get bonus.');
END;
END emp_bonus;
/

To execute , use the following statement :-


emp_bonus.calc_bonus(‘01-Dec-10’);
Creating Database Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name]
ON table_name [REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
CREATE or REPLACE TRIGGER
price_history_trigger
BEFORE UPDATE OF unit_price
ON product FOR EACH ROW
BEGIN
INSERT INTO product_price_history VALUES
(:old.product_id, :old.product_name,
:old.supplier_name, :old.unit_price);
END;
/
UPDATE PRODUCT SET
unit_price = 800 WHERE product_id = 100
Thank You

Vous aimerez peut-être aussi