# Amazon Redshift: A Practical Guide for People Who Know Postgres

A developer who knows PostgreSQL connects to Amazon Redshift for the first time. `psql` works. `\dt` lists the tables. The SQL looks like home.

Then the surprises start. `CREATE INDEX` is rejected. A row with a duplicate primary key inserts without complaint. A loop of single-row inserts that takes a moment on Postgres crawls for minutes. A join between two big tables is slow one day and fast the next after someone changes a single word in the table definition.

Redshift speaks the PostgreSQL language and uses its tools, but it is a different machine underneath. It is a columnar, massively parallel warehouse built to scan billions of rows, not to look up one. This guide explains the parts that are different, because those are the parts that decide whether it serves you well.

## What Redshift is

Amazon Redshift is the data warehouse service of AWS. It grew out of an old PostgreSQL release, which is why PostgreSQL drivers and much of its SQL work. Two ideas set it apart from Postgres:

- **Columnar storage.** Each column is stored and compressed separately. A query that needs three columns out of fifty reads only those three.
- **Massively parallel processing (MPP).** A leader node plans the query, and several compute nodes each work on their own slice of the data at the same time.

It comes in two forms:

| | Provisioned | Serverless |
|---|---|---|
| What you manage | A cluster with a node type and node count | A workgroup with a base capacity |
| Billing | Per node, for every hour the cluster is running | For the compute used while queries run, measured in RPU time |
| Good for | Steady, predictable, all-day workloads | Spiky or occasional use, new projects |
| When idle | Still billed unless you pause it | No compute charge |

RPU stands for Redshift Processing Unit, the serverless measure of compute.

## Why teams choose it

- **It lives inside AWS.** Loading from S3, reading IAM roles, sitting in your VPC and logging to CloudWatch all work without extra plumbing.
- **PostgreSQL tools connect.** `psql`, most BI tools and the common drivers work, on port 5439 by default.
- **It reads your data lake.** Redshift Spectrum queries files in S3 through external tables and can join them with warehouse tables.
- **Predictable cost for steady work.** A provisioned cluster, especially with a reserved commitment, has a known monthly figure however many queries you run.
- **Less tuning than it used to need.** Distribution, sort order and compression can all be left on `AUTO`, and vacuum and statistics run in the background.

## Where Redshift fits, and where it does not

**A strong choice for:**

- Companies whose data and applications are already on AWS
- Heavy reporting that runs all day, where a flat rate beats paying per query
- Joining warehouse tables with files in S3
- Teams that know PostgreSQL and want familiar tools

**Look elsewhere when:**

- **You need a transactional database.** Use Amazon RDS or Aurora for the application and copy data into Redshift for analysis.
- **You query rarely and the data already sits in S3.** Amazon Athena has nothing to keep running and charges per query.
- **You want compute that scales per team with almost no administration, on any cloud.** Snowflake's separate warehouses do that well.
- **You are on Google Cloud.** BigQuery is the natural neighbour there.
- **The data is small.** A PostgreSQL read replica answers reports on a few gigabytes perfectly well.

## What is different from PostgreSQL

Keep this list near you during the first month:

- **No indexes.** Speed comes from sort keys, distribution and column pruning.
- **Keys are not enforced.** `PRIMARY KEY`, `UNIQUE` and foreign keys are recorded as hints for the planner. Duplicates load freely, so removing them is your pipeline's job. Only `NOT NULL` is enforced.
- **`VARCHAR(n)` counts bytes, not characters.** Text with accents or non-Latin scripts needs more room than you expect.
- **Many PostgreSQL features are absent.** Extensions, arrays and a number of functions do not exist. Semi-structured data goes in the `SUPER` type.
- **Single-row writes are expensive.** Each one is a small distributed transaction.

## Using it the right way

### Design tables around joins and filters

```sql
CREATE TABLE orders (
  order_id    BIGINT NOT NULL,
  customer_id BIGINT NOT NULL,
  status      VARCHAR(20),
  total       DECIMAL(12,2),
  created_at  TIMESTAMP NOT NULL
)
DISTSTYLE KEY
DISTKEY (customer_id)
SORTKEY (created_at);
```

**Distribution** decides which node holds each row:

| Style | What it does | Use it for |
|---|---|---|
| `AUTO` | Redshift chooses and adjusts as the table grows | The default, and a good one |
| `KEY` | Rows with the same key value land on the same node | Large tables joined on that column |
| `ALL` | A full copy on every node | Small lookup tables |
| `EVEN` | Rows spread round-robin | Tables that are not joined |

When two big tables share a distribution key and you join on it, each node joins its own rows locally. When they do not, Redshift must move rows between nodes during the query, which is the usual cause of a slow join. Pick a key with many distinct values; a key where one value dominates piles data on one node (this is called skew).

The **sort key** stores rows in order. Redshift keeps the minimum and maximum of each block, so a filter on `created_at` skips blocks outside the range. Choose the column you filter on most, usually a date.

If you are not sure, leave everything on `AUTO` and check later.

### Load with COPY

```sql
COPY orders
FROM 's3://my-bucket/orders/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftLoadRole'
FORMAT AS PARQUET;
```

`COPY` reads many files in parallel, one stream per slice, so split a large load into several files of similar size instead of one huge one. Use an IAM role attached to the cluster, never access keys pasted into SQL.

When a load fails, the reason is recorded:

```sql
SELECT * FROM sys_load_error_detail ORDER BY start_time DESC LIMIT 20;
```

