惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
量子位
有赞技术团队
有赞技术团队
博客园 - 三生石上(FineUI控件)
博客园 - Franky
M
MIT News - Artificial intelligence
U
Unit 42
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
J
Java Code Geeks
V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MyScale Blog
MyScale Blog
T
Tailwind CSS Blog
T
The Blog of Author Tim Ferriss
V
V2EX

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
PREWHERE optimization with ReplacingMergeTree and FINAL i...
gaurang10119 · 2026-04-26 · via DEV Community
Cover image for PREWHERE optimization with ReplacingMergeTree and FINAL in Clickhouse

gaurang101197

In this blog, we will learn about how to reduce I/O and improve query performance using PREWHERE in queries with FINAL keyword on ReplacingMergeTree table in Clickhouse.

Prerequisite

  1. Clickhouse
  2. ReplacingMergeTree
  3. FINAL
  4. prewhere
    1. Above is the best place to understand prewhere optimiation and how it can improve the query performance. It is recommended to go through it before proceeding.

PREWHERE with FINAL in ReplacingMergeTree

ReplacingMergeTree table engine is widely used to design the update/delete use case in Clickhouse. And it is very common to use FINAL keyword to deduplicate and query the latest copy of data.

PREWHERE is one of the powerful technique to reduces I/O and improve query performance by avoiding unnecessary data reads, and filtering out irrelevant data before reading non-filter columns from disk.

By default PREWHERE optimization is enabled on all query except the one with FINAL keyword.

Why prewhere is disabled on query with FINAL ?

FINAL applies the table engine’s merge/deduplication logic at read time (e.g. ReplacingMergeTree picks the "winning" row).

PREWHERE runs before this merge. If PREWHERE filters on columns that differ between duplicate versions of a row (and are not in ORDER BY), it can drop the version that should have "won" under FINAL, or keep a version that should have been removed. This can change which row survives the FINAL merge and therefore change query results. To avoid incorrect results, ClickHouse does not automatically move conditions to PREWHERE when FINAL is present unless you explicitly allow it.

Exmaple

CREATE TABLE test_prewhere_final
(
    id       UInt64,
    status   String,
    ver      UInt64
)
ENGINE = ReplacingMergeTree(ver)
ORDER BY id;

INSERT INTO test_prewhere_final VALUES
(1, 'active', 1);  -- old version, should lose

INSERT INTO test_prewhere_final VALUES
(1, 'inactive', 2);  -- new version, should win

SELECT id, status, ver
FROM test_prewhere_final
FINAL
WHERE id=1 and status = 'active';
-- Returns 0 rows (correct: the winning row has status = 'inactive')

SELECT id, status, ver
FROM test_prewhere_final
FINAL
PREWHERE id=1 and status = 'active';
-- Can return 1 rows (incorrect: if merge is not performed then prewhere applied before deduplication and can return row with active status. Which can be incorrect result if you want to query the latest state of data.)

Enter fullscreen mode Exit fullscreen mode

id status ver comment
1 active 1 removed during merge
1 inactive 2 latest data

Which columns can be moved to prewhere clause

Rule of thumb: It is safe to move columns mentioned in order by clause to PREWHERE clause as deduplication is happaned on them.

SELECT id, status, ver
FROM test_prewhere_final
FINAL
PREWHERE id=1 WHERE status = 'active';
-- Gives correct result as it is safe to move order by column to prewhere clause.

Enter fullscreen mode Exit fullscreen mode

In above example, if user wants to query latest version of data using FINAL keyword then moving status column in PREWHERE clause can give you wrong results. But it is safe to move id column to PREWHERE.

Impact

PREWHERE can reduce the I/O operations and improve the query performance. There is no rule of thumb to measure the improvement but it can be as high as >90% reduction in data read.

For e.g. if you are building saas product then it is very likely that you always have filter on your client/tenant ids. As you only allow client to query only their data. And to efficiently filter the data, it is very common that client/tenant id is present in order by clause of table. In this scenario, we can safely move filters on client/tenant id to PREWHERE.

What is next ?

It is very useful if prewhere optimization is automatically applied on order by columns in queries with FINAL keyword same as it is applied on queries without FINAL keyword. If you like the idea and what this to be picked up, upvote the below open idea.