SQL Aliases (AS) 🏷️¶
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)."