SQLab Hub
Lesson 7 · Comments & Aliases
Lesson 7 · Fundamentals

SQL Aliases and Comments: AS, --, and /* */

An alias gives a column or a table a temporary name inside one query, and a comment is a note the database ignores. Both exist for the people who read SQL: aliases turn COUNT(*) into total_orders, and comments explain why a filter is there.

AS column and table aliases -- and /* */ comments ▶ Runnable Playground examples 🧪 5 practice exercises 📝 6-question quiz ⏱ ~12 min

Column Aliases With AS

Without an alias, a calculated column is named after its expression. With AS, you choose the name:

SQLite · runs in the Playground
SELECT COUNT(*), ROUND(AVG(total), 2)
FROM orders;

▶ Run this query in the SQL Playground

Calculated columns without aliases
COUNT(*)ROUND(AVG(total), 2)
2002554.85
✓ 1 row · real output from the Playground database
SQLite · runs in the Playground
SELECT COUNT(*)            AS total_orders,
       ROUND(AVG(total), 2) AS avg_order_value
FROM orders;

▶ Run this query in the SQL Playground

The same columns with aliases
total_ordersavg_order_value
2002554.85
✓ 1 row · real output from the Playground database

The alias only changes the result's column name. The table, its columns and its data are not touched, and the alias is gone when the query ends.

FormExampleNotes
With ASCOUNT(*) AS total_ordersThe clearest form
Without ASCOUNT(*) total_ordersAlso valid; easy to misread
With spacesCOUNT(*) AS "total orders"Needs double quotes (SQL Server also accepts [total orders], MySQL `total orders`)

Most people use lowercase names with underscores, such as total_orders, so no quoting is ever needed.

Table Aliases

A table alias is a short name for a table, used to qualify its columns. It matters most in joins, where two tables can have columns with the same name, such as id:

SQLite · runs in the Playground
SELECT o.id AS order_id,
       u.first_name,
       u.last_name,
       o.total
FROM orders AS o
JOIN users  AS u ON u.id = o.user_id
ORDER BY o.id
LIMIT 5;

▶ Run this query in the SQL Playground

Orders with the customer's name, using table aliases
order_idfirst_namelast_nametotal
1AmandaMitchell2638.11
2TimothyCampbell2947
3SarahHernandez683.24
4LindaAllen3920.44
5RobertLewis1120.99
✓ 5 rows · real output from the Playground database

o.id is the order's id and u.id the user's. Without the aliases you would write orders.id and users.id, and with a self join, where one table appears twice, aliases are required:

SQLite · runs in the Playground
SELECT e.first_name AS employee,
       m.first_name AS manager
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id
LIMIT 5;

▶ Run this query in the SQL Playground

Each employee with their manager
employeemanager
LauraWilliam
BettyWilliam
JoshuaMichelle
DonaldDaniel
BarbaraSteven
✓ 5 rows · real output from the Playground database
Oracle does not accept AS before a table alias. Write FROM orders o there. Leaving AS out of table aliases works in every database, so many teams write column aliases with AS and table aliases without it.

Where You Can Use an Alias

An alias is created when SELECT is processed. Clauses processed before SELECT cannot see it:

StepClauseCan use a SELECT alias?
1FROM / JOINNo (but table aliases defined here are usable everywhere)
2WHERENo
3GROUP BYSQLite, MySQL, PostgreSQL: yes. SQL Server, Oracle: no
4HAVINGSQLite and MySQL: yes. PostgreSQL, SQL Server, Oracle: no
5SELECTThe alias is defined here
6ORDER BYYes, everywhere

ORDER BY by an alias works in every database:

SQLite · runs in the Playground
SELECT department,
       COUNT(*) AS employees
FROM employees
GROUP BY department
ORDER BY employees DESC
LIMIT 5;

▶ Run this query in the SQL Playground

Sorting by an alias
departmentemployees
Legal16
Customer Success15
Operations13
Marketing13
HR12
✓ 5 rows · real output from the Playground database

In WHERE, repeat the expression, or wrap the query so the alias becomes a real column of a subquery:

SQLite · runs in the Playground
SELECT name, margin
FROM (SELECT name, ROUND(price - cost, 2) AS margin
      FROM products) AS t
