by Achshar · 9y ago · 0 comments
Strongly disagree.
Table columns should always be prefixed with table name. So users.user_id is one of the most hated patters for me. user.id looks so much cleaner. No one in their right mind should ever write the column name by itself. Especially with queries that use more than one tables.
I don't think it's very unusual to do this. The most obvious example is where there are multiple references to the same entity. For example, an Order table might contain two references to a user - one for the user who placed the order, and another for the person who approved the order.
But it's more general than this. Just saying that it's the user that's associated with the thing is frequently not enough to convey understanding, and naming with the role that the relationship is describing is helpful.
Take the following example:
SELECT s.`id`,
s.label,
s.`group`,
g.name AS group_name,
s.tags,
s.ssh_username,
s.ssh_port
FROM servers s
LEFT OUTER JOIN groups g
ON s.group = g.`id`
ORDER BY s.label ASC
In an unrelated note, how does everybody else format their SQL? The above format is what I typically use.On my team we have a lot of common table aliases which are used by convention. We understand what they mean and it gets the point across without using 20 characters.