I have about 6 tables in my MySQL database, like
mysql> describe Quiz;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| quiz_id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(25) | YES | | NULL | |
| category | varchar(20) | YES | | NULL | |
| is_published | tinyint(1) | YES | | 0 | |
| open_count | int(11) | YES | | 0 | |
| finish_count | int(11) | YES | | 0 | |
+--------------+-------------+------+-----+---------+----------------+
In all 6 tables, while writing CREATE TABLE ...
i didn't enforce NOT NULL
on each attribute(as visible above), but they should be NOT NULL.
Rows will be inserted in these tables using my PHP code. So I can ensure that none of them is NULL, before inserting.
I wanted to know, if there is a possible flaw in enforcing NOT NULL using application code, rather than MySQL?
A NOT NULL constraint in SQL is used to prevent inserting NULL values into the specified column, considering it as a not accepted value for that column. This means that you should provide a valid SQL NOT NULL value to that column in the INSERT or UPDATE statements, as the column will always contain data.
For us, in the context of null safety, that means that if an expression has a static type that does not permit null , then no possible execution of that expression can ever evaluate to null . The language provides this guarantee mostly through static checks, but there can be some runtime checks involved too.
No, it isn't necessary because without adding DEFAULT NULL, it gives NULL value. For example, let's say you haven't added DEFAULT NULL and inserted a record with no value, then the result would display the NULL value as the inserted value.
Importance of NULL value: It is important to understand that a NULL value is different from a zero value. A NULL value is used to represent a missing value, but that it usually has one of three different interpretations: The value unknown (value exists but is not known)
Off the top of my head, I can give you two reasons to enforce it in the database in addition to doing it in code.
If a bug shows up in your PHP code, your data won't be corrupt. You'll notice the bug right away if you just check your return codes from the database.
If someone decides to update data manually in the database, they won't be able to mistakenly leave fields as NULL that your application code can't cope with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With