AdvancedWHERE & Filtering
Find employees with consecutive salary increases
The query
SQL
WITH salary_changes AS (
SELECT
emp_id,
changed_at,
new_salary,
LAG(new_salary) OVER (PARTITION BY emp_id ORDER BY changed_at) AS prev_salary
FROM salary_history
),
increases AS (
SELECT
emp_id,
COUNT(*) AS increase_count,
BOOL_AND(new_salary > prev_salary) AS all_increases
FROM salary_changes
WHERE prev_salary IS NOT NULL
GROUP BY emp_id
)
SELECT
e.first_name,
e.last_name,
i.increase_count
FROM increases i
JOIN employees e ON i.emp_id = e.emp_id
WHERE i.all_increases = TRUE
ORDER BY i.increase_count DESC;Note
“BOOL_AND returns TRUE only if ALL rows in group are TRUE. Elegant way to check universal conditions.