I have a complex query
SELECT rcost.rId, resource.rId, resource.usedAt, empt.empId,
joint.joiningDate, salaryt.salId, deptt.dName
FROM rcost
RIGHT JOIN resource ON rcost.rId = resource.rId
RIGHT JOIN empt ON resource.empId = empt.empId
LEFT JOIN joint ON empt.empId = joint.empId
LEFT JOIN salaryt ON empt.empId = salaryt.empId
RIGHT JOIN deptt ON salaryt.salId = deptt.salId
WHERE empt.empId <> 1
GROUP BY rcost.rId, resource.rId, resource.usedAt, empt.empId, joint.joiningDate, salaryt.salId, deptt.dName;
This works because: All columns in the SELECT clause are either part of the GROUP BY clause or are aggregated (though in this case, there are no aggregate functions, so all selected columns must be in the GROUP BY clause).
But in the following query,
SELECT rcost.rId, resource.rId, resource.usedAt, empt.empId,
joint.joiningDate, salaryt.salId, deptt.dName
FROM rcost
RIGHT JOIN resource ON rcost.rId = resource.rId
RIGHT JOIN empt ON resource.empId = empt.empId
LEFT JOIN joint ON empt.empId = joint.empId
LEFT JOIN salaryt ON empt.empId = salaryt.empId
RIGHT JOIN deptt ON salaryt.salId = deptt.salId
WHERE empt.empId <> 1
GROUP BY rcost.rId, resource.usedAt, empt.empId, joint.joiningDate,
salaryt.salId, deptt.dName;
This doesn't work because: The resource.rId column is in the SELECT clause but not in the GROUP BY clause.
SQL requires that if a column is in the SELECT clause and is not used within an aggregate function, it must be included in the GROUP BY clause.
Since resource.rId is selected but not grouped, the database engine doesn’t know how to handle it when it tries to group the rows by the other columns.
But there is an exception, the following query will work,
SELECT rcost.rId, resource.rId, resource.usedAt, empt.empId,
joint.joiningDate, salaryt.salId, deptt.dName
FROM rcost
RIGHT JOIN resource ON rcost.rId = resource.rId
RIGHT JOIN empt ON resource.empId = empt.empId
LEFT JOIN joint ON empt.empId = joint.empId
LEFT JOIN salaryt ON empt.empId = salaryt.empId
RIGHT JOIN deptt ON salaryt.salId = deptt.salId
WHERE empt.empId <> 1
GROUP BY rcost.rId, resource.rId, empt.empId, joint.joiningDate,
salaryt.salId, deptt.dName;
Many relational database management systems (RDBMS) like MySQL or PostgreSQL allow this kind of query to run, even though it technically violates the strict SQL standard.
They might allow non-aggregated columns that are not in the GROUP BY clause to appear in the SELECT clause if the column is functionally dependent on the grouped columns.