How to use AS alias in SQL

Category: SQL :: Published at: 29.12.2021

Sometimes you want to change the column name to make it more readable and easier to analyze.

AS clause will fit all your expectations in this field

# simple use of AS clause
SELECT brand AS car_brand FROM cars

# the query above will list table with one column named car_brand

Other examples:

# this is how you can name aggregate function called in query
SELECT SUM(amount) AS summed_salary FROM payments

Remember that alias will be executed in the end of your query. This is why you can't use the name of this column inside
your WHERE neither HAVING clause. It just won't be visible there and you will get an error.

# wrong way
SELECT brand, SUM(amount) AS summed_amount FROM payments GROUP BY brand HAVING summed_amount > 1000

# correct way
SELECT brand, SUM(amount) AS summed_amount FROM payments GROUP BY brand HAVING SUM(amount) > 1000


- Click if you liked this article

Views: 72