SQL,處理空單元格

如何處理SQL數據庫中的空數據

當我們以這種方式創建表時:

CREATE TABLE people (
  age INT,
  name CHAR(20)
);

SQL自由地接受空值作為記錄:

INSERT INTO people VALUES (null, null);

這可能是一個問題,因為現在我們有一個帶有空值的行:

 age |  name  
-----+--------
  37 | Flavio
   8 | Roger
     | 

To solve this, we can declare constrains on our table rows. NOT NULL prevents null values:

CREATE TABLE people (
  age INT NOT NULL,
  name CHAR(20) NOT NULL
);

If we try to execute this query again:

INSERT INTO people VALUES (null, null);

We’d get an error, like this:

ERROR:  null value in column "age" violates not-null constraint
DETAIL:  Failing row contains (null, null).

Note that an empty string is a valid non-null value.


More database tutorials: