Start learning free

LESSON 62 OF 173 · BACKEND: SQL

Indexes in Go

Practice

To find the rows a WHERE asks for, SQLite needs a way in. With no help it reads the whole table, row by row: a scan. An index is a sorted list of one column's values, each pointing to its rows, like the index at the back of a book. With one, SQLite can search: jump straight to the matching rows.

You create an index with CREATE INDEX, a name, then ON, the table and the column in brackets. For example, an index for finding the order lines of a product:

var createIndex = "CREATE INDEX idx_items_product_id ON order_items (product_id) "

To see what SQLite does, put EXPLAIN QUERY PLAN in front of a query: instead of the rows, it answers its plan. An index never changes which rows a query finds, only how it finds them.

The check prints the plan of query, runs createIndex, then prints the plan again. It must show:

Plan: SCAN orders
Plan: SEARCH orders USING INDEX idx_orders_customer_id (customer_id=?)

Your task: write query, the plan of a query that finds the orders of customer 1, and createIndex, an index named idx_orders_customer_id on the customer_id column of orders.


Assignment
Follow the Coding Tutorial to write the query first, put EXPLAIN QUERY PLAN in front of it, then declare createIndex.


Hint
The query is SELECT * from orders with a WHERE on customer_id, one string per line, joined with +. EXPLAIN QUERY PLAN goes on the empty line right below var query =, in front of SELECT.


STEP 1 OF 5
    Ctrl + Enter to check

    Sql Indexes in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free