For the complete documentation index, see llms.txt. This page is also available as Markdown.

Explore SQL Capabilities

Use the GridGain 9 SQL command-line interface to build, populate, and query the sample Chinook database on a distributed cluster.

This guide walks you through using GridGain 9 SQL capabilities via the command-line interface. You'll set up a distributed Apache GridGain cluster, create and manipulate the Chinook database (a sample database representing a digital media store), and learn to leverage GridGain's powerful SQL features.

GridGain 9 SQL is a distributed, ANSI-based SQL dialect and differs from MariaDB Server SQL in both syntax and supported features. For the full list of supported statements, functions, and data types, see the SQL Reference.

Prerequisites

  • Docker and Docker Compose installed on your system;

  • Basic familiarity with SQL;

  • Command-line terminal access;

  • 8GB+ of available RAM for running the containers;

  • SQL directory with Chinook Database files downloaded.

Before Starting

This tutorial uses prepared files to streamline deployment. Make sure you have downloaded the required files:

Unpack the archive into a new folder, and place it and the docker compose file in the same directory where you will be running the Docker CLI commands. The tutorial expects these SQL files to be available and mounted to the container.

Setting Up a GridGain 9 Cluster

Before we can start using SQL, we need to set up a GridGain cluster. We will use Docker Compose to create a three-node cluster.

Starting the Cluster

Open a terminal in the directory containing the docker compose file docker-compose.yml file and start the cluster with Docker:

This command starts the cluster in detached mode. You should see startup messages from all three nodes. When they are ready, you will see messages indicating that the servers have started successfully.

You can check that all containers are running with the following command:

You should see all three nodes with a "running" status.

Verify that all three nodes are "running" before continuing.

Connecting to the Cluster Using GridGain CLI

Now we will connect to our running cluster using GridGain command-line interface (CLI).

Starting the CLI

In your terminal, run:

This starts an interactive CLI container connected to the same Docker network as our cluster and mounts a volume containing the sql files for the Chinook Database. When prompted, refuse the connection to the default node and connect to node1 by entering:

You should see a message that you're connected to http://node1:10300 and a note that the cluster is not initialized.

The CLI container runs separately from the cluster nodes, but connects to them over the Docker network.

Initializing the Cluster

Before we can use the cluster, we need to initialize it:

If the license is not available, make sure the license file was mounted correctly.

Creating the Chinook Database Schema

Now that our cluster is running and initialized, we can start using SQL to create and work with data in GridGain. The Chinook database is a digital music store dataset, with tables for artists, albums, tracks, customers, and sales.

Entering SQL Mode

To start working with SQL, enter SQL mode in the CLI:

Your prompt should change to sql-cli> indicating you're now in SQL mode.

Creating Distribution Zones

Before we create tables, let's set up distribution zones to control how our data is distributed and replicated across the cluster:

These commands create two zones:

  • Chinook - Standard zone with 2 replicas for most tables;

  • ChinookReplicated - Zone with 3 replicas for frequently accessed reference data.

Database Entity Relationship

Here's the entity relationship diagram for our Chinook database:

Entity relationship diagram of the Chinook sample database

Creating Core Tables

Now let's create the main tables for the Chinook database. We will start with the Artist and Album tables.

Copy and paste the following SQL blocks at the sql-cli> prompt then hit enter.

The COLOCATE BY clause in the Album table ensures that albums by the same artist are stored on the same nodes. This optimizes joins between Artist and Album tables by eliminating the need for network transfers during queries.

Next, let's create the Genre and MediaType reference tables:

These reference tables are placed in the ChinookReplicated zone with 3 replicas because they contain static data that is frequently joined with other tables. Having a copy on each node improves read performance.

Now, let's create the Track table, which references the Album, Genre, and MediaType tables:

Tracks are colocated by AlbumId, not by TrackId, because most queries join tracks with their albums. This colocation optimizes these common join patterns.

Let's also create tables to manage customers, employees, and sales:

Invoices are colocated by CustomerId and InvoiceLines are colocated by InvoiceId. This creates an efficient chain of locality: Customer → Invoice → InvoiceLine, optimizing queries that analyze customer purchase history.

Finally, let's create the playlist-related tables:

