Start learning free

LESSON 35 OF 173 · BACKEND: SQL

Your First Query

Practice

The shop keeps its data in a database, a file called shop.db. Inside, the data sits in tables. A table is like a slice of structs that all have the same fields: each row is one item, and each column is one of its fields. The products table has one row per product, with the columns id, name, price, category and stock.

Go's database/sql package opens the file: sql.Open("sqlite", "shop.db") gives back a database handle, the thing your program talks to the database through, plus an error, which you can drop with _. Your questions are written in SQL, as a string. SELECT says which columns you want, and * means all of them; FROM says which table to read. This one reads every column of every customer:

var query = "SELECT * " +
	"FROM customers "

Go joins strings with +, so query holds one string, "SELECT * FROM customers ". A line that ends with + continues on the next line, so you can write one clause per line. That's why each piece ends with a space: it keeps the words apart. Put no + after the last piece, or Go keeps reading into the code below it.

The check runs your query and prints the column names, the rows and how many there are. The gift card has no category, so that value is NULL, SQL's word for "no value", like nil in Go. Your code must print:

id | name | price | category | stock
1 | Mug | 12 | kitchen | 10
2 | Notebook | 7 | office | 0
3 | Lamp | 29 | home | 1
4 | Pen | 2 | office | 120
5 | Plant | 15 | home | 6
6 | Teapot | 22 | kitchen | 4
7 | Stapler | 9 | office | 15
8 | Gift card | 50 | NULL | 999
(8 rows)

Your task: open shop.db with sql.Open and keep the handle in a package variable named db. Then write a query that reads every column of the products table.


Assignment
Follow the Coding Tutorial to open the shop's database and write your first query: every column, from the products table.


Hint
The driver's name and the file name are strings, so they go in quotes. In the query, each piece is its own string ending with a space, one per line, with a + at the end of every line but the last.


STEP 1 OF 3
    Ctrl + Enter to check