Complex Query Examples
Real-World Scenarios for Advanced Counting
1. Multi-Table Conditional Counting
SELECT
d.department_name,
COUNT(CASE WHEN e.performance_rating > 4 THEN 1 END) AS high_performers,
COUNT(CASE WHEN e.salary > (SELECT AVG(salary) FROM employees) THEN 1 END) AS above_avg_salary
FROM
departments d
LEFT JOIN
employees e ON d.department_id = e.department_id
GROUP BY
d.department_name;
Nested Conditional Counting
2. Hierarchical Counting with Subqueries
SELECT
project_id,
project_name,
(SELECT COUNT(*)
FROM tasks
WHERE tasks.project_id = projects.id AND status = 'Completed') AS completed_tasks,
(SELECT COUNT(*)
FROM tasks
WHERE tasks.project_id = projects.id AND status = 'In Progress') AS ongoing_tasks
FROM
projects;
Complex Aggregation Techniques
3. Time-Based Conditional Counting
SELECT
YEAR(hire_date) AS hire_year,
COUNT(CASE WHEN age < 30 THEN 1 END) AS young_employees,
COUNT(CASE WHEN age BETWEEN 30 AND 45 THEN 1 END) AS mid_career_employees,
COUNT(CASE WHEN age > 45 THEN 1 END) AS senior_employees
FROM
employees
GROUP BY
YEAR(hire_date)
ORDER BY
hire_year;
Query Complexity Analysis
Complexity Level |
Characteristics |
Performance Impact |
Simple |
Basic WHERE conditions |
Minimal |
Moderate |
Multiple CASE statements |
Moderate |
Complex |
Subqueries, multiple joins |
Significant |
Conditional Counting Flow
graph TD
A[Start Complex Counting] --> B{Query Type}
B --> |Multi-Table| C[Join and Aggregate]
B --> |Nested Conditions| D[Subquery Counting]
B --> |Time-Based Analysis| E[Temporal Grouping]
C --> F[Apply Conditions]
D --> F
E --> F
F --> G[Generate Result Set]
Advanced Optimization Strategies
- Use indexed columns in conditional logic
- Minimize subquery complexity
- Leverage materialized views for repetitive complex queries
Common Challenges in Complex Counting
- Managing query performance
- Handling NULL values
- Balancing readability and efficiency
LabEx recommends incremental approach to mastering complex MySQL counting techniques, starting with simple queries and progressively adding complexity.