If you need to represent unknown data in a column, you make it nullable. If you will always have data in the column, it's better to make it not nullable, as

  1. Dealing with nulls can be annoying and counterintuitive
  2. It saves a bit of space
  3. On some database systems, null values are not indexed.
Answer from user610217 on Stack Overflow
🌐
W3Schools
w3schools.com › sql › sql_null_values.asp
SQL NULL Values - IS NULL and IS NOT NULL
ADD ADD CONSTRAINT ALL ALTER ALTER COLUMN ALTER TABLE AND ANY AS ASC BACKUP DATABASE BETWEEN CASE CHECK COLUMN CONSTRAINT CREATE CREATE DATABASE CREATE INDEX CREATE OR REPLACE VIEW CREATE TABLE CREATE PROCEDURE CREATE UNIQUE INDEX CREATE VIEW DATABASE DEFAULT DELETE DESC DISTINCT DROP DROP COLUMN DROP CONSTRAINT DROP DATABASE DROP DEFAULT DROP INDEX DROP TABLE DROP VIEW EXEC EXISTS FOREIGN KEY FROM FULL OUTER JOIN GROUP BY HAVING IN INDEX INNER JOIN INSERT INTO INSERT INTO SELECT IS NULL IS NOT NULL JOIN LEFT JOIN LIKE LIMIT NOT NOT NULL OR ORDER BY OUTER JOIN PRIMARY KEY PROCEDURE RIGHT JOIN ROWNUM SELECT SELECT DISTINCT SELECT INTO SELECT TOP SET TABLE TOP TRUNCATE TABLE UNION UNION ALL UNIQUE UPDATE VALUES VIEW WHERE MySQL Functions
🌐
W3Schools
w3schools.com › sql › sql_notnull.asp
SQL NOT NULL Constraint
ADD ADD CONSTRAINT ALL ALTER ALTER COLUMN ALTER TABLE AND ANY AS ASC BACKUP DATABASE BETWEEN CASE CHECK COLUMN CONSTRAINT CREATE CREATE DATABASE CREATE INDEX CREATE OR REPLACE VIEW CREATE TABLE CREATE PROCEDURE CREATE UNIQUE INDEX CREATE VIEW DATABASE DEFAULT DELETE DESC DISTINCT DROP DROP COLUMN DROP CONSTRAINT DROP DATABASE DROP DEFAULT DROP INDEX DROP TABLE DROP VIEW EXEC EXISTS FOREIGN KEY FROM FULL OUTER JOIN GROUP BY HAVING IN INDEX INNER JOIN INSERT INTO INSERT INTO SELECT IS NULL IS NOT NULL JOIN LEFT JOIN LIKE LIMIT NOT NOT NULL OR ORDER BY OUTER JOIN PRIMARY KEY PROCEDURE RIGHT JOIN ROWNUM SELECT SELECT DISTINCT SELECT INTO SELECT TOP SET TABLE TOP TRUNCATE TABLE UNION UNION ALL UNIQUE UPDATE VALUES VIEW WHERE MySQL Functions
🌐
Sololearn
sololearn.com › en › Discuss › 3240365 › what-is-the-difference-between-null-and-not-null
What is the difference between null and not null? | Sololearn: Learn to code for FREE!
Rows in the table can have NULL values in this column, which essentially means that the data is missing or unknown for those rows. NOT NULL: When a column is defined as NOT NULL, it means that it must contain a value for every row in the table.
🌐
Reddit
reddit.com › r/sql › need some knowledge on null and not null
r/SQL on Reddit: Need some knowledge on NULL and NOT NULL
December 22, 2021 -
  • Where and why exactly a null is used?

  • What is exactly null and not null? To my understanding Not null we use when its mandatory to insert some value in that field, also when we give check constraint so by default the column will be not null right?

  • By adding new column through alter method default values are null, so how would I be able to insert values in it and is it right to give not null constraint to that new column while adding through alter method, basically when null and when not null to be used?...

god this is so confusing please help me, ik im asking alot but im really confused

