SQL

SELECT

Asking a table for some of its columns, and nothing else.

After this lesson you can

  • Read specific columns out of a table
  • Rename a column in the output without touching the table
  • Explain why SELECT * is a habit worth dropping

A SQL query says what you want, not how to get it. You name the columns, you name the table, and the database works out the rest.

SELECT name, country
FROM customers;

Read it in the order the database does: FROM customers picks the table, then SELECT name, country picks the two columns to return. Every other column in the table is simply not in the answer.

Try it

Given — already loaded, nothing to run heresql
CREATE TABLE customers (  id      int PRIMARY KEY,  name    text NOT NULL,  country text NOT NULL,  credit  int  NOT NULL);INSERT INTO customers VALUES  (1, 'Nino Beridze', 'GE', 500),  (2, 'Ana Kapanadze', 'GE', 1200),  (3, 'Luka Meladze', 'DE', 0),  (4, 'Mari Tsiklauri', 'PL', 300);
Two columns from the customers tablepostgres-16
SELECT name, countryFROM customers;
What to look for

Renaming a column

AS renames a column in the output. The table is untouched; only the name in the result changes.

SELECT name AS customer, country AS market
FROM customers;

Why not SELECT *

SELECT * returns every column. It is fine while you are exploring, and a bad habit everywhere else:

  • it moves data you do not need across the network, on every row;
  • it breaks quietly when somebody adds a column, because your code is now reading a shape it has never seen;
  • it stops the database using an index that covers only the columns you actually wanted.

Naming the columns is two seconds of typing that says exactly what your code depends on.

Try it yourself

2 visible tests · 2 hidden tests

Table products(id, name, category, price). Return name and price for every product — those two columns, in that order, nothing else.

Given — already loaded, nothing to run heresql
CREATE TABLE products (  id       int PRIMARY KEY,  name     text NOT NULL,  category text NOT NULL,  price    numeric(10,2) NOT NULL);INSERT INTO products VALUES  (1, 'Notebook', 'stationery', 3.50),  (2, 'Desk lamp', 'office', 24.00),  (3, 'Pen', 'stationery', 1.20);
Loading editor…

Sign up to check the hidden tests and save your progress. Sign up