1--
2-- SELECT_HAVING
3--
4
5-- load test data
6CREATE TABLE test_having (a int, b int, c char(8), d char);
7INSERT INTO test_having VALUES (0, 1, 'XXXX', 'A');
8INSERT INTO test_having VALUES (1, 2, 'AAAA', 'b');
9INSERT INTO test_having VALUES (2, 2, 'AAAA', 'c');
10INSERT INTO test_having VALUES (3, 3, 'BBBB', 'D');
11INSERT INTO test_having VALUES (4, 3, 'BBBB', 'e');
12INSERT INTO test_having VALUES (5, 3, 'bbbb', 'F');
13INSERT INTO test_having VALUES (6, 4, 'cccc', 'g');
14INSERT INTO test_having VALUES (7, 4, 'cccc', 'h');
15INSERT INTO test_having VALUES (8, 4, 'CCCC', 'I');
16INSERT INTO test_having VALUES (9, 4, 'CCCC', 'j');
17
18SELECT b, c FROM test_having
19	GROUP BY b, c HAVING count(*) = 1 ORDER BY b, c;
20
21-- HAVING is effectively equivalent to WHERE in this case
22SELECT b, c FROM test_having
23	GROUP BY b, c HAVING b = 3 ORDER BY b, c;
24
25SELECT lower(c), count(c) FROM test_having
26	GROUP BY lower(c) HAVING count(*) > 2 OR min(a) = max(a)
27	ORDER BY lower(c);
28
29SELECT c, max(a) FROM test_having
30	GROUP BY c HAVING count(*) > 2 OR min(a) = max(a)
31	ORDER BY c;
32
33-- test degenerate cases involving HAVING without GROUP BY
34-- Per SQL spec, these should generate 0 or 1 row, even without aggregates
35
36SELECT min(a), max(a) FROM test_having HAVING min(a) = max(a);
37SELECT min(a), max(a) FROM test_having HAVING min(a) < max(a);
38
39-- errors: ungrouped column references
40SELECT a FROM test_having HAVING min(a) < max(a);
41SELECT 1 AS one FROM test_having HAVING a > 1;
42
43-- the really degenerate case: need not scan table at all
44SELECT 1 AS one FROM test_having HAVING 1 > 2;
45SELECT 1 AS one FROM test_having HAVING 1 < 2;
46
47-- and just to prove that we aren't scanning the table:
48SELECT 1 AS one FROM test_having WHERE 1/a = 1 HAVING 1 < 2;
49
50DROP TABLE test_having;
51