cockroachdb / cockroachdb/cockroach

sql: consider removing support for SRFs in CASE and COALESCE

Open
#99,883 0 comments 0 reactions 0 assignees View on GitHub
C-bug O-qa T-sql-queries
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

**Describe the problem**

Postgres does not support set-returning functions within conditional-evaluation constructs, such as CASE or COALESCE, but CRDB does.

The [Postgres docs](https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTIONS-RETURNING-SET) give the example and explanation:
```sql
SELECT x, CASE WHEN x > 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;
```
> It might seem that this should produce five repetitions of input rows that have x > 0, and a single repetition of those that do not; but actually, because generate_series(1, 5) would be run in an implicit LATERAL FROM item before the CASE expression is ever evaluated, it would produce five repetitions of every input row. To reduce confusion, such cases produce a parse-time error instead.

**To Reproduce**

The statement above does not produce an error on CRDB, but exhibits the possibly confusing behavior described above:
```
demo@127.0.0.1:26257/movr> SELECT x, CASE WHEN x > 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;
x | case
-----+-------
1 | 1
2 | 1
-1 | 0
1 | 2
2 | 2
-1 | 0
1 | 3
2 | 3
-1 | 0
1 | 4
2 | 4
-1 | 0
1 | 5
2 | 5
-1 | 0
(15 rows)
```

**Expected behavior**

We should consider disallowing this to be consistent with Postgres.

Jira issue: CRDB-26113

Contributor guide

Open the contributing guide

Research direction

The issue names no files or tests; start by reproducing the CASE query with generate_series and reviewing the linked PostgreSQL behavior. Determine where CockroachDB accepts set-returning functions in CASE or COALESCE, then verify that the finished change rejects the example consistently with PostgreSQL.

Written by the indexing model from the issue text.

Assessment

Tech stack
go, sql
Domain
databases
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.