[ MySQL ] sql 처리 순서 + select max(컬럼)의 위험성

신범철·2023년 3월 2일
1

Database

목록 보기
2/2

서론

가격이 제일 비싼 식품의 정보 출력하기 문제를 푸는 도중 필자가 처음 생각했던 방식으로는 문제가 풀리지 않았는데 이유를 모르겠어서 찾아본 내용들을 정리합니다.

내가 생각한 방식
SELECT product_id, product_name, product_cd, category, max(price) as price from food_product

인터넷의 답안지들
SELECT * from food_product where price = (select max(price) from food_product)

SELECT * from food_product order by price desc limit 1

문제 분석

결론은 row의 값이 다른 값들이 출력되었다.

예를 들면, 상품 테이블이 있을 때

idprice
11000
24000
32000

아래와 같은 결과를 원했지만

idprice
24000

아래와 같은 결과가 나온 상황이다.

idprice
14000

프로그래머스 문제 예시

프로그래머스 문제로 분석해보면

select * from food_product을 찍으면 테스트 케이스의 테이블이 찍힌다.

내가 생각한 방식(SELECT product_id, product_name, product_cd, category, max(price) as price from food_product)을 찍으면 위 문제 상황이 발생한다.

정답(SELECT * from food_product where price = (select max(price) from food_product))을 찍으면

답의 차이는 product_id, product_name, product_cd, category는 가장 위의 row가 찍히고 max(price) as price만 최대값으로 선택되었다.

그렇다면 정렬을 통해 동일하게 줄수 있지 않을까? 라는 생각을 했다.

SELECT product_id, product_name, product_cd, category, max(price) as price from food_product order by price desc limit 1

하지만 여전히 틀리다..

이유는 sql의 처리순서이다.

정답에서 where 절은 select 절 이전에 처리되는데

틀린 답에서는 select 절 이후에 order by 절이 실행되기 때문이다.

추가로 group by절을 통해 정답을 도출할 수 있다.

SELECT product_id, product_name, product_cd, category, max(price) as price from food_product group by product_cd, price order by price desc limit 1

group by 절이 select 절 이전에 처리 되기 때문에 정답을 도출할 수 있다.

결론

  1. sql 처리순서를 생각하자
  2. select를 각각 선언했을 때는 다른 row의 값이 나올 수 있다.
profile
https://github.com/beombu

2개의 댓글

comment-user-thumbnail
2023년 3월 4일

링크 안에 댓글이 도움이 되었으면 좋겠네요!
https://okky.kr/articles/1408707?note=1642318

1개의 답글