NULL 의미 체계

적용 대상:검사 표시됨 예 Databricks SQL 검사 예 Databricks Runtime으로 표시됨

테이블은 행 집합으로 구성되며 각 행에는 열 집합이 포함됩니다. 열은 데이터 형식과 연결되며 엔터티의 특정 특성을 나타냅니다(예 age : 라는 person엔터티의 열). 행이 존재할 때 행과 관련된 열의 값을 알 수 없는 경우가 있습니다. 에서 SQL이러한 값은 로 NULL표시됩니다. 이 섹션에서는 다양한 연산자, 식 및 기타 SQL 구문에서 처리하는 값의 NULL 의미 체계를 자세히 설명합니다.

다음은 라는 person테이블의 스키마 레이아웃 및 데이터를 보여 줍니다. 데이터에는 열의 값이 age 포함 NULL 되며 이 테이블은 아래 섹션의 다양한 예제에서 사용됩니다.

 Id  Name   Age
 --- -------- ----
 100 Joe      30
 200 Marry    NULL
 300 Mike     18
 400 Fred     50
 500 Albert   NULL
 600 Michelle 30
 700 Dan      50

비교 연산자

Azure Databricks는 , , <>==<=와 같은 >표준 비교 연산자를 지원합니다. 이러한 연산자의 결과는 알 수 없거나 NULL 피연산자 또는 피연산자 중 하나가 알 수 없거나 NULL인 경우 입니다. 같음 값을 비교 NULL 하기 위해 Azure Databricks는 피연산자 중 하나가 일 때 를 반환 False 하고 두 피연산자가 NULL 일 때 를 반환 True 하는 null 안전 등호 연산자NULL(<=>)를 제공합니다. 다음 표에서는 하나 또는 두 피연산자가 인 경우 비교 연산자의 동작을 보여 줍니다 NULL.

왼쪽 피연산자 오른쪽 피연산자 > >= = < <= <=>
Null 모든 값 Null Null Null Null Null False
모든 값 Null Null Null Null Null Null False
Null Null Null Null Null Null Null 사실

-- Normal comparison operators return `NULL` when one of the operand is `NULL`.
> SELECT 5 > null AS expression_output;
 expression_output
 -----------------
              null

-- Normal comparison operators return `NULL` when both the operands are `NULL`.
> SELECT null = null AS expression_output;
 expression_output
 -----------------
              null

-- Null-safe equal operator return `False` when one of the operand is `NULL`
> SELECT 5 <=> null AS expression_output;
 expression_output
 -----------------
             false

-- Null-safe equal operator return `True` when one of the operand is `NULL`
> SELECT NULL <=> NULL;
 expression_output
 -----------------
              true
 -----------------

논리 연산자

Azure Databricks는 , ORNOT와 같은 AND표준 논리 연산자를 지원합니다. 이러한 연산자는 식을 인수로 사용하고 Boolean 값을 반환합니다 Boolean .

다음 표에서는 하나 또는 두 피연산자가 일 때 논리 연산자의 동작을 보여 줍니다 NULL.

왼쪽 피연산자 오른쪽 피연산자 또는
사실 Null 사실 Null
False Null Null False
Null 사실 사실 Null
Null False Null False
Null Null Null Null
피연산자 아님
Null Null

-- Normal comparison operators return `NULL` when one of the operands is `NULL`.
> SELECT (true OR null) AS expression_output;
 expression_output
 -----------------
              true

-- Normal comparison operators return `NULL` when both the operands are `NULL`.
> SELECT (null OR false) AS expression_output
 expression_output
 -----------------
              null

-- Null-safe equal operator returns `False` when one of the operands is `NULL`
> SELECT NOT(null) AS expression_output;
 expression_output
 -----------------
              null

비교 연산자와 논리 연산자는 Azure Databricks에서 식으로 처리됩니다. 또한 Azure Databricks는 다음과 같이 광범위하게 분류할 수 있는 다른 형태의 식도 지원합니다.

  • Null 불내용 식
  • 값 피연산자를 처리 NULL 할 수 있는 식
    • 이러한 식의 결과는 식 자체에 따라 달라집니다.

Null 불내용 식

식의 인수가 하나 이상이고 대부분의 식이 이 범주에 속하는 경우 Null 내성 식이 반환 NULL 됩니다 NULL .

