Sub topic 3
Choosing columns and naming them with aliases
This chapter covers the select list, the part of a query between SELECT and FROM. You will choose columns, rename them with aliases, and learn where an alias can and cannot be used. It assumes you can run a query in SQL*Plus, SQL Developer or SQL Worksheet. It also assumes you know what a table, row and column are, and that you have the HR sample schema (employees, departments) available.
The select list
The select list says which columns, or which computed values, appear in each result row. You can write it in three ways:
*, which means all columns.- A comma-separated list of column names.
- A list that mixes columns, expressions and function calls.
SELECT * FROM employees;
SELECT employee_id, first_name, last_name FROM employees;SELECT * returns every visible column in the order the table was defined. It is convenient at a prompt. In application code it is risky, for these reasons:
- If someone adds or reorders a column, your result shape changes.
- You transfer data you do not need.
- The optimizer cannot use an index that covers only the columns you really need.
Name the columns you need in code that other people or programs depend on.
The order in the select list controls the order of the output columns. It does not need to match the table definition, and you can repeat a column:
SELECT last_name, first_name, last_name
FROM employees
WHERE department_id = 90;Each column appears as many times as you list it. This is legal, but it gets awkward when you need to refer to one of the copies, which is one reason aliases exist.
Default column headings
Without an alias, Oracle labels each output column with the column name or, for an expression, the expression text. Unquoted names are displayed in uppercase in most clients:
SELECT first_name, salary * 12
FROM employees
WHERE employee_id = 100;The headings are FIRST_NAME and SALARY*12. The second heading is hard to read. Programs that read results by column name, such as JDBC or Python drivers, receive that awkward text as the column name. An alias avoids this.
Column aliases
A column alias is a name you assign to a select-list item. It becomes the heading of that column in the result. The syntax is the item, then an optional AS, then the alias:
SELECT first_name AS given_name,
last_name surname,
salary * 12 AS annual_salary
FROM employees
WHERE employee_id = 100;Both AS given_name and the shorter surname forms are valid. Using AS is the better habit, and the next section shows why.
The missing-comma trap
Because AS is optional, a forgotten comma does not always cause an error. It can silently create an alias:
SELECT first_name last_name
FROM employees;This is valid. It returns one column, the first names, labeled LAST_NAME. No error appears, so the mistake is easy to miss. Writing AS for every alias makes this kind of mistake easier to spot, because an AS you did not mean to type stands out.
The opposite mistake, a stray comma or two items run together where an alias with a space was intended, often produces ORA-00923: FROM keyword not found where expected. This is the error you will see most often with alias problems.
Aliases with spaces, mixed case or special characters
An unquoted alias follows the rules for ordinary identifiers:
- It starts with a letter.
- It contains letters, digits,
_,$and#. - It is not a reserved word.
- Oracle stores and displays it in uppercase.
To get spaces, lowercase letters or punctuation, wrap the alias in double quotes:
SELECT first_name AS "First Name",
salary * 12 AS "Annual Salary ($)"
FROM employees
WHERE employee_id = 100;A quoted alias keeps its exact case and characters. The same rule applies to a reserved word. SELECT salary AS date fails because DATE is a reserved word, while SELECT salary AS "DATE" works.
Use single quotes for string literals and double quotes for identifiers. Oracle treats them very differently. AS 'Annual Salary' raises an error in most versions because a string literal is not an identifier.
Length limit
An alias is an identifier, so the identifier length limit applies. It is 128 bytes from Oracle Database 12.2 when COMPATIBLE is 12.2 or higher, and 30 bytes in earlier releases. Exceeding the limit raises ORA-00972: identifier is too long.
Where an alias can be used
An alias is created when the select list is evaluated, and that happens late in processing. Clauses that run before the select list cannot see it. The chapter on logical processing order covers this fully. For now, the practical rule is:
| Clause | Can it use a select-list alias? |
|---|---|
| `WHERE` | No |
| `SELECT` (another item in the same list) | No |
| `ORDER BY` | Yes |
| Outer query that selects from this query as an inline view | Yes |
This fails:
SELECT salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;Oracle raises ORA-00904: "ANNUAL_SALARY": invalid identifier. Repeat the expression in WHERE, or wrap the query in an inline view:
SELECT employee_id, annual_salary
FROM (
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
)
WHERE annual_salary > 100000;ORDER BY can use the alias:
SELECT last_name, salary * 12 AS annual_salary
FROM employees
WHERE department_id = 80
ORDER BY annual_salary DESC;Quoted aliases and ORDER BY
Case matters once an alias is quoted. If you define "Annual Salary", you must refer to it the same way:
SELECT last_name, salary * 12 AS "Annual Salary"
FROM employees
ORDER BY "Annual Salary" DESC;Writing ORDER BY annual salary or ORDER BY "ANNUAL SALARY" does not match and raises ORA-00904. If you will refer to an alias again, an unquoted name such as annual_salary is simpler. Reserve quoted aliases for final output headings where you want a specific label.
Table aliases
Tables can also have aliases. They shorten long names and make it clear which table a column comes from, which becomes essential once you join tables. The syntax differs from column aliases in one respect: Oracle does not accept AS before a table alias.
SELECT e.employee_id, e.last_name, e.salary
FROM employees e
WHERE e.department_id = 50;FROM employees AS e raises ORA-00933: SQL command not properly ended. Write the alias directly after the table name.
Two rules to remember:
- Once you give a table an alias, you must use that alias as the qualifier.
employees.last_namefails withORA-00904when the table has the aliase. e.*selects all columns of that one table. This is useful when you later join tables and want all columns from one side plus a few from the other.
SELECT e.*, e.salary * 12 AS annual_salary
FROM employees e
WHERE e.employee_id = 100;Without a prefix, * must stand alone in the select list. A query like SELECT *, salary * 12 FROM employees raises an error. Writing SELECT employees.*, salary * 12 FROM employees or using a table alias as above works.
Aliases for expressions and functions
Aliases matter most for computed items, because their default headings are unreadable. Compare these two outputs:
SELECT UPPER(last_name),
ROUND(salary / 22, 2),
first_name || ' ' || last_name
FROM employees
WHERE employee_id = 100;
SELECT UPPER(last_name) AS last_name_upper,
ROUND(salary / 22, 2) AS daily_rate,
first_name || ' ' || last_name AS full_name
FROM employees
WHERE employee_id = 100;The first query yields headings such as UPPER(LAST_NAME) and FIRST_NAME||''||LAST_NAME. The second yields names you can use directly in a report or in code that reads results by name. Later chapters cover the expressions and functions themselves.
A related point is that views, CREATE TABLE ... AS SELECT and inline views take their column names from your aliases. Without an alias, a computed column in CREATE TABLE ... AS SELECT fails with ORA-00998: must name this expression with a column alias. Aliasing every expression is required in that case.
CREATE TABLE emp_annual AS
SELECT employee_id, salary * 12 AS annual_salary
FROM employees;Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ORA-00904: invalid identifier` on an alias in `WHERE` | Alias is not visible in `WHERE` | Repeat the expression or use an inline view |
| `ORA-00904` on a quoted alias in `ORDER BY` | Case or spacing differs from the definition | Match the quotes and case exactly |
| `ORA-00923: FROM keyword not found where expected` | Alias with a space but no double quotes, or a missing comma | Quote the alias or add the comma |
| `ORA-00933` after `FROM employees AS e` | `AS` is not allowed for table aliases | Remove `AS` |
| One column labeled with a second column's name | Missing comma turned a column into an alias | Add the comma, and use `AS` for aliases |
| `ORA-00998` in `CREATE TABLE ... AS SELECT` | Expression without an alias | Add an alias |
Exercises
Exercise
A colleague writes SELECT salary * 12 AS annual_salary FROM employees WHERE annual_salary > 100000; and gets ORA-00904. Explain why, and give two ways to fix it.
Show answer
The WHERE clause is evaluated before the select list, so the alias annualsalary does not exist yet. Fix 1: repeat the expression, as in WHERE salary * 12 > 100000. Fix 2: put the query in an inline view that defines the alias, then filter in the outer query with WHERE annualsalary > 100000.
Exercise
What does SELECT first_name last_name FROM employees; return, and why is there no error? Rewrite it so it returns both columns.
Show answer
It returns a single column containing the first names, with the heading LASTNAME. The AS keyword is optional, so lastname is read as an alias for firstname. Add the missing comma: SELECT firstname, last_name FROM employees;
Exercise
Write a query on employees that returns last_name with the heading "Employee Name" and salary * 12 with the heading "Annual Pay", sorted by the annual amount from highest to lowest.
Show answer
SELECT last_name AS "Employee Name", salary * 12 AS "Annual Pay" FROM employees ORDER BY "Annual Pay" DESC;