---
title: "ClickHouse® tips #6: Filtering data in subqueries to avoid joins"
excerpt: "Faster JOINs without joining: use WHERE instead. This ClickHouse tip speeds up queries that don't actually need full joins."
authors: "Xoel Lopez"
categories: "The Data Base"
createdOn: "2023-09-25 00:00:00"
publishedOn: "2021-04-23 00:00:00"
updatedOn: "2022-09-09 00:00:00"
status: "published"
---

<p>Imagine that you want to join two tables, and filter by a column that comes from the table in the right side of the join. On ClickHouse® the query a bit different than what you’d do in other databases like Postgres, and it will result in a big performance improvement.</p><p>Let’s say one of the tables is this <code>events</code> table, with 100M rows:</p><figure class="kg-card kg-embed-card"><iframe loading="lazy" width="100%" src="https://snippets.tinybird.co/endpoint?code=SELECT%20%2A%20FROM%20events%0A&amp;language=Tinybird&amp;title=events&amp;run=run&amp;token=p.eyJ1IjogIjdmOTIwMmMzLWM1ZjctNDU4Ni1hZDUxLTdmYzUzNTRlMTk5YSIsICJpZCI6ICI3N2NiMDljOS1hYjVjLTQ2MzYtYTA4Yi00ZDYwNDQwMzUyZTYifQ.XhZPypxjhaeJbdJzNozOKmKPbFqM9CWkAil8WiXFaAE"></iframe></figure><p>And the other table is this <code>products</code> one, with ~2M rows</p><figure class="kg-card kg-embed-card"><iframe loading="lazy" width="100%" src="https://snippets.tinybird.co/endpoint?code=SELECT%20%2A%20FROM%20products%0A&amp;language=Tinybird&amp;title=products&amp;run=run&amp;token=p.eyJ1IjogIjdmOTIwMmMzLWM1ZjctNDU4Ni1hZDUxLTdmYzUzNTRlMTk5YSIsICJpZCI6ICI3N2NiMDljOS1hYjVjLTQ2MzYtYTA4Yi00ZDYwNDQwMzUyZTYifQ.XhZPypxjhaeJbdJzNozOKmKPbFqM9CWkAil8WiXFaAE"></iframe></figure><p>If you will always filter the result after making the join as in the query above, you don’t need to make a join at all. ClickHouse® saves data column-by-column, so filtering by the values in a column is a very fast operation. If you rewrite the query as follows, it would be just as fast. And you wouldn’t have create a Join table for it:</p><figure class="kg-card kg-embed-card"><iframe loading="lazy" width="100%" src="https://snippets.tinybird.co/endpoint?code=SELECT%20%2A%0AFROM%20events%0AWHERE%20product_id%20IN%20%28SELECT%20sku%20FROM%20products%20WHERE%20section_id%20%3D%201%29%0A&amp;language=Tinybird&amp;title=no_join_at_all&amp;run=run&amp;token=p.eyJ1IjogIjdmOTIwMmMzLWM1ZjctNDU4Ni1hZDUxLTdmYzUzNTRlMTk5YSIsICJpZCI6ICI3N2NiMDljOS1hYjVjLTQ2MzYtYTA4Yi00ZDYwNDQwMzUyZTYifQ.XhZPypxjhaeJbdJzNozOKmKPbFqM9CWkAil8WiXFaAE"></iframe></figure><p>Tinybird lets you create real-time API endpoints on in minutes instead of hours of days, powered by ClickHouse®. We’re still in private beta, but if you want to try out product, create an account <a href="https://www.tinybird.co/signup">here</a>.</p>