> SELECT concat('John', null) AS expression_output;
 expression_output
 -----------------
              null

> SELECT positive(null) AS expression_output;
 expression_output
 -----------------
              null

> SELECT to_date(null) AS expression_output;
 expression_output
 -----------------
              null

null 값 피연산자를 처리할 수 있는 식

이 식 클래스는 값을 처리 NULL 하도록 설계되었습니다. 식의 결과는 식 자체에 따라 달라집니다. 예를 들어 함수 식 isnull 은 null 입력 및 null이 아닌 입력에서 를 반환 true 합니다 false . 여기서 as 함수 coalesce 는 피연산자 목록에서 첫 번째 비 NULL 값을 반환합니다. 그러나 coalesce 는 모든 피연산자 가 인 경우 를 반환 NULL 합니다 NULL. 다음은 이 범주의 불완전한 식 목록입니다.

  • 합체
  • NULLIF
  • IFNULL
  • Nvl
  • NVL2
  • ISNAN
  • NANVL
  • Isnull
  • ISNOTNULL
  • ATLEASTNNONNULLS
  • IN

> SELECT isnull(null) AS expression_output;
 expression_output
 -----------------
              true

-- Returns the first occurrence of non `NULL` value.
> SELECT coalesce(null, null, 3, null) AS expression_output;
 expression_output
 -----------------
                 3

-- Returns `NULL` as all its operands are `NULL`.
> SELECT coalesce(null, null, null, null) AS expression_output;
 expression_output
 -----------------
              null

> SELECT isnan(null) AS expression_output;
 expression_output
 -----------------
             false

기본 제공 집계 식

집계 함수는 입력 행 집합을 처리하여 단일 결과를 계산합니다. 다음은 집계 함수에서 값을 처리하는 방법에 NULL 대한 규칙입니다.

  • NULL 값은 모든 집계 함수에서 처리에서 무시됩니다.
    • 이 규칙에 대한 예외는 COUNT(*) 함수입니다.
  • 일부 집계 함수는 모든 입력 값이 있거나 NULL 입력 데이터 집합이 비어 있을 때 를 반환 NULL 합니다. 이러한 함수 목록은 다음과 같습니다.
    • MAX
    • MIN
    • SUM
    • AVG
    • EVERY
    • ANY
    • SOME

-- `count(*)` does not skip `NULL` values.
> SELECT count(*) FROM person;
 count(1)
 --------
        7

-- `NULL` values in column `age` are skipped from processing.
> SELECT count(age) FROM person;
 count(age)
 ----------
          5

-- `count(*)` on an empty input set returns 0. This is unlike the other
-- aggregate functions, such as `max`, which return `NULL`.
> SELECT count(*) FROM person where 1 = 0;
 count(1)
 --------
        0

-- `NULL` values are excluded from computation of maximum value.
> SELECT max(age) FROM person;
 max(age)
 --------
       50

-- `max` returns `NULL` on an empty input set.
> SELECT max(age) FROM person where 1 = 0;
 max(age)
 --------
     null

, HAVINGJOIN 절의 WHERE조건 식

WHEREHAVING 산자는 사용자가 지정한 조건에 따라 행을 필터링합니다. JOIN 연산자는 조인 조건에 따라 두 테이블의 행을 결합하는 데 사용됩니다. 세 연산자 모두에 대해 조건 식은 부울 식이며 또는 를 반환 TrueFalseUnknown (NULL)수 있습니다. 조건 True의 결과가 인 경우 "만족"됩니다.

-- Persons whose age is unknown (`NULL`) are filtered out from the result set.
> SELECT * FROM person WHERE age > 0;
     name age
 -------- ---
 Michelle  30
     Fred  50
     Mike  18
      Dan  50
      Joe  30

-- `IS NULL` expression is used in disjunction to select the persons
-- with unknown (`NULL`) records.
> SELECT * FROM person WHERE age > 0 OR age IS NULL;
     name  age
 -------- ----
   Albert null
 Michelle   30
     Fred   50
     Mike   18
      Dan   50
    Marry null
      Joe   30

-- Person with unknown(`NULL`) ages are skipped from processing.
> SELECT * FROM person GROUP BY age HAVING max(age) > 18;
 age count(1)
 --- --------
  50        2
  30        2

