데이터 타입 변환

대부분의 경우, 한 데이터 타입의 값을 다른 데이터 타입으로 변환할 수 있습니다. 예를 들어, INTEGER 값은 부동 소수점 데이터 타입 값으로 변환할 수 있습니다. 데이터 타입을 변환하는 것을 형 변환 이라고 합니다.

이 항목의 내용:

명시적 캐스팅 vs 암시적 캐스팅

사용자는 값을 한 데이터 타입에서 다른 데이터 타입으로 명시적으로 변환할 수 있습니다. 이것을 명시적 캐스팅 이라고 합니다.

경우에 따라 Snowflake는 값을 다른 데이터 타입으로 자동 변환합니다. 이것을 암시적 캐스팅 또는 강제 변환 이라고 합니다.

명시적 캐스팅

사용자는 다음 옵션 중 하나를 사용하여 명시적으로 값을 캐스팅할 수 있습니다.

  • CAST 함수.

  • The :: operator, called the cast operator.

  • The appropriate SQL function; for example, TO_DOUBLE.

예를 들어, 각 쿼리는 문자열 값을 DATE 값으로 형 변환합니다.

SELECT CAST('2022-04-01' AS DATE);

SELECT '2022-04-01'::DATE;

SELECT TO_DATE('2022-04-01');
Copy

WHERE 절을 포함하여 일반적 식이 허용되는 대부분의 컨텍스트에서 캐스팅이 허용됩니다. 예:

SELECT date_column
  FROM log_table
  WHERE date_column >= '2022-04-01'::DATE;
Copy

암시적 형 변환(“강제 변환”)

강제 변환은 함수(또는 연산자)가 인자(또는 피연산자)와는 다르되 호환되는 데이터 타입을 요구할 때 발생합니다.

  • 함수 또는 저장 프로시저의 예:

    • 다음 코드는 FLOAT를 예상하는 my_float_function() 함수에 값을 전달할 수 있도록 my_integer_column 열의 INTEGER 값을 FLOAT로 강제 변환합니다.

      SELECT my_float_function(my_integer_column)
        FROM my_table;
      
      Copy
  • 연산자의 예:

    • 다음 코드는 || 연산자를 사용하여 값을 연결할 수 있도록 INTEGER 값 17 을 VARCHAR로 강제 변환합니다.

      SELECT 17 || '76';
      
      Copy

      이 SELECT 문의 결과는 문자열 '1776' 입니다.

    • The following statement coerces the INTEGER value in column my_integer_column to FLOAT so that the value can be compared to the value my_float_column by using the < comparison operator:

      SELECT ...
        FROM my_table
        WHERE my_integer_column < my_float_column;
      
      Copy

Not all contexts — for example, not all operators — support coercion.

캐스팅 및 우선순위

식 내에서 캐스팅할 때 코드는 식의 다른 연산자에 상대적인 캐스트 연산자의 우선순위를 고려해야 합니다.

다음 예를 살펴보겠습니다.

SELECT height * width::VARCHAR || ' square meters'
  FROM dimensions;
Copy

The cast operator has higher precedence than the arithmetic operator * (multiply), so the statement is interpreted as shown in the following example:

... height * (width::VARCHAR) ...
Copy

To cast the result of the expression height * width, use parentheses, as shown in the following example:

SELECT (height * width)::VARCHAR || ' square meters'
  FROM dimensions;
Copy

또 다른 예로 다음 문을 고려하십시오.

SELECT -0.0::FLOAT::BOOLEAN;
Copy

You might expect this to be interpreted as shown in the following example:

SELECT (-0.0::FLOAT)::BOOLEAN;
Copy

따라서FALSE (0 = FALSE , 1 = TRUE)를 반환해야 합니다.

However, the cast operator has higher precedence than the unary minus (negation) operator, so the statement is interpreted as shown in the following example:

SELECT -(0.0::FLOAT::BOOLEAN);
Copy

따라서 BOOLEAN 에는단항 마이너스를 적용할 수 없기 때문에 쿼리 결과에 오류 메시지가 표시됩니다.

캐스팅할 수 있는 데이터 타입

다음 테이블은 Snowflake에서 유효한 데이터 타입 변환을 보여줍니다. 이 표에는 Snowflake가 자동으로 수행할 수 있는 강제 변환도 나와 있습니다.

참고

Internally, the CAST function and the :: operator call the appropriate conversion function. For example, if you cast a NUMBER to a BOOLEAN, Snowflake calls the TO_BOOLEAN function. The usage notes for each conversion function apply when the function is called indirectly by using a cast, and also when the function is called directly. For example, if you execute CAST(my_decimal_column AS BOOLEAN), the rules for calling TO_BOOLEAN with a DECIMAL value apply. For convenience, the table includes links to the relevant conversion functions.

