Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
How to query more than one table
Creating JOINs
Referencing columns
9. Rename columns with AS
Let's practice

Instruction

Good job! We can do one more thing with our columns: rename them. Up until now, the column named Id was always shown as Id in the result. But we can rename it:

SELECT
  Person.Id AS PersonId,
  Car.Id AS CarId
FROM Person
JOIN Car
  ON Person.Id = Car.OwnerId;

After the column name (e.g., Person.Id) we use the new keyword AS, and we put the new name after it (PersonId). We can repeat this process with every column.

The new name is just an alias, which means it's temporary and doesn't change the actual column name in the database. It only influences the way the column is shown in the result of this specific query. This technique is often used when there are a few columns under the same name coming from different tables. Normally, when T-SQL displays columns in the result, there is no information about the table that a specific column is part of.

In our example, we had two columns Id, so we renamed them to PersonId and CarId respectively. Now, if we see the columns in the result, we will know which column comes from which table.

Exercise

Select the director name and movie title from the tables Movie and Director such that each movie is shown together with its director. Rename the Title column to MovieTitle.

Stuck? Here's a hint!

Type:

SELECT
  Movie.Title AS MovieTitle,
  Director.Name
FROM Movie
JOIN Director
  ON Movie.DirectorId = Director.Id;