Skip to main content
SQL Fundamentals
1 / 5
0%

SELECT: choosing columns

0/4 solved4 to unlock next
Locked

Lesson 01

SELECT: choosing columns

Lesson Description

Pick the columns you want from a table.

Easy Project

Mini project: Turn this lesson into a real-world query artifact by writing one clean business report query and validating output quality.

The problem SELECT solves

A database table can hold dozens of columns, and most questions only need a few of them. Say the HR team asks: "Can you send me a list of everyone's name and salary?" The employees table in the HR sandbox has ten columns, including email, phone, manager and department. You do not want to hand over all of that. You want three columns, nothing more.

SELECT is how you say exactly which columns you want back. It is the first word of almost every query you will ever write, and everything else in this course builds on it. In this lesson you will learn to pick columns, rename them, and compute brand new values from the ones that already exist.

Syntax

SELECT column1, column2, ...
FROM table_name;

Two pieces are required for a normal query:

  • SELECT followed by a comma-separated list of what you want to see.
  • FROM followed by the table that holds the data.

The semicolon at the end marks the end of the statement. Most tools, including the editor on this site, will run a single query without it, but it is a good habit because it becomes mandatory once you put several statements in one script.

SQL keywords are not case sensitive, so select, SELECT and Select all work. The convention used on this site (and in most teams) is uppercase keywords and lowercase table and column names, which makes queries easier to scan.

Worked examples

Example 1: pick specific columns

Start with the HR request from the opening:

SELECT first_name, last_name, salary
FROM employees;

This returns 40 rows, one for every employee, with exactly three columns in the order you listed them. The first row is Steven King with a salary of 24000. Notice that you did not filter anything, so every row in the table comes back. You will narrow rows down with WHERE in the next lesson.

Column order in the result follows the order in your SELECT list, not the order in the table. If you write SELECT salary, last_name, salary comes first.

Example 2: every column with SELECT *

When you are exploring a table you have never seen, the asterisk is a handy shortcut for "all columns":

SELECT *
FROM departments;

You get 10 rows and three columns: id, name and location_id. It is the fastest way to learn what a table looks like.

Use * for exploration, not for finished queries. A saved query that says SELECT * silently changes its output whenever someone adds a column to the table, and it pulls data you do not need over the network. Listing columns explicitly also documents your intent for the next person who reads the query.

Example 3: calculated columns and aliases

SELECT can do more than copy columns. You can put any expression in the list, and give the result a readable name with AS. The store wants to preview a 10% discount on every product:

SELECT
  name,
  price,
  ROUND(price * 0.9, 2) AS sale_price
FROM products;

This runs against the store sandbox and returns 27 rows. Wireless Headphones at 199.99 shows a sale_price of 179.99, and the USB-C Hub at 49.95 shows 44.96. Without ROUND, the raw result of price * 0.9 would be 179.991 and 44.955, which is correct arithmetic but ugly on an invoice. ROUND(value, 2) keeps two decimal places.

The alias sale_price becomes the column header in the result. Without it, PostgreSQL would name the column round, after the function, which tells the reader nothing. Aliases only rename the output; the products table itself is unchanged.

You can combine columns with each other, too. Here is the value of stock on hand for each product:

SELECT name, price, stock, price * stock AS stock_value
FROM products;

Wireless Headphones: 199.99 times 45 units gives a stock_value of 8999.55.

Example 4: building text with ||

In PostgreSQL the || operator joins strings together. This is how you turn separate name columns into one display name:

SELECT
  first_name || ' ' || last_name AS full_name,
  salary * 12                    AS annual_salary
FROM employees;

The first rows read "Steven King" with an annual_salary of 288000, then "Neena Kochhar" and "Lex De Haan", both at 204000. The ' ' in the middle is a literal string containing one space. Without it you would get "StevenKing".

The same technique works in the hospital sandbox, where you might want a formal label for each doctor:

SELECT
  'Dr. ' || last_name AS doctor,
  specialty,
  hire_date
FROM doctors;

This returns 15 rows, starting with "Dr. Johnson", a Cardiologist hired on 2015-04-12. The text 'Dr. ' is the same on every row; the last name changes.

Example 5: when a piece is missing

The HR locations table has a state column, but only the US and Canadian offices fill it in. Six of the ten locations have no state at all, which the database stores as NULL (meaning "unknown" or "not applicable"). Watch what happens when you concatenate:

SELECT
  city,
  state,
  city || ', ' || state AS label
FROM locations;

For Southlake you get "Southlake, TX". For Roma, the label column is not "Roma, " as you might expect. It is NULL. Combining anything with NULL using || produces NULL, because the database cannot know what the full value would be.

PostgreSQL has a function built for this situation. CONCAT_WS(', ', city, state) joins its arguments with a separator and simply skips the ones that are NULL, so Roma becomes "Roma" and Southlake stays "Southlake, TX". You will dig into NULL properly in the next course; for now, just remember that it spreads through expressions.

Under the hood: why SELECT runs late

You write SELECT first, but the database does not evaluate it first. The logical order for the clauses in this course is:

StepClauseWhat happens
1FROMPick the table and read its rows
2WHEREThrow away rows that fail the condition
3SELECTCompute the output columns and aliases
4DISTINCTRemove duplicate output rows
5ORDER BYSort the result
6LIMIT / OFFSETKeep only part of the sorted result

