From e56beb8240b5b23d8c8bf7086c6eff6b07aadd69 Mon Sep 17 00:00:00 2001 From: Matt Aitken Date: Fri, 13 Feb 2026 17:17:16 +0000 Subject: [PATCH] TRQL: always add FINAL keyword MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For now we’re going to always add FINAL to TRQL queries for data correctness. In the future we will implement an automated optimization where we use `SELECT argMax(column, _version)` and `WHERE _is_deleted = 0`. But this is a more complex change and needs more investigation of downsides. --- internal-packages/tsql/src/query/printer.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/internal-packages/tsql/src/query/printer.ts b/internal-packages/tsql/src/query/printer.ts index ff3c608430..4ac85b559e 100644 --- a/internal-packages/tsql/src/query/printer.ts +++ b/internal-packages/tsql/src/query/printer.ts @@ -1559,9 +1559,14 @@ export class ClickHousePrinter { joinStrings.push(`AS ${this.printIdentifier(node.alias)}`); } - // Add FINAL - if (node.table_final) { - joinStrings.push("FINAL"); + // Always add FINAL for direct table references to ensure deduplicated results + // from ReplacingMergeTree tables in ClickHouse + if (node.table) { + const tableExpr = node.table; + const isDirectTable = (tableExpr as Field).expression_type === "field"; + if (isDirectTable) { + joinStrings.push("FINAL"); + } } // Add SAMPLE