Renaming Columns — AS (Aliases)
Give columns and tables readable names, understand where aliases can and cannot be used, and write queries that communicate clearly to every reader
// Part 01
What an Alias Is and Why It Exists
Every column in a SQL result has a header — the name that appears at the top of that column. Without aliases, that header is whatever the database decides to call it: the raw column name for simple selections, or the full expression text for calculated columns. The results are technically correct but often unreadable.
An alias is a temporary name you assign to a column or table for the duration of a query. It exists only in the result — the database schema is never changed. The AS keyword introduces the alias, though AS is optional in most databases (a space works too — but AS is always clearer and recommended).
// Part 02
Column Aliases — Naming Your Output Columns
A column alias renames a column in the query result. It is placed immediately after the column expression using AS.
Aliasing raw columns
Aliasing calculated columns
This is where aliases are most essential. Without an alias, a calculated column's header is the full expression — unreadable in reports and unusable in application code that references columns by name.
// Part 03
Alias Naming Rules — What Is and Is Not Allowed
Alias names follow specific rules. Violating them causes syntax errors or unexpected behaviour.
| Rule | Valid | Invalid | Note |
|---|---|---|---|
| No spaces (unquoted) | margin_pct | margin pct | Use underscore instead of space |
| No reserved words (unquoted) | order_count | count | "count" needs quotes — COUNT is a SQL function |
| No special chars (unquoted) | gst_price | gst-price | Hyphen is interpreted as subtraction |
| Start with letter or underscore | _total, total | 123total | Cannot start with a digit |
| Quoted aliases — anything goes | "Margin %" | Double quotes allow spaces, special chars, reserved words | |
| Case sensitivity | Margin, margin, MARGIN | Unquoted aliases are case-insensitive in most databases |
Quoted aliases — for special characters and spaces
When you need spaces, special characters, or SQL reserved words in an alias, wrap it in double quotes (PostgreSQL/standard SQL) or backticks (MySQL).
// Part 04
Where Aliases Can and Cannot Be Used — The Execution Order Rule
This is the most important thing to understand about aliases. Because SQL clauses are executed in a specific order — and aliases are defined in SELECT — aliases can only be referenced in clauses that execute after SELECT.
WHERE cannot use SELECT aliases
ORDER BY CAN use SELECT aliases
GROUP BY — database-dependent
GROUP BY executes before SELECT in the logical order, so technically aliases should not be available. However, MySQL and DuckDB (this playground) allow GROUP BY to reference SELECT aliases as a convenience extension. PostgreSQL follows the standard strictly — GROUP BY cannot use SELECT aliases. Always repeat the expression in GROUP BY for cross-database compatibility.
// Part 05
Table Aliases — Shorter Names for Tables
Aliases are not just for columns — you can also alias tables. Table aliases give a table a short name for the duration of the query. This is most useful in JOIN queries where you reference the same table multiple times, or when table names are long and repetitive.
Self-join requires table aliases
When a table joins itself (a self-join — used for hierarchies like manager/employee), aliases are not just convenient — they are required. Without aliases, there is no way to distinguish the two instances of the same table.
// Part 06
Subquery Aliases — Every Subquery Needs a Name
When you use a subquery in the FROM clause (a derived table), it must be given an alias. The database needs to refer to the subquery result as if it were a table, and it cannot do so without a name.
// Part 07
Alias Conventions — How Professional Teams Name Things
Consistent alias naming conventions make queries readable across a team. Here are the conventions used at most Indian tech companies and data teams.
Column alias conventions
Table alias conventions
// Part 08
Practical Alias Examples — Complete FreshCart Queries
Here are complete, well-aliased queries for real FreshCart reporting scenarios.
Customer summary report
Product catalogue with computed fields
Order analysis report
// Part 09
What This Looks Like at Work
You are a data analyst at Amazon's seller analytics team. Sellers use a dashboard to monitor their product performance. The dashboard pulls data from a SQL query that you maintain. The query was written six months ago by a colleague who has since left — and it has no aliases anywhere.
🎯 Pro Tip
Every query you write will eventually be read by someone else — a colleague, a future version of yourself, or a new hire debugging an issue at 2 AM. Aliases cost 10 seconds to write and save hours of confusion. Make aliasing every computed column and every table in a JOIN a non-negotiable personal standard. The best SQL writers are distinguished not just by correctness but by clarity.
// Part 10
Interview Prep — 5 Questions With Complete Answers
A SQL alias is a temporary name assigned to a column expression or a table for the duration of a query. It exists only in the query output — it does not change the database schema, the table structure, or the column names stored in the database. The AS keyword introduces the alias: expression AS alias_name. AS is optional in most databases but always recommended for readability.
The two types are column aliases and table aliases. A column alias renames a column in the result set — it controls the header name that appears in the output. Column aliases are most important for calculated columns, where without an alias the header would be the full expression text: unit_price - cost_price as a column header versus profit. Column aliases are also used to rename existing columns to more readable names for specific reports or applications.
A table alias gives a table a shorthand name for use throughout the query. Table aliases serve two purposes: they shorten long table names in queries that reference the same table many times, and they are essential in JOIN queries to distinguish which table each column comes from when multiple tables share the same column name. In self-joins — where a single table appears twice in the FROM clause — table aliases are required because the database needs two distinct names to refer to the two instances.
The answer comes from SQL's logical execution order. SQL clauses are not executed in the order they are written. The actual execution order is: FROM (identify source tables), WHERE (filter rows), GROUP BY (group filtered rows), HAVING (filter groups), SELECT (compute and name output columns), ORDER BY (sort the result), LIMIT (truncate to N rows).
Column aliases are defined during the SELECT step — step 6 in this sequence. WHERE is step 2 and GROUP BY is step 3. Since both execute before SELECT, aliases do not yet exist when WHERE and GROUP BY run. Referencing an alias in WHERE — WHERE profit > 50, where profit is a SELECT alias — would ask the database to use a name that has not been defined yet, which is why it fails with "column does not exist."
ORDER BY, however, executes after SELECT — step 7. By that point the SELECT has already run and all aliases have been defined. The database knows what profit means because SELECT has already computed and named it. This is why ORDER BY margin_pct DESC works correctly. The practical implication: repeat the full expression in WHERE and GROUP BY, but use the cleaner alias in ORDER BY. Some databases (MySQL, DuckDB) extend the standard and allow aliases in GROUP BY as a convenience — but this is not portable and should be avoided in code intended to run on multiple database systems.
Without an alias, a calculated column's header in the result is whatever the database chooses to call it — typically the full expression text. In PostgreSQL, unit_price - cost_price appears as a column named exactly "?column?" or "unit_price - cost_price". In MySQL it might be "unit_price - cost_price". ROUND((unit_price - cost_price) / unit_price * 100, 1) might appear as a column named with the entire expression.
This creates three practical problems. First, readability — a column named "ROUND((unit_price - cost_price) / unit_price * 100, 1)" in a report is useless to any business user. Second, application code — most application frameworks reference columns by name. A Python script doing result['margin_pct'] works. result['ROUND((unit_price - cost_price) / unit_price * 100, 1)'] does not. Third, portability — the auto-generated column name varies by database system, so the same query produces differently named columns on PostgreSQL and MySQL, breaking any code that references the column name.
The professional standard: every calculated column, every CASE expression, every aggregate function result, and every concatenated string expression should have an explicit alias. This applies even when you think only you will run the query — the next person to run it (or future you) will thank the aliases.
Table aliases are required in two specific situations. First, self-joins — when a table is joined to itself, the database needs two distinct names to refer to the two instances. Without aliases, FROM employees JOIN employees produces an error because there is no way to distinguish the two copies of the table. FROM employees AS e JOIN employees AS m provides the two names needed: e for the employee record and m for the manager record. This pattern is used for any hierarchy stored in a single table: org charts, category trees, location hierarchies.
Second, subquery aliases — any subquery in the FROM clause must be given an alias. The database treats the subquery result as a temporary table and needs a name to refer to it. FROM (SELECT ...) as an unnamed subquery produces a syntax error. FROM (SELECT ...) AS subq gives the derived table the name subq, which can then be referenced in the outer query's WHERE, JOIN ON, and SELECT clauses.
Table aliases are recommended (but not required) in all JOIN queries involving multiple tables. Without aliases, every column reference must be fully qualified with the table name: customers.customer_id, orders.order_id, customers.first_name — verbose and repetitive. With aliases c, o, the same references become c.customer_id, o.order_id, c.first_name — much more concise. Professional SQL writers use table aliases in every multi-table query as a matter of course, not just when required.
For column aliases — no, and it should not be done. If you define two columns with the same alias name in the same SELECT, the behaviour is database-specific. PostgreSQL returns both columns with the same name, which confuses application code that reads columns by name. Most other databases exhibit similar undefined or database-specific behaviour. The practical rule: every column alias in a SELECT must be unique. Column aliases are the names application code uses to access values, and duplicate names make it impossible to reliably access either value.
For table aliases — no, for the same reason. Two tables with the same alias in the FROM clause would create ambiguity about which table a column reference belongs to. FROM customers AS c JOIN orders AS c creates an error — the database cannot determine whether c.customer_id refers to the customers or orders alias. All table aliases in a FROM clause must be distinct.
The only scenario where the same alias name can appear is in separate subqueries at different levels of nesting. A subquery alias named totals does not conflict with another subquery alias also named totals in a different part of the query, because each alias is scoped to its own level of the query. However, this is still bad practice — use descriptive, unique names for every alias in the query regardless of scope. Repeated alias names, even in different scopes, create confusion for anyone reading the query.
// Part 11
Errors You Will Hit — And Exactly Why They Happen
🎯 Key Takeaways
- ✓An alias is a temporary name for a column or table, defined with AS. It exists only in the query output — the database schema is never changed.
- ✓Column aliases rename output column headers. They are most essential for calculated columns — without them, the header is the full expression text, which is unreadable and unusable in application code.
- ✓Table aliases give tables a shorthand name. They are required in self-joins (a table joined to itself) and for subqueries in FROM. They are strongly recommended in all multi-table JOIN queries.
- ✓Column aliases are defined during SELECT (step 6 of execution). They can only be referenced in clauses that run after SELECT — ORDER BY works, WHERE and GROUP BY do not.
- ✓To filter on a calculated value, repeat the expression in WHERE — not the alias: WHERE (unit_price - cost_price) > 50, not WHERE profit > 50.
- ✓Subquery aliases are mandatory. Every subquery in FROM must be named: FROM (SELECT ...) AS subq_name. Without the alias, the query throws a syntax error.
- ✓Quoted aliases (double quotes in PostgreSQL, backticks in MySQL) allow spaces, special characters, and SQL reserved words: AS "Margin %", AS "Order Count".
- ✓Alias naming conventions: snake_case for programmatic use (margin_pct, total_revenue), quoted Title Case for human-readable reports ("Margin %", "Total Revenue"). Prefix aggregates: total_, avg_, max_, min_.
- ✓Never use positional references in GROUP BY (GROUP BY 1) — they break when columns are reordered. Always use column names or repeat the expression.
- ✓Every calculated column, every aggregate result, every CASE expression, and every concatenated string in a production query should have an explicit alias. This is not optional — it is the professional standard.
What comes next
In Module 14, you learn pattern matching with LIKE and wildcards — finding rows that match a pattern rather than an exact value. This is how you search for emails by domain, product names by brand prefix, or any partial text match.
Module 14 → Pattern Matching — LIKE & WildcardsDiscussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.