본문 바로가기
데이터베이스/postgresql

Postgres type casting

by 우보틀 2022. 2. 26.

postgres 에선 칼럼의 타입 변환이 가능하다(어느 dbms나 마찬가지)
최근에 1달 이전까지의 기간 내에 생성된 데이터들을 가져오고 이것들을 표시해주어야 했다.
그 과정중에서 type casting을 사용하였고 기록으로 남겨두려 한다.

수행했던 sql문은 다음과 같다

SELECT created_at::date, count(*) FROM "users_posts" "users_posts" WHERE ( user_id = 38 AND "users_posts"."created_at" > date '2022-01-26' ) AND ( "users_posts"."deleted_at" IS NULL ) GROUP BY users_posts.created_at::date;

user_id가 38이고 생성 날짜가 1월 26일 이후의 것들만 가져오고 created_at으로 group_by를 시켜준다.

요청사항은 아래와 같았다.

하루마다 카운팅 된것을 확인 하고 싶어요!!!

created_at의 생성된 원래 타입은 timestamp without time zone 이다.
pg_typeof(col_name)으로 확인할수 있다.

이렇게 되면 grouping된 출력되는 값은 우리가 원하는 값이 아니다.


만약에 created_at을 date type으로 casting 해주면??

우리가 원하는 형태로 하루씩 카운팅 된것을 볼 수 있다.


캐스팅은 두개의 방식으로 할 수 있다.
1. ::operator을 사용하는 방식
2. cast(column as type) 명령어를 사용하는 방식

1번의 예시는

SELECT CREATED_AT::DATE FROM USERS;

2번의 예시는

SELECT CAST(CREATED_AT AS DATE) FROM USERS;

postgres에서 나타낼 수 있는 Type들은 다양하다.
전부다 알고있을 필요는 없고 자주 쓰는것들만 숙지하고 있다가 필요할 때만 문서 찾아가면서 원하는 도구들을 꺼내 쓰는게 적절하지 않을까 싶다!!!

https://www.postgresql.org/docs/9.5/datatype.html

Data Types

Compatibility: The following types (or spellings thereof) are specified by SQL: bigint, bit, bit varying, boolean, char, character varying, character, varchar, date, double precision, integer, interval, numeric, decimal, real, smallint, time (with or witho

www.postgresql.org

'데이터베이스 > postgresql' 카테고리의 다른 글

Postgres timezone!!  (0) 2022.02.26
postgresql instance update 문  (0) 2022.01.18
Postgres에 백업하기  (0) 2020.02.02