Before you begin
Start the on a 3-node CockroachDB demo cluster with a larger data set.Rule 1. Scan as few rows as possible
First, study the schema so you understand the relationships between the tables. Run :users table:
rides table. Let’s look at it:
rider_id field that you can use to match each ride to a user. There is also a start_time field that you can use to filter the rides by date.
This means that to get the information you want, you’ll need to do a on the users and rides tables.
Next, get the row counts for the tables that you’ll be using in this query. You need to understand which tables are large, and which are small by comparison. You will need this later if you need to verify you are using the right join type.
As specified by your command, the users table has 12,500 records, and the rides table has 125,000 records. Because it’s so large, you want to avoid scanning the entire rides table in your query. In this case, you can avoid scanning rides using an index, as shown in the next section.
Rule 2. Use the right index
Here is a query that fetches the right answer to your question: “Who are the top 10 users by number of rides on a given date?”users and rides tables (see spans: FULL SCAN). This tells you that you do not have indexes on the columns in your WHERE clause, which is .
Therefore, you need to create an index on the column in your WHERE clause, in this case: rides.start_time.
It’s also possible that there is not an index on the rider_id column that you are doing a join against, which will also hurt performance.
Before creating any more indexes, let’s see what indexes already exist on the rides table by running :
start_time or rider_id, so you’ll need to create indexes on those columns.
Because another performance best practice is to , create an index on start_time that stores the join key rider_id:
WHERE clause that stores the join key, let’s run the query again:
rides table. Instead, it is now doing a much smaller range scan against only the values in rides that match the index you just created on the start_time column (12,863 rows instead of 125,000).
Rule 3. Use the right join type
Out of the box, the will select the right join type for your statement in the majority of cases. Therefore, you should only provide in your query if you can prove to yourself through experimentation that the optimizer should be using a different than it is selecting. You can confirm that in this case the optimizer has already found the right join type for this statement by using a hint to force another join type. For example, you might think that a could perform better in this instance, since one of the tables in the join is 10x smaller than the other. In order to get CockroachDB to plan a lookup join in this case, you will need to add an explicit index on the join key for the right-hand-side table, in this case,rides.

