2. PL/SQL Development Environments
• PL/SQL is designed to meet such requirements. It provides a programming
extension to the already-existing SQL.
• Oracle provides several tools that can be used to write PL/SQL code. Some of
the development tools that are available for use in this course:
– Oracle SQL Developer: A graphical tool, is a free graphical tool that
enhances productivity and simplifies database development tasks. connect
to any target Oracle database schema using standard Oracle database
authentication.
– Oracle SQL*Plus: A window or command-line application
– Oracle JDeveloper: A window-based integrated development environment
(IDE), allows developers to create, edit, test, and debug PL/SQL code by
using a sophisticated GUI. Oracle JDeveloper is a part of Oracle Developer
Suite and is also available as a separate product.
3.
4. Overview of SQL
• Structured Query Language (SQL) is the set of statements with which all
programs and users access data in an Oracle database.
• Application programs and Oracle tools often allow users access to the
database without using SQL directly.
• SQL is a language you can use in (at least) two different ways: interactively or
embedded.
– Using SQL interactively means that you enter SQL commands via a
keyboard, and you get the command results displayed on a terminal or
computer screen.
– Using embedded SQL involves incorporating SQL commands within a
program in a different programming language (such as Java or C).
• Although SQL is called a query language, its possibilities go far beyond simply
data retrieval. Normally, the SQL language is divided into the following four
command categories:
1. Data definition (Data Definition Language, or DDL)
2. Data manipulation (Data Manipulation Language, or DML)
3. Retrieval
4. Security and authorization
5. •The Oracle database for executing stored subprograms
• The Oracle Forms client when you run client/server applications, or in the Oracle Application
Server when you use Oracle Forms Services to run Forms on the Web
6. Data Definition
• SQL data definition commands allow you to create, modify, and remove
components of a database structure. Typical database structure components
are tables, views, indexes, constraints, synonyms, sequences, and so on.
• Almost all SQL data definition commands start with one of the following three
keywords:
– CREATE, to create a new database object
– ALTER, to change an aspect of the structure of an existing database object
– DROP, to drop (remove) a database object
• One of the strengths of an RDBMS is the fact that you can change the structure
of a table without needing to change anything in your existing database
application programs.
• For example, you can easily add a column or change its width with the ALTER
TABLE command. In modern DBMSs such as Oracle, you can even do this while
other database users or applications are connected and working on the
database—like changing the wheels of a train at full speed.
7. Data Manipulation and Transactions
• SQL data definition commands allow you to change the structure of a
database, SQL data manipulation commands allow you to change the contents
of your database. For this purpose, SQL offers three basic data manipulation
commands:
– INSERT, to add rows to a table
– UPDATE, to change column values of existing rows
– DELETE, to remove rows from a table
• You can add rows to a table with the INSERT command in two ways. One way is
to add rows one by one by specifying a list of column values in the VALUES
clause of the INSERT statement. The other is to add one or more rows to a
table based on a selection (and manipulation) of existing data in the database
(called a subquery).
8. Retrieval
• The only SQL command used to query database data is SELECT. This command
acts at the set (or table) level, and always produces a set (or table) as its result.
If a certain query returns exactly one row, or no rows at all, the result is still a
set: a table with one row or the empty table, respectively.
• FROM: Which table(s) is (are) needed for retrieval?
• WHERE: What is the condition to filter the rows?
• GROUP BY: How should the rows be grouped/aggregated?
• HAVING: What is the condition to filter the aggregated groups?
• SELECT: Which columns do you want to see in the result?
• ORDER BY: In which order do you want to see the resulting rows?
9. Security
• SQL offers several commands to implement data security and to restrict data
access. First of all, access to the database must be defined. User authorization
is implemented by providing database users a login name and a password,
together with some database-wide privileges.
• These are the most important commands in this area:
– CREATE USER, to define new database users
• ALTER USER, to change properties (privileges and passwords) of existing
database users
– DROP USER, to remove user definitions from the database
10. Security
• Privileges and Roles
• If users are authorized to access the database, you can implement fine-grained
data access by granting specific privileges.
• The Oracle DBMS offers two types of privileges: system privileges and object
privileges.
– System privileges pertain to the right to perform certain (nonobject-related)
actions; for example, you can have the CREATE SESSION privilege (allows
you to log on to the database) and the CREATE TABLE privilege. Oracle
supports approximately 140 different system privileges.
– Object privileges involve the right to access a specific database object in a
specific way; for example, the right to issue SELECT, INSERT, and UPDATE
commands against the EMPLOYEESA table.
11.
12. Security
• The Oracle DBMS allows you to group privileges into roles. Roles make user
management much easier, more flexible, and also more manageable. The
following are the corresponding SQL commands used to administer these
privileges and roles:
– GRANT, to grant certain privileges or roles to users or roles
– REVOKE, to revoke certain privileges or roles from users or roles
– 33
13. Basic SQL Concepts and Terminology
• Constants (Literals)
– A constant (or literal) is something with a fixed value. We distinguish
numbers (numeric constants) and text (alphanumeric constants). In
database jargon, alphanumeric constants are also referred to as strings.
– alphanumeric constants (strings) must be placed between single quotation
marks (quotes).
– Numbers are also relatively straightforward in SQL; however, don’t put
them between quotes or they will be interpreted as strings.
– you can explicitly indicate that you want SQL to interpret numeric values as
floating point numbers by adding the suffixes f or d to indicate single (float)
or double precision, respectively.
– decimal period and group separators ( (commas) in numbers, because the
correct interpretation of these characters depends on the value of a
session parameter (NLS_NUMERIC_CHARACTERS), and there are some
cultural differences in this area.
– dates and time durations (intervals) are special cases. They are typically
specified and represented as alphanumeric constants, but they need
something else to distinguish them from regular strings.
14. Basic SQL Concepts and Terminology
• Options to specify date and time-related constants in SQL:
– Specify them as alphanumeric constants (strings) and rely on implicit
interpretation and conversion by the Oracle DBMS. Dangerous, because
things go wrong if the actual format parameter for that session is different
from the format of the string.
– Specify them as alphanumeric constants (strings) and use a CAST or
TO_DATE conversion function to specify explicitly how the strings must be
interpreted
– Specify them as alphanumeric constants (strings), prefixed with DATE,
TIMESTAMP, or INTERVAL. If you use INTERVAL, you also need a suffix to
indicate a dimension, such as DAY, MONTH, or YEAR.
15. Basic SQL Concepts and Terminology
• Note:
– difference between 132 and '132'.
– the SQL language is case-insensitive, alphanumeric constants (strings) are
case-sensitive. For example, 'JOneS' is not equal to 'Jones'.
16. Operators, Operands, Conditions, and Expressions
• An operator does something. Operands are the “victims” of operations; that is,
operands serve as input for operators.
• Sometimes, operators need only a single operand (in which case, they are also
referred to as monadic operators), but most operators need two or more
operands.
• The SQL operators are divided in four categories, where the differentiating
factor is the operand datatype:
– Arithmetic operators
– Alphanumeric operators
– Comparison operators
– Logical operators
17. Arithmetic Operators
• apply arithmetic operators only on NUMBER values; however, there are some
exceptions:
– If you subtract two DATE values, you get the difference between those two
dates, expressed in days.
– You can add a DATE and an INTERVAL value, which results in another date.
– If you add a DATE and a NUMBER, the number is interpreted as an interval
expressed in days.
18. Scalar Data Type
• Hold a single value
• Have no internal component
– CHAR [(maximum_length)]
– VARCHAR2 (maximum_length)
– NUMBER [(precision, scale)]
– BINARY_INTEGER
– PLS_INTEGER
– BOOLEAN
– BINARY_FLOAT
– BINARY_DOUBLE
• Comment in Oracle SQL
– --My text
– --THis is money calculation for riel
– /*
– kadjhfasdjhfkadjfhkadjfh
– adkfaksdfhkdf
– */
19.
20.
21. Variables
• A variable is something that may have a varying value over time, or even an
unknown value. A variable always has a name, so you can refer to it.
• SQL supports two types of variables:
– Column name variables: The name of a column stays the same, but its
value typically varies from row to row while scanning a table.
– System variables: These have nothing to do with tables; nevertheless,
they can play an important role in SQL. They are commonly referred to as
pseudo columns.
23. Variables
• PL/SQL variable has a data type, which specifies a storage format, constraints,
and a valid range of values.
– Scalar data types: Scalar data types hold a single value.
– Reference data types: Reference data types hold values, called pointers,
which point to a storage location.
– LOB data types: LOB data types hold values, called locators, which specify
the location of large objects (such as graphic images) that are stored
outside the table.
– Composite data types: are available by using PL/SQL collection and record
variables. PL/SQL collections and records contain internal elements that
you can treat as individual variables.
The slide illustrates the following data types:
• TRUE represents a Boolean value.
• 15-JAN-09 represents a DATE.
• The image represents a BLOB.
• The text in the callout can represent a VARCHAR2 data type or a CLOB.
• 256120.08 represents a NUMBER data type with precision and scale.
• The film reel represents a BFILE.
• The city name Atlanta represents a VARCHAR2 data type.
24. Declaring and Initializing PL/SQL Variables
• Initialize variables that are designated as NOT NULL and CONSTANT.
• Initialize variables with the assignment operator (:=) or the DEFAULT keyword:
25. PL/SQL Block Structure
• PL/SQL Block Structure
• DECLARE (optional)
– Variables, cursors, user-defined exceptions
• BEGIN (mandatory)
– SQL statements
– PL/SQL statements
• EXCEPTION (optional)
– Actions to perform when exceptions occur
• END; (mandatory)
• A PL/SQL block consists of four sections:
• Declarative (optional): The declarative section begins with the keyword DECLARE and ends when
the executable section starts.
• Begin (required): The executable section begins with the keyword BEGIN. This section needs to
have at least one statement.
• Exception handling (optional): The exception section is nested within the executable section. This
section begins with the keyword EXCEPTION.
• End (required): All PL/SQL blocks must conclude with an END statement. Observe that
• END is terminated with a semicolon.
26. Variables
+ EX1:
• Initialize variables with the assignment operator (:=) or the
• DEFAULT keyword:
v_myName VARCHAR2(20):='John';
v_myName VARCHAR2(20) DEFAULT 'John';
+ Ex2:
DECLARE
v_myName VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
+ Ex3:
DECLARE
v1 CONSTANT NUMBER(6,2):=10.555667;
BEGIN
v1:=300;
DBMS_OUTPUT.PUT_LINE(v1);
END;
27. Variables
• Use of Variables
• Variables can be used for:Temporary storage of data, Manipulation of stored
values,Reusability.
• Requirements for Variable Names
– Must start with a letter
– Can include letters or numbers
– Can include special characters (such as $, _, and #)
– Must contain no more than 30 characters
– Must not include reserved words
Syntax:
Examples:
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
DECLARE
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := 'Atlanta';
c_comm CONSTANT NUMBER := 1400;
28. Scalar Data Type
• Hold a single value
• Have no internal component
– CHAR [(maximum_length)]
– VARCHAR2 (maximum_length)
– NUMBER [(precision, scale)]
– BINARY_INTEGER
– PLS_INTEGER
– BOOLEAN
– BINARY_FLOAT
– BINARY_DOUBLE
• Comment in Oracle SQL
– --My text
– --THis is money calculation for riel
– /*
kadjhfasdjhfkadjfhkadjfh
adkfaksdfhkdf
*/
29. Create Table
• CREATE Table Statemet
• Syntax:
CREATE TABLE tb_Name(
column1 datatype [Null | NOT NULL],
column2 datatype [Null | NOT NULL],
.........
columnN datatype [Null | NOT NULL]
);
EX1: CREATE TABLE TBPRODUCT
(
PRODUCTID NUMBER NOT NULL
, PRODUCTNAME VARCHAR2(20) NOT NULL
, QTY INT
, UNITPRICE FLOAT
, DATEIN DATE
, CONSTRAINT TBPRODUCT_PK PRIMARY KEY
(
PRODUCTID
)
ENABLE
);
EX2: CREATE TABLE tbEmployee(
EmpID NUMBER(10) NOT NULL,
EmpName VARCHAR2(50) NOT NULL,
Gender VARCHAR(20) NOT NULL,
Address VARCHAR(30) NULL,
DOB DATE NOT NULL,
CONSTRAINT TBEmployee_PK PRIMARY KEY(
EmpID
)
ENABLE
);
Ex3:
CREATE TABLE TBSALEDETAIL
(
INVOICEID NUMBER NOT NULL
, PRODUCTID NUMBER NOT NULL
, UNITPRICE NUMBER NOT NULL
, QUANTITY NUMBER NOT NULL
, DISCOUNT NUMBER
, CONSTRAINT TBSALEDETAIL_PK PRIMARY KEY
(
INVOICEID
, PRODUCTID
)
ENABLE
);
31. Edit=Alter
Ex1: ALTER TABLE TBCUSTOMER
ADD (SSID VARCHAR2(20) );
Ex2: ALTER TABLE TBCUSTOMER
MODIFY (ADDRESS NOT NULL);
ALTER TABLE TBCUSTOMER
MODIFY (DOB NOT NULL);
EX3:ALTER TABLE TBEMPLOYEE
MODIFY (EMPNAME DEFAULT Chan Dara );
EX4:ALTER TABLE tbEmployee
ADD (SSID VARCHAR2(20) NOT NULL);
EX5:ALTER TABLE TBPRODUCT
DROP COLUMN DATEIN;
EX6:ALTER TABLE TBPRODUCT
DROP CONSTRAINT TBPRODUCT_PK;
EX7:ALTER TABLE TBPRODUCT
ADD CONSTRAINT TBPRODUCT_PK PRIMARY KEY
(
PRODUCTID
)
ENABLE;
Ex8:ALTER TABLE TBPRODUCT RENAME
COLUMN QTY TO QUANTITY;
EX9:
ALTER TABLE TBPRODUCT
MODIFY (PRODUCTNAME CHAR(50) );
ALTER TABLE TBPRODUCT
MODIFY (UNITPRICE NUMBER DEFAULT '0' );
32. Drop Table
EX1: drop table "SYSTEM"."TABLE1"
EX2: Rename
alter table "SYSTEM"."TBPRODUCT" rename to tbProducts;
Editor's Notes
PL/SQL statements are processed in the Procedural Statement Executor, and all
SQL statements must be sent to the SQL Statement Executor for processing by the Oracle Server
processes. The SQL environment may also invoke the PL/SQL environment. For example, the
PL/SQL environment is invoked when a PL/SQL function is used in a SELECT statement.
The PL/SQL engine is a virtual machine that resides in memory and processes the PL/SQL
m-code instructions. When the PL/SQL engine encounters a SQL statement, a context switch is
made to pass the SQL statement to the Oracle Server processes. The PL/SQL engine waits for
the SQL statement to complete and for the results to be returned before it continues to process
subsequent statements in the PL/SQL block. The Oracle Forms PL/SQL engine runs in the client
for the client/server implementation, and in the application server for the Forms Services
implementation. In either case, SQL statements are typically sent over a network to an Oracle
Server for processing.
DECLARE
ch CHAR(10);
BEGIN
ch:='HELLO';
DBMS_OUTPUT.PUT_LINE(ch || 'Dara');
END;
DECLARE
v_event VARCHAR2(15);
BEGIN
v_event := q'!Father's day!';
DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is :'|| v_event );
v_event := q'[Mother's day]';
DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is :'|| v_event );
END;