Never forget to use aliases in your SQL queries

Never forget to use aliases in your SQL queries

Newest frameworks does all hard work for us, I known a lot of programmers, most commonly Java developers, that don’t know anything about SQL, they only know about what can do with their preferred persistence framework. EclipseLink, Hibernate and others, have a solid implementations to the most known databases. These implementations always use columns and tables aliases due framework mapping.

When we are working with reports using SQL, and not Java objects, is our responsibility to know about SQL ANSI and database specifics, like PostgreSQL schemas, PSQL on Oracle, etc. It’s in this time that many developers fall down. Generally they only know to write something like that:

Don’t be like those guys!

The query below doesn’t have problems, except if ‘bar’ is a giant table with a lot of row (millions or billions). But, the problem is when we need to join many tables, ambiguous columns are the first problem, followed by wrong columns on our select.

In the query above, is so easy to identify possible errors:

  1. ‘id’ can be a primary key on product table and in category too;
  2. ‘description’ follows the same principle, where is it from?

When you name you tables, you don’t have these headaches.

Another important point is about database scope, like on many programming languages, scopes delimit variables’ visibility. Sometimes, when you have sub queries, you’ll pay attention to it.

Sometimes MySQL can run correctly, another one, it cannot, its just lose internally and doesn’t match the correct ‘id’ fields. One more time, aliases can save them:

Follow these principles even when you have more than one nested sub query.

Believe, aliases can save you from a tons of problems.

Blog Databases