SQLite: DATE - DATE subtracts the years instead of returning the day difference
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 what's motivating these issues? Are you actually using sqlglot or is an LLM generating them?
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.
Ok cool, just curious. This particular issue was closed because it seems a bit annoying to deal with and not a high priority atm.