Create Tables and Query Data With SQL
Create tables, run queries, and use EXPLAIN to understand colocated query execution in GridGain SQL.
Introduction
A multi-table JOIN in a single-node database is straightforward. In a distributed cluster, the same JOIN might execute locally on each node or move data across the network. The difference depends on how you designed your schema: colocation applies only between tables that are partitioned by the same join key. In this tutorial, you run both kinds of joins against the Music Store dataset from the first tutorial, read the EXPLAIN plans, and see exactly where the data moves.
Prerequisites
A running 3-node cluster with the Music Store dataset loaded from Start Your Local GridGain 9 Development Cluster
Familiarity with the GridGain CLI. See How to Work with the GridGain CLI for the full reference.
What You Will Learn
How to create tables and assign them to distribution zones
How to insert, update, and delete data with SQL
How to query data with filters, joins, and aggregations
How EXPLAIN reveals colocated vs. distributed query execution
Step 1: Connect to the SQL CLI
If you are continuing directly from the previous tutorial, you are already at the sql-cli> prompt. Skip to Step 2.
Otherwise, open the GridGain CLI inside a running node:
At the CLI prompt, connect to the cluster and enter the SQL sub-REPL:
The prompt changes to sql-cli>. Enter all SQL statements in this tutorial at this prompt. Each statement must end with a semicolon.
Step 2: Create a Scratch Table
The 11 Music Store tables already exist from the previous tutorial. To learn the DDL syntax without repeating that work, create a small scratch table that you can experiment with and drop at the end.
Create a Bookmark table in the MusicStore zone:
Updated 0 rows. is normal for DDL: it modifies schema, not data. ZONE MusicStore assigns the table to the same distribution zone as the other business data tables, giving it 2 replicas across the 3-node cluster.
Verify the table exists:
SYSTEM.TABLES is one of several system catalog views (alongside SYSTEM.ZONES and SYSTEM.INDEXES) that you can query like regular tables.
Step 3: Insert, Update, and Delete Data
The table exists but is empty. Populate it with a few rows to see how DML works in GridGain SQL:
Add several more rows in one statement:
Multi-row INSERT sends all values in a single round-trip to the cluster. Verify:
Four rows, and the column headers confirm the uppercase normalization from Step 2: BOOKMARKID, not BookmarkId.
Now modify existing data. Update a label:
And remove a row:
All DML operations report Updated N rows. in the CLI. Verify:
Three rows remain after deleting the workout track.
How did the engine find the row to update? EXPLAIN works on DML too:
KeyValueModify with key: [1] writes the row directly by its primary key. There is no scan, no Exchange, and no other partition involved. The WHERE BookmarkId = 1 predicate routes the operation to the single node that owns that key. This is why primary key design matters in a distributed database: it determines which node handles the write.
Step 4: Query With Filters and Sorting
You know how to create, populate, and modify a table. Now turn to the 3,503-row Track table and see what the Music Store dataset looks like under real queries.
Find the five longest Rock tracks (Genre ID 1 is Rock):
"Dazed And Confused" appears twice: track IDs 1666 and 1581 are different recordings with different durations. The Name column has no uniqueness constraint and no index. How do you know? Prefix any query with EXPLAIN to see how the engine executes it:
TableScan with no index lookup: the engine reads every Track row on every partition to evaluate the predicate. The est: (rows=1166) is the planner's estimate of how many rows it scans, not how many it returns.
For 3,503 rows on a development cluster, this is fast enough. On a production dataset, you would create an index: CREATE INDEX idx_track_name ON Track (Name);
To disambiguate the two recordings, join to Album:
Two live recordings from different albums. Track is partitioned by AlbumId, but Album is partitioned by ArtistId, so this join is not a colocated join and the cluster may move data to match the rows. For production workloads that filter by Name frequently, you would create an index: CREATE INDEX idx_track_name ON Track (Name);
Search for tracks by name using a pattern match:
LIKE '%Love%' matches "Love" anywhere in the track name. The search is case-sensitive: %love% would miss "All My Love."
Use arithmetic expressions in the SELECT list to convert milliseconds to minutes:
The longest "tracks" are 49-88 minutes. These are TV show episodes stored alongside music in the catalog, not songs.
Step 5: Join Colocated Tables
So far, EXPLAIN has shown two patterns: direct primary key access (KeyValueModify) for primary key operations (Step 3), and TableScan for unindexed filters (Step 4). Joins introduce a third question: does the data need to move between nodes before the join can execute? The previous tutorial set up the Music Store tables with COLOCATE BY clauses. Artist and Album are a colocated pair by ArtistId, but Track is colocated by a different column, AlbumId. Join Artist, Album, and Track to see what that means for the plan:
Led Zeppelin has 114 tracks across 14 albums. Album colocates by ArtistId, so each Led Zeppelin album sits in the same partition as the artist row. Track colocates by AlbumId, so all tracks of one album share a partition with each other, but a track is not placed with its Album row or its Artist row. Colocation is decided only by the columns a table hashes for its own rows, and it does not chain through a middle table. The query returns correct results, but the join to Track moves data between nodes.
Start with the colocated pair. This two-table join of Artist and Album uses the same filter:
The only Exchange sits at the top of the plan, where the coordinator collects the final rows. No Exchange appears between the two TableScan inputs of the HashJoin, so Artist and Album join locally on each node. Both tables are colocated by ArtistId, which is the join key.
Now add Track, which is colocated by AlbumId, a different column. EXPLAIN shows the difference:
Read the plan from bottom to top. Two TableScan operators read ALBUM and ARTIST, and a HashJoin combines them on ARTISTID. An Exchange then redistributes the joined rows with distribution: table PUBLIC.TRACK in zone MUSICSTORE by [ALBUMID], which sends each row to the partition that holds the matching Track rows. A second HashJoin combines that result with the Track TableScan on ALBUMID. The top Exchange collects the final rows on the coordinator. The Exchange operators with distribution: single above the ALBUM and ARTIST scans gather those rows on one node before the inner join. For this three-table query the planner picks a different strategy than for the two-table query, so you cannot read the locality of the Artist-Album pair from this plan alone. The Exchange by [ALBUMID] is the one that shows the colocation boundary.
In Step 4, the single-table plan had one Exchange that collected results. The two-table plan also has one Exchange, at the top, because Artist and Album are colocated by the join key. The three-table plan has more Exchange operators, including one between the Artist-Album join and the Track join that redistributes rows by AlbumId, because Track is partitioned by AlbumId, not ArtistId. Colocation helps the join it was designed for and does not extend to the next table.
What happens when colocation does not apply? Track is colocated by AlbumId and InvoiceLine is colocated by InvoiceId. Neither is placed by TrackId, so joining them by TrackId crosses colocation boundaries:
The structure flipped. Two Exchange operators now appear below the HashJoin, one for each table input. The planner must pull all matching InvoiceLine rows (estimated 2,240) and all matching Track rows (estimated 1,166) to a single node before the join can execute. That is a full data shuffle for a query that returns 10 rows.
On this 3-node dev cluster with 3,503 tracks, the shuffle completes in milliseconds. In production with millions of rows across dozens of nodes, the cost scales linearly with data volume and cluster size. A colocated join stays constant: each node joins its local data regardless of how many nodes the cluster has.
The pattern: in the colocated two-table plan, Exchange sits above the join (collecting results). In the three-table and non-colocated plans, Exchanges sit below a join (moving data). Where Exchange appears relative to Join tells you whether a join scales with your cluster or fights it.
When you design your own schema, you choose which join paths to optimize with colocation. The Music Store colocates Artist with Album, Customer with Invoice, and Playlist with PlaylistTrack. Those pairs are the hot paths for catalog browsing and revenue analysis. Colocation does not chain, so adding a third table such as Track or InvoiceLine, or joining Track to InvoiceLine, still works but pays the network cost. One colocation key per table, one optimized pair.
Step 6: Aggregate and Analyze
Now put those joins to work with aggregation. Genre lives in the MusicStoreReplicated zone (3 replicas, one per node), so the Track-to-Genre join resolves locally:
Rock dominates at 1,297 tracks with a 4.7-minute average. TV Shows (35.7 min), Drama (42.9 min), and Sci Fi & Fantasy (48.5 min) have high averages because those genres contain video episodes, not songs.
Customer and Invoice are colocated by CustomerId, so revenue aggregation also runs locally. Use HAVING to keep only countries with 10 or more orders:
Nine countries have 10 or more orders. The USA leads with 91 orders and $523.06 in revenue. How does the engine handle aggregation across a distributed dataset? EXPLAIN the revenue query:
A new pattern. Read from the bottom:
The
HashJoinbetween INVOICE and CUSTOMER has no Exchange between its inputs (colocated byCustomerId).Above that,
MapHashAggregateruns the COUNT and SUM locally on each node.The results cross the Exchange to
ReduceHashAggregate, which combines the per-node partial aggregates into the final answer.The
Filterat the top applies theHAVINGclause after the aggregation is complete.
This is a map-reduce pattern: compute locally, combine centrally.
Combine the three-table join with aggregation to rank the top 10 artists by catalog value:
Iron Maiden leads with 213 tracks across their discography. "Lost" and "The Office" rank high because the dataset includes TV show episodes priced at $1.99 each, which inflates their catalog value relative to $0.99 music tracks.
The GROUP BY includes both a.ArtistId and a.Name. Grouping by ArtistId (the unique identifier) avoids collisions if two artists share the same name; a.Name is included so it can appear in the SELECT list.
Step 7: Clean Up the Scratch Table
The scratch table has served its purpose. Drop it so future tutorials start with a clean 11-table schema:
Verify the table is gone:
The Music Store data remains intact for future tutorials. Type exit; to leave the SQL sub-REPL, then exit again to close the CLI.
Summary
Throughout this tutorial, EXPLAIN revealed how the engine handles each type of operation:
Primary key operations use direct key access (
KeyValueModifyfor writes) to route straight to the owning node (Step 3).Unindexed filters produce a
TableScanacross every partition. Create indexes for columns you filter on frequently (Step 4).Colocated joins (tables partitioned by the same join key, such as Artist and Album) execute locally with no Exchange between the join inputs. Joins that add a table partitioned by a different column, such as Track, shuffle data through an Exchange below the join. Colocation does not chain through a middle table (Step 5).
Distributed aggregation uses a map-reduce pattern:
MapHashAggregatecomputes locally,ReduceHashAggregatecombines results across the Exchange (Step 6).
Two other GridGain-specific behaviors to remember:
System catalog views (
SYSTEM.TABLES,SYSTEM.ZONES,SYSTEM.INDEXES) expose cluster metadata as queryable tables.Uppercase normalization applies to all SQL identifiers in the catalog and query results, regardless of the case used in DDL.
Data locality is the thread running through every plan you read in this tutorial:
Colocated joins between a true pair, such as Artist and Album, execute on each node without crossing the network between join inputs.
Map-reduce aggregation computes partial results locally, then combines them across the Exchange.
Primary key operations route directly to the node that owns the key.
The same principle extends beyond SQL: the Compute API pushes application code to the node that owns the data, eliminating the network round-trip. See About Distributed Computing for that pattern.
The cluster and dataset are ready for the next step: writing a Java application that connects to the cluster and works with the same data through the thin client API.
Next Step
Continue to Connect with the Java Thin Client to build a Java application that connects to this cluster and works with the same data through the Table API. You'll use RecordView, KeyValueView, and SQL from Java code.
Related
Start Your Local GridGain 9 Development Cluster for the cluster setup and dataset loading this tutorial builds on
How to Work with the GridGain CLI for the full CLI reference: file loading, output formatting, cluster inspection
Connect with the Java Thin Client for the Java thin client, Table API, and RecordView
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

