CREATE TABLE EMPLOYEE (
empId INTEGER AUTO_INCREMENT PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL
);
INSERT INTO EMPLOYEE(name, dept) VALUES ('Clark', 'Sales');
INSERT INTO EMPLOYEE(name, dept) VALUES ('Dave', 'Accounting');
INSERT INTO EMPLOYEE(name, dept) VALUES ('Ava', 'Sales');
SELECT *
FROM EMPLOYEE AS a
INNER JOIN EMPLOYEE b
ON a.empId = (SELECT MIN(b.empId));
Output:
+-------+-------+------------+-------+-------+------------+
| empId | name | dept | empId | name | dept |
+-------+-------+------------+-------+-------+------------+
| 1 | Clark | Sales | 1 | Clark | Sales |
| 2 | Dave | Accounting | 2 | Dave | Accounting |
| 3 | Ava | Sales | 3 | Ava | Sales |
+-------+-------+------------+-------+-------+------------+
I expect the query to return only the row with empId = 1.
Why does it returns all rows?
How is the INNER JOIN evaluating the ON clause with the subquery?
What is the correct behavior here?
How can I fix this to only get the row with the smallest empId?
MINof a row is the row itself. What else would it be if there's only 1 row.JOIN? If you just want the earliestemp_id, just order it byemp_id.