Sub topic 2
Choosing columns instead of using *
This chapter assumes you know what a table, row, and column are. It also assumes you can run SQL in PostgreSQL, MySQL, or SQLite and have written a basic SELECT ... FROM. Here you will learn what the select list is, what * does, and why named columns are the safer choice in most real work.
The select list
The part of a query between SELECT and FROM is the select list. It decides which columns appear in the result, and in what order. The list is separated by commas:
SELECT first_name, last_name, salary
FROM employees;This returns every row of employees, but only three columns. The columns appear in the order you wrote them. That order does not have to match the order in the table definition.
The examples in this chapter use an employees table. To follow along, create it with this script. It works in PostgreSQL, MySQL, and SQLite.
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary NUMERIC(10, 2),
hire_date DATE,
manager_id INTEGER
);
INSERT INTO employees VALUES (1, 'Ada', 'Lovelace', 'Engineering', 95000, '2019-03-01', NULL);
INSERT INTO employees VALUES (2, 'Grace', 'McKay', 'Sales', 52000, '2021-06-15', 1);
INSERT INTO employees VALUES (3, 'Linus', 'Berg', 'Support', 41000, '2022-01-10', 1);
INSERT INTO employees VALUES (4, 'Mara', 'McNeil', 'Sales', 58000, '2020-09-30', 2);What * means
The asterisk is shorthand for "every column in the table, in table order":
SELECT *
FROM employees;For this table, the result has seven columns: employee_id, first_name, last_name, department, salary, hire_date, and manager_id.
The database expands * into the full column list when it processes the query. That expansion happens each time the query runs, not when you write it. The query text stays the same while its meaning follows the table. This explains most of the problems below.
When * is fine
Use * when you are exploring and a person reads the output:
- Looking at an unfamiliar table to see what it holds.
- Checking that an
INSERTorUPDATEdid what you expected. - Running a quick one-off query in a SQL client.
In these cases you want to see everything, and nothing depends on the result's shape. Add a row limit when you do this on a large table, so you do not pull millions of rows into your client. Row limits are covered later in this tutorial.
Why named columns are safer in applications
Code that reads query results depends on the shape of those results. Naming columns makes that shape explicit and stable.
Schema changes break position-based code
Suppose your application runs SELECT * FROM employees and reads the fourth value in each row as the department. Later someone adds a column named middle_name after last_name. Every position after it shifts by one, and your code now reads the wrong value. Nothing fails with an error. The data is simply wrong.
Reading values by column name helps, but named columns in the query are still better. If someone drops a column your query names, you get an immediate "column does not exist" error. That is easier to find than silently wrong data.
Extra data costs time
A wide table may include large text, JSON, or binary columns. With SELECT *, the database reads and sends all of them, even if you only need a name. This costs disk reads, memory, and network transfer. It also exposes columns you may not want to show, such as salary or internal notes, to code that never needed them.
Naming columns can also allow a faster plan. If an index contains every column the query asks for, the database may answer from the index alone and never touch the table. This is often called a covering index. SELECT * rules that out in almost every case.
Names can collide in joins
When a query combines two tables, both may have a column with the same name, such as id. SELECT * returns both columns under the same name. Some client libraries keep only one of them, and which one varies by library. You can use table.* to take all columns from just one table, but listing columns explicitly avoids the problem.
Inserts can silently shift
A statement like INSERT INTO archive SELECT * FROM employees matches columns by position. If either table changes, values land in the wrong columns, or the statement fails. Listing the columns on both sides prevents this:
INSERT INTO archive (first_name, last_name, salary)
SELECT first_name, last_name, salary
FROM employees;This example assumes an archive table with those three columns exists.
Views and subqueries
Some databases fix the column list of a view when the view is created. In MySQL and SQLite the view stores its definition, but in older PostgreSQL versions the expanded list is stored at creation time. A view defined with SELECT * can therefore keep the old columns after the table changes, or fail. Behavior differs between databases, so naming columns in view definitions avoids the question.
Details of the select list
Order and repetition
You can list columns in any order, and you can repeat a column. Each mention produces a separate result column:
SELECT salary, first_name, salary
FROM employees;Repeating a column is rarely useful, but it is legal. You will more often reorder columns so the result reads naturally, for example putting last_name before first_name.
Case and quoting
Unquoted column names are not case-sensitive in standard SQL, so FIRST_NAME and first_name refer to the same column. PostgreSQL folds unquoted names to lowercase. If a column was created with double quotes and mixed case, such as "FirstName", you must quote it the same way every time. MySQL uses backticks for this by default. Avoid quoted mixed-case names in your own schemas, because they cause repeated friction.
Qualified names
You can prefix a column with its table name:
SELECT employees.first_name, employees.salary
FROM employees;For a single table this adds nothing, but it becomes required in joins when two tables share a column name. Getting used to it early costs little.
Selecting no table columns
A select list does not have to name columns at all. It can hold expressions, such as SELECT 1 + 1;. Most databases accept that with no FROM. Oracle requires FROM dual. The next chapter covers expressions and aliases in detail.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Trailing comma: `SELECT first_name, FROM employees;` | Syntax error near `FROM` | Remove the last comma |
| Missing comma: `SELECT first_name last_name FROM employees;` | No error. `last_name` becomes an alias for `first_name`, so one column comes back, holding first names | Add the comma |
| Misspelled column | "column does not exist" error | Check the table definition |
| Using `*` in application code | Results change when the table changes | List the columns |
| Using `*` on a huge table in a client | Slow query and a flood of output | Name columns and limit rows |
The missing comma is the most dangerous because it runs without complaint. The reason is that AS is optional in a column alias in most databases. Because of this, first_name last_name is read as "the column first_name, renamed to last_name". If a result has fewer columns than you expected, check for a missing comma first.
A practical habit
Write SELECT * freely when you explore. Before a query goes into code, a report, or a view, replace the * with the columns you need. Most SQL clients can expand * for you, and in any case it takes a minute. The result is a query that documents its own output, runs with less data, and fails loudly instead of quietly returning the wrong thing.
Exercise
A colleague writes SELECT first_name last_name, salary FROM employees; and says the query returns three columns. How many columns does it really return, what are they called, and how do you fix it?
Show answer
It returns two columns. Because AS is optional, last_name is read as an alias for first_name, so the first column holds first names but is labeled last_name. The second column is salary. Fix it by adding a comma: SELECT first_name, last_name, salary FROM employees;.
Exercise
An application runs SELECT * FROM employees and reads the department from the fourth value of each row. A teammate adds a new column named middle_name right after last_name. What goes wrong, and how would you write the query to avoid it?
Show answer
The fourth value is now middle_name instead of department, so the application reads wrong data without any error. Name the columns, for example SELECT first_name, last_name, department FROM employees;, and read values by name rather than by position where the client library allows it.