xref: /sqlite-3.40.0/test/subselect.test (revision b19a2bc6)
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.4 2001/09/16 00:13:28 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 {INSERT INTO t1 VALUES(NULL,8)}
59  execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=5)}
60} {8}
61
62# Try multiple subselects within a single expression.
63#
64do_test subselect-1.5 {
65  execsql {
66    CREATE TABLE t2(x int, y int);
67    INSERT INTO t2 VALUES(1,2);
68    INSERT INTO t2 VALUES(2,4);
69    INSERT INTO t2 VALUES(3,8);
70    INSERT INTO t2 VALUES(4,16);
71  }
72  execsql {
73    SELECT y from t2
74    WHERE x = (SELECT sum(b) FROM t1 where a notnull) - (SELECT sum(a) FROM t1)
75  }
76} {8}
77
78# Try something useful.  Delete every entry from t2 where the
79# x value is less than half of the maximum.
80#
81do_test subselect-1.6 {
82  execsql {DELETE FROM t2 WHERE x < 0.5*(SELECT max(x) FROM t2)}
83  execsql {SELECT x FROM t2 ORDER BY x}
84} {2 3 4}
85
86finish_test
87