SQLWarningSyntax ErrorJuly 4, 2026

Syntax Error

Cannot use an index on a table that has not been fully joined: 'SELECT * FROM employees E1 JOIN departments D ON E1.department_id = D.id JOIN locations L ON D.location_id = L.id WHERE E1.salary > (SELECT AVG(salary) FROM employees WHERE department_id = E1.department_id) AND E1.department_id = (SELECT id FROM departments WHERE name = 'Sales') LIMIT 1;

What This Error Means

This error occurs when SQL is unable to use an index on a table that is not fully joined due to the presence of a correlated subquery or a function that prevents the use of the index.

Why It Happens

This error typically occurs due to the use of a correlated subquery or a function that prevents the use of the index. In the example query, the subquery '(SELECT AVG(salary) FROM employees WHERE department_id = E1.department_id)' prevents the use of the index on the 'employees' table, resulting in the inability to use an index on the table.

How to Fix It

  1. 1To fix this error, consider rewriting the query to avoid the use of correlated subqueries. One possible solution is to use a subquery to compute the average salary for each department, and then join the result with the 'employees' table. Alternatively, consider reorganizing the database to enable the use of an index on the 'employees' table.

Example Code Solution

❌ Before (problematic code)
SQL
SELECT * FROM employees E1 JOIN departments D ON E1.department_id = D.id JOIN locations L ON D.location_id = L.id WHERE E1.salary > (SELECT AVG(salary) FROM employees WHERE department_id = E1.department_id) AND E1.department_id = (SELECT id FROM departments WHERE name = 'Sales') LIMIT 1;
✅ After (fixed code)
SQL
WITH sales_avg AS (SELECT department_id, AVG(salary) as avg_salary FROM employees GROUP BY department_id)
SELECT * FROM employees E1 JOIN departments D ON E1.department_id = D.id JOIN locations L ON D.location_id = L.id JOIN sales_avg S ON E1.department_id = S.department_id WHERE E1.salary > S.avg_salary AND E1.department_id = (SELECT id FROM departments WHERE name = 'Sales') LIMIT 1;

Fix for Cannot use an index on a table that has not been fully joined: 'SELECT * FROM employees E1 JOIN departments D ON E1.department_id = D.id JOIN locations L ON D.location_id = L.id WHERE E1.salary > (SELECT AVG(salary) FROM employees WHERE department_id = E1.department_id) AND E1.department_id = (SELECT id FROM departments WHERE name = 'Sales') LIMIT 1;

Related SQL Errors

Related SQL Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error