cockroachdb / cockroachdb/cockroach

sql: possibly incorrectly optimizing away one of the projections

Open
#124,695 5 comments 0 reactions 0 assignees View on GitHub
C-enhancement O-community T-sql-queries
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

**Describe the problem**

I have a table with two columns of relevance: a column with an enum type, and a bytes column.

I'm doing a conditional update on multiple rows of this table, using `CASE ... WHEN`, and part of that includes values which are `NULL`.

Unfortunately, in the instance I'm using, updating both the bytes and enum column with `NULL` values: this types the latter `NULL` as the enum column and so a mismatched type error is produced.

e.g. `ERROR: value type debug_t doesn't match type bytes of column "bytes_col"`

**To Reproduce**

Set up a cockroach cluster per your own wishes, and run the following queries to set up a table and type:
```sql
CREATE TYPE IF NOT EXISTS debug_t AS ENUM('test1', 'test2');

CREATE TABLE debug (
id INT NOT NULL,
enum_col debug_t DEFAULT NULL,
bytes_col BYTES DEFAULT NULL,
PRIMARY KEY(id)
);

INSERT INTO debug ("id", "enum_col", "bytes_col") VALUES (1, 'test1', 'some_bytes_yo');
```

Then observe that this query _does_ work:
```sql
UPDATE debug SET "enum_col"=NULL, "bytes_col"=NULL WHERE "id" IN (1);
```

But this query, despite being valid syntax, does not work and raises `ERROR: value type debug_t doesn't match type bytes of column "bytes_col"`:
```sql
UPDATE debug SET
"enum_col" = (CASE "id"
WHEN 1 THEN
NULL
ELSE
NULL
END),
"bytes_col" = (CASE "id"
WHEN 1 THEN
NULL
ELSE
NULL
END)
WHERE "id" IN (1);
```

Now, when the first NULL is updated to any other valid enum value, the query works. Likewise, casting the third NULL using `CAST(NULL AS BYTES)` also works.

**Expected behavior**
See above.

If applicable, add screenshots to help explain your problem.

**Environment:**
Cockroach DB version v23.1.14

**Additional context**
This seems to impact PostgreSQL as well.

Jira issue: CRDB-39015

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the failing UPDATE and the working variants in the issue against CockroachDB, then review the SQL optimizer area related to projections and CASE expressions. Use Jira issue CRDB-39015 for additional context. Done means the reproduced query succeeds without the enum/bytes type mismatch, with regression coverage for the reported case.

Written by the indexing model from the issue text.

Assessment

Tech stack
go, sql
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.