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

推荐订阅源

Google DeepMind News
Google DeepMind News
SecWiki News
SecWiki News
博客园 - Franky
V
V2EX
罗磊的独立博客
美团技术团队
大猫的无限游戏
大猫的无限游戏
Simon Willison's Weblog
Simon Willison's Weblog
S
Securelist
C
Cyber Attacks, Cyber Crime and Cyber Security
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
Webroot Blog
Webroot Blog
N
News | PayPal Newsroom
博客园 - 司徒正美
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cloudbric
Cloudbric
AI
AI
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
Recent Commits to openclaw:main
Recent Commits to openclaw:main
月光博客
月光博客
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Troy Hunt's Blog
Project Zero
Project Zero
Schneier on Security
Schneier on Security
TaoSecurity Blog
TaoSecurity Blog
博客园 - 【当耐特】
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
P
Privacy & Cybersecurity Law Blog
博客园_首页
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
J
Java Code Geeks
P
Proofpoint News Feed

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Day 46: A Guide to ClickHouse® Window Functions
Kanishga Subramani · 2026-06-28 · via DEV Community

Introduction

Analyzing data often requires comparing rows, calculating rankings, finding running totals, or computing moving averages without changing the number of rows returned. Traditionally, these tasks required complex self-joins or nested subqueries, making SQL queries harder to write and maintain.

ClickHouse® Window Functions simplify these analytical operations by allowing calculations across a group of related rows while preserving every row in the result set. This enables cleaner SQL, better readability, and more powerful analytics.

In this guide, you'll learn what window functions are, how the OVER() clause works, and how to use the most common window functions in ClickHouse® with practical examples.


What Are Window Functions?

A window function performs calculations over a set of rows called a window.

Unlike GROUP BY, which combines multiple rows into a single result, window functions calculate values while keeping every original row.

Consider the following employee salary data:

Employee Department Salary
Alice HR 50,000
Bob HR 65,000
Charlie HR 55,000

Using GROUP BY, you can calculate the average salary for HR, but the result contains only one row.

With a window function, every employee remains visible while also displaying the department's average salary.

Employee Salary Department Average
Alice 50,000 56,666
Bob 65,000 56,666
Charlie 55,000 56,666

This ability to retain individual rows while performing analytical calculations is what makes window functions so powerful.


Basic Syntax

Every window function uses the OVER() clause.

SELECT
    column_name,
    window_function() OVER (
        PARTITION BY column
        ORDER BY column
    )
FROM table_name;

The OVER() clause defines how the window is created.

It can specify:

  • How rows are grouped (PARTITION BY)
  • How rows are ordered (ORDER BY)
  • Which rows belong to the window (ROWS BETWEEN)

Sample Table

We'll use the following table throughout the examples.

CREATE TABLE employee_sales
(
    Employee String,
    Department String,
    SaleDate Date,
    Sales UInt32
)
ENGINE = MergeTree
ORDER BY SaleDate;

Sample data:

Employee Department SaleDate Sales
Alice Electronics 2025-01-01 120
Bob Electronics 2025-01-02 150
Charlie Electronics 2025-01-03 180
David Furniture 2025-01-01 90
Emma Furniture 2025-01-01 110

Ranking Functions

ROW_NUMBER()

Assigns a unique sequential number to every row.

SELECT
    Employee,
    Sales,
    ROW_NUMBER() OVER (ORDER BY Sales DESC) AS RowNum
FROM employee_sales;

Output:

Employee Sales RowNum
Charlie 180 1
Bob 150 2
Alice 120 3
Emma 110 4

Common Use Cases

  • Ranking reports
  • Pagination
  • Top-N queries

RANK()

Assigns the same rank to equal values.

SELECT
    Employee,
    Sales,
    RANK() OVER (ORDER BY Sales DESC) AS Rank
FROM employee_sales;

Output:

Employee Sales Rank
Alice 200 1
Bob 180 2
Charlie 180 2
David 150 4

Notice that Rank 3 is skipped because two employees share Rank 2.


DENSE_RANK()

Works like RANK(), but does not leave gaps.

SELECT
    Employee,
    Sales,
    DENSE_RANK() OVER (ORDER BY Sales DESC) AS DenseRank
FROM employee_sales;

Output:

Employee Sales DenseRank
Alice 200 1
Bob 180 2
Charlie 180 2
David 150 3

NTILE()

Splits ordered rows into approximately equal-sized buckets.

SELECT
    Employee,
    Sales,
    NTILE(2) OVER (ORDER BY Sales DESC) AS SalesGroup
FROM employee_sales;

Output:

