Start learning free

LESSON 35 OF 188 · 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 list of dicts that all have the same keys: each row is one item, and each column is one of its keys. The products table has one row per product, with the columns id, name, price, category and stock.

Python's sqlite3 module opens the file: sqlite3.connect("shop.db") gives back a connection, the line your program talks to the database through. 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:

query = (
    "SELECT * "
    "FROM customers "
)

Python glues strings that sit side by side inside parentheses, so query holds one string, "SELECT * FROM customers ". That's why each piece ends with a space: it keeps the words apart. Put no comma between the pieces, or Python makes a tuple instead of a string.

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 None in Python. 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 and keep the connection in a 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 file name is a string, so it goes in quotes. In the query, each piece is its own string ending with a space, one per line inside the parentheses, with no comma between them.


STEP 1 OF 3
    Ctrl + Enter to check