Amazon Redshift Distribution and Sort Keys: A Practical Guide

Amazon Redshift Distribution and Sort Keys: A Practical Guide

Amazon Redshift is a massively parallel processing (MPP) warehouse. Every table is split across the slices of your compute nodes, and every query runs on all of those slices at once. That design is fast when each slice can work on its own data, and slow when slices have to ship rows to each other over the network or scan blocks they did not need. Two table settings decide which of those happens: the distribution style and the sort key.

This guide is for data engineers who build or tune Redshift tables, whether on provisioned RA3 clusters or Redshift Serverless. It covers how each distribution style works, when to choose a compound sort key, how to read the EXPLAIN plan for data movement, and the system views that tell you whether a table is healthy.

How Redshift stores a table

Each compute node is divided into slices. When you load a table, Redshift assigns each row to a slice according to the table’s distribution style. Inside each slice, data is stored by column in 1 MB blocks, and Redshift keeps the minimum and maximum value of every block (zone maps). If the table is sorted on a column you filter by, Redshift can skip every block whose range cannot match your filter.

So the two settings solve two different problems:

  • Distribution decides where rows live. Good distribution keeps joins and aggregations local to each slice and spreads work evenly.
  • Sort keys decide the order of rows within each slice. A good sort key lets range-restricted scans skip most of the table.

The four distribution styles

StyleHow rows are placedBest forWatch out for
AUTORedshift chooses and changes the style as the table growsThe default; most new tablesYou give up control while it decides
EVENRound-robin across slicesLarge tables that are not joined on a common keyJoins usually need redistribution
KEYRows with the same value of one column go to the same sliceLarge fact and dimension tables joined on that columnSkew if the key has few or very uneven values
ALLA full copy of the table on every nodeSmall, slowly changing dimensionsStorage and load time multiply by node count

With DISTSTYLE AUTO, Redshift typically starts a small table as ALL and switches it to EVEN as it grows. When automatic table optimization (ATO) is active, it can also pick a KEY column based on the joins it observes. AWS documents that tables created without an explicit distribution style or sort key default to AUTO, and that setting one explicitly means the table is no longer managed automatically.

Choosing a distribution key

A good KEY column is used in the most expensive joins, has many distinct values, and has an even spread of rows per value. The classic pattern is to distribute your largest fact table and its largest dimension on the same join column, so the join happens without any network shuffle. Distribute small dimensions with ALL.

Sort keys: compound vs interleaved vs AUTO

  • Compound sort key: rows are ordered by the first column, then the second, and so on. It works best when queries filter on the leading column, for example a date or timestamp. It also helps merge joins and GROUP BY on those columns.
  • Interleaved sort key: gives equal weight to up to 8 columns, so queries filtering on any one of them can skip blocks. The cost is slower loads and a heavier VACUUM REINDEX. It suits a narrow set of workloads and is rarely the right first choice.
  • SORTKEY AUTO: Redshift watches the filter and join predicates in your queries and chooses a sort key based on how often and how selectively columns are used.

For most event or transaction tables, a compound sort key that starts with the event timestamp is the safe choice, because almost every query filters on a date range.

Hands-on: a fact and dimension pair

Here is a typical orders model. The fact table and the customer dimension share customer_id as the distribution key, the small product dimension is copied to every node, and the fact is sorted by order date.

-- Large dimension: co-located with the fact on customer_id
CREATE TABLE dim_customer (
    customer_id   BIGINT       NOT NULL,
    customer_name VARCHAR(200),
    country_code  CHAR(2),
    created_at    TIMESTAMP
)
DISTSTYLE KEY
DISTKEY (customer_id)
SORTKEY (customer_id);

-- Small dimension: one full copy per node
CREATE TABLE dim_product (
    product_id   INT          NOT NULL,
    product_name VARCHAR(200),
    category     VARCHAR(50)
)
DISTSTYLE ALL;

-- Fact: same DISTKEY as dim_customer, sorted by date for range filters
CREATE TABLE fct_orders (
    order_id     BIGINT        NOT NULL,
    order_date   DATE          NOT NULL,
    customer_id  BIGINT        NOT NULL,
    product_id   INT           NOT NULL,
    quantity     INT,
    amount       DECIMAL(12,2)
)
DISTSTYLE KEY
DISTKEY (customer_id)
COMPOUND SORTKEY (order_date, customer_id);