For small trickles of data, use multi-row inserts (`INSERT INTO t VALUES (...), (...), (...)`), or stage the rows and merge them in one statement.

### Send old data back to S3

```sql
UNLOAD ('SELECT * FROM orders WHERE created_at < ''2024-01-01''')
TO 's3://my-bucket/archive/orders_'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftLoadRole'
FORMAT AS PARQUET;
```

Archived files stay queryable through Spectrum:

```sql
CREATE EXTERNAL SCHEMA lake
FROM DATA CATALOG DATABASE 'archive'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftLoadRole';

SELECT COUNT(*) FROM lake.orders_2023;
```

The external schema points at a database in the AWS Glue Data Catalog. Spectrum queries are billed by the data they scan in S3, so keep those files in Parquet and partitioned.

### Check the health of your tables

```sql
SELECT "table", diststyle, sortkey1, size AS size_mb, tbl_rows,
       skew_rows, unsorted, stats_off
FROM svv_table_info
ORDER BY size DESC
LIMIT 20;
```

Read three columns first. A high `skew_rows` means a poor distribution key. A high `unsorted` percentage means the sort key is not helping until a vacuum catches up. A high `stats_off` means the planner is guessing; run `ANALYZE orders;`.

Redshift vacuums and analyses on its own in quiet periods. After a very large delete or load you can run `VACUUM orders;` yourself.

### Read the plan for data movement

```sql
EXPLAIN
SELECT c.country, SUM(o.total)
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.country;
```

Look at the join lines. `DS_DIST_NONE` means no rows had to move. `DS_BCAST_INNER` and `DS_DIST_BOTH` mean one or both tables were shipped between nodes for this query. Seeing those on big tables is your cue to revisit distribution keys.

### Find slow queries

```sql
SELECT query_id, status, elapsed_time / 1000000.0 AS seconds,
       LEFT(query_text, 80) AS query_start
FROM sys_query_history
WHERE start_time >= DATEADD(day, -1, GETDATE())
ORDER BY elapsed_time DESC
LIMIT 20;
```

`SYS_QUERY_HISTORY` works on both serverless and provisioned Redshift.

## How the pricing shapes your habits

**Provisioned** clusters bill for every hour they run, queries or no queries. So:

- Pause development and test clusters outside working hours. A paused cluster costs only its storage.
- Fill the cluster's day. Schedule heavy loads at night, when analysts are away.
- For a cluster that will run all year, a reserved commitment lowers the rate.

**Serverless** bills for compute while queries run, with a short minimum each time, and nothing for compute when idle. So:

- Set a base capacity that matches your normal queries, not your worst one.
- Set usage limits on the workgroup so a runaway job cannot run up the bill.
- Watch out for a dashboard that refreshes every few minutes: it can keep serverless busy all day and cost more than a small provisioned cluster.

In both forms, storage is billed separately on current node types, Spectrum is billed by data scanned, and repeated identical queries can be answered from the result cache without doing the work again.

## Common mistakes

- **Treating it like PostgreSQL.** Row-by-row inserts, updates in a loop and an expectation of enforced keys all go badly.
- **A skewed distribution key.** One busy node sets the pace for the whole cluster.
- **`SELECT *` on wide tables.** It reads every column and throws away the benefit of columnar storage.
- **Loading one enormous file.** `COPY` cannot parallelise it.
- **Access keys inside `COPY` statements.** They end up in logs and query history. Use an IAM role.
- **A publicly reachable cluster with a wide-open security group.** Keep it private and reach it through a bastion host or VPN.
- **Never pausing a test cluster.** It bills around the clock.
- **Using it for the application's live traffic.** Many small concurrent queries are the wrong shape for a warehouse.

## Quick reference

| Task | Command |
|---|---|
| Connect | `psql "host=<endpoint> port=5439 dbname=dev user=awsuser sslmode=require"` |
| Table sizes and health | `SELECT * FROM svv_table_info;` |
| Running queries | `SELECT pid, user_name, starttime, query FROM stv_recents WHERE status = 'Running';` |
| Cancel a query | `CANCEL 12345;` |
| End a session | `SELECT pg_terminate_backend(12345);` |
| Refresh statistics | `ANALYZE orders;` |
| Re-sort and reclaim space | `VACUUM orders;` |
| Table definition | `SHOW TABLE orders;` |
| Recent load errors | `SELECT * FROM sys_load_error_detail ORDER BY start_time DESC;` |

Redshift rewards people who stop expecting Postgres. Load in bulk, let distribution and sort order do the work that indexes do elsewhere, and match the pricing model to how steadily you query.

## Exploring Redshift with CreamDB

Because Redshift speaks the PostgreSQL protocol, [CreamDB](https://www.creamdb.com) connects to it like any Postgres relative, from a browser tab with nothing to install.

- Browse databases, schemas, tables, views and columns in a tree, see a table's definition, and open any table in a grid where paging, sorting and filtering run in Redshift.
- Write SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- View the schema as an ER diagram, and read users and roles on a read-only page. The Status panel shows as much session detail as Redshift exposes.
- Ask in plain English, for example "top ten customers by revenue this quarter", and get the SQL, a result table and a chart.

The assistant only reads on its own. Any change waits as an approval card that you answer, and read-only mode on the server blocks writes.

A Redshift cluster normally sits in a private network. CreamDB can reach it through an SSH tunnel to a bastion host, so you do not need to make the cluster public. Passwords and pasted SSH keys are encrypted at rest. It is free to start.

