xref: /sqlite-3.40.0/test/subselect.test (revision f5905aa7)
1# 2001 September 15
2#
3# The author disclaims copyright to this source code.  In place of
4# a legal notice, here is a blessing:
5#
6#    May you do good and not evil.
7#    May you find forgiveness for yourself and forgive others.
8#    May you share freely, never taking more than you give.
9#
10#***********************************************************************
11# This file implements regression tests for SQLite library.  The
12# focus of this file is testing SELECT statements that are part of
13# expressions.
14#
15# $Id: subselect.test,v 1.5 2002/05/26 20:54:35 drh Exp $
16
17set testdir [file dirname $argv0]
18source $testdir/tester.tcl
19
20# Basic sanity checking.  Try a simple subselect.
21#
22do_test subselect-1.1 {
23  execsql {
24    CREATE TABLE t1(a int, b int);
25    INSERT INTO t1 VALUES(1,2);
26    INSERT INTO t1 VALUES(3,4);
27    INSERT INTO t1 VALUES(5,6);
28  }
29  execsql {SELECT * FROM t1 WHERE a = (SELECT count(*) FROM t1)}
30} {3 4}
31
32# Try a select with more than one result column.
33#
34do_test subselect-1.2 {
35  set v [catch {execsql {SELECT * FROM t1 WHERE a = (SELECT * FROM t1)}} msg]
36  lappend v $msg
37} {1 {only a single result allowed for a SELECT that is part of an expression}}
38
39# A subselect without an aggregate.
40#
41do_test subselect-1.3a {
42  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=2)}
43} {2}
44do_test subselect-1.3b {
45  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=4)}
46} {4}
47do_test subselect-1.3c {
48  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=6)}
49} {6}
50do_test subselect-1.3c {
51  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=8)}
52} {}
53
54# What if the subselect doesn't return any value.  We should get
55# NULL as the result.  Check it out.
56#
57do_test subselect-1.4 {
58  execsql {SELECT b from t1 where a = coalesce((SELECT a FROM t1 WHERE b=5),1)}
59} {2}
60
61# Try multiple subselects within a single expression.
62#
63do_test subselect-1.5 {
64  execsql {
65    CREATE TABLE t2(x int, y int);
66    INSERT INTO t2 VALUES(1,2);
67    INSERT INTO t2 VALUES(2,4);
68    INSERT INTO t2 VALUES(3,8);
69    INSERT INTO t2 VALUES(4,16);
70  }
71  execsql {
72    SELECT y from t2
73    WHERE x = (SELECT sum(b) FROM t1 where a notnull) - (SELECT sum(a) FROM t1)
74  }
75} {8}
76
77# Try something useful.  Delete every entry from t2 where the
78# x value is less than half of the maximum.
79#
80do_test subselect-1.6 {
81  execsql {DELETE FROM t2 WHERE x < 0.5*(SELECT max(x) FROM t2)}
82  execsql {SELECT x FROM t2 ORDER BY x}
83} {2 3 4}
84
85finish_test
86