Database AdministrationUnit 713 min read
Database Performance Tuning: SQL, Memory, Storage, and RMAN
Unit 7 of Database Administration covers techniques to optimize Oracle Database performance, including SQL tuning, memory management (SGA/PGA), storage structures, RMAN backup strategies, and real-world recovery scenarios. Learn how to diagnose bottlenecks, configure automatic diagnostics, and apply best practices for
TAKEAWAYS:
- SQL tuning identifies slow queries using the Automatic Workload Repository (AWR) and SQL Tuning Advisor, with hints like
/*+ INDEX */to optimize execution plans. - Memory structures (SGA: shared pool, buffer cache, redo logs; PGA: per-session memory) directly impact performance—misconfiguration causes timeouts or crashes.
- Storage tuning involves segment management (tablespaces, extents, freelists), multiplexing redo logs/control files, and Automatic Storage Management (ASM) for redundancy.
- RMAN automates backups (full, incremental, differential) and recovery (point-in-time, crash, media failure) using channels and retention policies.
- Automatic Diagnostic Repository (ADR) logs errors, traces, and alerts for proactive troubleshooting (e.g., "ORA-00600" deadlocks).
- Real-world example: Nepal Rastra Bank’s core banking system uses RMAN for daily incremental backups and ASM for high availability during peak transaction hours (e.g., salary disbursements).
1. Why Performance Tuning Matters
Databases are the backbone of modern systems. In Nepal, eSewa processes thousands of transactions per second during festival seasons, while Ncell’s billing system must handle 10M+ records without delays. Poor tuning leads to:
- Slow queries (e.g., a Daraz order status check taking 5+ seconds).
- Resource exhaustion (e.g., NTC’s network outages due to overloaded database buffers).
- Data loss (e.g., NEPSE’s stock trading system crashes during volatility).
Key metric: Response time (target: <2s for 95% of queries). Tuning focuses on CPU, memory, I/O, and SQL.
2. SQL Performance Tuning
A. Identifying Slow Queries
Oracle provides tools to analyze query performance:
Automatic Workload Repository (AWR):
- Stores performance statistics (CPU, I/O, waits) every 1 hour.
- Query:
SELECT * FROM DBA_HIST_SQLSTATS WHERE SQL_ID = '...'; - Example: A
SELECT * FROM CUSTOMERSquery runs in 10s due to a full table scan. AWR shows it uses 80% CPU.
SQL Tuning Advisor:
- Automatically suggests optimizations (e.g., "Add index on
customer_id"). - Command:
BEGIN DBMS_SQLTUNE.TUNE_SQL( sql_id => 'g12345678', scope => DBMS_SQLTUNE.SCOPE_ADVISOR, time_limit => 60 ); END;
- Automatically suggests optimizations (e.g., "Add index on
B. Optimization Techniques
| Technique | When to Use | Example |
|---|---|---|
| Indexing | Frequent WHERE, JOIN, ORDER BY |
CREATE INDEX idx_customer_name ON CUSTOMERS(last_name); |
| Query Hints | Override optimizer choices | SELECT /*+ INDEX(cust idx_customer_name) */ * FROM CUSTOMERS; |
| Partitioning | Large tables (e.g., ORDERS by year) |
CREATE TABLE ORDERS (order_id NUMBER) PARTITION BY RANGE (order_date); |
| Materialized Views | Aggregations (e.g., daily sales reports) | CREATE MATERIALIZED VIEW daily_sales AS SELECT date, SUM(amount) FROM ORDERS GROUP BY date; |
Worked Example: Pathao’s Ride Requests
- Problem: A query to fetch nearby drivers takes 3s during peak hours (5–9 PM).
- Solution:
- Add a spatial index on
driver_location(latitude/longitude). - Use a partitioned table for
RIDE_REQUESTSby hour. - Rewrite the query with a hint:
SELECT * FROM RIDE_REQUESTS WHERE driver_location WITHIN_DISTANCE('POINT(27.7172 85.3240)', 500) /*+ INDEX(rq idx_driver_location) */;
- Add a spatial index on
- Result: Response time drops to <500ms.
3. Memory Management: SGA vs. PGA
A. Oracle Memory Structures
graph TD
A["SGA: Shared Global Area"] --> B["Buffer Cache"]
A --> C["Redo Log Buffer"]
A --> D["Shared Pool"]
E["PGA: Program Global Area"] --> F["Sort Area"]
E --> G["Session Memory"]
E --> H["Cursor Cache"]| Component | Purpose | Tuning Parameter | Example |
|---|---|---|---|
| Buffer Cache | Stores data blocks in memory for fast access | DB_BLOCK_BUFFERS |
ALTER SYSTEM SET DB_BLOCK_BUFFERS=1024M; |
| Redo Log Buffer | Records all changes for crash recovery | LOG_BUFFER |
ALTER SYSTEM SET LOG_BUFFER=50M; |
| Shared Pool | Caches SQL, PL/SQL, and execution plans | SHARED_POOL_SIZE |
ALTER SYSTEM SET SHARED_POOL_SIZE=2G; |
| PGA | Per-session memory (sorts, hashes, joins) | PGA_AGGREGATE_TARGET |
ALTER SYSTEM SET PGA_AGGREGATE_TARGET=4G; |
B. Key Differences: SGA vs. PGA
| Feature | SGA | PGA |
|---|---|---|
| Scope | Shared across all sessions | Private to each session |
| Memory Usage | Fixed size (configured) | Dynamic (allocated on demand) |
| Purpose | Caching data, redo logs, SQL plans | Temporary workspace (sorts, joins) |
| Tuning Goal | Avoid "cache misses" (high physical reads) |
Prevent "PGA memory limit exceeded" errors |
Real-World Impact:
- Nepal Investment Bank’s core system crashes during month-end due to PGA exhaustion from complex reports. Solution: Increase
PGA_AGGREGATE_TARGETand use parallel queries for batch jobs.
4. Storage Tuning
A. Tablespace and Segment Management
erDiagram
TABLESPACE ||--o{ DATAFILE : contains
TABLESPACE ||--o{ TABLESPACE_GROUP : part of
TABLESPACE ||--o{ TABLE : stores
TABLE ||--o{ INDEX : uses
TABLE ||--o{ LOB : storesKey Terms:
- Extent: Logical storage unit (1–32 blocks).
- Freelist: Tracks free extents for new rows.
- PCTFREE: % of space left empty to avoid row chaining (default: 10%).
Example: Daraz’s Product Catalog
- Problem:
PRODUCTStable has row chaining (fragments across blocks), slowing queries. - Solution:
ALTER TABLE PRODUCTS MOVE TABLESPACE products_ts STORAGE (INITIAL 100M NEXT 50M PCTINCREASE 0 FREELISTS 3 FREELIST GROUPS 3);PCTFREE=20to reduce chaining.FREELISTS=3for concurrent inserts.
B. Multiplexing for Reliability
Multiplexing duplicates critical files (redo logs, control files) across disks to prevent single-point failures.
| File Type | Multiplexing Benefit | Example Command |
|---|---|---|
| Redo Logs | Survives disk failure | ALTER DATABASE ADD LOGFILE GROUP 2 ('/disk2/redo02.log') SIZE 100M; |
| Control Files | Ensures metadata consistency | ALTER DATABASE CREATE CONTROLFILE REUSE DATABASE; |
| Datafiles | Protects against corruption | ALTER DATABASE DATAFILE '/disk1/datafile.dbf' BACKUP; |
Worked Example: NTC’s Billing System
- Scenario: A power outage corrupts the primary control file.
- Recovery:
- Start in mount mode:
STARTUP MOUNT; - Recreate control file from multiplexed copy:
ALTER DATABASE CREATE CONTROLFILE REUSE DATABASE; - Open database:
ALTER DATABASE OPEN;
- Start in mount mode:
5. Backup and Recovery with RMAN
A. RMAN Backup Types
mindmap
root((RMAN Backup Strategies))
Full Backup
Pros: Complete, fast restore
Cons: Large storage
Command: `BACKUP DATABASE PLUS ARCHIVELOG;`
Incremental Backup
Pros: Saves space
Cons: Slower restore
Command: `BACKUP DATABASE INCREMENTAL LEVEL 1;`
Differential Backup
Pros: Balanced speed/storage
Cons: Complex recovery
Command: `BACKUP DATABASE DIFFERENTIAL;`
Archived Redo Logs
Pros: Point-in-time recovery
Cons: Requires archiving
Command: `BACKUP ARCHIVELOG ALL;`B. Recovery Scenarios
| Failure Type | Recovery Steps | RMAN Command |
|---|---|---|
| Instance Crash | Restore control file, redo logs, and open resetlogs. | RECOVER DATABASE; |
| Media Failure | Restore corrupted datafile from backup. | RESTORE DATAFILE '/datafile.dbf'; |
| User Error (DROP) | Flashback Database or restore from backup. | FLASHBACK DATABASE TO TIMESTAMP TO_TIMESTAMP; |
| Corruption | Rebuild blocks or restore from backup. | RECOVER DATAFILE '/datafile.dbf' UNTIL TIME '...'; |
Worked Example: NEPSE’s Trading System
- Problem: A
TRUNCATE TABLE SHAREScommand accidentally deletes 2023’s data. - Solution:
- Flashback (if enabled):
FLASHBACK TABLE SHARES TO BEFORE DROP; - RMAN restore (if flashback disabled):
RESTORE TABLESPACE shares_ts; RECOVER TABLESPACE shares_ts;
- Flashback (if enabled):
C. RMAN Configuration
- Set Up RMAN:
RMAN> CONFIGURE CHANNEL DEVICE TYPE DISK; RMAN> CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS; - Backup Command:
RMAN> BACKUP DATABASE PLUS ARCHIVELOG; - Verify Backup:
RMAN> LIST BACKUP;
6. Automatic Diagnostic Repository (ADR)
ADR stores:
- Alert logs (critical errors like
ORA-00600). - Trace files (slow SQL, deadlocks).
- Incident dumps (crash diagnostics).
Example: Diagnosing a Deadlock
- Check ADR for trace files:
SELECT name, value FROM v$diag_info; - Analyze deadlock graph:
SELECT * FROM DBA_DEADLOCKS; - Solution: Rewrite the transaction to avoid locks (e.g., use
SKIP LOCKEDinSELECT).
Real-World Use:
- Khalti’s payment system uses ADR to detect and resolve deadlocks during Diwali sales (peak: 50K transactions/minute).
7. Performance Tuning Checklist
| Area | Action Items |
|---|---|
| SQL | - Use AWR/SQL Tuning Advisor. |
- Add indexes for WHERE, JOIN, ORDER BY. |
|
- Avoid SELECT *; use hints like /*+ INDEX */. |
|
| Memory | - Monitor V$SGA, V$PGA. |
- Adjust DB_BLOCK_BUFFERS, SHARED_POOL_SIZE. |
|
| Storage | - Multiplex redo logs/control files. |
| - Use ASM for high availability. | |
| Backup | - Schedule RMAN backups (full + incremental). |
| - Test recovery procedures quarterly. | |
| Monitoring | - Set up alerts for ORA-00600, ORA-01555 (snapshot too old). |
In the Real World
eSewa’s Transaction Processing
- Idea Used: Partitioning + Indexing
- How: The
PAYMENTStable is partitioned bytransaction_date(monthly), with a bitmap index onpayment_status(success/failure). This reduces query time from 5s to <100ms during festival seasons.
Ncell’s Charging System
- Idea Used: PGA Tuning + Parallel Queries
- How: During month-end, the system runs batch jobs to generate bills. To avoid PGA exhaustion:
PGA_AGGREGATE_TARGETis set to 8GB.- Queries use
/*+ PARALLEL(4) */to distribute load across CPU cores.
Nepal Rastra Bank’s Core Banking
- Idea Used: RMAN + ASM for High Availability
- How: The bank uses:
- ASM to stripe data across 6 disks for I/O performance.
- RMAN incremental backups (daily) + archived redo logs for point-in-time recovery.
- Automated failover to a standby database in Chitwan during Kathmandu outages.
Exam Tip
SQL Tuning Questions:
- Always show AWR/SQL Tuning Advisor output in your answer.
- For indexing, explain why a column needs an index (e.g., "frequent
WHEREclause").
Memory Management:
- Compare SGA vs. PGA in a table (as above).
- Mention
V$SGASTATandV$PGASTATfor monitoring.
RMAN Backup/Recovery:
- Describe 3 backup types (full, incremental, differential) and their use cases.
- For recovery, list 4 failure types and the corresponding RMAN command.
ADR:
- Define ADR and its 3 components (alert logs, trace files, incident dumps).
- Relate to deadlocks or ORA-00600 errors.
Worked Examples:
- Always tie your answer to a real-world scenario (e.g., "Like eSewa’s payment system...").
- Use commands (even if not asked) to show practical knowledge.
Based on the TU BCA syllabus for Database Administration (CACS405), unit 7.
Discussion
Loading…