Start learning free

LESSON 41 OF 173 · BACKEND: SQL

Missing Values: NULL in Java

Practice

Sometimes a value is missing. SQL writes a missing value as NULL, like null in Java. In the shop, the Gift card has no category: its category is NULL.

NULL means "unknown", so a comparison with it is never true. category = NULL is unknown for every row, even for the gift card, and WHERE keeps only the rows whose test is true, so it finds nothing. To test for a missing value, SQL has IS NULL, and its opposite, IS NOT NULL:

String query = "";
query += "SELECT name, price ";
query += "FROM products ";
query += "WHERE category IS NOT NULL ";

This query keeps the 7 products that have a category. In this lesson you write two queries, and the check prints both, with show(db, query) and show(db, query2). Your code must print exactly this:

name | category
(0 rows)

name | category
Gift card | NULL
(1 row)

Your task: the connection db to shop.db and the empty strings query and query2 are already there. In query, look for the products without a category with = NULL and see that it finds nothing. In query2, find them the right way, with IS NULL.


Assignment
Follow the Coding Tutorial to write both queries, one clause per line added with +=: SELECT, FROM, then a WHERE.


Hint
NULL goes without quotes: 'NULL' in quotes is just a four-letter text. query2 has the same SELECT and FROM lines as query; only the WHERE changes. End each string with a space so the clauses don't run together.


STEP 1 OF 5
    Ctrl + Enter to check

    Sql Null in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free