IFNULL Function in SQL

Level 4124 keystrokes

IFNULL returns the second argument if the first is NULL.

SQL code

-- Return the name, the discount and the price after discount
1SELECT
2 name,
-- Show 0 instead of NULL when a product has no discount
3 IFNULL(discount, 0) AS discount,
-- price - NULL would be NULL, so IFNULL keeps the subtraction working
4 price - IFNULL(discount, 0) AS final_price
5FROM
6 products
-- Sort from the cheapest final price (an alias can be used in ORDER BY)
7ORDER BY
8 final_price;

Output

+--------+----------+-------------+
| name   | discount | final_price |
+--------+----------+-------------+
| Banana |     0.10 |        0.65 |
| Apple  |     0.00 |        1.50 |
| Orange |     0.00 |        2.00 |
+--------+----------+-------------+
3 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • ,× 4
  • _× 2
  • (× 2
  • )× 2
  • -× 1
  • ;× 1

More SQL examples at level 4

← SQL typing practice