Aliases are temporary names that you assign to columns or tables to make your SQL queries more readable and clean . They don’t change the original names in the database — they only exist within the context of that query .
π§ Syntax
π For Column Aliases:
SELECT column_name AS alias_name
FROM table_name;
π For Table Aliases:
SELECT t.column_name
FROM table_name AS t;
π Why Use Aliases?
- Make column names more descriptive
- Simplify long or complex table names
- Improve readability in joins and subqueries
- Format output for reports
π§ͺ Our Sample Table: students
| id | name | age | course | marks |
|---|---|---|---|---|
| 1 | Rahul Sharma | 21 | Advanced SQL | 90.00 |
| 2 | Anjali Kapoor | 22 | Advanced SQL | 91.75 |
| 3 | Vikas Gupta | 24 | Advanced SQL | 91.00 |
| 4 | Riya Jain | 20 | Python | 92.50 |
| 5 | Aman Verma | 24 | Advanced SQL | 76.00 |
π Example 1: Column Alias
SELECT
name AS student_name,
marks AS obtained_marks
FROM students;
Output:
| student_name | obtained_marks |
|---|---|
| Rahul Sharma | 90.00 |
| Anjali Kapoor | 91.75 |
| ... | ... |
π Example 2: Table Alias
SELECT s.name, s.course FROM students AS s;
✅ s is a short alias for the students table.
π Example 3: Use in Aggregation
SELECT course, AVG (marks) AS average_score
FROM students GROUP BY course;
✅ average_score is easier to understand than AVG(marks) in the output.
π Example 4: Alias Without AS
Using AS is optional. You can also write:
SELECT name student_name, marks obtained_marks
FROM students;
But using AS is recommended for clarity.
⚠️ Alias Rules
| Rule | Example |
|---|---|
| Alias with spaces? Use quotes | AS "Total Marks" |
| Avoid using SQL keywords as aliases | AS total (OK), not AS select |
| Case sensitivity depends on DB system | "Name" vs name |
π§ Best Practices
- Always use aliases in joins or subqueries .
- Use clear, descriptive names (avoid
x,yunless in simple examples). - Prefer
ASfor readability.
✅ Summary
| Feature | Example | Purpose |
|---|---|---|
| Column Alias | marks AS total_marks |
Rename output column |
| Table Alias | students AS s |
Shorten table name |
Optional AS |
marks total |
Still valid but less readable |
π― Real Life Tip: When writing reports , dashboards , or complex joins , aliases make queries much more understandable and professional.