SELECT FROM

The first, most basic operation is to get all data from a table. We can do this with the SELECT and FROM clauses. Let's go back to the hypothetical dating app, "Teender", that stores its users in a table named daters. We can get all the data from daters like so:

SELECT *
FROM daters;
name
VARCHAR
height_cm
INTEGER
eye_color
VARCHAR
Ray
180
brown
Florence
167
blue
Claude
156
brown
Kim
178
blue
Frederick
170
green
Anita
188
brown

We've fetched all rows and all columns from the daters table.

The FROM clause specifies the table we are sourcing from. In this case, daters is the table name. The SELECT clause specifies what you want from that table. Here, * is a special shortcut for all columns. So this query simply gets the entire table without any transformations.

Specific Columns

What if we don't want all the columns? We can control this in the SELECT clause. For example:

SELECT name, eye_color
FROM daters;
name
VARCHAR
eye_color
VARCHAR
Ray
brown
Florence
blue
Claude
brown
Kim
blue
Frederick
green
Anita
brown
SELECT name, height_cm
FROM daters;
name
VARCHAR
height_cm
INTEGER
Ray
180
Florence
167
Claude
156
Kim
178
Frederick
170
Anita
188

Instead of *, we list the column names we want in a comma-separated list.

As mentioned before, clauses represent relational algebra operations, or transformations on a table. Here is a visual way to represent this transformation.

col_1 1 2 3 4 5 ... ... ... ... ... col_2 ... ... ... ... ... col_4 ... ... ... ... ... col_5 ... ... ... ... ... col_3 col_1 1 2 3 4 5 ... ... ... ... ... col_2 ... ... ... ... ... col_4 ... ... ... ... ... col_5 ... ... ... ... ... col_3 col_1 1 2 3 4 5 ... ... ... ... ... col_4 ... ... ... ... ... col_3 col_1, col_3, col_4 SELECT

Generally, to select columns we want, we need to know which columns are available. In practice, one way to know the column names is to SELECT * FROM table_name first, then see the columns in the result.

A better way is to look at a diagram like this:


daters
column_name type
name
VARCHAR
height_cm
INTEGER
eye_color
VARCHAR

It shows the names and types for each column. Remember that the type is the kind of data in the column. We'll look at this more in the next section.

Aliasing

The SELECT clause can do more than just select columns, it can also alias them. This is done by adding AS new_name after the column.

SELECT
  name AS first_name,
  height_cm
FROM daters;
first_name
VARCHAR
height_cm
INTEGER
Ray
180
Florence
167
Claude
156
Kim
178
Frederick
170
Anita
188

Notice how name was changed to first_name, but height_cm was left alone. This isn't a permanent rename. It only applies to this query.

© 2022 Andrew Carlson. All rights reserved.