WHERE margin > 1300
ORDER BY margin DESC;

▶ Run this query in the SQL Playground

Filtering on an alias through a subquery
namemargin
Succulent Plant Set1373.21
Single Origin Coffee 500g1334.47
Japanese Green Tea 50 bags1317.51
✓ 3 rows · real output from the Playground database

A subquery in FROM needs an alias of its own (AS t here) in most databases.

Single-Line and Multi-Line Comments

-- starts a comment that runs to the end of the line. /* ... */ marks a comment that can span several lines or sit in the middle of one. The database ignores both:

SQLite · runs in the Playground
SELECT status,          -- one row per status
       COUNT(*) AS orders
FROM orders
/* Cancelled and refunded orders are left out
   because finance does not count them as sales. */
WHERE status NOT IN ('cancelled', 'refunded')
GROUP BY status
ORDER BY orders DESC;

▶ Run this query in the SQL Playground

A commented query
statusorders
delivered82
processing28
pending23
shipped21
✓ 4 rows · real output from the Playground database
SyntaxScopeSupported by
-- commentUntil the end of the lineAll databases (MySQL needs a space after --)
/* comment */Everything between the markers, across linesAll databases
# commentUntil the end of the lineMySQL only
Nested /* /* */ */A comment inside a commentPostgreSQL and SQL Server; not MySQL or SQLite

Commenting out code

While testing, comments switch parts of a query off without deleting them. Here the ORDER BY and LIMIT are disabled, so all categories come back:

SQLite · runs in the Playground
SELECT category, COUNT(*) AS products
FROM products
GROUP BY category
-- ORDER BY products DESC
-- LIMIT 3
;

▶ Run this query in the SQL Playground

The same query with two lines commented out
categoryproducts
Automotive11
Books16
Clothing9
Electronics7
Food & Beverage17
Health & Beauty10
Home & Garden11
Office Supplies15
Sports & Outdoors12
Toys12
✓ 10 rows · real output from the Playground database

What Makes a Useful Comment

Less usefulMore useful
-- select orders-- delivered orders only: shipped orders can still be returned
-- filter-- 2024-07-01: start of the new pricing, earlier orders are not comparable
-- join users-- LEFT JOIN so customers without orders still appear with 0

Comments are most useful when they say why: the business rule behind a filter, the reason for an unusual join, a known data problem. The query itself already says what it does. Comments cost nothing at run time; the database strips them before planning the query.

Common Alias and Comment Mistakes

Five errors and how to avoid them.

1. Using a SELECT alias in WHERE

❌ Error: no such column
SQL
SELECT name, price - cost AS margin
FROM products
WHERE margin > 1300;
✅ Repeat the expression or wrap the query
SQL
SELECT name, price - cost AS margin
FROM products
WHERE price - cost > 1300;

WHERE is processed before SELECT, so margin does not exist yet.

2. An alias with spaces and no quotes

❌ Syntax error
SQL
SELECT COUNT(*) AS total orders
FROM orders;
✅ Quote it, or use underscores
SQL
SELECT COUNT(*) AS total_orders
FROM orders;

SQL reads "orders" as a separate word. Double quotes or underscores fix it.

3. Single quotes around an alias

❌ A text value in some databases
SQL
SELECT COUNT(*) AS 'total orders'
FROM orders;
✅ Double quotes for names
SQL
SELECT COUNT(*) AS "total orders"
FROM orders;

Single quotes mean text. Some databases accept them as an alias, but PostgreSQL rejects it and in other places they create a string, not a name.

4. Mixing an alias with the full table name

❌ Error once the alias is defined
SQL
SELECT orders.total
FROM orders AS o;
✅ Use the alias
SQL
SELECT o.total
FROM orders AS o;

After FROM orders AS o, the table is known as o in the rest of the query in most databases.

5. A -- comment that swallows code

❌ WHERE is part of the comment
SQL
SELECT * FROM orders -- recent only WHERE order_date >= '2024-07-01'
✅ Put code on its own line
SQL
SELECT * FROM orders  -- recent only
WHERE order_date >= '2024-07-01'

