Oracle Features Deep Dive: Interview
Module: Database-Specific Features
Explain the difference between packages and standalone procedures in Oracle. What are the benefits of using packages?
**Standalone Procedures**: Individual procedures created separately
- CREATE OR REPLACE PROCEDURE proc_name AS BEGIN ... END;
- Each procedure is independent
- No encapsulation or grouping
**Packages**: Group related procedures, functions, and variables
- Package specification (interface): Public declarations
- Package body (implementation): Private and public code
- Provides encapsulation and namespace management
**Benefits of Packages**:
1. **Encapsulation**: Public vs private members
- Package spec: Public interface
- Package body: Private procedures/variables
- Hide implementation details
2. **Performance**: Entire package loaded into memory
- First call loads entire package
- Subsequent calls use cached package
- Faster than loading individual procedures
3. **Namespace Management**: Avoid naming conflicts
- order_management.create_order
- inventory_management.create_order
- Same procedure name, different packages
4. **Session State**: Package variables persist across calls
- Store session-specific data
- Avoid repeated queries
5. **Easier Maintenance**: Related code grouped together
- All order operations in order_management package
- Easier to find and modify
**Example**:
```sql
-- Package specification
CREATE OR REPLACE PACKAGE order_mgmt AS
PROCEDURE create_order(p_customer_id IN NUMBER);
FUNCTION get_total(p_order_id IN NUMBER) RETURN NUMBER;
END;
-- Package body
CREATE OR REPLACE PACKAGE BODY order_mgmt AS
-- Private variable
v_order_count NUMBER := 0;
-- Private procedure (not in spec)