본문 바로가기
연구노트

Row Generation - SingleStore, Oracle, MySQL PostgreSQL

by 에이플랫폼 [Team SingleStore Korea] 2024. 1. 4.

🎯 Row Generation

이번 포스트에서는 임의의 n개 row 를 생성하는 방법을 알아 보겠습니다.

🎯 Oracle

Oracle 에서는 Hierarchical Query 를 이용해서 임의의 row 를 생성합니다.

 

SQL> select rownum from dual connect by level <= 3;

    ROWNUM
----------
         1
         2
         3

 

 

Recursive With 구문을 이용해서 MySQL 처럼 row 를 생성할 수도 있습니다.

🎯 MySQL

MySQL 8.0 이상에서는 Recursive CTE 를 이용하여 임의의 row 를 생성합니다.

 

with recursive t(n) as ( 
  select 1 as n 
  union all 
  select n+1 as n from t where n < 3
)
select * from t;
+------+
| n    |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.00 sec)

 

 

 

🎯 PostgreSQL

PostgreSQL 에서는 generate_series 함수를 사용합니다.

 

postgres=# select * from generate_series(1,3);
 generate_series
-----------------
               1
               2
               3
(3 rows)

postgres=# select generate_series(1,3);
 generate_series
-----------------
               1
               2
               3
(3 rows)
 

 

🎯 SingleStore

SingleStore 에서는 Array 와 Table 함수를 이용합니다.Table 함수는 인수로 Array 를 받아 Row 를 반환합니다.

생성할 row 가 몇개 되지 않으면 다음과 같이 Table 함수안에 Array 를 바로 명시하여 사용합니다.

 

singlestore> select * from table([1,2,3]);
+-----------+
| table_col |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)
 

만일 많은 row 를 생성해야 한다면 다음과 같이 create_array 함수를 이용합니다.

 

singlestore> select * from table(create_array(3):>array(bigint));
+-----------+
| table_col |
+-----------+
|      NULL |
|      NULL |
|      NULL |
+-----------+
3 rows in set (0.10 sec)
 

table_col 컬럼이 모두 NULL 이므로 row_number() 함수를 이용해 원하는 row 를 얻을 수 있습니다.

 

singlestore> select row_number() over () as rn from table(create_array(3):>array(bigint));
+----+
| rn |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.19 sec)
 

PostgreSQL 과 같은 generating 함수를 사용하고 싶다면 SingleStore 의 TVF(Table Valued Function) 을 이용합니다.

 

 

create or replace function gen_rows(n bigint)
returns table as return
select row_number() over () as rn from table(create_array(n):>array(bigint));

singlestore> select * from gen_rows(3);
+----+
| rn |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.11 sec)

 

🎯 마무리

이상으로 SingleStore 에서 명시적인 Table 생성 없이 간편하게 row 를 생성하는 방법을 살펴 보았습니다.