Note that PlaylistTrack is not colocated with Track. This is a design decision that prioritizes playlist operations over joining with track details. In a real-world scenario, you might make a different colocation choice depending on your most common query patterns.

Verifying Table Creation

Let's confirm that all our tables were created successfully:

This query checks the system tables to verify that our tables exist. You should see a list of all the tables we've created.

Checkpoint: Verify that all tables appear in the system.tables output with their proper zones and colocation settings before proceeding to the next section.

Inserting Sample Data

Now that we have our tables set up, let's populate them with sample data.

Adding Artists and Albums

Let's start by adding some artists.

  • Exit the interactive sql mode by typing exit;.

  • Then, load the current store catalog from the sql data file.

Adding Genres and Media Types

Let's populate our reference tables the same way:

Adding Tracks

Now let's add some tracks to our albums:

Adding Employees and Customers

Let's add some employee and customer data:

Adding Invoices and Invoice Lines

Finally, let's add some sales data:

Checkpoint: Verify that all the data has been loaded successfully by checking that the "Updated X rows" messages match the expected row counts for each file.

Querying Data in GridGain SQL

Now that we have data in our tables, let's run some SQL queries to explore the Chinook database.

Basic Queries

Let's return to the sql-cli> and start with some simple SELECT queries:

Joins

Now let's try some more complex queries with joins:

This complex query uses multiple CTEs to achieve what would typically be done with the RANK() window function. We first count tracks per album, then determine the maximum track count per artist, and finally join these results to identify albums with the most tracks for each artist.

Data Manipulation in GridGain SQL

Let's explore how to modify data using SQL in GridGain.

Understanding Distributed Updates

When you update data in a distributed database, the changes need to be coordinated across multiple nodes:

Diagram of how updates are coordinated and propagated across nodes in a distributed database

Inserting New Data

Let's add a new artist and album:

Updating Existing Data

Now let's update some of our existing data:

In a distributed database like GridGain, these updates are automatically propagated to all replicas. The primary copy is updated first, then the changes are sent to the backup copies on other nodes.

Deleting Data

Finally, let's clean up by deleting the data we added:

Advanced SQL Features

Let's explore some of GridGain's more advanced SQL features.

Querying System Views

GridGain provides system views that let you inspect cluster metadata:

System views provide important metadata about your cluster configuration. They are essential for monitoring and troubleshooting in production environments.

Creating Indexes for Better Performance

Let's add some indexes to improve query performance:

Indexes improve query performance, but come with maintenance costs. Each write operation must also update all indexes. Choose indexes that support your most common query patterns rather than indexing everything.

Creating a Dashboard Using SQL

Let's create SQL queries that could be used for a music store dashboard. These queries could be saved and run periodically to generate reports.

Monthly Sales Summary

This query formats the year and month into a sortable string (YYYY-MM) while calculating several key business metrics.

Top Selling Genres

Sales Performance by Employee

Top 20 Longest Tracks with Genres

Customer Purchase Patterns by Month

Performance Tuning with Colocated Tables

One of the key advantages of GridGain is its ability to optimize joins through data colocation. Let's explore this with our existing colocated tables.

Colocated Queries

Let's start by looking at a query where there is a mismatch in the colocation strategy.

If we create the InvoiceLine table to be colocated by InvoiceId, we end up with a mismatch for our query.

  • Album is colocated by ArtistId

  • Track is colocated by AlbumId

  • InvoiceLine is colocated by InvoiceId

This means that when you run a query joining InvoiceLine, Track, and Album, the data might be spread across different nodes because they're colocated on different keys. Our query is looking for invoice ID 1, then joining with Track and Album, but these tables are colocated on different keys.

Key Observations in the Execution Plan

ColocatedHashAggregate Operation: The plan uses a ColocatedHashAggregate operation, which indicates GridGain recognizes that portions of the aggregation can happen on colocated data before results are combined. This reduces network transfer during the GROUP BY operation.

Exchange Operations: Several Exchange(distribution=[single]) operations appear in the plan, indicating data movement between nodes is still necessary. These operations are applied to the Album table, Track table, and InvoiceLine filtered results.

Join Implementation: The plan shows a combination of HashJoin and MergeJoin operations rather than nested loop joins. The optimizer has determined these join types are more efficient for the data volumes involved:

  • HashJoin for joining Track with Album

  • MergeJoin for joining the above result with InvoiceLine