-- A self join case with a join condition `p1.age = p2.age AND p1.name = p2.name`.
-- The persons with unknown age (`NULL`) are filtered out by the join operator.
> SELECT * FROM person p1, person p2
    WHERE p1.age = p2.age
    AND p1.name = p2.name;
     name age     name age
 -------- --- -------- ---
 Michelle  30 Michelle  30
     Fred  50     Fred  50
     Mike  18     Mike  18
      Dan  50      Dan  50
      Joe  30      Joe  30

-- The age column from both legs of join are compared using null-safe equal which
-- is why the persons with unknown age (`NULL`) are qualified by the join.
> SELECT * FROM person p1, person p2
    WHERE p1.age <=> p2.age
    AND p1.name = p2.name;
     name  age     name  age
 -------- ---- -------- ----
   Albert null   Albert null
 Michelle   30 Michelle   30
     Fred   50     Fred   50
     Mike   18     Mike   18
      Dan   50      Dan   50
    Marry null    Marry null
      Joe   30      Joe   30

집계 연산자(GROUP BY, DISTINCT)

비교 연산자에서 설명한 것처럼 두 NULL 값은 같지 않습니다. 그러나 그룹화 및 고유 처리를 위해 와 함께 NULL data두 개 이상의 값이 동일한 버킷으로 그룹화됩니다. 이 동작은 SQL 표준 및 다른 엔터프라이즈 데이터베이스 관리 시스템을 준수합니다.

-- `NULL` values are put in one bucket in `GROUP BY` processing.
> SELECT age, count(*) FROM person GROUP BY age;
  age count(1)
 ---- --------
 null        2
   50        2
   30        2
   18        1

-- All `NULL` ages are considered one distinct value in `DISTINCT` processing.
> SELECT DISTINCT age FROM person;
  age
 ----
 null
   50
   30
   18

Sort 연산자(ORDER BY 절)

Azure Databricks는 절에서 null 순서 지정 사양을 ORDER BY 지원합니다. Azure Databricks는 ORDER BY null 순서 지정에 따라 모든 NULL 값을 처음 또는 마지막에 배치하여 절을 처리합니다. 기본적으로 모든 값은 NULL 처음에 배치됩니다.

-- `NULL` values are shown at first and other values
-- are sorted in ascending way.
> SELECT age, name FROM person ORDER BY age;
  age     name
 ---- --------
 null    Marry
 null   Albert
   18     Mike
   30 Michelle
   30      Joe
   50     Fred
   50      Dan

-- Column values other than `NULL` are sorted in ascending
-- way and `NULL` values are shown at the last.
> SELECT age, name FROM person ORDER BY age NULLS LAST;
  age     name
 ---- --------
   18     Mike
   30 Michelle
   30      Joe
   50      Dan
   50     Fred
 null    Marry
 null   Albert

-- Columns other than `NULL` values are sorted in descending
-- and `NULL` values are shown at the last.
> SELECT age, name FROM person ORDER BY age DESC NULLS LAST;
  age     name
 ---- --------
   50     Fred
   50      Dan
   30 Michelle
   30      Joe
   18     Mike
 null    Marry
 null   Albert

집합 연산자(UNION, INTERSECT, EXCEPT)

NULL 값은 설정된 작업의 컨텍스트에서 같음을 위해 null로부터 안전한 방식으로 비교됩니다. 즉, 행을 비교할 때 두 NULL 값은 일반 EqualTo(=) 연산자와는 다른 것으로 간주됩니다.

> CREATE VIEW unknown_age AS SELECT * FROM person WHERE age IS NULL;

-- Only common rows between two legs of `INTERSECT` are in the
-- result set. The comparison between columns of the row are done
-- in a null-safe manner.
> SELECT name, age FROM person
    INTERSECT
    SELECT name, age from unknown_age;
   name  age
 ------ ----
 Albert null
  Marry null

-- `NULL` values from two legs of the `EXCEPT` are not in output.
-- This basically shows that the comparison happens in a null-safe manner.
> SELECT age, name FROM person
    EXCEPT
    SELECT age FROM unknown_age;
 age     name
 --- --------
  30      Joe
  50     Fred
  30 Michelle
  18     Mike
  50      Dan

-- Performs `UNION` operation between two sets of data.
-- The comparison between columns of the row ae done in
-- null-safe manner.
> SELECT name, age FROM person
    UNION
    SELECT name, age FROM unknown_age;
     name  age
 -------- ----
   Albert null
      Joe   30
 Michelle   30
    Marry null
     Fred   50
     Mike   18
      Dan   50

