StarRocks Tutorial for Beginners

StarRocks Tutorial for Beginners

The quickest way to understand an analytical database is to give it some data and ask it questions. This tutorial does exactly that with StarRocks. You’ll start a cluster in Docker, design a small e-commerce schema, load ten thousand orders, run joins and window functions, watch partition pruning in an execution plan, upsert rows in a Primary Key table, and finish with a materialized view that rewrites your queries automatically.

If you haven’t met StarRocks yet, our What Is StarRocks complete guide covers the history, architecture, and table types. Here we’ll mostly type commands and look at results. Everything runs on one machine, and you don’t need any prior experience beyond basic SQL.

What You’ll Build

By the end of this tutorial you’ll have:

  1. A running single-node StarRocks cluster in Docker.
  2. Three tables: a partitioned fact table for orders, plus two Primary Key dimension tables for customers and products.
  3. About ten thousand generated orders loaded in batches.
  4. Queries covering aggregation, joins, window functions, and approximate distinct counts.
  5. A look at partition pruning through EXPLAIN.
  6. Hands-on experience with upserts, updates, and deletes.
  7. An asynchronous materialized view.
  8. A taste of Stream Load, StarRocks’ HTTP loading interface.

Prerequisites

  • Docker installed and running.
  • Python 3 on your host machine, which we’ll use only to generate sample data.
  • About 40 minutes.
  • Optional: a SQL client such as DBeaver. (cite index=”108-1″>The documentation lists the mysql CLI, DBeaver, and MySQL Workbench as supported ways to connect.

Step 1: Start StarRocks

(cite index=”108-1″>The all-in-one image runs a complete test cluster inside a single container:

bash
docker pull starrocks/allin1-ubuntu
docker run -p 9030:9030 -p 8030:8030 -p 8040:8040 -itd \
  --name quickstart starrocks/allin1-ubuntu

The three ports each have a job. Port 9030 is the SQL endpoint, which speaks the MySQL protocol. Ports 8030 and 8040 serve HTTP interfaces for the frontend and backend, which matter when loading data and checking health.

Starting up takes a minute or two, because the container launches a frontend (FE) and a backend (BE) process. Check the logs if you’re curious:

bash
docker logs -f quickstart

Press Ctrl+C when the output settles.

Step 2: Connect and Check the Cluster

(cite index=”108-1″>The easiest way to use the mysql CLI is to run it from inside the container:

bash
docker exec -it quickstart \
  mysql -P 9030 -h 127.0.0.1 -u root --prompt="StarRocks > "

Before creating anything, confirm that both node types are alive:

sql
SHOW FRONTENDS;
SHOW BACKENDS;

Look for an Alive column showing true in each result. If the backend isn’t alive yet, wait another minute and retry. Creating tables before the BE registers is the most common cause of confusing errors in the first ten minutes.

Now create a database for the tutorial:

sql
CREATE DATABASE IF NOT EXISTS shop;
USE shop;

Step 3: Design the Tables

Table design in StarRocks is more deliberate than in a typical OLTP database, because the choices you make determine how data is stored and how quickly queries run. We’ll create three tables and explain each decision.

The Orders Fact Table
sql
CREATE TABLE orders (
    order_time  DATETIME       NOT NULL,
    order_id    BIGINT         NOT NULL,
    customer_id INT            NOT NULL,
    product_id  INT            NOT NULL,
    quantity    INT,
    amount      DECIMAL(10, 2)
)
DUPLICATE KEY(order_time, order_id)
PARTITION BY date_trunc('month', order_time)
DISTRIBUTED BY HASH(order_id) BUCKETS 4
PROPERTIES ("replication_num" = "1");

Let’s unpack it.

Duplicate Key. (cite index=”110-1″>Duplicate Key is the default table type, and it’s the right fit for append-only events like orders. (cite index=”114-1″>Rows with identical key content simply coexist, so nothing is merged or replaced. The key columns, order_time and order_id, also act as the sort key, which means data on disk is ordered by time first. That helps every query that filters on a time range.

Partitioning by month. The PARTITION BY date_trunc('month', order_time) clause splits the table into monthly partitions. Queries that filter on a date range can skip entire partitions, which we’ll verify in Step 7. Expression partitioning like this depends on your StarRocks version, so if the statement is rejected, check the documentation for the partitioning syntax your version supports.

Hash bucketing. (cite index=”113-1″>With hash bucketing, data is distributed into buckets based on the hash values of the bucketing key. We hash on order_id because it has a unique value per row, which spreads data evenly. Four buckets is plenty for a tutorial dataset.

Replication. The replication_num = 1 property is essential on a single-node test cluster. The default asks for several replicas, and a single BE can’t satisfy that.

The Customers Dimension Table
sql
CREATE TABLE customers (
    customer_id INT         NOT NULL,
    name        VARCHAR(50),
    country     VARCHAR(10),
    plan        VARCHAR(20)
)
PRIMARY KEY(customer_id)
DISTRIBUTED BY HASH(customer_id) BUCKETS 4
PROPERTIES ("replication_num" = "1");

Customers change over time, since people upgrade plans or move countries. That makes this a natural fit for a Primary Key table. (cite index=”113-1″>Primary Key tables add unique and non-null constraints to the key columns, and (cite index=”114-1″>newer values replace earlier ones for the same key according to import order. In effect, loading a row with an existing key updates it.

The Products Dimension Table
sql
CREATE TABLE products (
    product_id INT         NOT NULL,
    name       VARCHAR(50),
    category   VARCHAR(30),
    price      DECIMAL(10, 2)
)
PRIMARY KEY(product_id)
DISTRIBUTED BY HASH(product_id) BUCKETS 4
PROPERTIES ("replication_num" = "1");

Same pattern. Products get renamed and repriced, and you’ll want one current row per product.

Step 4: Generate and Load Data

Instead of downloading a dataset, we’ll generate one so the tutorial stays self-contained. Create a file named gen_data.py on your host machine:

python
import random
from datetime import datetime, timedelta

random.seed(42)

countries = ["IN", "US", "DE", "BR", "JP", "GB"]
plans = ["free", "pro", "team"]
products = [
    (1, "Keyboard", "Accessories", 49.00),
    (2, "Mouse", "Accessories", 25.00),
    (3, "Monitor", "Displays", 199.00),
    (4, "Headset", "Audio", 79.00),
    (5, "Webcam", "Video", 59.00),
    (6, "Laptop Stand", "Accessories", 35.00),
    (7, "Microphone", "Audio", 99.00),
    (8, "USB Hub", "Accessories", 29.00),
    (9, "Tablet", "Displays", 299.00),
    (10, "Speaker", "Audio", 89.00),
]
prices = {p[0]: p[3] for p in products}

print("USE shop;")

cust_rows = [
    f"({i}, 'user{i}', '{random.choice(countries)}', '{random.choice(plans)}')"
    for i in range(1, 201)
]
print("INSERT INTO customers VALUES " + ",".join(cust_rows) + ";")

prod_rows = [f"({p[0]}, '{p[1]}', '{p[2]}', {p[3]:.2f})" for p in products]
print("INSERT INTO products VALUES " + ",".join(prod_rows) + ";")

start = datetime(2026, 1, 1)
order_id = 1
for batch in range(5):
    rows = []
    for _ in range(2000):
        ts = start + timedelta(seconds=random.randint(0, 89 * 24 * 3600))
        pid = random.randint(1, 10)
        qty = random.randint(1, 4)
        rows.append(
            f"('{ts:%Y-%m-%d %H:%M:%S}', {order_id}, "
            f"{random.randint(1, 200)}, {pid}, {qty}, {qty * prices[pid]:.2f})"
        )
        order_id += 1
    print("INSERT INTO orders VALUES " + ",".join(rows) + ";")

The script prints SQL, so you can pipe it straight into the MySQL client inside the container. Exit your interactive session first (type exit), then run:

bash
python3 gen_data.py | docker exec -i quickstart \
  mysql -P 9030 -h 127.0.0.1 -u root

Notice that the orders are loaded as five statements of 2,000 rows each rather than 10,000 single-row inserts. That’s deliberate, and it reflects a rule that applies to every analytical database: batch your loads. Each load creates new data versions that must later be compacted, so a few large loads beat many tiny ones.

Reconnect and check the row counts:

bash
docker exec -it quickstart \
  mysql -P 9030 -h 127.0.0.1 -u root --prompt="StarRocks > "
sql
USE shop;
SELECT COUNT(*) FROM orders;
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM products;

You should see 10,000, 200, and 10.

Step 5: Your First Queries

Start with aggregations over the fact table alone:

sql
SELECT COUNT(*)      AS orders,
       SUM(amount)   AS revenue,
       AVG(amount)   AS avg_order_value
FROM orders;

Now group by month:

sql
SELECT date_trunc('month', order_time) AS month,
       COUNT(*)                         AS orders,
       SUM(amount)                      AS revenue
FROM orders
GROUP BY date_trunc('month', order_time)
ORDER BY month;

You should see three rows, January through March. These queries scan a few columns across ten thousand rows, which is trivial here. The point is the shape of the query: scan, filter, group, aggregate. That’s what StarRocks’ vectorized engine is built to do over billions of rows, processing columns in batches rather than row by row.

Step 6: Joins and Window Functions

Revenue by Country

Joining a fact table to a dimension table is bread-and-butter analytics:

sql
SELECT c.country,
       COUNT(*)      AS orders,
       SUM(o.amount) AS revenue
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.country
ORDER BY revenue DESC;

Many real-time analytics engines push you to flatten everything into one wide table because joins are expensive. StarRocks’ cost-based optimizer is designed so joins on normalized tables remain practical, which is why we kept customers and products as separate dimension tables.

Top Products With a Ranking
sql
SELECT p.name,
       p.category,
       SUM(o.amount) AS revenue,
       RANK() OVER (ORDER BY SUM(o.amount) DESC) AS revenue_rank
FROM orders o
JOIN products p ON o.product_id = p.product_id
GROUP BY p.name, p.category
ORDER BY revenue_rank;

The window function ranks products after aggregation. Standard SQL features like this are fully supported, so queries you’ve written for other databases usually work with minimal changes.

Distinct Counts

Exact distinct counts are expensive at scale, so analytical engines offer approximate versions:

sql
SELECT p.category,
       COUNT(DISTINCT o.customer_id)        AS exact_customers,
       APPROX_COUNT_DISTINCT(o.customer_id) AS approx_customers
FROM orders o
JOIN products p ON o.product_id = p.product_id
GROUP BY p.category;

On this tiny dataset the two columns will match or be very close. On a billion rows, the approximate version is dramatically cheaper, and the small error is usually acceptable for dashboards.

Step 7: Partition Pruning and Statistics

Now let’s see why we partitioned the orders table. Ask StarRocks for the plan of a query restricted to March:

sql
EXPLAIN
SELECT SUM(amount)
FROM orders
WHERE order_time >= '2026-03-01' AND order_time < '2026-04-01';

Scroll through the output to the scan node for orders and look for a line about partitions, typically shown as a fraction such as one partition selected out of the total. That’s partition pruning: StarRocks recognized that only the March partition could contain matching rows and skipped the others entirely. Run the same EXPLAIN without the WHERE clause and compare. The difference grows with data size.

Next, help the optimizer make good decisions by collecting statistics:

sql
ANALYZE TABLE orders;
ANALYZE TABLE customers;
ANALYZE TABLE products;

The optimizer uses table and column statistics to choose join orders and access paths. StarRocks can also collect them automatically, but running ANALYZE yourself after a big load is a good habit, and it’s one of the first things to check when a join query is slower than you expect.

Step 8: Upserts, Updates, and Deletes

Primary Key tables are where StarRocks differs most from append-only engines, so let’s exercise them.

Upsert by Loading a Duplicate Key
sql
SELECT * FROM customers WHERE customer_id = 1;

INSERT INTO customers VALUES (1, 'user1', 'IN', 'team');

SELECT * FROM customers WHERE customer_id = 1;

Customer 1 still appears exactly once, but with the new plan. Because the key matched, the new row replaced the old one, which is the replace-by-key behavior covered in Step 3.

UPDATE and DELETE Statements

Primary Key tables also support familiar statements:

sql
UPDATE customers SET plan = 'pro' WHERE customer_id = 2;

DELETE FROM customers WHERE customer_id = 200;

SELECT COUNT(*) FROM customers;

The count is now 199. This is the model to use for data synced from an operational database through change data capture, where rows are constantly modified and deleted. If you want to see that pattern end to end, our RisingWave guide shows how a streaming database can sink results into StarRocks Primary Key tables.

Updates resolve at write time in this model, so reads stay fast, which is the tradeoff against the merge-on-read approach of the older Unique Key tables.

Step 9: Create an Asynchronous Materialized View

Dashboards ask the same question over and over. A materialized view answers it once and keeps the result fresh. (cite index=”98-1″>StarRocks materialized views can be updated automatically during data import and are selected automatically when a query executes.

sql
CREATE MATERIALIZED VIEW daily_product_revenue
REFRESH ASYNC
AS
SELECT DATE(order_time) AS day,
       product_id,
       SUM(amount)      AS revenue,
       COUNT(*)         AS orders
FROM orders
GROUP BY DATE(order_time), product_id;

Materialized view syntax and refresh options differ between versions, so if this statement is rejected, check the documentation for your release. Once created, inspect it:

sql
SHOW MATERIALIZED VIEWS;
SELECT * FROM daily_product_revenue ORDER BY day, product_id LIMIT 10;

If the view is still building, give it a moment, or trigger a refresh manually:

sql
REFRESH MATERIALIZED VIEW daily_product_revenue;

Now the interesting part. Write a query that groups by day and product against the base table, then look at its plan:

sql
EXPLAIN
SELECT DATE(order_time) AS day, SUM(amount) AS revenue
FROM orders
GROUP BY DATE(order_time);

Check whether the plan reads from daily_product_revenue instead of orders. That’s the automatic rewrite. You didn’t change your query, the optimizer noticed a precomputed result could answer it and substituted the view. Whether a rewrite happens depends on the version and on settings, so if you don’t see it, consult the documentation on materialized view rewrite for your release.

Step 10 (Optional): Load Data With Stream Load

So far we’ve loaded through SQL. For files, StarRocks has a dedicated HTTP interface. (cite index=”111-1″>Stream Load transfers data to StarRocks over HTTP, allowing direct import of local data without relying on other systems or components.

First create a small CSV inside the container:

bash
docker exec -it quickstart bash -c "cat > /tmp/new_orders.csv <<'EOF'
2026-03-31 23:00:00,10001,5,3,2,118.00
2026-03-31 23:05:00,10002,17,9,1,299.00
2026-03-31 23:10:00,10003,42,1,4,196.00
EOF"

Then load it. Running curl from inside the container avoids a common networking snag, where the frontend redirects the request to a backend address your host machine can’t reach:

bash
docker exec -it quickstart curl --location-trusted -u root: \
  -H "label:orders_batch_1" \
  -H "column_separator:," \
  -H "columns:order_time,order_id,customer_id,product_id,quantity,amount" \
  -T /tmp/new_orders.csv \
  -XPUT http://127.0.0.1:8030/api/shop/orders/_stream_load

The response is a JSON document with a status field. A successful load reports a status of Success and the number of loaded rows. The label is worth noticing, since labels make loads idempotent: submitting the same label again won’t load the data twice. That’s useful when a pipeline retries after a network failure. Verify with:

sql
SELECT COUNT(*) FROM orders;

If the image doesn’t include curl, install it in the container or run Stream Load from a host where the backend port is reachable. In production setups, you’d more often use a connector from Flink, Kafka, or a streaming database rather than hand-built curl commands.

Step 11: Explore and Clean Up

A few commands show what you’ve built:

sql
SHOW TABLES;
SHOW CREATE TABLE orders\G
SHOW PARTITIONS FROM orders;
DESC customers;

SHOW PARTITIONS confirms the monthly partitions from Step 3. When you’re finished, drop everything:

sql
DROP MATERIALIZED VIEW daily_product_revenue;
DROP DATABASE shop;

Then stop the container:

bash
docker stop quickstart && docker rm quickstart

Troubleshooting Quick Reference

“Table replication num should be less than or equal to the number of available BE nodes.” You’re on a single-node cluster. Add PROPERTIES ("replication_num" = "1") to your CREATE TABLE.

Connection refused on port 9030. The container may still be starting. Check docker logs quickstart and retry in a minute.

Backends not alive. Run SHOW BACKENDS; and wait for Alive to become true before creating tables.

Partitioning syntax error. Expression partitioning depends on your version. Consult the CREATE TABLE documentation for the partitioning syntax your release supports.

Stream Load can’t connect or redirects fail. Run curl from inside the container, as shown above.

A join query is slow. Run ANALYZE TABLE on the tables involved, then check the EXPLAIN output for the join strategy and the order of tables.

Common Beginner Mistakes to Avoid

Using many tiny inserts. Batch your loads. Thousands of single-row inserts create a lot of small data versions that have to be compacted.

Using the wrong table type. Duplicate Key for append-only events, Primary Key for rows that change. Mixing them up leaves stale duplicates or needlessly constrains your data.

Choosing a low-cardinality bucketing key. A column with only a few distinct values piles data onto a few buckets. Pick something with many distinct values.

Skipping statistics. Join performance depends on the optimizer knowing your table sizes and value distributions.

Treating it as a transactional MySQL. The wire protocol is MySQL-compatible, but StarRocks is built for analytics, not for many small concurrent transactions.

Where to Go Next

With the basics down, there are several directions worth exploring:

  • Query a data lake. Create an external catalog for Iceberg, Hudi, Delta Lake, or Hive and join lake tables to your native ones. Our Apache Iceberg tutorial explains the format underneath.
  • Stream changes in. Connect Flink, Kafka, or a streaming database to keep Primary Key tables synchronized with an operational system.
  • Try shared-data mode. Run compute nodes over object storage to see storage and compute scale independently, a concept we compare with other engines in our ClickHouse architecture guide.
  • Compare engines. Run the same queries in ClickHouse using our ClickHouse tutorial and see how each handles the join-heavy ones.

Frequently Asked Questions

Do I need to know MySQL to use StarRocks? Not really, but it helps. StarRocks speaks the MySQL protocol, so MySQL clients connect directly, and the SQL feels familiar. If you know standard SQL, you can follow this tutorial.

Why did I need replication_num = 1? The default replication setting expects multiple backend nodes. A single-node test cluster has only one, so you must request one replica explicitly.

What’s the difference between a Duplicate Key table and a Primary Key table? A Duplicate Key table keeps every row, even rows with identical keys, which suits append-only events. A Primary Key table keeps one row per key and replaces older values when a matching key arrives, which suits mutable data.

What does partition pruning do? It lets the engine skip partitions that can’t match a query’s filter. If a table is partitioned by month and a query asks about March, only the March partition is read.

Is APPROX_COUNT_DISTINCT accurate? It returns an estimate with a small error, in exchange for being much cheaper than an exact distinct count on large data. It’s commonly used for dashboards where a tiny error is acceptable.

What is Stream Load? An HTTP-based loading interface. You send a file to StarRocks with an HTTP request, and it loads the data, using labels to make retries safe.

Why use ANALYZE TABLE? It collects statistics the cost-based optimizer uses to choose join orders and access paths. Fresh statistics after large loads help avoid poor query plans.

Can I use this tutorial’s setup in production? No. The all-in-one image is for learning and testing. Production deployments run separate FE and BE or CN nodes with replication, monitoring, and, optionally, shared-data storage on object storage.

Final Thoughts

You’ve now seen the full loop: design tables with the right model, load data in batches, query with joins and window functions, check partition pruning in a plan, handle changing data with a Primary Key table, and let a materialized view accelerate repeated questions. Each step mirrors a decision you’d make in a real deployment, only at a size that fits on a laptop.

The best next move is to replace the generated data with a slice of your own and rerun the queries you care about. For authoritative reference on every statement and option, StarRocks’ official documentation is the best place to go deeper.

For more hands-on guides to open-source data infrastructure and real-time analytics, keep exploring CourseDrill.

Popular Courses

Leave a Comment