Everything after -- on the line is ignored, including the filter, so all orders come back.

Practice Comments & Aliases Queries

5 exercises on the real Playground tables.

Write each query yourself first. Every solution has been run against the Playground database.

  1. 1Easy Show each product's name and price with the columns renamed to product and price_usd. Show 5. Table: products

    Show solution
    SQLite · runs in the Playground
    SELECT name  AS product,
           price AS price_usd
    FROM products
    ORDER BY id
    LIMIT 5;

    ▶ Run this query in the SQL Playground

    AS renames only the output columns.

  2. 2Easy Show each department's average salary as avg_salary, rounded, highest first. Table: employees

    Show solution
    SQLite · runs in the Playground
    SELECT department,
           ROUND(AVG(salary)) AS avg_salary
    FROM employees
    GROUP BY department
    ORDER BY avg_salary DESC;

    ▶ Run this query in the SQL Playground

    ORDER BY can use the alias.

  3. 3Medium Using table aliases oi and p, list 5 order lines with the product name and quantity. Table: order_items, products

    Show solution
    SQLite · runs in the Playground
    SELECT oi.order_id, p.name AS product, oi.quantity
    FROM order_items AS oi
    JOIN products AS p ON p.id = oi.product_id
    ORDER BY oi.id
    LIMIT 5;

    ▶ Run this query in the SQL Playground

    Each column is qualified with the alias of its table.

  4. 4Medium Count the orders per year with a comment explaining why cancelled orders are excluded. Table: orders

    Show solution
    SQLite · runs in the Playground
    SELECT strftime('%Y', order_date) AS order_year,
           COUNT(*) AS orders
    FROM orders
    WHERE status <> 'cancelled'   -- cancelled orders never reached the customer
    GROUP BY order_year
    ORDER BY order_year;

    ▶ Run this query in the SQL Playground

    The comment explains the business reason, which the SQL alone cannot.

  5. 5Medium List the products whose margin (price minus cost) is above 1,300, using a subquery so you can filter on the alias. Table: products

    Show solution
    SQLite · runs in the Playground
    SELECT name, margin
    FROM (SELECT name, ROUND(price - cost, 2) AS margin
          FROM products) AS t
    WHERE margin > 1300
    ORDER BY margin DESC;

    ▶ Run this query in the SQL Playground

    Inside the subquery, margin is a real column the outer WHERE can see.

📝 Quiz — Comments & Aliases

Test your understanding · 0/6 answered

Question 1 of 6

What does the database do with a comment?

Question 2 of 6

Which syntax starts a single-line comment in standard SQL?

Question 3 of 6

What does AS do?

Question 4 of 6

What is the output column name of SELECT COUNT(*) AS total FROM orders?

Question 5 of 6

Does AS total change a column name in the table?

Question 6 of 6

What happens to SQL inside /* ... */ when the query runs?

Comments & Aliases Interview Questions

Q1. Why can you not use a SELECT alias in WHERE?

WHERE is processed before SELECT, so the alias does not exist yet. Repeat the expression or filter in an outer query.

Q2. When are table aliases required?

When the same table appears twice, as in a self join, and in practice whenever columns with the same name come from different tables. Subqueries in FROM also need an alias in most databases.

Q3. Which clauses can use a column alias?

ORDER BY everywhere. GROUP BY in SQLite, MySQL and PostgreSQL. HAVING in SQLite and MySQL. Never WHERE.

Q4. Do comments affect performance?

No. They are removed before the query is parsed and planned.

Frequently Asked Questions

What are SQL comments?

Notes inside a query that the database ignores. They explain what a query does or why, or switch code off temporarily. Single-line comments start with -- and multi-line comments sit between /* and */.

What is a SQL alias?

A temporary name for a column, an expression or a table, usually given with AS. COUNT(*) AS total_orders names the result column total_orders. Aliases do not change the database.

What is a SQL column alias?

A new name for a result column: SELECT SUM(total) AS revenue FROM orders labels the column revenue instead of SUM(total). It makes results readable in reports.

What is a SQL table alias?

A short name for a table within one query: FROM orders AS o lets you write o.total instead of orders.total. Table aliases are essential in joins and required in self joins.

