A comprehensive collection of DB2 SQL examples demonstrating advanced SQL features, best practices, and common use cases.
- Recursive SQL - Hierarchical queries, graph traversal, and recursive CTEs
- OLAP Functions - Window functions, ranking, and analytical queries
- Temporal Tables - System-versioned tables and time-travel queries
- Advanced Joins - Complex join patterns and optimization techniques
- Data Generation - Sample data creation and test data utilities
- Performance Tuning - Query optimization examples and explain plans
- XML/JSON - Working with semi-structured data in DB2
- DB2 11.1 or higher (some features require 11.5+)
- Database with appropriate privileges (CREATE TABLE, SELECT, INSERT, etc.)
- Optional: DB2 Command Line Processor (CLP) or any SQL client
- Clone this repository:
git clone https://github.com/yourusername/db2-sql-examples.git
cd db2-sql-examples- Connect to your DB2 database:
db2 connect to user - Run the setup script to create sample tables:
db2 -tvf setup/01_create_sample_tables.sql
db2 -tvf setup/02_load_sample_data.sql-- Find all employees in a manager's hierarchy
db2 -tvf examples/01_recursive_sql.sql-- Calculate running totals and rankings
db2 -tvf examples/02_olap_functions.sql-- Query historical data
db2 -tvf examples/03_temporal_tables.sqldb2-sql-examples/
├── README.md
├── setup/
│ ├── 01_create_sample_tables.sql
│ └── 02_load_sample_data.sql
├── examples/
│ ├── 01_recursive_sql.sql
│ ├── 02_olap_functions.sql
│ ├── 03_temporal_tables.sql
│ ├── 04_advanced_joins.sql
│ ├── 05_data_generation.sql
│ ├── 06_xml_json.sql
│ └── 07_performance_tuning.sql
└── cleanup/
└── cleanup_all.sql
- Hierarchical data traversal
- Bill of materials (BOM) explosion
- Graph path finding
- Cycle detection
- Depth and breadth-first search
- ROW_NUMBER, RANK, DENSE_RANK
- Window frames (ROWS, RANGE)
- Moving averages and cumulative sums
- LEAD/LAG for time series analysis
- NTILE for bucketing
- FIRST_VALUE/LAST_VALUE
- System-versioned tables
- Point-in-time queries
- Historical data analysis
- Audit trail queries
- Common Table Expressions (CTEs)
- MERGE statements
- Table functions
- ARRAY and MULTISET operations
- Regular expressions
- Full-text search
- Use EXPLAIN - Always check execution plans for complex queries
- Index Strategy - Create appropriate indexes for recursive and window queries
- Statistics - Keep RUNSTATS up to date for optimal performance
- Memory Configuration - Adjust SHEAPTHRES_SHR for complex sorts
- Commit Points - Use appropriate commit frequency for large operations
-- Enable query optimization
SET CURRENT QUERY OPTIMIZATION = 9;
-- Check execution plan
db2exfmt -d -g TIC -w -1 -n % -s % -# 0 -o explain.out
-- Monitor statement execution
db2 get snapshot for dynamic sql on The repository includes scripts to generate realistic sample data:
- Employee hierarchy (1000+ employees)
- Sales transactions (10000+ records)
- Product catalog with categories
- Customer orders with line items
- Time dimension table
SQL0440N - No authorized routine found
-- Grant execute on functions
GRANT EXECUTE ON FUNCTION SYSFUN.GENERATE_UNIQUE TO PUBLIC;SQL0952N - Processing was cancelled
-- Increase agent stack size
db2set DB2_HASH_JOIN=YSQL1585W - Recursive SQL with no termination condition
-- Always include proper WHERE clause in recursive anchorContributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Florian
Project Link: https://github.com/mockchainblaster/db2sql
- IBM DB2 Documentation Team
- DB2 Community Contributors
- Stack Overflow DB2 Community