Efficient Data Access: The query uses an IndexScan with the IDX_INVOICELINE_INVOICE_TRACK index rather than a full table scan on InvoiceLine. This provides:

  • Efficient filtering with searchBounds: [ExactBounds [bound=1], null] for InvoiceId = 1

  • Pre-sorted results with collation: [INVOICEID ASC, TRACKID ASC]

Row Count Estimation: There appears to be a significant increase in estimated row counts after joins:

  • Initial InvoiceLine filtered rows: 746

  • After HashJoin with Album: 182,331

  • After MergeJoin with Track: 20,400,668

Improved Cololocation Strategy

However, if we create the InvoiceLine table to be colocated by TrackId, we dramaticly optimize our query.

And run EXPLAIN PLAN FOR again...

Key Observations in the Execution Plan

ColocatedHashAggregate Operation: The plan uses a ColocatedHashAggregate operation, which indicates GridGain recognizes that portions of the aggregation can happen on colocated data before results are combined. This reduces network transfer during the GROUP BY operation.

Improved Row Count Estimates: Notice the dramatic improvement in row count estimates, which now show just 1 row at each step. This indicates the optimizer has much better statistics and understanding of the actual data distribution compared to the original plan that estimated millions of rows.

Join Implementation: The plan shows a combination of HashJoin and MergeJoin operations:

  • HashJoin for joining Track with InvoiceLine

  • MergeJoin for joining the above result with Album

Efficient Index Usage: The query now uses the composite index IDX_TRACK_ALBUMID_NAME on the Track table, providing:

  • Efficient sorted access by AlbumId and Name

  • Direct access to the fields needed for the join and select operations

Exchange Operations: While Exchange operations still appear in the plan, the estimated row counts are now minimal (just 1 row per exchange). This suggests much less data movement between nodes compared to the original plan where millions of rows were estimated to be transferred.

Colocation Impact

The substantial improvement in this execution plan demonstrates the power of proper data colocation in GridGain. By:

  1. Structuring the query to join the tables in the optimal order (Track → Album → InvoiceLine)

  2. Creating appropriate supporting indexes

  3. Ensuring proper colocation between related tables

We've achieved a dramatic reduction in estimated row counts and data movement. The execution plan now shows streamlined operations with minimal row estimates at each step, indicating an efficient execution path that takes advantage of data locality.

This optimization approach highlights three key principles for optimal performance in distributed SQL databases:

  • Proper colocation of related data

  • Supporting indexes aligned with join patterns

  • Query structure that follows the colocation model

Cleaning Up

When you are finished with the GridGain SQL CLI, you can exit by typing:

This will return you to the GridGain CLI. To exit the GridGain CLI, type:

To stop the GridGain cluster, run the following command in your terminal:

This will stop and remove the Docker containers for your GridGain cluster.

Best Practices for GridGain SQL

To get the most out of GridGain SQL, follow these best practices:

Schema Design

  • Use appropriate colocation for tables that are frequently joined;

  • Choose primary keys that distribute data evenly across the cluster;

  • Design with query patterns in mind, especially for large-scale deployments.

Query Optimization

  • Create indexes for columns used in WHERE, JOIN, and ORDER BY clauses;

  • Use the EXPLAIN statement to analyze and optimize your queries;

  • Avoid cartesian products and inefficient join conditions.

Transaction Management

  • Keep transactions as short as possible;

  • Do not hold transactions open during user think time;

  • Group related operations into a single transaction for atomicity.

Resource Management

  • Monitor query performance in production;

  • Consider partitioning strategies for very large tables;

  • Use appropriate data types to minimize storage requirements.

What's Next

GridGain's SQL capabilities make it a powerful platform for building distributed applications that require high throughput, low latency, and strong consistency. By following the patterns and practices in this guide, you can leverage GridGain SQL to build scalable, resilient systems.

Remember that GridGain is not just a SQL database—it's a comprehensive distributed computing platform with capabilities beyond what we've covered here. As you become more comfortable with GridGain SQL, you may want to explore other features such as compute grid, machine learning, and stream processing.

Happy querying!

See Also

This page is: Copyright © 2026 MariaDB. All rights reserved.

spinner

Last updated

Was this helpful?