cockroachdb / cockroachdb/cockroach

sql: incorrect decorrelation of lateral join

Open
#151,609 4 comments 0 reactions 0 assignees View on GitHub
A-sql-optimizer branch-release-25.3 C-bug O-support P-3 S-3-erroneous-edge-case T-sql-queries
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

For the following example query, CRDB gets different results than PG. I think there might be something wrong with the way CRDB is decorrelating the lateral join:

```sql
CREATE TABLE a (
shard
INT8 NOT NULL,
id
TEXT NOT NULL,
created_at
TIMESTAMPTZ NOT NULL,
PRIMARY KEY (shard, id)
);

CREATE TABLE b (
shard
INT8 NOT NULL,
id
TEXT NOT NULL,
created_at
TIMESTAMPTZ NOT NULL,
PRIMARY KEY (shard, id)
);

INSERT INTO a VALUES (2, '2', '2025-08-07');
INSERT INTO b VALUES (2, '2', '2025-08-05'), (3, '3', '2025-08-06');

SELECT
*
FROM
a
LEFT JOIN LATERAL (
SELECT
b.*
FROM
b
WHERE
b.created_at
< a.created_at
ORDER BY
b.created_at DESC
LIMIT
1
)
AS b ON b.id = a.id;
```

I get this result from PG 16.9:

```
shard | id | created_at | shard | id | created_at
-------+----+------------------------+-------+----+------------
2 | 2 | 2025-08-07 00:00:00-07 | | |
(1 row)
```

And this result from CRDB 25.3:

```
shard | id | created_at | shard | id | created_at
--------+----+------------------------+-------+----+-------------------------
2 | 2 | 2025-08-07 00:00:00+00 | 2 | 2 | 2025-08-05 00:00:00+00
(1 row)
```

Jira issue: [CRDB-53357](https://cockroachlabs.atlassian.net/browse/CRDB-53357)

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.