Updated on 2026-11-06 GMT+08:00

Arithmetic Operators

Arithmetic operators include binary operations and unary operations. These operators all return numeric types.

Table 1 Arithmetic operators

Operator

Result Type

Description

A + B

All numeric types

Adds A and B. The result data type is related to the operand data types. For example, adding an integer type data to a floating-point type data results in a floating-point type value.

A - B

All numeric types

Subtracts B from A. The result data type is related to the operand data types.

A * B

All numeric types

Multiplies A and B. The result data type is related to the operand data types.

A / B

All numeric types

Divides A by B. The result is a double-precision numeric value.

A % B

All numeric types

Returns the remainder of A divided by B. The result data type is related to the operand data types.

A & B

All numeric types

Performs a bitwise AND operation on the binary representations of the two parameters. If a bit is 1 in both expressions, the corresponding bit in the result is 1. Otherwise, the corresponding bit in the result is 0.

A | B

All numeric types

Performs a bitwise OR operation on the binary representations of the two parameters. If a bit is 1 in either expression, the corresponding bit in the result is 1. Otherwise, the corresponding bit in the result is 0.

A ^ B

All numeric types

Performs a bitwise XOR operation on the binary representations of the two parameters. If and only if a bit is 1 in exactly one expression, the corresponding bit in the result is 1. Otherwise, the corresponding bit in the result is 0.

~A

All numeric types

Performs a bitwise NOT operation (inversion) on an expression.

Precautions

  • Integer division uses the div function. The / operator always returns a DOUBLE type.
  • In ANSI mode (enabled by default in Spark 4.0), integer division by zero throws an exception rather than returning NULL.
  • Bitwise operators (&, |, ^, ~) only apply to integer types.
  • The % modulo operator is equivalent to the mod() function.

Example 1: Basic Arithmetic Operations

SELECT 1 + 2;    -- 3
SELECT 5 - 3;    -- 2
SELECT 2 * 3;    -- 6
SELECT 10 / 3;   -- 3.333...

Example 2: Modulo Operation

SELECT 10 % 3;   -- 1
SELECT 7 % 2;    -- 1

Example 3: Bitwise Operations

SELECT 5 & 3;    -- 1   (0101 & 0011 = 0001)
SELECT 5 | 3;    -- 7   (0101 | 0011 = 0111)
SELECT 5 ^ 3;    -- 6   (0101 ^ 0011 = 0110)
SELECT ~5;       -- -6  (bitwise NOT)

Example 4: Mixed Type Operations

SELECT 1 + 2.5;      -- 3.5 (integer + floating-point = floating-point)
SELECT 10 / 3;        -- 3.333... (division returns DOUBLE)
SELECT CAST(10 AS DOUBLE) / 3; -- 3.333...