[PostgreSQL] SQL Error [42883]: ERROR: function sum(character varying) does not exist. Hint: No function matches the given name and argument types. You might need to add explicit type casts 쿼리 오류 해결하기
쿼리
select sum(sub_value) as sum_sub_value from tb_info
오류 내용
SQL Error [42883]: ERROR: function sum(character varying) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 8
Error position: line: 160 pos: 7
sub_value 컬럼이 VARCHAR(문자열) 이기 때문에 PostgreSQL은 숫자 합계(SUM)를 계산할 수 없다. 문자열로 되어 있으니 직접 숫자로 변환해주라고 알려주는 것이다.
해결방법: ::numeric 또는 ::int 형 변환 추가
✔ 일반적인 해결
SELECT SUM(sub_value::numeric) AS sum_sub_value
FROM tb_info;
✔ 정수라면
SELECT SUM(sub_value::int) AS sum_sub_value
FROM tb_info;
✔ NULL-safe + 공백safe (권장)
문자열에 공백 또는 빈 문자열이 있을 수 있으면 이렇게 해야 오류 없음.
SELECT SUM(NULLIF(sub_value, '')::numeric) AS sum_sub_value
FROM tb_info;
문자열에 숫자가 아닌 값이 들어있으면?
예:"10", "20", "ABC", "5" 이런 식으로 들어있으면 아래 오류 발생:
invalid input syntax for type numeric: "ABC"
이럴 때는 숫자인 값만 필터링:
SELECT SUM((regexp_replace(sub_value, '[^0-9]', '', 'g'))::numeric)
FROM tb_info;


