Start learning free

LESSON 36 OF 173 · BACKEND: SQL

Choose the Columns in Java

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:

String query = "";
query += "SELECT name, city ";
query += "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 SQLite answers no such column and show throws an exception.

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. Add to query the pieces that read 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 pieces don't run together when += joins them.


STEP 1 OF 2
    Ctrl + Enter to check

    Sql Select Columns in Java

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