Employee Sales SalesGroup
Charlie 180 1
Bob 150 1
Alice 120 2
David 90 2

Common Use Cases

  • Customer segmentation
  • Sales quartiles
  • Performance grading
  • Ranking analysis

Aggregate Window Functions

Traditional aggregate functions such as SUM(), AVG(), MIN(), MAX(), and COUNT() can also operate as window functions.


SUM() OVER()

Calculates running totals.

SELECT
    SaleDate,
    Sales,
    SUM(Sales)
    OVER (ORDER BY SaleDate) AS RunningTotal
FROM employee_sales;

Output:

SaleDate Sales RunningTotal
Jan 1 120 120
Jan 2 150 270
Jan 3 180 450

Ideal for cumulative sales reports.


AVG() OVER()

Calculates averages without collapsing rows.

SELECT
    Employee,
    Department,
    Sales,
    AVG(Sales)
    OVER (PARTITION BY Department) AS DepartmentAverage
FROM employee_sales;

Output:

Employee Department Sales DepartmentAverage
Alice Electronics 120 150
Bob Electronics 150 150
Charlie Electronics 180 150

Moving Average

Moving averages become very simple with window functions.

SELECT
    SaleDate,
    Sales,
    AVG(Sales)
    OVER (
        ORDER BY SaleDate
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ) AS MovingAverage
FROM employee_sales;

Output:

SaleDate Sales MovingAverage
Jan 1 120 120
Jan 2 150 135
Jan 3 180 150

The calculation includes:

  • Current row
  • Previous row
  • Two rows before the current row

Understanding Window Frames

Window frames determine which rows participate in the calculation.

Example:

ROWS BETWEEN 2 PRECEDING AND CURRENT ROW

This means:

  • 2 PRECEDING → Include the previous two rows.
  • CURRENT ROW → Include the current row.

Window frames are commonly used for:

  • Moving averages
  • Rolling sums
  • Sliding calculations
  • Time-series analytics

Navigation Functions

LAG()

Returns the value from the previous row.

SELECT
    SaleDate,
    Sales,
    LAG(Sales)
    OVER (ORDER BY SaleDate) AS PreviousSales
FROM employee_sales;

Output:

SaleDate Sales PreviousSales
Jan 1 120 NULL
Jan 2 150 120
Jan 3 180 150

Useful for day-over-day comparisons.


LEAD()

Returns the value from the next row.

SELECT
    SaleDate,
    Sales,
    LEAD(Sales)
    OVER (ORDER BY SaleDate) AS NextSales
FROM employee_sales;

Output:

SaleDate Sales NextSales
Jan 1 120 150
Jan 2 150 180
Jan 3 180 NULL

Useful for forecasting and sequential analysis.


FIRST_VALUE() and LAST_VALUE()

Retrieve the first or last value from the window.

SELECT
    Employee,
    Sales,
    FIRST_VALUE(Sales)
    OVER (
        ORDER BY Sales DESC
    ) AS HighestSale,
    LAST_VALUE(Sales)
    OVER (
        ORDER BY Sales
        ROWS BETWEEN UNBOUNDED PRECEDING
        AND UNBOUNDED FOLLOWING
    ) AS LastSale
FROM employee_sales;

Output:

Employee Sales HighestSale LastSale
Charlie 180 180 180
Bob 150 180 180
Alice 120 180 180

Here:

  • FIRST_VALUE() returns the highest sales value after sorting in descending order.
  • LAST_VALUE() returns the final value across the complete window.

Window Functions vs GROUP BY

GROUP BY Window Functions
Combines rows Keeps all rows
One result per group One result per row
Used for summaries Used for row-level analytics
Cannot easily compare neighboring rows Easily compares previous, next, ranked, and cumulative values

Performance Best Practices

For better performance when using window functions in ClickHouse®:

  • Choose an efficient ORDER BY key.
  • Use PARTITION BY only when necessary.
  • Filter rows before applying window functions whenever possible.
  • Keep window frames as small as practical.
  • Use MergeTree tables for analytical workloads.
  • Avoid unnecessary sorting on very large datasets.

Conclusion

Window Functions are one of the most powerful SQL features available in ClickHouse® for analytical workloads. They allow you to perform rankings, running totals, moving averages, cumulative calculations, and row-to-row comparisons while preserving every row in the result set.

By understanding the OVER() clause and mastering functions such as ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), SUM(), AVG(), LAG(), LEAD(), FIRST_VALUE(), and LAST_VALUE(), you can write cleaner SQL and solve complex analytical problems without relying on complicated joins or subqueries.

For anyone working with ClickHouse®, mastering window functions is an essential skill for building efficient, readable, and high-performance analytical queries.