A query that joins the three tables and filters on the last 30 days can now skip old blocks, join orders to customers locally on each slice, and join to products without moving data, because every node already holds the full product table.

Reading EXPLAIN for data movement

Run EXPLAIN on your slowest queries and look at the join steps. Redshift labels each join with how it moved data:

LabelMeaningVerdict
DS_DIST_NONENo redistribution; tables are co-locatedIdeal
DS_DIST_ALL_NONEInner table is DISTSTYLE ALLIdeal
DS_DIST_INNER / DS_DIST_OUTEROne side is redistributedAcceptable for smaller tables
DS_BCAST_INNERInner table is broadcast to every nodeCostly if the inner table is large
DS_DIST_BOTHBoth sides are redistributedUsually a sign of a missing or mismatched DISTKEY
EXPLAIN
SELECT c.country_code, SUM(o.amount) AS revenue
FROM fct_orders o
JOIN dim_customer c ON c.customer_id = o.customer_id
WHERE o.order_date >= DATEADD(day, -30, CURRENT_DATE)
GROUP BY c.country_code;

If the hash join for this query shows DS_DIST_NONE, the distribution keys are doing their job. If you see DS_BCAST_INNER or DS_DIST_BOTH on a large table, that join is your tuning target.

Checking table health with system views

SVV_TABLE_INFO gives one row per table with its distribution style, first sort key column, row skew, percentage unsorted and how stale its statistics are.

SELECT "schema",
       "table",
       diststyle,
       sortkey1,
       skew_rows,      -- ratio of rows on the fullest slice vs the emptiest
       unsorted,       -- % of rows not in sort-key order
       stats_off,      -- 0 = statistics current, 100 = stale
       tbl_rows
FROM svv_table_info
ORDER BY skew_rows DESC NULLS LAST
LIMIT 20;

A skew_rows far above 1 means one slice holds much more data than the others, so the whole query waits on that slice. A high unsorted value means zone maps are less effective; a high stats_off means the planner may pick a poor plan. To see what ATO would change, query SVV_ALTER_TABLE_RECOMMENDATIONS; to see what it has already applied, query SVL_AUTO_WORKER_ACTION.

Changing keys on an existing table

You no longer need a deep copy to change most settings. ALTER TABLE can change the distribution style, distribution key and sort key in place, or hand the table back to automatic management:

-- Fix a skewed table by changing its distribution key
ALTER TABLE fct_orders ALTER DISTKEY customer_id;

-- Or let Redshift manage it again
ALTER TABLE fct_orders ALTER DISTSTYLE AUTO;
ALTER TABLE fct_orders ALTER SORTKEY AUTO;

These operations rewrite data in the background and use cluster resources, so run them on large tables outside peak hours.

Common pitfalls

  • Distributing on a low-cardinality column. A status or country column puts most rows on a few slices. Check skew_rows after every load.
  • Distributing on a column with many NULLs. All NULLs hash to the same slice, which creates a hot spot.
  • Using ALL on large or fast-changing tables. Every insert is written to every node, and storage grows with the cluster size.
  • Wrapping the sort key in a function. A filter such as WHERE DATE_TRUNC('month', order_date) = ... can prevent block skipping. Filter on the raw column with a range instead.
  • Mismatched join column types. Joining a BIGINT to a VARCHAR forces a conversion and can defeat co-location. Keep key columns the same type on both sides.
  • Tuning by guesswork. Always compare EXPLAIN plans and query run times before and after a change.

Key takeaways

  • Start with AUTO for new tables and let automatic table optimization learn from your workload.
  • Set KEY distribution yourself when you know the dominant join, and put the large fact and its largest dimension on the same key.
  • Use DISTSTYLE ALL for small dimensions only.
  • Lead a compound sort key with the column most queries filter by, usually a date or timestamp.
  • Look for DS_DIST_NONE in EXPLAIN, and treat DS_BCAST_INNER and DS_DIST_BOTH on big tables as warnings.
  • Monitor skew_rows, unsorted and stats_off in SVV_TABLE_INFO, and fix problems in place with ALTER TABLE.

Get distribution and sort keys right and most Redshift performance problems disappear before they start. For more on AWS data tooling, see our guides to AWS Glue and the AWS vs Azure services comparison.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your comment appears after we check it.