In previous lessons, we learned how to select data from tables. Sometimes, the default column names in a database aren't very descriptive, or you might want to give a new name to a column you've calculated. This is where Column Aliasing comes in.
Column aliasing allows you to assign a temporary, alternative name to a column in the result set of a SELECT query. This doesn't change the actual name of the column in the table; it only affects how the column is displayed in the query's output.
You can create a column alias using the AS keyword, although it is often optional:
SELECT column_name AS alias_name
FROM table_name;
-- OR (without AS)
SELECT column_name alias_name
FROM table_name;
column_name: The name of the column you want to alias.AS alias_name: The AS keyword followed by the desired alias name.alias_name: The new, temporary name for the column. If the alias contains spaces or special characters, it needs to be enclosed in double quotes (").Using aliases provides several benefits for data presentation and query construction:
Let's look at some practical examples using the Sakila database structure.
This query selects the first_name and last_name columns from the actor table, but displays them as "Given Name" and "Surname" in the result set. Note the use of double quotes because the alias contains a space.
SELECT first_name AS "Given Name", last_name AS "Surname"
FROM actor;
This query calculates the rental duration in days and assigns the alias rental_duration to the calculated column.
SELECT rental_date, return_date - rental_date AS rental_duration
FROM rental;
This query concatenates the first_name and last_name columns to create a full name and assigns the alias "Full Name" to the resulting column.
SELECT first_name || ' ' || last_name AS "Full Name"
FROM actor;
Note: The
||operator is used for string concatenation in SQLite and PostgreSQL. Other databases may use different operators or functions (e.g.,+in SQL Server,CONCAT()function in MySQL).
Key Takeaways from this Lesson:
AS keyword (or simply a space) to create an alias.").