SQL Aliases (AS) π·οΈΒΆ
Prerequisites: SELECT Statement
Mentor's Note: Aliases are like "Nicknames". They don't change the actual name in the database, but they make your results and your code much easier to read. π‘
π The Scenario: The Nickname πΒΆ
- Actual Name: "Christopher Columbus"
- Alias: "Chris"
- Technical Column:
p_id_001_sales_net - Alias:
Priceβ
π» 1. Column Aliases πΒΆ
Used to make column headers more descriptive or readable.
-- Scenario: Calculating total price with tax
SELECT
product_name,
price * 1.18 AS "Price_With_Tax" -- π·οΈ Readable Alias
FROM products;
Rules:
- The AS keyword is optional but recommended.
- Use Double Quotes " " if the alias has spaces.
π» 2. Table Aliases π’ΒΆ
Used to shorten table names, especially when joining multiple tables together.
-- Scenario: Fetching employee and department names
SELECT E.name, D.dept_name
FROM employees AS E -- π·οΈ E is easier to type than employees
JOIN departments AS D ON E.dept_id = D.id;
π¨ Visual Logic: The MapΒΆ
| Technical Database | Query View (The Alias) |
|---|---|
emp_first_name |
First_Name |
dept_loc_zip |
Zip_Code |
salary + bonus |
Total_Pay |
π‘ Pro TipΒΆ
"In Joins, always use Table Aliases (like
Efor Employees). It prevents 'Ambiguous Column' errors if both tables have a column with the same name (likecreated_at)."