by eirki · 5y ago · 0 comments
SELECT
title,
last_name,
first_name
FROM books
LEFT JOIN authors
ON books.author_id = authors.id
> Prefer SELECT
b.title,
a.last_name,
a.first_name
FROM books AS b
LEFT JOIN authors AS a
ON b.author_id = a.id
Couldn't disagree more. One letter abbreviations hurt readability IMO. SELECT t1.thing
, t2.stuff
, t3.stuffagain
, t4.more
FROM SomeTable t1
JOIN TableThatLinksToSelf t2 ON <join predicate>
JOIN TableThatLinksToSelf t3 ON <join predicate>
JOIN AnotherTable t4 ON <join predicate>
that is not the point that is being made here. The point is that explicitly naming tables is beneficial to understanding and reducing issues later. Short alias is preferable to not specifying column sources at all.I prefer descriptive table and other object names, and abbreviate them in aliases within queries (though usually not to single letters).
Sure it does not help to understand the origins of a given field without aliases, unless someone is very familiar with the schema.
If the tables names are long, by all means abbreviate them a little, but never just use 1 letter aliases.
I wonder if the author has ever worked with a system that has more than a handful of tables.
SELECT
bo.title,
au.last_name,
au.first_name
FROM books AS bo
LEFT JOIN authors AS au ON
bo.author_id = au.idIn simple cases that may be just the singular of the table name, e.g.:
SELECT
book.title,
author.last_name,
author.first_name
FROM books AS book
LEFT JOIN authors AS author ON
book.author_id = author.id
But in other cases, it will be different, e.g.: SELECT
manager.last_name || ', ' || manager.first_name AS manager_name,
coalesce(employee.title, 'All Titles') AS staff_title,
count(employee.id) AS count
FROM employees AS manager
LEFT JOIN employees AS employee ON
manager.id = employee.manager_id
GROUP BY manager.id, ROLLUP(employee.title)
HAVING employee.title IS NOT NULL
OR GROUPING(employee.title)=1