Start learning free

LESSON 36 OF 188 · BACKEND: SQL

Choose the Columns in Python

Practice

Last lesson, SELECT * gave you every column of the table. Most of the time you need fewer. A price list, for example, only needs each product's name and price, not its id, category or stock.

After SELECT, write the column names you want, separated by commas, without quotes. The answer has only those columns, in the order you list them. This reads each customer's name and city, and nothing else:

query = (
    "SELECT name, city "
    "FROM customers "
)

Choosing columns doesn't drop any rows: you still get one row per customer, just narrower. And you still need FROM: a column only exists inside a table, so without it the database answers no such column.

Your query must print:

name | price
Mug | 12
Notebook | 7
Lamp | 29
Pen | 2
Plant | 15
Teapot | 22
Stapler | 9
Gift card | 50
(8 rows)

Your task: the connection db is already open. Write a query that reads each product's name, then its price, from the products table.


Assignment
Follow the Coding Tutorial to write a query that picks two columns of the products table: the name and the price.


Hint
Column names go after SELECT as plain words, with a comma between them. Keep the space at the end of each piece of the string, so the two lines don't run together.


STEP 1 OF 2
    Ctrl + Enter to check

    Sql Select Columns in Python

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