EXISTSNOT EXISTS 하위 쿼리

Azure Databricks에서 EXISTSNOT EXISTS 식은 절 내에서 WHERE 허용됩니다. 이러한 식은 또는 FALSE을 반환하는 부울 식입니다TRUE. 즉, 는 EXISTS 멤버 자격 조건이며 참조하는 하위 쿼리가 하나 이상의 행을 반환할 때 를 반환 TRUE 합니다. 마찬가지로 NOT EXISTS는 멤버 자격이 아닌 조건이며 하위 쿼리에서 행 또는 0개의 행이 반환되지 않을 때 를 반환 TRUE 합니다.

이러한 두 식은 하위 쿼리의 결과에서 NULL의 존재에 의해 영향을 받지 않습니다. null 인식에 대한 특별한 규정 없이 세미조인 및 반반조인으로 변환할 수 있기 때문에 일반적으로 더 빠릅니다.

-- Even if subquery produces rows with `NULL` values, the `EXISTS` expression
-- evaluates to `TRUE` as the subquery produces 1 row.
> SELECT * FROM person WHERE EXISTS (SELECT null);
     name  age
 -------- ----
   Albert null
 Michelle   30
     Fred   50
     Mike   18
      Dan   50
    Marry null
      Joe   30

-- `NOT EXISTS` expression returns `FALSE`. It returns `TRUE` only when
-- subquery produces no rows. In this case, it returns 1 row.
> SELECT * FROM person WHERE NOT EXISTS (SELECT null);
 name age
 ---- ---

-- `NOT EXISTS` expression returns `TRUE`.
> SELECT * FROM person WHERE NOT EXISTS (SELECT 1 WHERE 1 = 0);
     name  age
 -------- ----
   Albert null
 Michelle   30
     Fred   50
     Mike   18
      Dan   50
    Marry null
      Joe   30

INNOT IN 하위 쿼리

Azure Databricks에서 INNOT IN 식은 쿼리의 절 내에서 WHERE 허용됩니다. 식과 달리 식은 EXISTSIN 또는 FALSEUNKNOWN (NULL) 값을 반환할 TRUE수 있습니다. 개념적으로 IN 식은 분리 연산자(OR)로 구분된 같음 조건 집합과 의미상 동일합니다. 예를 들어 c1 IN(1, 2, 3)은 의미상 과 (C1 = 1 OR c1 = 2 OR c1 = 3)동일합니다.

값 처리와 NULL 관련하여 의미 체계는 비교 연산자() 및 논리 연산OR자(=)의 값 처리에서 NULL 추론할 수 있습니다. 요약하자면 식의 결과를 IN 계산하기 위한 규칙은 다음과 같습니다.

  • TRUE 는 해당 NULL이 아닌 값이 목록에 있으면 반환됩니다.
  • FALSE 는 목록에 NULL이 아닌 값을 찾을 수 없으며 목록에 NULL 값이 없는 경우 반환됩니다.
  • UNKNOWN 값이 NULL이거나 NULL이 아닌 값이 목록에 없으면 이 반환되고 목록에 하나 NULL 이상의 값이 포함됩니다.

NOT IN 입력 값에 관계없이 목록에 가 포함되어 NULL있으면 항상 UNKNOWN을 반환합니다. 값이 IN 를 포함하는 NULL목록에 없는 경우 를 반환 UNKNOWN 하고 NOT UNKNOWN 가 다시 UNKNOWN이므로 입니다.

-- The subquery has only `NULL` value in its result set. Therefore,
-- the result of `IN` predicate is UNKNOWN.
> SELECT * FROM person WHERE age IN (SELECT null);
 name age
 ---- ---

-- The subquery has `NULL` value in the result set as well as a valid
-- value `50`. Rows with age = 50 are returned.
> SELECT * FROM person
    WHERE age IN (SELECT age FROM VALUES (50), (null) sub(age));
 name age
 ---- ---
 Fred  50
  Dan  50

-- Since subquery has `NULL` value in the result set, the `NOT IN`
-- predicate would return UNKNOWN. Hence, no rows are
-- qualified for this query.
> SELECT * FROM person
    WHERE age NOT IN (SELECT age FROM VALUES (50), (null) sub(age));
 name age
 ---- ---