ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

JSONB Path Existence Check

SQL PostgreSQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE OR REPLACE FUNCTION jsonb_path_exists(
2doc JSONB,
3path_expr TEXT
4)
5RETURNS BOOLEAN
6AS $$
7DECLARE
8result JSONB;
9BEGIN
10-- Attempt to extract the value at the specified path.
11-- If the path exists, jsonb_extract_path will return a non-null JSONB value.
12-- If the path does not exist, it will return NULL.
13result := jsonb_extract_path(doc, path_expr);
14
15-- Check if the extracted result is not NULL.
16IF result IS NOT NULL THEN
17RETURN TRUE;
18ELSE
19RETURN FALSE;
20END IF;
21END;
22$$ LANGUAGE plpgsql;
Algorithm description viewbox

JSONB Path Existence Check

Algorithm description:

This function checks for the existence of a specific path within a JSONB document. It leverages PostgreSQL's built-in JSONB functions to traverse the document structure. This is useful for validating data structures before attempting to access potentially missing fields, preventing errors in applications that process JSON data.

Algorithm explanation:

The function `jsonb_path_exists` takes a JSONB document and a text representation of a path. It uses `jsonb_extract_path` to attempt to retrieve the value at that path. If `jsonb_extract_path` returns a non-null value, it implies the path exists, and the function returns TRUE. Otherwise, if `jsonb_extract_path` returns NULL (meaning the path or any part of it is missing), the function returns FALSE. The time complexity is dependent on the depth of the JSONB document and the length of the path expression, generally proportional to the number of keys traversed. Space complexity is minimal, primarily for storing the result.

Pseudocode:

FUNCTION jsonb_path_exists(document, path_expression):
  extracted_value = extract_jsonb_path(document, path_expression)
  IF extracted_value IS NOT NULL:
    RETURN TRUE
  ELSE:
    RETURN FALSE
END FUNCTION