🌐
W3Schools
w3schools.com › mysql › mysql_null_values.asp
MySQL NULL Values - IS NULL and IS NOT NULL
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value. Note: A NULL value is different from a zero value or a field that contains spaces.
Find elsewhere
Top answer
1 of 8
505

TL;DR

The key to understanding what null! means is understanding the ! operator. You may have used it before as the "not" operator. However, since C# 8.0 and its new "nullable-reference-types" feature, the operator got a second meaning. It can be used on a type to control Nullability, it is then called the "Null Forgiving Operator".

Basically, null! applies the ! operator to the value null. This overrides the nullability of the value null to non-nullable, telling the compiler that null is a "non-null" type.


Typical usage

Assuming this definition:

class Person
{
    // Not every person has a middle name. We express "no middle name" as "null"
    public string? MiddleName;
}

The usage would be:

void LogPerson(Person person)
{
    Console.WriteLine(person.MiddleName.Length);  // WARNING: may be null
    Console.WriteLine(person.MiddleName!.Length); // No warning
}

This operator basically turns off the compiler null checks for this usage.

Technical Explanation

The groundwork that you will need to understand what null! means.

Null Safety

C# 8.0 tries to help you manage your null-values. Instead of allowing you to assign null to everything by default, they have flipped things around and now require you to explicitly mark everything you want to be able to hold a null value.

This is a super useful feature, it allows you to avoid NullReferenceExceptions by forcing you to make a decision and enforcing it.

How it works

There are 2 states a variable can be in - when talking about null-safety.

  • Nullable - Can be null.
  • Non-Nullable - Cannot be null.

Since C# 8.0 all reference types are non-nullable by default. Value types have been non-nullable since C# 2.0!

The "nullability" can be modified by 2 new (type-level) operators:

  • ! = from Nullable to Non-Nullable
  • ? = from Non-Nullable to Nullable

These operators are counterparts to one another. The Compiler uses the information that you define with these operators to ensure null-safety.

Examples

? Operator usage.

This operator tells the compiler that a variable can hold a null value. It is used when defining variables.

  • Nullable string? x;

    • x is a reference type - So by default non-nullable.
    • We apply the ? operator - which makes it nullable.
    • x = null Works fine.
  • Non-Nullable string y;

    • y is a reference type - So by default non-nullable.
    • y = null Generates a warning since you assign a null value to something that is not supposed to be null.

Nice to know: Using object? is basically just syntactic sugar for System.Nullable<object>

! Operator usage.

This operator tells the compiler that something that could be null, is safe to be accessed. You express the intent to "not care" about null safety in this instance. It is used when accessing variables.

string x;
string? y;
  • x = y
    • Illegal! Warning: "y" may be null
    • The left side of the assignment is non-nullable but the right side is nullable.
    • So it does not work, since it is semantically incorrect
  • x = y!
    • Legal!
    • y is a reference type with the ? type modifier applied so it is nullable if not proven otherwise.
    • We apply ! to y which overrides its nullability settings to make it non-nullable
    • The right and left side of the assignment are non-nullable. Which is semantically correct.

WARNING The ! operator only turns off the compiler-checks at a type-system level - At runtime, the value may still be null.

Use carefully!

You should try to avoid using the Null-Forgiving-Operator, usage may be the symptom of a design flaw in your system since it negates the effects of null-safety you get guaranteed by the compiler.

Reasoning

Using the ! operator will create very hard to find bugs. If you have a property that is marked non-nullable, you will assume you can use it safely. But at runtime, you suddenly run into a NullReferenceException and scratch your head. Since a value actually became null after bypassing the compiler-checks with !.

Why does this operator exist then?

There are valid use-cases (outlined in detail below) where usage is appropriate. However, in 99% of the cases, you are better off with an alternative solution. Please do not slap dozens of !'s in your code, just to silence the warnings.

  • In some (edge) cases, the compiler is not able to detect that a nullable value is actually non-nullable.
  • Easier legacy code-base migration.
  • In some cases, you just don't care if something becomes null.
  • When working with Unit-tests you may want to check the behavior of code when a null comes through.

Ok!? But what does null! mean?

It tells the compiler that null is not a nullable value. Sounds weird, doesn't it?

