sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

SQLite: DATE - DATE subtracts the years instead of returning the day difference

Open EnesSoydan opened this issue 2 weeks ago • 3 comments

Subtracting two dates is passed through as plain - when writing SQLite. SQLite has no date type, so DATE(...) returns text and - coerces both strings to their leading integer (the year). The query runs but returns a wrong number instead of the day difference:

import sqlglot

sqlglot.transpile("SELECT CAST('2024-03-01' AS DATE) - CAST('2024-02-01' AS DATE)", read="postgres", write="sqlite")
# ["SELECT DATE('2024-03-01') - DATE('2024-02-01')"]
# Postgres / DuckDB: 29
# SQLite: 0   (2024 - 2024)

sqlglot.transpile("SELECT DATE '2024-01-01' - DATE '2023-12-01'", read="duckdb", write="sqlite")
# SQLite: 1, expected 31

Both operands are explicitly DATE, so the result type is unambiguous after annotate_types. I'd expect something like CAST(JULIANDAY(a) - JULIANDAY(b) AS INTEGER) when both sides annotate to DATE, and the current output otherwise.

Tested on main (2deb7547).

Official Documentation https://www.postgresql.org/docs/current/functions-datetime.html (date - date → integer, number of days elapsed) https://www.sqlite.org/lang_datefunc.html (julianday())

EnesSoydan avatar Nov 19 '26 17:11 EnesSoydan

@EnesSoydan what's motivating these issues? Are you actually using sqlglot or is an LLM generating them?

georgesittas avatar Nov 19 '26 17:11 georgesittas

Haha fair question :) I do use sqlglot, mostly for moving queries between SQLite and DuckDB, and I've been running the same queries on both engines to see where the results differ. That's where these came from. I do get help from Claude on the fixes, and it also helps me polish my English, but I check every case against both engines myself before opening anything. If these are too low priority, just let me know and I'll ease off a bit.

EnesSoydan avatar Nov 19 '26 17:11 EnesSoydan

Ok cool, just curious. This particular issue was closed because it seems a bit annoying to deal with and not a high priority atm.

georgesittas avatar Nov 20 '26 00:11 georgesittas