What is the difference between null and not null? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference between null and not null?

16th Sep 2023, 1:48 PM
Sarraga John Clyde
3 Answers
+ 1
Null means there is no value. Say you have a table call employee, which as the following fields: id, first_name, last_name, age, position Now you execute following SQL command INSERT INTO employee VALUES (1, "Jack", "Ryan", null, "President"); There will be one record inserted into the employee table, with below values id: 1 first_name: Jack last_name: Ryan age: null position: President When you want to insert a record but some fields you want to omit, you insert the field a "null" value. In the example above, the field age in this record IS NULL, because we said it is null. Other fields are NOT NULL. MORE ABOUT NULL Now we change the INSERT statement into this: INSERT INTO employee VALUES (1, "Jack", "Ryan", null, "President"); And adding this line too INSERT INTO employee VALUES (2, "Hikaru", "Sulu", "", "Helm"); And then run SELECT * FROM employee, you will find both record show nothing in the field age. HOWEVER, if you run below statement it may surprise you. SELECT * FROM employee WHERE age IS NOT NULL; There will be only one record, which is 2, Hikaru, Sulu, , Helm A blank ("") is not the same as NULL. You can think of a blank is a string value with zero character. Someone may ask can we write a SELECT statement like below: SELECT * FROM employee WHERE age = NULL; It will run but the result is not as you expected. The first record will not be returned. In fact, nothing will return. It is because we cannot compare a NULL to another NULL. NULL is like undefined. Given there are 2 creatures, creature A has 4 legs and creature B has 2 legs, but you don't know what their species is. Both creatures are "undefined", but is creature A = creature B? Surely they are not. Back to SQL, NULL = NULL will return nothing because NULL cannot be compared, but you can tell the field is NULL or not. Hope it helps.
16th Sep 2023, 3:07 PM
Wong Hei Ming
Wong Hei Ming - avatar
+ 4
♾️ 🙂
16th Sep 2023, 9:20 PM
JaScript
JaScript - avatar
+ 3
NULL: When a column is defined as NULL, it means that it can contain no value, and it is not required to have a value. 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. Rows in the table are not allowed to have NULL values in this column.
16th Sep 2023, 2:56 PM
JAY
JAY - avatar