Forem

Michael
Michael

Posted on

Understanding the ISNULL() Function in GBase 8s

Handling NULL values is a common challenge in database queries. The gbase database provides a flexible ISNULL() function that works in two forms: with two parameters or with one. Let's dive into how it works and see some practical examples.


Two‑Parameter Form: ISNULL(a, b)

  • If a is not NULL, returns a.
  • If a is NULL, returns b.
  • If both are NULL, returns NULL.

This behaves like returning the first non‑NULL value from left to right.

One‑Parameter Form: ISNULL(a)

  • If a is NULL, returns the boolean t (true).
  • Otherwise, returns f (false).

This is useful for checking whether a column or expression is NULL.


Examples

Two‑Parameter Examples

SELECT ISNULL(12, NULL) FROM DUAL;   -- Result: 12
SELECT ISNULL(NULL, 'aa') FROM DUAL; -- Result: 'aa'
SELECT ISNULL(NULL, NULL) FROM DUAL; -- Result: NULL
SELECT ISNULL(ISNULL('abc', NULL), 'ef') FROM DUAL; -- Result: 'abc'
OneParameter Examples
sql
SELECT ISNULL('aa') FROM DUAL;   -- Result: 'f'
SELECT ISNULL(NULL) FROM DUAL;   -- Result: 't'
SELECT ISNULL('null') FROM DUAL; -- Result: 'f'
RealWorld Scenario
Let's create a table and use ISNULL() in a CTE to identify NULL values and compute aggregations.

sql
DROP TABLE IF EXISTS t1;
CREATE TABLE t1 (id INT, col1 INT, col2 INT);
INSERT INTO t1 VALUES (1,1,1), (2,NULL,NULL), (3,4,4), (4,0,0);

WITH tmp1 AS (
  SELECT id, col1, ISNULL(col1) AS null_flag, SUM(col2) AS total_col2
  FROM t1
  GROUP BY id, col1
),
tmp2 AS (
  SELECT id, col1, ISNULL(tmp1.total_col2) AS null_col2
  FROM tmp1
  WHERE id > 1 AND ISNULL(col1) = 't'
)
SELECT id, col1, null_col2 FROM tmp2;
-- Output: id=2, col1=NULL, null_col2=1
Enter fullscreen mode Exit fullscreen mode

Summary
The ISNULL() function in GBase 8s provides a clean way to handle NULL values. Use the two‑parameter form to return a fallback value, and the one‑parameter form to quickly test for NULL. Whether you're writing simple queries or building complex reports, this function is a handy tool in your SQL toolbox.

If you have any questions or want to share your own examples, feel free to leave a comment below! 🚀

Top comments (0)