Search code examples
sqldatabasenlp-question-answering

How to SELECT record from a table where column is equal to a value but shouldn't be equal to another value?


I have listed two different solutions to the given problem. is there any better approach to solve these types of problems?

Q: GIVEN EMPLOYEE TABLE below, SELECT name whose id = 1 but not = 3

-- ID   NAME
-- 1    ram
-- 2    shayam
-- 1    mohan
-- 7    mohan
-- 4    monu
-- 3    monu
-- 1    monu
-- 5    sonu
-- 1    sonu
-- 2    sonu


-- OUTPUT
-- mohan
-- ram
-- sonu

-- Solution 1:
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE e1.id = 1 AND e1.NAME NOT IN (
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE  e2.id = 3);

-- Solution 2:
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE e1.id = 1 
MINUS
SELECT DISTINCT(e1.NAME) FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.name = e2.name WHERE  e2.id = 3;

-- Use this code to test the logic:
CREATE TABLE EMPLOYEE( id INT, name VARCHAR(25) ); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'ram'); 
INSERT INTO EMPLOYEE(id, name) VALUES(2, 'shayam'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'mohan'); 
INSERT INTO EMPLOYEE(id, name) VALUES(7, 'mohan'); 
INSERT INTO EMPLOYEE(id, name) VALUES(4, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(3, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'monu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(5, 'sonu'); 
INSERT INTO EMPLOYEE(id, name) VALUES(1, 'sonu');
INSERT INTO EMPLOYEE(id, name) VALUES(2, 'sonu');

SELECT * FROM EMPLOYEE;

Solution

  • The minus is fine, but you don't need the select distinct. Minus is a set function that only returns distinct rows. I tend to use aggregation for this:

    select e.name
    from employee e
    where id in (1, 3)
    group by e.name
    having max(id) = 1;   -- there is no 3 if the max is 1
    

    However, your methods are basically fine although I'll repeat that the select distincts are not necessary.