PostgreSQL AS

PostgreSQL AS (Aliases)

SQL aliases are utilized to give a table, or a column in a table, a temporary name. Aliases are specifically created to make output column names substantially more readable.

An alias only rigidly exists for the duration of that specific SQL query. It does not permanently rename the actual architectural columns within your database.

Column Aliases

When using aggregate functions like SUM() or COUNT(), the output column name is ugly. PostgreSQL usually titles the column with the literal mathematical function string.

By actively utilizing the AS keyword, you assign a clean, professional display name. This greatly helps frontend developers understand the exact data they are receiving.

Column Alias Example:

-- Create two readable aliases for the output
SELECT CustomerID AS ID, CustomerName AS Name
FROM Customers;

Aliases with Spaces

If you want your alias to robustly contain blank spaces, it requires special formatting. You must meticulously enclose the alias string in standard double quotation marks.

Without the double quotes, the compiler will aggressively throw a syntax error. It will assume the second word of your alias is an illegal SQL command keyword.

Spaced Alias Example:

-- Using double quotes to safely include a blank space
SELECT CustomerName AS "Customer Name"
FROM Customers;

Concatenating Columns

You frequently need to merge multiple columns cleanly into a single output field. PostgreSQL uses the double pipe operator (||) to heavily concatenate text strings.

You can then universally apply a singular alias to the final computed string result. This creates structured data points like "Full Name" or "Complete Address" instantly.

Concatenation Alias Example:

-- Merge the address, city, and postal code into one solid column
SELECT CustomerName, Address || ', ' || City || ', ' || PostalCode AS "Complete Address"
FROM Customers;

Table Aliases

Aliases are not strictly limited to individual data columns; tables use them too. Table aliases drastically shorten complex SQL queries making them highly legible.

They are mandatory when joining multiple relational tables tightly together. You assign a short letter (like c for Customers) to avoid typing the full name constantly.

Summary

The AS keyword establishes highly readable, temporary aliases for query outputs. It ensures frontend applications receive cleanly structured JSON object keys.

Use double quotes when your alias strictly requires blank architectural spaces.

Exercise

What punctuation must surround an alias if it intentionally contains blank spaces?