Sub topic 3
Naming the Columns of a View
Prerequisites and scope
This chapter assumes you can write SELECT queries with joins and aliases, and that you have created the departments and employees tables from the earlier chapters. It covers how a view gets its column names, the two ways to set them, the errors that come from getting them wrong, and what happens to names when a view is redefined.
Column names matter more for a view than for a plain query. A query result is read once by one caller. A view's column names become a contract: other queries, reports, and application code refer to them by name. Choosing them deliberately is part of designing the view.
Where view column names come from by default
If you do not name the columns, the database takes them from the defining query. A plain column reference keeps its name. A column with an alias takes the alias. An expression with no alias gets a name that the database generates, and that name differs between systems.
CREATE VIEW employee_raw AS
SELECT id, name, salary / 12
FROM employees;In PostgreSQL the third column is named ?column?. In MySQL the statement fails or produces an awkward name based on the expression text, depending on the version and settings. In Oracle it fails because the expression needs an alias. A view whose columns have generated names is hard to use, because you must quote the odd name every time you refer to it.
The rule of thumb: every column in a view's SELECT list should be either a plain column with a good name or an expression with an explicit name.
Method 1: aliases in the SELECT list
The first method is the AS alias you already know from ordinary queries. The alias becomes the view's column name.
CREATE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;Here the alias is required. Both tables have a column called name. Without the alias on d.name, the view would have two columns called name, and most systems reject that.
-- Fails in PostgreSQL: column "name" specified more than once
CREATE VIEW employee_directory_bad AS
SELECT e.name, d.name
FROM employees e
JOIN departments d ON d.id = e.department_id;Aliasing keeps the naming next to the expression it describes. When you read the query, you see each output name beside the thing that produces it. This is the usual choice for views with a handful of columns.
Method 2: a column list after the view name
The second method puts the names in parentheses after the view name. The names are matched to the SELECT list by position.
CREATE VIEW employee_summary (employee_id, employee_name, monthly_salary) AS
SELECT id, name, salary / 12
FROM employees;The first name applies to the first selected column, the second to the second, and so on. The column list overrides any names the query would have produced, including aliases.
Positional matching has one strict requirement: the number of names must equal the number of columns in the SELECT list. If they differ, the statement fails.
-- Fails: the column list has 2 names but the query returns 3 columns
CREATE VIEW employee_summary_bad (employee_id, employee_name) AS
SELECT id, name, salary / 12
FROM employees;PostgreSQL reports that the view has too few or too many column names specified. Other systems use different wording, but all reject the mismatch.
Choosing between the two methods
| Situation | Better choice |
|---|---|
| A few columns, one or two need renaming | Aliases in the SELECT list |
| Many computed columns that all need names | Column list |
| The query is generated or long, and the names are the public interface | Column list |
| You want the name visible next to its expression | Aliases |
| The view is a `UNION` of several queries | Column list, or aliases in the first query only |
For a UNION, the output names normally come from the first SELECT. A column list lets you state the names once instead of relying on that rule.
CREATE VIEW all_contacts (contact_name, contact_email) AS
SELECT name, email FROM employees
UNION ALL
SELECT name, NULL FROM departments;You can also combine the methods, but the column list wins. Mixing them in one view invites confusion, so pick one per view.
How names affect the queries that use the view
Once the view exists, the names you chose are the only names callers see. The original column names in the base table are hidden.
SELECT employee_id, monthly_salary
FROM employee_summary
WHERE monthly_salary > 4000;This works. The next query fails, even though salary exists in employees:
-- Fails: column "salary" does not exist in the view
SELECT salary FROM employee_summary;This is intended behavior. The view exposes its own column set. It is also why renaming columns is a useful way to hide the structure of the underlying tables: you can rename emp_sal_amt to salary in the view, and callers never see the old name.
Case and quoting
Unquoted identifiers are folded to a standard case: lower case in PostgreSQL, upper case in Oracle. A view column defined as Monthly Pay with double quotes keeps its exact case and its space, and you must then quote it in every query.
CREATE VIEW employee_pay AS
SELECT id, salary / 12 AS "Monthly Pay"
FROM employees;
-- Requires the quotes and the exact capitalization
SELECT "Monthly Pay" FROM employee_pay;Avoid quoted names in views. Use snake_case names made of letters, digits, and underscores. They work without quotes everywhere, and they behave the same across systems.
MySQL uses backticks instead of double quotes by default, which is another reason to avoid quoted names if the view might move between systems.
Name stability and redefinition
A view's column names and their order are part of its interface. This matters when you change a view with CREATE OR REPLACE VIEW. The next chapter covers replacing views in full. For now, note one rule that comes directly from naming.
In PostgreSQL, CREATE OR REPLACE VIEW can add new columns at the end of the list. It cannot rename, reorder, or remove existing columns. The existing columns must keep the same names, the same order, and compatible data types.
CREATE VIEW employee_names AS
SELECT id, name
FROM employees;
-- Works in PostgreSQL: adds a column at the end
CREATE OR REPLACE VIEW employee_names AS
SELECT id, name, email
FROM employees;
-- Fails in PostgreSQL: renames the second column
CREATE OR REPLACE VIEW employee_names AS
SELECT id, name AS full_name, email
FROM employees;To rename a column in PostgreSQL, you can use ALTER VIEW ... RENAME COLUMN, or drop and recreate the view. Other systems are more permissive. MySQL and Oracle let CREATE OR REPLACE VIEW replace the entire definition, including names. Because the rules differ, check your system's documentation before relying on either behavior.
-- PostgreSQL
ALTER VIEW employee_names RENAME COLUMN name TO full_name;Treat a rename as a breaking change. Any query, report, or application that uses the old name will fail afterward. Adding columns at the end is safe for callers that name their columns. It is not safe for callers that use SELECT * or depend on column position, as a later chapter on pitfalls explains.
Common errors
- Duplicate names. Two columns end up with the same name, often from a join of two tables that both have
idorname. Fix: alias one or both. - Count mismatch. A column list has a different number of names than the query returns. Fix: count the SELECT list, including expressions.
- Unnamed expressions. An expression has no alias and the database either rejects it or invents a name. Fix: always alias expressions.
- Names that depend on
SELECT *. A view defined asSELECT * FROM employeesgets the table's column names at creation time. In most systems the list is fixed then, and columns added to the table later do not appear in the view. Fix: list columns explicitly. - Wrong positional order. A column list matches by position, so a swapped name silently labels the wrong data. A view with
(employee_name, employee_id)overSELECT id, nameruns without error and mislabels both columns. Fix: keep the list and the SELECT list visually aligned, and test the view with a few rows.
Checking the result
After creating a view, confirm its column names rather than trusting the definition. The standard catalog view information_schema.columns lists them, in order.
SELECT column_name, ordinal_position, data_type
FROM information_schema.columns
WHERE table_name = 'employee_summary'
ORDER BY ordinal_position;For employee_summary, the output should be employee_id, employee_name, and monthly_salary in positions 1 to 3. The schema name of the view and the exact data types vary by system. PostgreSQL shows monthly_salary as numeric.
A mermaid diagram of the decision shows how a name is chosen.
Summary
- A view's column names come from a column list, an alias, or the source column, in that order of precedence.
- Aliases keep each name beside its expression. A column list states all names in one place and matches by position.
- The number of names in a column list must equal the number of columns selected.
- Duplicate names and unnamed expressions are the most common naming errors.
- Use plain
snake_casenames to avoid quoting. - Renaming a view column breaks callers, and some systems restrict it in
CREATE OR REPLACE VIEW.
Exercise
The view below fails with an error. Give two different fixes, one using an alias and one using a column list. Then explain what would go wrong if you wrote the column list as (department, employee) instead of (employee, department). CREATE VIEW staffdepartments AS SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.departmentid;
Show answer
The view fails because both output columns are named name. Fix with an alias: SELECT e.name AS employee, d.name AS department FROM employees e JOIN departments d ON d.id = e.departmentid. Fix with a column list: CREATE VIEW staffdepartments (employee, department) AS SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.department_id. Column lists match by position, so (department, employee) would run without error but label the employee names as department and the department names as employee.
Exercise
A view is defined as CREATE VIEW pay (emp_id, monthly) AS SELECT id, name, salary / 12 FROM employees. What happens, and what is the correction?
Show answer
The statement fails because the column list has two names but the SELECT list returns three columns. Either add a third name, for example (empid, empname, monthly), or remove the unneeded column from the SELECT list so that the counts match.