It is the same as y! from the example above. It only looks weird since you apply the operator to the null literal. But the concept is the same. In this case, the null literal is the same as any other expression/type/value/variable.

The null literal type is the only type that is nullable by default! But as we learned, the nullability of any type can be overridden with ! to non-nullable.

The type system does not care about the actual/runtime value of a variable. Only its compile-time type and in your example the variable you want to assign to LastName (null!) is non-nullable, which is valid as far as the type-system is concerned.

Consider this (invalid) piece of code.

object? null;
LastName = null!;
2 of 8
37

null! is used to assign null to non-nullable variables, which is a way of promising that the variable won't be null when it is actually used.

I'd use null! in a Visual Studio extension, where properties are initialized by MEF via reflection:

[Import] // Set by MEF
VSImports vs = null!;
[Import] // Set by MEF
IClassificationTypeRegistryService classificationRegistry = null!; 

(I hate how variables magically get values in this system, but it is what it is.)

I also use it in unit tests to mark variables initialized by a setup method:

public class MyUnitTests
{
    IDatabaseRepository _repo = null!;

    [OneTimeSetUp]
    public void PrepareTestDatabase()
    {
        ...
        _repo = ...
        ...
    }
}

If you don't use null! in such cases, you'll have to use an exclamation mark every single time you read the variable, which would be a hassle without benefit.

Note: cases where null! is a good idea are fairly rare. I treat it as somewhat of a last resort.

Top answer
1 of 7
40

It's convenient for the way SQL is typically used. Consider this statements:

SELECT people.name, cars.model FROM people
INNER JOIN cars
    ON people.car_licenceplate = cars.licenceplate

If null = null, then this would return all pairs of people with no license plate with all unregistered cars in the database, a usually undesirable result.

It's particularly convenient that, even if you use any null value even in a more complex expression, you won't get a value back, even if other values may also happen to be null. In other languages you'd need to null check everything in advance to get that behavior, having it by default is very convenient for the type of things SQL is typically used for.

null in SQL is exempt from a lot of other rules too. For example they are excluded from unique constraints. All indicating it represents more the absence of a value rather than a special value.

Some other languages do also have a ThreeValueBoolean or a similar type that behaves more like a SQL null, though only for booleans. Also most every language has similar non self-equality for NaN. It's not a concept unique to SQL.

2 of 7
23

One way to look at this is to compare these two questions:

  1. Is value A definitely the same as value B?
  2. Is value A definitely different from value B?

On the face of it, these are symmetrical: if question 1 is true, question 2 is false, and vice versa.

But what if both A and B are missing or invalid data points?

  1. False. We can't know for sure that the two missing or invalid data points are the same.
  2. False. We can't know for sure that the two missing or invalid data points are different.

That puts us in a peculiar position: A = B and A <> B should both be false, but that means that NOT (A = B) is no longer the same as A <> B, which is surprising.

SQL handles this by returning a further NULL - if the data for A and B is missing, then the information about whether they are the same or different is also missing. This is consistent with other operations on NULL, e.g. NULL + NULL is NULL, because adding two unknown numbers gives you a third unknown number. And since that also includes boolean negation - if A is NULL, then NOT A is also NULL, the result of NOT (A = B) is always the same as A <> B, as we'd intuitively expect.

However, there are situations where we want to ask the strict negation of those questions:

  1. Is value A not definitely the same as value B? (Strict inverse of question 1)
  2. Is value A not definitely different from value B? (Strict inverse of question 2)

For these, SQL provides the DISTINCT FROM and NOT DISTINCT FROM operators.

More commonly, you want to know explicitly that a particular value is or is not null, for which there are the operators IS NULL and IS NOT NULL.

Top answer
1 of 16
49

Null: The Billion Dollar Mistake. Tony Hoare:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. In recent years, a number of program analysers like PREfix and PREfast in Microsoft have been used to check references, and give warnings if there is a risk they may be non-null. More recent programming languages like Spec# have introduced declarations for non-null references. This is the solution, which I rejected in 1965.

2 of 16
32

null is a sentinel value that is not an integer, not a string, not a boolean - not anything really, except something to hold and be a "not there" value. Don't treat it as or expect it to be a 0, or an empty string or an empty list. Those are all valid values and can be geniunely valid values in many circumstances - the idea of a null instead means there is no value there.

