cockroachdb / cockroachdb/cockroach

sql: subquery producing `NULL` is incorrectly elided

Open
#128,115 1 comment 0 reactions 0 assignees View on GitHub
branch-master branch-release-20.1 branch-release-20.2 branch-release-21.1 branch-release-21.2 branch-release-22.1 branch-release-22.2 branch-release-23.1 branch-release-23.2 branch-release-24.1 branch-release-24.2 C-bug S-3-erroneous-edge-case T-sql-queries
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

A subquery projecting `NULL` and used in a scalar expression can be incorrectly elided and replaced with a constant `NULL` in the query plan. This is incorrect because the subquery could produce multiple rows, which should result in an error.

Example:

```sql
CREATE TABLE t (
i INT
);

INSERT INTO t VALUES (1), (2);

-- This should result in an error:
--
-- ERROR: more than one row returned by a subquery used as an expression
-- SQLSTATE: 21000
--
SELECT j + (SELECT NULL FROM t) FROM (VALUES (0)) v(j);
-- ?column?
-- ------------
-- NULL
-- (1 row)

EXPLAIN (OPT, VERBOSE)
SELECT j + (SELECT NULL FROM t) FROM (VALUES (0)) v(j);
-- info
-- -------------------------------
-- values
-- ├── columns: "?column?":7
-- ├── cardinality: [1 - 1]
-- ├── stats: [rows=1]
-- ├── cost: 0.02
-- ├── key: ()
-- ├── fd: ()-->(7)
-- ├── distribution: us-east1
-- ├── prune: (7)
-- └── (NULL,)
-- (10 rows)
```

After a quick investigation, the subquery appears to be elided during static analysis, before optimization.

This bug has been present since v19.1 or earlier.

Jira issue: CRDB-40804

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.