Oracle: Advanced PL/SQL: Interview
Module: Database-Specific Features
Explain the difference between FORALL and cursor FOR loop. When would you use each?
**FORALL** (Bulk DML):
- Executes DML for entire array in single operation
- Minimizes context switches (1 switch for entire array)
- 10-100x faster than cursor
- Syntax: FORALL i IN 1..array.COUNT UPDATE/INSERT/DELETE ...
- Use for: Array processing, batch updates
**Cursor FOR Loop** (Row-by-row):
- Processes rows one-by-one
- Context switch for each row
- 10-100x slower than FORALL
- Syntax: FOR r IN cursor LOOP ... END LOOP;
- Use for: Complex per-row logic, external API calls
**Performance Comparison** (10,000 rows):
- FORALL: 0.3 seconds (1 context switch)
- Cursor: 30 seconds (10,000 context switches)
- 100x faster with FORALL
**When to use FORALL**:
- Batch updates/inserts/deletes
- Array processing
- Performance critical operations
- Example: Update 1M orders in batch job
**When to use Cursor**:
- Complex per-row logic that varies
- Calling external API per row
- Need to stop on first error
- Example: Process orders, call shipping API per order
**Real-world**: Oracle ERP uses FORALL for batch processing 1M+ records (5 minutes vs 8 hours with cursor).
What is SQL injection and how do you prevent it in dynamic SQL?
**SQL Injection**: Security vulnerability where attacker injects malicious SQL through user input.
**Example Attack**:
```sql
-- Vulnerable code
v_user_input := "100 OR 1=1";
v_sql := 'SELECT * FROM orders WHERE customer_id = ' || v_user_input;
EXECUTE IMMEDIATE v_sql;
-- Executes: SELECT * FROM orders WHERE customer_id = 100 OR 1=1
-- Returns ALL orders (security breach)
```
**Prevention Methods**: