Oracle: PL/SQL Basics: Concept
Module: Database-Specific Features
PL/SQL (Procedural Language/SQL) extends SQL with procedural capabilities. Think of SQL as giving instructions ("get me all orders"), while PL/SQL is writing a program ("if order total > $1000, apply discount, else charge shipping"). SQL is declarative (what you want), PL/SQL is procedural (how to get it). This matters because complex business logic requires variables, loops, and conditional logic that SQL alone cannot provide. PL/SQL is compiled and cached, making it 3-5x faster than sending multiple SQL statements from application.
**1. PL/SQL Block Structure**
Every PL/SQL code follows this structure:
```sql
DECLARE
-- Variable declarations (optional)
v_customer_name VARCHAR2(100);
v_order_total NUMBER;
BEGIN
-- Executable statements (required)
SELECT name INTO v_customer_name
FROM customers
WHERE customer_id = 100;
DBMS_OUTPUT.PUT_LINE('Customer: ' || v_customer_name);
EXCEPTION
-- Exception handlers (optional)
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Customer not found');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/
```
**Why this matters**: The block structure provides clear separation: declarations, logic, error handling. The forward slash (/) executes the block. This structure is used in procedures, functions, triggers, and anonymous blocks.
**2. Variables and Data Types**
Variables store intermediate results. Use %TYPE to anchor to column type, %ROWTYPE for entire row.
```sql
DECLARE
-- Basic types
v_count NUMBER := 0; -- Initialize with value
v_name VARCHAR2(100);
v_price NUMBER(10,2);
v_active BOOLEAN := TRUE;
v_order_date DATE := SYSDATE;
-- Anchored types (recommended)
v_customer_name customers.name%TYPE; -- Same type as customers.name
v_order_amount orders.total_amount%TYPE;
-- Row type
v_customer_rec customers%ROWTYPE; -- Entire row structure
-- Constants