For more information about conversions between semi-structured types and structured types, see 정형 유형과 반정형 유형 변환하기.

소스 데이터 타입

대상 데이터 타입

캐스팅 가능

강제 변환 가능

변환 함수

참고

ARRAY

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

VECTOR

변환을 위해 명시적 형변환 을 사용합니다. 자세한 내용은 벡터 변환 섹션을 참조하십시오.

BINARY

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

BOOLEAN

DECFLOAT

TO_DECFLOAT

For example, from FALSE to 0.

NUMBER

TO_NUMBER

None.

VARCHAR

TO_VARCHAR

예를 들어, TRUE 에서 'true' 로 변경합니다.

VARIANT

TO_VARIANT

None.

DATE

TIMESTAMP

TO_TIMESTAMP

None.

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

DECFLOAT . (decimal floating-point numbers)

BOOLEAN

TO_BOOLEAN

예를 들어, 0 에서 FALSE 로 변경합니다.

FLOAT

TO_DOUBLE

None.

NUMBER[(p,s)]

TO_NUMBER

None.

VARCHAR

TO_VARCHAR

None.

FLOAT . (부동 소수점 숫자)

BOOLEAN

TO_BOOLEAN

예를 들어, 0.0 에서 FALSE 로 변경합니다.

DECFLOAT

TO_DECFLOAT

None.

NUMBER[(p,s)]

TO_NUMBER

None.

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

GEOGRAPHY

VARIANT

TO_VARIANT

None.

GEOMETRY

VARIANT

TO_VARIANT

None.

NUMBER[(p,s)] . (고정 소수점 숫자, INTEGER 포함)

BOOLEAN

TO_BOOLEAN

예를 들어, 0 에서 FALSE 로 변경합니다.

DECFLOAT

TO_DECFLOAT

None.

FLOAT

TO_DOUBLE

None.

TIMESTAMP

TO_TIMESTAMP

[1]

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

OBJECT

ARRAY

TO_ARRAY

None.

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

TIME

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

TIMESTAMP

DATE

TO_DATE , DATE

None.

TIME

TO_TIME , TIME

None.

VARCHAR

TO_VARCHAR

None.

VARIANT

TO_VARIANT

None.

VARCHAR

BOOLEAN

TO_BOOLEAN

예를 들어, 'false' 에서 FALSE 로 변경합니다.

DATE

TO_DATE , DATE

None.

DECFLOAT

TO_DECFLOAT

None.

FLOAT

TO_DOUBLE

예를 들어, '12.34' 에서 12.34 로 변경합니다.

NUMBER[(p,s)]

TO_NUMBER

예를 들어, '12.34' 에서 12.34 로 변경합니다.

TIME

TO_TIME , TIME

None.

TIMESTAMP

TO_TIMESTAMP

None.

VARIANT

TO_VARIANT

None.

VARIANT

ARRAY

TO_ARRAY

None.

BOOLEAN

TO_BOOLEAN

예를 들어, 'false' 가 포함된 VARIANT 에서 FALSE 로 변경합니다.

DATE

TO_DATE , DATE

None.

FLOAT

TO_DOUBLE

None.

GEOGRAPHY

TO_GEOGRAPHY

None.

NUMBER[(p,s)]

TO_NUMBER

None.

OBJECT

TO_OBJECT

None.

TIME

TO_TIME , TIME

None.

TIMESTAMP

TO_TIMESTAMP

None.

VARCHAR

TO_VARCHAR

None.

VECTOR

VARIANT에는 FLOAT 타입이나 INT 타입으로 구성된 ARRAY가 포함되어야 합니다.

VECTOR

ARRAY

TO_ARRAY

None.

참고

For each listed data type — for example, FLOAT — the rules apply to all aliases for that data type. For example, the rules for FLOAT apply to DOUBLE, which is an alias for FLOAT.

사용법 노트

