Search code examples
sqlsqlitesubqueryderived-table

SQL syntax error: near "("


When I try to run this query:

select branch_no, max (avg_salary)
from (select allocatedto, avg (salary)
      from staff, worker
      where staff.staff_no = worker.staff_no
      group by allocatedto) 
      as branch_avg (branch_no, avg_salary);

I get this error:

Error: near "(": syntax error

Solution

  • select my_alias1,my_alias2 from (select col1,col2,...) as A (my_alias1,my_alias2)
    

    The above syntax is valid in SQL Server.

    To alias the column in derived table you need to use AS inside the derived table. Try this

    SELECT Max (avg_salary)
    FROM   (SELECT allocatedto  AS branch_no,
                   Avg (salary) AS avg_salary
            FROM   staff
                   INNER JOIN worker
                           ON staff.staff_no = worker.staff_no
            GROUP  BY allocatedto) AS branch_avg;
    

    Also start using INNER JOIN instead of old style comma separated join