What is the difference between -- and /* */ in SQL?

-- makes the rest of the line a comment. /* */ makes everything between the markers a comment, across as many lines as needed or in the middle of a line.

What does the AS keyword do in SQL?

AS defines an alias. With a column, COUNT(*) AS total renames the output column. With a table, FROM orders AS o gives the table a short name. Both last only for the query.

Does an alias permanently change the column or table name in the database?

No. An alias exists only while that query runs. The table, its columns and its data are unchanged. To rename a column permanently, use ALTER TABLE ... RENAME COLUMN.

Can aliases contain spaces?

Yes, inside double quotes: COUNT(*) AS "total orders". SQL Server also accepts square brackets and MySQL backticks. Most people use underscores, such as total_orders, which never need quotes.

Can aliases be used in a WHERE clause?

No. WHERE runs before SELECT, so the alias does not exist yet. Repeat the expression in WHERE, or put the query in a subquery and filter in the outer query.

Can aliases be used in ORDER BY?

Yes, in every database, because ORDER BY runs after SELECT. Example: SELECT department, COUNT(*) AS employees FROM employees GROUP BY department ORDER BY employees DESC.

Can aliases be used in GROUP BY?

In SQLite, MySQL and PostgreSQL, yes. SQL Server and Oracle do not allow it, so there you repeat the expression. Repeating it is the portable choice.

Are SQL comments executed by the database?

No. Comments are removed before the query is parsed. They produce no output and change no data.

Do SQL comments affect query performance?

No. They are stripped before planning, so long explanatory comments cost nothing measurable.

Are SQL aliases permanent?

No. An alias exists only for the query that defines it. It creates no view, column or other object.

Does a SQL alias change the database schema?

No. It only affects how a column is labelled in that query's result, or how a table is referred to inside that query.

Why use aliases with JOINs?

They make join queries shorter and remove ambiguity. When orders and users both have an id column, o.id and u.id make clear which one you mean.

Can aliases improve query readability?

Yes, that is their main purpose. A result column called total_orders is clearer to anyone reading a report than one called COUNT(*).

What databases support SQL aliases?

All major ones: SQLite, MySQL, PostgreSQL, SQL Server, Oracle, MariaDB and DB2. Aliases are part of standard SQL. Oracle is the one that does not accept AS before a table alias.

Does MySQL support the # comment syntax?

Yes. MySQL supports --, /* */ and #. The # form does not work in PostgreSQL, SQL Server or SQLite, so use -- in SQL that has to run elsewhere. In MySQL, -- must be followed by a space.

What is the SQL comment syntax in PostgreSQL?

PostgreSQL supports -- for single-line and /* */ for multi-line comments, and allows block comments to be nested. # is a syntax error there.

What is the SQL comment syntax in SQL Server?

SQL Server supports -- and /* */, and allows nested block comments, which is useful when commenting out code that already contains comments.

Can I use SQL comments to disable code temporarily?

Yes. Put -- in front of a line or wrap a block in /* */ to switch it off without deleting it, then remove the markers to switch it back on.

Can I use a SQL alias in a subquery?

Yes, and a subquery in FROM needs an alias in most databases: SELECT * FROM (SELECT city, COUNT(*) AS users FROM users GROUP BY city) AS city_counts WHERE users > 10.

What is the difference between a column alias and a table alias?

A column alias names a column of the result (SELECT COUNT(*) AS total). A table alias names a table inside the query text (FROM orders AS o). Both are temporary.

How do developers use SQL comments in real work?

To label the steps of a long query, record the business reason behind a filter, note known data problems and leave TODOs. Good comments explain why the SQL is written the way it is.

Should AS be written in uppercase?

SQL keywords are not case-sensitive, so as and AS both work. Writing keywords in uppercase is a common convention that makes them stand out from column names.

What is the SQL query evaluation order and how does it affect where aliases work?

FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. Aliases are defined at SELECT, so WHERE can never use them, ORDER BY always can, and GROUP BY and HAVING depend on the database.

Where can I practise SQL comments and aliases?

In the SQLabHub Playground: every query on this page has a "Run this query" link, and you can add your own comments and aliases to any of them.