From a3d3b17df43177229e8ba2ed9e4e523695028d23 Mon Sep 17 00:00:00 2001 From: Matt Aitken Date: Fri, 13 Feb 2026 17:34:43 +0000 Subject: [PATCH] TRQL: always add FINAL keyword (#3051) 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 ff3c60843..4ac85b559 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