4

I've got an array of dates in a field called from. It can look something like this.

['2016-05-01', '2016-05-03', '2016-05-04']

I want to SELECT the last item (here 2016-05-04).

I've tried this:

SELECT `from`->"$[JSON_LENGTH(`from`) - 1]" FROM `table` WHERE `id` = 3;

but got that error:

ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 2.

I've tried using a variable like this :

SET @count = (SELECT JSON_LENGTH(`from`) - 1 FROM `table` WHERE `id` = 3);
SELECT `from`->"$[@count]" FROM `table` WHERE `id` = 3;

but got the exact same error. But if I do:

SELECT `from`->"$[2]" FROM `table` WHERE `idx` = 3;

It works fine.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Havarem
  • 85
  • 1
  • 6

2 Answers2

9

you can use :

SELECT JSON_EXTRACT(`from`,CONCAT("$[",JSON_LENGTH(`from`)-1,"]"))      FROM `table`;

to get the last item in a json array.

jmounim
  • 931
  • 7
  • 5
0

MySQL 8 brings a very straight forward way to accomplish this:

select json_extract(json_array(1, 2, 3, 4, 5), '$[last]');

which returns

5

Can also do cool ranges, like everything but the last one:

select json_extract(json_array(1, 2, 3, 4, 5), '$[0 to last-1]');

which returns

[1, 2, 3, 4]
Brian Leishman
  • 8,155
  • 11
  • 57
  • 93