Skip to main content
Database

Filter Aggregated Results

QueryValidateMedium

What you will learn

  • HAVING filters GROUPS (aggregates), WHERE filters ROWS โ€” WHERE on an aggregate fails at parse time
  • Prune rows with WHERE first (cheap), then GROUP, then HAVING โ€” reversing order kills performance at scale
  • HAVING references aggregate aliases (HAVING count > 5) โ€” raw column expressions silently work in MySQL but not Postgres

Description

Find users who have placed more than 1 order.

Test Scenario

-- Your query:
SELECT u.name, COUNT(o.id) as order_count
FROM users u
JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 1;

-- Expected: Users with multiple orders

Testing Tips

  • โ€ขHAVING filters after GROUP BY
  • โ€ขWHERE filters before GROUP BY
  • โ€ขUse HAVING with aggregate functions
// Playwright API Testing - Database
import { test, expect } from '@playwright/test';
test('Database query via API', async ({ request }) => {
const response = await request.post('/api/database/query', {
data: {
sql: 'SELECT * FROM users WHERE id = ?',
params: [1]
}
});
expect(response.ok()).toBeTruthy();
const { rows } = await response.json();
expect(rows.length).toBeGreaterThan(0);
});

Challenge ID: sql-having

2 frameworks available