PostgreSQL Select

The SELECT statement is how you read data out of a PostgreSQL table, and nearly every other clause you'll learn attaches to it.

The SELECT Statement

A SELECT statement names the columns you want and the table to read them from. PostgreSQL executes the FROM clause first internally, then applies any filtering, and finally projects only the columns you listed. Column names are separated by commas, and the statement ends with a semicolon.

Selecting specific columns

SELECT name, department, salary
FROM employees;

Selecting All Columns

The asterisk (*) is shorthand for every column in the table, in the order they were defined. It's convenient while exploring data interactively, but it returns columns you may not need and breaks if the table's shape changes later.

Note: Avoid SELECT * in application code and views. Listing exact columns makes queries resilient to schema changes and documents intent for the next reader.

Aliases and Computed Columns

SELECT isn't limited to raw column names. You can rename output columns with AS, combine columns with expressions, call functions, and concatenate text, all within the same list. An alias only renames the result set; it never changes the underlying table.

Renaming and computing columns with AS

SELECT name,
       salary AS annual_salary,
       salary / 12 AS monthly_salary
FROM employees;
  • AS renames a column or expression in the result set
  • Arithmetic expressions (salary / 12) can appear directly in the column list
  • String concatenation uses the || operator, e.g. first_name || ' ' || last_name
  • Function calls like UPPER(name) can be used anywhere a column can

Removing duplicate rows with DISTINCT

SELECT DISTINCT department
FROM employees;
FormWhat it returns
SELECT col1, col2 FROM tOnly the named columns, in the order listed
SELECT * FROM tEvery column, in table definition order
SELECT DISTINCT col FROM tUnique values of col, duplicates removed
SELECT expr AS alias FROM tA computed value labeled with the alias

Exercise: PostgreSQL Select

What is a main downside of routinely using SELECT * in application queries?