SQL: Using NULL values vs. default values

前端 未结 13 2221
南旧
南旧 2020-12-01 01:28

What are the pros and cons of using NULL values in SQL as opposed to default values?

13条回答
  •  無奈伤痛
    2020-12-01 01:51

    As with many things, there are good and bad points to each.

    Good points about default values: they give you the ability to set a column to a known value if no other value is given. For example, when creating BOOLEAN columns I commonly give the column a default value (TRUE or FALSE, whatever is appropriate) and make the column NOT NULL. In this way I can be confident that the column will have a value, and it'll be set appropriate.

    Bad points about default values: not everything has a default value.

    Good things about NULLs: not everything has a known value at all times. For example, when creating a new row representing a person I may not have values for all the columns - let's say I know their name but not their birth date. It's not appropriate to put in a default value for the birth date - people don't like getting birthday cards on January 1st (if that's the default) if their birthday is actually July 22nd.

    Bad things about NULLs: NULLs require careful handling. In most databases built on the relational model as commonly implemented NULLs are poison - the presence of a NULL in a calculation causes the result of the calculation to be NULL. NULLs used in comparisons can also cause unexpected results because any comparison with NULL returns UNKNOWN (which is neither TRUE nor FALSE). For example, consider the following PL/SQL script:

    declare 
      nValue NUMBER;
    begin
      IF nValue > 0 THEN
        dbms_output.put_line('nValue > 0');
      ELSE
        dbms_output.put_line('nValue <= 0');
      END IF;
    
      IF nValue <= 0 THEN
        dbms_output.put_line('nValue <= 0');
      ELSE
        dbms_output.put_line('nValue > 0');
      END IF;
    end;
    

    The output of the above is:

    nValue <= 0
    nValue > 0
    

    This may be a little surprising. You have a NUMBER (nValue) which is both less than or equal to zero and greater than zero, at least according to this code. The reason this happens is that nValue is actually NULL, and all comparisons with NULL result in UNKNOWN instead of TRUE or FALSE. This can result in subtle bugs which are hard to figure out.

    Share and enjoy.

提交回复
热议问题