db/MySQL

[MySQL] EXISTS, NOTEXISTS

잘할수있을거야 2022. 8. 8. 17:27

SELECT문의 결과에 로우가 포함되어있는지 유무 확인

 

select exists (select * from 테이블) ;
서브 쿼리에 해당하는 로우가 존재하면 true(1), 존재하지 않으면 false(0)


select not exists (select * from 테이블) ;
서브 쿼리에 해당하는 로우가 존재하지 않으면 true(1), 존재하면 false(0)

 

CREATE TABLE exists_test (id INT);

SELECT EXISTS(SELECT id FROM exists_test) AS '존재?' ;
SELECT NOT EXISTS(SELECT id FROM exists_test) AS '미존재?';

INSERT INTO exists_test(id) VALUES(1);

SELECT EXISTS(SELECT id FROM exists_test) AS '존재?' ;
SELECT NOT EXISTS(SELECT id FROM exists_test) AS '미존재?';