14. MySQL: Aliases

14. MySQL: Aliases

  • Aliases are used for our convenience to give the result columns a temporary name and make them more readable.

  • Aliases are temporary, meaning they exist for the duration of the query.

  • We use the AS keyword to create an alias.

Let's have a look at the film table.

SELECT * FROM film;

Output:


  • Suppose we wish to show the rental rate for the movie to the customer, but we need to make it clear that it is 0.99$ per day, so we will just name the column the same.

If the alias name consists of spaces, we need to include it in a double or single quote.

SELECT title AS 'Film Title', rental_rate AS 'Rent Per Day (in $)', rating as Rating 
FROM film
LIMIT 5;

Output:


  • Let's have a look at the category table and the film_category tables.
SELECT * FROM category;

Output:

SELECT * FROM film_category;

Output:


We can also use an alias to reduce the length of our query, meaning we can reduce the name of the table to reduce typing it repetitively.

Try to understand the query below, it is a bit more complex than the others we have used before.

We are trying to name the category of the films and we are extracting information from multiple tables here.

SELECT f.film_id AS Film_id, f.title AS Title, c.name AS Category_name
FROM film AS f, category AS c, film_category AS fc
WHERE f.film_id = fc.film_id AND c.category_id = fc.category_id
ORDER BY film_id;

Output:


If we would have not used aliases, the query would have looked like this which is much messier.

SELECT film.film_id, film.title, category.name
FROM film, category, film_category
where film.film_id = film_category.film_id AND category.category_id = film_category.category_id
order by film_id;

'll meet again tomorrow!

To see more examples, you can always refer w3 schools; it has always been my go-to website to understand things.

References: w3schools.com/mysql/default.asp

*****All the outputs provided are a snippet of the actual result.