llisit
V2EX  ›  问与答

Mysql 字段有必要都设置为 not null 吗

  •  
  •   llisit · Dec 9, 2021 · 3801 views
    This topic created in 1800 days ago, the information mentioned may be changed or developed.

    昨天公司事故复盘,提到字段最好都设置为 not null ,有几个疑问:

    1. allow null 比 not null 字段每行会多占用 1 字节的标志位,这个是否可以忽略不记?
    2. not null 能够带来更好的性能吗?
    3. 对于 Integer 类型,not null 字段给一个默认值如 0 表示值为空,是不是使用 null 表示语义化会更好?
    13 replies  •  2021-12-11 16:34:08 +08:00
    zoharSoul
    zoharSoul
    Dec 9, 2021
    1
    如果不是需要 null 语义的, 建议都设成 not null
    kiripeng
    kiripeng
    Dec 9, 2021
    2
    如果这个字段之后要用来构建索引的话,会导致索引树构建复杂性能下降,对于一些查询的情况根据不同的数据库得到的结论不一定是一样的意思,数据迁移会比较麻烦,等等情况吧
    Mohanson
    Mohanson
    Dec 9, 2021
    3
    Null References: The Billion Dollar Mistake - Tony Hoare

    注: Tony Hoare 是 Null 语义的发明者

    E2gCaBAT5I87sw1M
    E2gCaBAT5I87sw1M
    Dec 9, 2021
    4
    都给个默认值比较好,Null 对于 索引 不友好
    h82258652
    h82258652
    Dec 9, 2021
    5
    看业务,业务可 null 就 null ,业务不可 null 就 not null
    2123123
    2123123
    Dec 9, 2021
    6
    不涉及索引的字段还是看业务场景,比如一个金额字段 0 在业务中也是有意义的,用 null 表示未设值我认为这是合理的。
    dqzcwxb
    dqzcwxb
    Dec 9, 2021
    7

    说 null 不走索引的大概和之前说 or 不走索引(特定情况下 or 才不走索引)的人是同一拨
    sagaxu
    sagaxu
    Dec 9, 2021 via Android
    8
    孝子贤孙
    makelove
    makelove
    Dec 9, 2021
    9
    这难道不是该怎么用就怎么用吗?难道没日期也要强行搞个空日期值出来
    Jooooooooo
    Jooooooooo
    Dec 9, 2021
    10
    最好是, 给自己少埋坑.
    gadfly3173
    gadfly3173
    Dec 9, 2021
    11
    mysql 的 null 和 null 之间是不一样的,所以会导致唯一索引失效。
    是否允许 null 还是和业务有关的,一般来说如果一个字段不应该为 null 那自然就应该设 not null
    yidinghe
    yidinghe
    PRO
    Dec 9, 2021 via Android
    12
    cccer
    cccer
    Dec 11, 2021
    13
    @dqzcwxb Oracle 可为空的字段在 order by 的时候会导致索引失效,MySQL 没试过。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4517 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 06:33 · PVG 14:33 · LAX 22:33 · JFK 01:33
    ♥ Do have faith in what you're doing.