G-3120: Always use table aliases when your SQL statement involves more than one source.
Major
Maintainability
Reason
It is more human readable to use aliases instead of writing columns with no table information.
Especially when using subqueries the omission of table aliases may end in unexpected behavior and result.
Example (bad)
SELECT last_name
,first_name
,department_name
FROM employees
JOIN departments USING (department_id)
WHERE EXTRACT(MONTH FROM hire_date) = EXTRACT(MONTH FROM SYSDATE);
Example (better)
SELECT e.last_name
,e.first_name
,d.department_name
FROM employees e
JOIN departments d ON (e.department_id = d.department_id)
WHERE EXTRACT(MONTH FROM e.hire_date) = EXTRACT(MONTH FROM SYSDATE);
Example (good)
Using meaningful aliases improves the readability of your code.
SELECT emp.last_name
,emp.first_name
,dept.department_name
FROM employees emp
JOIN departments dept ON (emp.department_id = dept.department_id)
WHERE EXTRACT(MONTH FROM emp.hire_date) = EXTRACT(MONTH FROM SYSDATE);
Example Subquery (bad)
If the jobs
table has no employee_id
column and employees
has one this query will not raise an error but return all rows of the employees
table as a subquery is allowed to access columns of all its parent tables - this construct is known as correlated subquery.
SELECT last_name
,first_name
FROM employees
WHERE employee_id IN (SELECT employee_id
FROM jobs
WHERE job_title like '%Manager%');
Example Subquery (good)
If the jobs
table has no employee_id
column this query will return an error due to the directive (given by adding the table alias to the column) to read the employee_id
column from the jobs
table.
SELECT emp.last_name
,emp.first_name
FROM employees emp
WHERE emp.employee_id IN (SELECT j.employee_id
FROM jobs j
WHERE j.job_title like '%Manager%');