달리 명시된 경우를 제외하고 다음 규칙은 명시적 형 변환과 암시적 형 변환 둘 다에 적용됩니다.

  • Conversion depends not only on the data type, but also the value, of the source; for example:

    • VARCHAR 값 '123' 은 숫자 값으로 변환할 수 있지만, VARCHAR 값 'xyz' 는 숫자 값으로 변환할 수 없습니다.

    • The ability to cast a specific value of type VARIANT depends on the type of the data inside the VARIANT. For example, if the VARIANT contains a value of type TIME, then you can’t cast the VARIANT value to a TIMESTAMP value, because you can’t cast a TIME value to a TIMESTAMP value.

  • Snowflake performs implicit conversion of arguments to make them compatible. For example, if one of the input expressions is a numeric type, the return type is also a numeric type. That is, SELECT COALESCE('17', 1); first converts the VARCHAR value '17' to the NUMBER value 17, and then returns the first non-NULL value.

    When conversion isn’t possible, implicit conversion fails. For example, SELECT COALESCE('foo', 1); returns an error because the VARCHAR value 'foo' can’t be converted to a NUMBER value.

    We recommend passing in arguments of the same type or explicitly converting arguments if needed.

  • When implicit conversion converts a non-numeric value to a numeric value, the result is a value of type NUMBER(18,5).

    상수가 아닌 숫자형 문자열 인자의 경우 NUMBER(18,5)가 숫자 값을 나타내기에 충분하지 않으면 해당 값을 나타낼 수 있는 형식으로 인자를 형 변환 해야 합니다.

  • For some pairs of data types, conversion can result in loss of precision; for example:

    • FLOAT 값을 INTEGER 값으로 변환하면 값이 반올림됩니다.

    • Converting a value from fixed-point numeric — for example, NUMBER(38, 0) — to floating point — for example, FLOAT — can result in rounding or truncation if the fixed-point number can’t be precisely represented in a floating point number.

    • TIMESTAMP 값을 DATE 값으로 변환하면 시간 정보가 제거됩니다.

  • Although Snowflake converts values in some situations where loss of precision can occur, Snowflake doesn’t allow conversion in other situations where a loss of precision would occur. For example, Snowflake doesn’t allow conversion when conversion would cause the following situations to happen:

    • VARCHAR 값을 자릅니다. 예를 들어, Snowflake는 VARCHAR(10)을 VARCHAR(5)로 암시적이든 명시적이든 전송하지 않습니다.

    • Result in the loss of digits other than the least significant digits. For example, the following loss of digits fails:

      SELECT 12.3::FLOAT::NUMBER(3,2);
      
      Copy

      이 예제에서 12.3 숫자는 소수점 앞에 자릿수가 두 자리이지만 데이터 타입 NUMBER(3,2) 는 소수점 앞에 자릿수가 한 자리만 있습니다.

  • 정밀도가 낮은 타입에서 정밀도가 더 높은 타입으로 변환할 때 변환은 기본값을 사용합니다. 예를 들어, DATE 값을 TIMESTAMP_NTZ 값으로 변환하면 시, 분, 초 및 분수 초가 0 으로 설정됩니다.

  • FLOAT 값을 VARCHAR 값으로 형 변환하면 후행 0이 생략됩니다.

    For example, the following statements create a table and insert a row that contains a VARCHAR value, a FLOAT value, and a VARIANT value. The VARIANT value is constructed from JSON that contains a floating-point value represented with trailing zeros:

    CREATE OR REPLACE TABLE convert_test_zeros (
      varchar1 VARCHAR,
      float1 FLOAT,
      variant1 VARIANT);
    
    INSERT INTO convert_test_zeros SELECT
      '5.000',
      5.000,
      PARSE_JSON('{"Loan Number": 5.000}');
    
    Copy

    다음 SELECT 문은 FLOAT 열과 VARIANT 열 내부의 FLOAT 값을 둘 다 VARCHAR로 명시적으로 캐스팅합니다. 각각의 경우에 VARCHAR에는 후행 0이 없습니다.

    SELECT varchar1,
           float1::VARCHAR,
           variant1:"Loan Number"::VARCHAR
      FROM convert_test_zeros;
    
    Copy
    +----------+-----------------+---------------------------------+
    | VARCHAR1 | FLOAT1::VARCHAR | VARIANT1:"LOAN NUMBER"::VARCHAR |
    |----------+-----------------+---------------------------------|
    | 5.000    | 5               | 5                               |
    +----------+-----------------+---------------------------------+
    
  • Some operations can return different data types, depending on a conditional expression. For example, the following IFNULL calls return slightly different data types depending on the input values:

    SELECT SYSTEM$TYPEOF(IFNULL(12.3, 0)),
           SYSTEM$TYPEOF(IFNULL(NULL, 0));
    
    Copy
    +--------------------------------+--------------------------------+
    | SYSTEM$TYPEOF(IFNULL(12.3, 0)) | SYSTEM$TYPEOF(IFNULL(NULL, 0)) |
    |--------------------------------+--------------------------------|
    | NUMBER(3,1)[SB1]               | NUMBER(1,0)[SB1]               |
    +--------------------------------+--------------------------------+
    

    If the expression has more than one possible data type, Snowflake chooses the data type based on the actual result. For more information about precision and scale in calculations, see 산술 연산의 소수 자릿수와 전체 자릿수. If the query generates more than one result — for example, multiple rows of results — Snowflake chooses a data type that is capable of holding each of the individual results.

  • Some applications, such as SnowSQL, and some graphical user interfaces, such as the Classic Console, apply their own conversion and formatting rules when they display data. For example, SnowSQL displays BINARY values as a string that contains only hexadecimal digits; that string is generated by implicitly calling a conversion function. Therefore, the data that SnowSQL displays might not unambiguously indicate which data conversions that Snowflake coerced.