공통 테이블 식
공통 테이블 식 (Common Table Expression, CTE)
공통 테이블 식(CTE)은 WITH 절에 지정된 단순 쿼리에서 파생되는 임시 결과 집합이에요. WITH 절은 SELECT 또는 INSERT 키워드 바로 앞에 옵니다. CTE는 단일 문장의 실행 범위 안에서만 정의됩니다. 하나 이상의 CTE를 Hive의 SELECT, INSERT, CREATE TABLE AS SELECT, CREATE VIEW AS SELECT 문에서 사용할 수 있어요.
출처: 문서
본문
버전 (Version)
공통 테이블 식은 HIVE-1180을 통해 Hive 0.13.0에 추가되었어요.
공통 테이블 식 구문 (Common Table Expression Syntax)
withClause: cteClause (, cteClause)*
cteClause: cte_name AS (select statment)
추가 문법 규칙 (Additional Grammar Rules)
WITH절은 서브쿼리 블록(SubQuery Blocks) 안에서는 지원되지 않아요.- CTE는 View, CTAS(Create Table As Select), INSERT 문에서 지원됩니다.
- 재귀 쿼리(Recursive Queries)는 지원되지 않아요.
예제 (Examples)
SELECT 문에서의 CTE
with q1 as ( select key from src where key = '5')
select *
from q1;
-- from style
with q1 as (select * from src where key= '5')
from q1
select *;
-- chaining CTEs
with q1 as ( select key from q2 where key = '5'),
q2 as ( select key from src where key = '5')
select * from (select key from q1) a;
-- union example
with q1 as (select * from src where key= '5'),
q2 as (select * from src s2 where key = '4')
select * from q1 union all select * from q2;
View, CTAS, Insert 문에서의 CTE
-- insert example
create table s1 like src;
with q1 as ( select key, value from src where key = '5')
from q1
insert overwrite table s1
select *;
-- ctas example
create table s2 as
with q1 as ( select key from src where key = '4')
select * from q1;
-- view example
create view v1 as
with q1 as ( select key from src where key = '5')
select * from q1;
select * from v1;
-- view example, name collision
create view v1 as
with q1 as ( select key from src where key = '5')
select * from q1;
with q1 as ( select key from src where key = '4')
select * from v1;
두 번째 View 예제에서, 쿼리의 CTE는 뷰를 만들 때 사용한 CTE와 달라요. 결과에는 key = '5'인 행들이 포함되는데, 그 이유는 뷰의 쿼리 문에서 뷰 정의에 정의된 CTE가 적용되기 때문입니다.
관련 JIRA:
- HIVE-1180 Support Common Table Expressions (CTEs) in Hive
더 알아보기 (Learn more)
CTE는 복잡한 쿼리를 WITH 절로 분해해 가독성과 재사용성을 높여 줘요. 단, 서브쿼리 블록 안에서는 사용할 수 없고 재귀 쿼리는 지원하지 않는다는 점을 기억하세요.