Perhaps it's a little bit like a function throwing an exception instead of returning a value. Except instead of manufacturing and returning an ordinary value with a special meaning, it returns a special value that already has a special meaning. If a language expects you to work with null, then you can't really ignore it.

🌐
Programiz
programiz.com › sql › is-null-not-null
SQL IS NULL and IS NOT NULL (With Examples)
However, space and 0 are not considered NULL. In SQL, the IS NOT NULL condition is used to select rows if the specified field is NOT NULL.
🌐
Khoury College of Computer Sciences
khoury.northeastern.edu › home › kenb › MeaningOfNull.html
The Meaning of Null in Databases and Programming Languages
The main distinction between the relational null and the programming language null is the following: The relational null represents the absence of a value in a field of a record; whereas the programming language null represents one of the possible values of a variable.
🌐
Quora
quora.com › What-does-NULL-mean-in-programming-languages
What does NULL mean in programming languages? - Quora
Answer (1 of 6): null is the pointer or reference to address zero. Why would this be needed or used? Let’s say you are searching for a library book that you want to read. Unlike Amazon, your library doesn’t have every book. If you search for “Object Oriented Software Construction” by ...
🌐
Quora
quora.com › What-is-the-SQL-IS-NOT-NULL-condition-and-how-is-it-used
What is the SQL IS NOT NULL condition and how is it used? - Quora
Answer (1 of 4): IS NULL and IS NOT NULL are substitutes for the “=” sign. Equations are for stating that everything on the left side of the equation evaluates to the same thing as everything on the right side.
Top answer
1 of 5
7

Actually, you can use a literal 0 anyplace you would use NULL.

Section 6.3.2.3p3 of the C standard states:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

And section 7.19p3 states:

The macros are:

NULL

which expands to an implementation-defined null pointer constant

So 0 qualifies as a null pointer constant, as does (void *)0 and NULL. The use of NULL is preferred however as it makes it more evident to the reader that a null pointer is being used and not the integer value 0.

2 of 5
5

NULL is used to make it clear it is a pointer type.

Ideally, the C implementation would define NULL as ((void *) 0) or something equivalent, and programmers would always use NULL when they want a null pointer constant.

If this is done, then, when a programmer has, for example, an int *x and accidentally writes *x = NULL;, then the compiler can recognize that a mistake has been made, because the left side of = has type int, and the right side has type void *, and this is not a proper combination for assignment.

In contrast, if the programmer accidentally writes *x = 0; instead of x = 0;, then the compiler cannot recognize this mistake, because the left side has type int, and the right side has type int, and that is a valid combination.

Thus, when NULL is defined well and is used, mistakes are detected earlier.

In particular answer to your question “Is there a context in which just plain literal 0 would not work exactly the same?”:

  • In correct code, NULL and 0 may be used interchangeably as null pointer constants.
  • 0 will function as an integer (non-pointer) constant, but NULL might not, depending on how the C implementation defines it.
  • For the purpose of detecting errors, NULL and 0 do not work exactly the same; using NULL with a good definition serves to help detect some mistakes that using 0 does not.

The C standard allows 0 to be used for null pointer constants for historic reasons. However, this is not beneficial except for allowing previously written code to compile in compilers using current C standards. New code should avoid using 0 as a null pointer constant.

🌐
Wikipedia
en.wikipedia.org › wiki › Null
Null - Wikipedia
1 month ago - Null pointer or reference (sometimes written NULL, nil, or None), an object pointer (or reference) not currently set to point (or refer) to a valid object · Null (mathematics), a zero value in several branches of mathematics · Null (physics), a point in a field where the field quantity is zero
🌐
Programiz
programiz.com › sql › not-null
SQL NOT NULL Constraint (With Examples)
Try Programiz PRO! ... In SQL, the NOT NULL constraint in a column means that the column cannot store NULL values. -- create table with NOT NULL constraint CREATE TABLE Colleges ( college_id INT NOT NULL, college_code VARCHAR(20), college_name VARCHAR(50) ); Here, the college_id column of the ...