skip to Main Content

I have a MariaDB table including a JSON field:

{
    arrayOfDates : ['2020-01-11', '2021-01, 12', '2019-03-12'],
    ...
}

For each record in my-table I need to extract the field arrayOfDates and pick the min value in the array.

Note I’m using MariaDB v 10.5.x so I cannot use JSON_TABLE.

How can I achieve this?

2

Answers


  1. You can do it using a recursive CTE:

    with recursive cte as (
          select '            ' as dt, REPLACE(REPLACE(JSON_QUERY(myjson, '$.arrayOfDates'), '[', ''), ']', ',') as dates, 1 as lev
          from mytable
          union all
          select substring_index(dates, ',', 1),
                 substr(dates, instr(dates, ',') + 2), lev + 1
          from cte
          where dates like '%,%'
    )
    select MAX(dt) AS max_date
    from cte
    where lev > 1;
    

    Demo here

    see :

    Login or Signup to reply.
  2. In MariaDB 10.5, if you cannot use JSON_TABLE,
    However, you can use the combination of JSON functions and regular SQL. Here’s an example query to get the minimum value from the arrayOfDates field for each record:

        SELECT 
            your_table.*, 
            (SELECT MIN(CAST(date AS DATE)) 
             FROM JSON_TABLE(your_table.json_column, '$.arrayOfDates[*]' 
             COLUMNS (date CHAR(10) PATH '$'))) AS min_date
        FROM 
            your_table;
    

    Replace your_table with the actual name of your table and json_column with the name of your JSON column.

    This query uses a subquery to extract the arrayOfDates from the JSON column using JSON_TABLE. It then uses the MIN function to find the minimum value after casting the dates to the DATE type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search