Answer the question
In order to leave comments, you need to log in
Why use NULL in databases?
When creating tables, the question arises whether to set "not null" or not.
I'm not talking about cases where null is necessary, for example, if you have a unique index set or an empty string - this is also a meaningful value and must be distinguished from null.
The inconvenience we get if the field is nullable is the double check for missing data.
A simple example: a table of users and a form for editing them. If we do not fill in the field and submit the form, then an empty string comes to the server, which is stored in the database.
Further, if we need, for example, to pull out all users who do not have a phone number, we need to write like this: where `phone` != '' and `phone` is not null
And if we did not use null, then it would be enoughwhere `phone` != ''
Here you can set all empty fields to null at the stage of writing to the database (this is how laravel behaves by default).
But why complicate things? Why not just use the default empty string where null is not needed?
Also, I read in some optimization tips that an empty string is faster.
How do you create tables? Are you using not null or not?
Answer the question
In order to leave comments, you need to log in
A simple example: a table of users and a form for editing them. If we do not fill in the field and submit the form, then an empty string comes to the server, which is stored in the database.you keep it. What's stopping you from doing it? After validating the business logic, it is enough to go through the data array, before inserting it into the database, and set NULL for all variables with empty strings. Blank lines in the database are never needed. There is no reason to keep them there.
an empty string is also a meaningful valuetheoretically - this is a "meaningful value", practically - this is garbage, this is the result of the development of high-level languages, such as php, which allow you to write an empty string to the base (encourage this in view of their design features).
where phone is not null
Because this is a selection of records where there is no phone, not where it consists of 0 characters.
The value with '' must not pass the validator.
The absence of a value (null) will not be used in string operations. For example, if you calculate the average of a column, then such rows will be discarded, and if there is 0 instead of null, then they will be taken into account and the result will be incorrect.
So choose wisely.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question