In this tutorial you can learn how to work with NULL in MySQL tables: Insert, Update, and Select columns with NULL value.

Add column with NULL value

To insert into a MySQL table rows with columns having NULL, add the NULL value without quotes.
$sql = "INSERT INTO `table_name`
 (`column1`, `column2`, `column3`)
 ('val1', NULL, 'val3')";

Or, if the NULL value is stored into a variable, add "NULL" as a string to that variable, then write the variable into the SQL query, without quotes.
$nul = 'NULL';
$sql = "INSERT INTO `table_name`
 (`column1`, `column2`, `column3`)
 ('val1', $nul, 'val3')";

- If you create the $nul value like this:   $nul = NULL; , the SQL query will contain nothing in the place where this variable is added. Will result:
INSERT INTO `table_name` (`column1`, `column2`, `column3`) VALUES ('val1', , 'val3')

- If you want to insert the string "NULL", add it within quotes:
$sql = "INSERT INTO `table_name`
 (`column1`, `column2`, `column3`)
 ('val1', 'NULL', 'val3')";

UPDATE with NULL value

The same works with UPDATE.
$sql = "UPDATE `table_name` SET `column1`='val1', `column2`=NULL, WHERE `column3`='val3'";
$nul = 'NULL';
$sql = "UPDATE `table_name` SET `column1`='val1', `column2`=$nul, WHERE `column3`='val3'";

SELECT fields with NULL value

To select rows in a MySQL table according to columns with NULL value, use IS NULL.
$sql = "SELECT * FROM `table_name` WHERE `column` IS NULL";

If you want to Not return the rows with a specific NULL field, use IS NOT NULL.
$sql = "SELECT * FROM `table_name` WHERE `column` IS NOT NULL";

Daily Test with Code Example

Which tag is used to include external CSS file in web page?
<body> <script> <link>
<link href="/templ/style.css" rel="stylesheet" type="text/css" />
Which CSS property sets the text size?
font-weight text-decoration font-size
h2 {
  font-size: 1em;
Indicate the JavaScript property that can add HTML code into an element.
text value innerHTML
document.getElementById("someID").innerHTML = "HTML content";
Click on the function that returns the number of characters of a string in PHP.
count() strlen() stristr()
$str = "";
$nr_chr = strlen($str);
echo $nr_chr;       // 22
Insert, Select and Update NULL value in MySQL

Last accessed pages

  1. Read Excel file data in PHP - PhpExcelReader (55567)
  2. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (70694)
  3. OOP - Classes and objects - Create Class (1343)
  4. html2canvas - Save page screenshoot on server (401)
  5. Ajax-PHP Chat Script (36231)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (1387)
  2. Qwop (670)
  3. Theme Hotel (590)
  4. Read Excel file data in PHP - PhpExcelReader (575)
  5. Register and show online users and visitors (527)