Conversão do tipo de dados¶
Em muitos casos, um valor de um tipo de dados pode ser convertido em outro tipo de dados. Por exemplo, um valor INTEGER pode ser convertido em um valor do tipo de dados de ponto flutuante. A conversão de um tipo de dados é chamada de conversão.
Neste tópico:
Conversão explícita vs. conversão implícita¶
Os usuários podem converter explicitamente um valor de um tipo de dados em outro. Isto é chamado de conversão explícita.
Em algumas situações, o Snowflake converte automaticamente um valor em outro tipo de dados. Isto é chamado de conversão implícita ou coerção.
Conversão explícita¶
Os usuários podem converter um valor explicitamente usando qualquer uma das seguintes opções:
A função CAST.
The
::operator, called the cast operator.The appropriate SQL function; for example, TO_DOUBLE.
Por exemplo, cada consulta converte um valor de cadeia de caracteres em um valor de DATE:
SELECT CAST('2022-04-01' AS DATE); SELECT '2022-04-01'::DATE; SELECT TO_DATE('2022-04-01');
A conversão é permitida na maioria dos contextos nos quais uma expressão geral é permitida, incluindo a cláusula WHERE. Por exemplo:
SELECT date_column FROM log_table WHERE date_column >= '2022-04-01'::DATE;
Conversão implícita (coerção)¶
A coerção ocorre quando uma função (ou operador) requer um tipo de dados diferente, mas compatível com os argumentos (ou operandos).
Exemplos para funções ou procedimentos armazenados:
O seguinte código aplica a coerção ao valor INTEGER na coluna
my_integer_columnpara convertê-lo em FLOAT, de modo que o valor possa ser passado para a funçãomy_float_function(), que espera um FLOAT:SELECT my_float_function(my_integer_column) FROM my_table;
Exemplos para operadores:
O código a seguir aplica a coerção ao valor INTEGER
17para convertê-lo em VARCHAR, de modo que os valores possam ser concatenados usando o operador||:SELECT 17 || '76';
O resultado dessa instrução SELECT é a cadeia de caracteres
'1776'.The following statement coerces the INTEGER value in column
my_integer_columnto FLOAT so that the value can be compared to the valuemy_float_columnby using the<comparison operator:SELECT ... FROM my_table WHERE my_integer_column < my_float_column;
Not all contexts — for example, not all operators — support coercion.
Conversão e precedência¶
Ao converter dentro de uma expressão, o código deve levar em conta a precedência do operador de conversão em relação aos outros operadores da expressão.
Considere o seguinte exemplo:
SELECT height * width::VARCHAR || ' square meters'
FROM dimensions;
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) ...
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;
Como outro exemplo, considere a seguinte instrução:
SELECT -0.0::FLOAT::BOOLEAN;
You might expect this to be interpreted as shown in the following example:
SELECT (-0.0::FLOAT)::BOOLEAN;
Portanto, espera-se que ele retorne 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);
Portanto, a consulta resulta em uma mensagem de erro porque o sinal de menos unário não pode ser aplicado a um BOOLEAN.
Tipos de dados que podem ser convertidos¶
A tabela a seguir mostra as conversões de tipo de dados válidas no Snowflake. A tabela também mostra quais coerções o Snowflake pode executar automaticamente.
Nota
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 Conversão de tipos estruturados e semiestruturados.
Tipo de dados de origem |
Tipo de dados de destino |
Conversível |
Coercível |
Função de conversão |
Notas |
|---|---|---|---|---|---|
ARRAY |
|||||
✔ |
❌ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
Use conversão explícita para conversão. Para obter mais informações, consulte Conversão de vetores. |
|||
BINARY |
|||||
✔ |
❌ |
None. |
|||
✔ |
❌ |
None. |
|||
BOOLEAN |
|||||
✔ |
✔ |
For example, from |
|||
✔ |
❌ |
None. |
|||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
DATE |
|||||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
❌ |
None. |
|||
DECFLOAT . (decimal floating-point numbers) |
|||||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
FLOAT . (números de ponto flutuante) |
|||||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
GEOGRAPHY |
|||||
✔ |
❌ |
None. |
|||
GEOMETRY |
|||||
✔ |
❌ |
None. |
|||
NUMBER[(p,s)] . (Números de ponto fixo, incluindo INTEGER) |
|||||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
||||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
OBJECT |
|||||
✔ |
❌ |
None. |
|||
✔ |
❌ |
None. |
|||
✔ |
✔ |
None. |
|||
TIME |
|||||
✔ |
✔ |
None. |
|||
✔ |
❌ |
None. |
|||
TIMESTAMP |
|||||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
❌ |
None. |
|||
VARCHAR |
|||||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
Por exemplo, de |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
❌ |
None. |
|||
VARIANT |
|||||
✔ |
✔ |
None. |
|||
✔ |
✔ |
Por exemplo, de um VARIANT contendo |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
❌ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
✔ |
None. |
|||
✔ |
❌ |
O VARIANT deve conter uma ARRAY do tipo FLOAT ou INT. |
|||
VECTOR |
|||||
✔ |
✔ |
None. |
Nota
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.
Notas de uso¶
Exceto onde indicado de outra forma, as seguintes regras se aplicam tanto para conversão explícita quanto para conversão implícita:
Conversion depends not only on the data type, but also the value, of the source; for example:
O valor VARCHAR
'123'pode ser convertido em um valor numérico, mas o valor VARCHAR'xyz'não pode ser convertido em um valor numérico.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 value17, 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).
Para argumentos de cadeia de caracteres numérica que não sejam constantes, se NUMBER(18,5) não for suficiente para representar o valor numérico, então converta o argumento para um tipo que possa representar o valor.
For some pairs of data types, conversion can result in loss of precision; for example:
A conversão de um valor FLOAT em um valor INTEGER arredonda o valor.
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.
A conversão de um valor TIMESTAMP em um valor DATE remove as informações sobre a hora do dia.
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:
Trunca um valor VARCHAR. Por exemplo, o Snowflake não converte VARCHAR(10) para VARCHAR(5), nem implícita nem explicitamente.
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);
Neste exemplo, o número
12.3tem dois dígitos antes do ponto decimal, mas o tipo de dadosNUMBER(3,2)tem espaço para apenas um dígito antes do ponto decimal.
Ao converter de um tipo com menos precisão em um tipo com mais precisão, a conversão utiliza valores padrão. Por exemplo, a conversão de um valor DATE em um valor TIMESTAMP_NTZ faz com que a hora, o minuto, o segundo e os segundos fracionários sejam definidos como
0.Quando um valor FLOAT é convertido em um valor VARCHAR, os zeros finais são omitidos.
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}');
A instrução SELECT a seguir converte explicitamente tanto a coluna FLOAT como o valor FLOAT dentro da coluna VARIANT em VARCHAR. Em cada caso, o VARCHAR não contém zeros finais:
SELECT varchar1, float1::VARCHAR, variant1:"Loan Number"::VARCHAR FROM convert_test_zeros;
+----------+-----------------+---------------------------------+ | 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));
+--------------------------------+--------------------------------+ | 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 Escala e precisão em operações aritméticas. 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.