Skip to main content

Query Optimization

The Data Warehouse is built on ClickHouse, a columnar database. This means queries behave differently than in a traditional relational database. Here’s how to leverage the structure to get fast results.

Key Principles

1. Always filter by date

All fact tables are partitioned by month (toYYYYMM(created_at)). Filtering by date allows ClickHouse to skip entire partitions without reading them.

2. You don’t need to filter by company_id

Your user has a row policy that automatically filters by your company. You don’t need to add WHERE company_id = ... — it’s applied transparently.

3. Select only the columns you need

ClickHouse is columnar: it only reads the columns you mention in your SELECT. Fewer columns = less data read = faster.

4. Use LIMIT to explore

When exploring data, use LIMIT to avoid pulling millions of rows:

Internal Table Structure

Each table has a sort key that determines how the data is organized on disk. Queries that filter by the first columns of the sort key are much more efficient.

Sort Keys by Table

company_id is always the first column of the sort key. Since your user has an automatic filter by company, all your queries take advantage of this optimization without you having to do anything.

Secondary Indexes

Some tables have additional indexes that help filter by columns that aren’t in the sort key:

System Limits

Your user has the following limits to protect system stability: If your query exceeds any of these limits, it will be cancelled automatically. To avoid it:
  • Add tighter date filters
  • Select fewer columns
  • Use LIMIT
  • Pre-aggregate with GROUP BY instead of pulling individual rows

Common Patterns

JOIN between fact tables

You can cross tables using conversation_id or survey_user_id:

JOIN with dimensions

Custom service level