This order explains a lot of behavior that seems odd at first. An alias like annual_salary is created at step 3, so WHERE (step 2) has never heard of it, while ORDER BY (step 5) can use it freely. Keep this table in mind; you will come back to it in every lesson of this course.

Common mistakes

Using an alias in WHERE

SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 150000;

PostgreSQL responds with column "annual_salary" does not exist. The alias is not built yet when WHERE runs. The fix is to repeat the expression:

SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 150000;

That returns 6 employees, from Steven King at 288000 down to Michael Hartstein at 156000.

Double quotes around text

SELECT "Dr. " || last_name FROM doctors;

The error is column "Dr. " does not exist. In PostgreSQL, double quotes mean "this is the name of a column or table", and single quotes mean "this is a piece of text". Write 'Dr. ' with single quotes.

A missing comma

SELECT first_name last_name
FROM employees;

This does not error, which makes it dangerous. Without the comma, PostgreSQL reads last_name as an alias for first_name, so you get one column called last_name containing values like "Steven" and "Neena". If a result has fewer columns than you expected, check your commas.

Surprising integer division

SELECT 7 / 2 returns 3, not 3.5. When both sides are integers, PostgreSQL does integer division and drops the remainder. Make one side a decimal (7 / 2.0) and you get 3.5. The salary and price columns in the sandboxes are numeric, so this mostly bites when you divide two integer columns, such as stock by a whole number.

How other databases differ

  • MySQL treats || as logical OR by default, not string concatenation. Use CONCAT(first_name, ' ', last_name) there. CONCAT also exists in PostgreSQL, and it treats NULL as an empty string.
  • SQL Server joins strings with + (or CONCAT) rather than ||.
  • SQLite supports || just like PostgreSQL.
  • Plain SELECT col FROM table with aliases via AS works the same way everywhere.

Practice

The exercises below this lesson run against the HR sandbox. You will list names for every employee, rename a column with an alias, compute a yearly figure from a monthly one, and pull a few columns from the jobs table in a specific order (a small preview of ORDER BY, covered two lessons from now). Check the column names in the prompt carefully: the grader compares your column names as well as your values.

Key takeaways

  • SELECT chooses which columns come back, in the order you list them; FROM names the table.
  • Prefer named columns over SELECT * in anything you plan to keep.
  • Any expression can be a column: arithmetic, ROUND, string concatenation with ||. Name it with AS.
  • NULL combined with || gives NULL; CONCAT_WS skips missing pieces.
  • SELECT is evaluated after FROM and WHERE, which is why WHERE cannot see your aliases.

SELECT: choosing columns: in depth

Almost every report starts by deciding which columns the reader actually needs. Naming columns explicitly instead of using SELECT * keeps results readable, makes queries survive schema changes, and moves less data over the network. Aliases let you rename columns into the labels a stakeholder expects without touching the table.

Worked examples

Pick and rename columns for a staff list

SELECT first_name AS "First name",
       last_name  AS "Last name",
       salary
FROM employees;

Returns one row per employee with exactly three columns. Double-quoted aliases keep spaces and capital letters in the output header.

Compute a column instead of storing it

SELECT first_name || ' ' || last_name AS full_name,
       salary,
       salary / 12 AS monthly_salary
FROM employees;

Expressions are evaluated per row. The concatenated name and the monthly figure exist only in the result, not in the table.

Common mistakes

  • Using SELECT * in saved queries: a new column added to the table silently changes the output shape of every report built on it.
  • Referencing an alias in WHERE of the same query (WHERE monthly_salary > 5000). Aliases are assigned after WHERE runs; repeat the expression or wrap the query.
  • Dividing two integers and expecting decimals. In PostgreSQL 7 / 2 is 3; cast one side (salary::numeric / 12) when precision matters.

Other databases

  • String concatenation is || in PostgreSQL, Oracle and SQLite, but CONCAT() or + in SQL Server and CONCAT() in MySQL.
  • MySQL quotes identifiers with backticks; PostgreSQL and the SQL standard use double quotes.
Check yourself: Why does SELECT salary * 1.1 AS raised FROM employees WHERE raised > 10000 fail?

WHERE is evaluated before the SELECT list, so the alias raised does not exist yet. Use WHERE salary * 1.1 > 10000.

Concept check

Quick check: SELECT: choosing columns

3 quick questions. One at a time. Instant score at the end.

Exercise 1

List all first and last names

Enterprise Workforce AnalyticseasyPostgreSQL

Return the first_name and last_name of every employee.

Autocomplete: start typing table/column namesPaste supported

No results yet

Run a query to see results here

Exercise 2

Rename the salary column

Enterprise Workforce AnalyticseasyPostgreSQL

Return every employee's first_name and their salary aliased as monthly_pay.

Autocomplete: start typing table/column namesPaste supported

No results yet

Run a query to see results here

Exercise 3

Compute annual salary

Enterprise Workforce AnalyticseasyPostgreSQL

Return first_name, last_name, and salary * 12 aliased as annual_salary for every employee.

Autocomplete: start typing table/column namesPaste supported

No results yet

Run a query to see results here

Exercise 4

Job titles and salary range

Enterprise Workforce AnalyticseasyPostgreSQL

Return title, min_salary, and max_salary from the jobs table, ordered by min_salary ascending.

Autocomplete: start typing table/column namesPaste supported

No results yet

Run a query to see results here

SQL Fundamentals
1 / 5
0%

SELECT: choosing columns

0/4 solved4 to unlock next
Locked