title: How to get last element in a MySQL JSON array?
body: <p>I recently found time to upgrade to MySQL 5.7 and I am testing the new <a href="https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html" rel="noreferrer">JSON functions</a>. So far, pretty awesome!</p>
  
  <p>I have a use case where I need to access the last element in a JSON array. Its easy to retrieve an element when you <em>know</em> the ordinal like this: </p>
  
  <pre><code>SELECT `json_field`-&gt;"$.my_array[0]" from `my_table` where `id` = 1;
  </code></pre>
  
  <p>But in the case when you don't know how many elements you have, this is not available to you. Now, you can find out (and store) how many elements there are like this:</p>
  
  <pre><code>set @arrayLength = (SELECT JSON_LENGTH(`json_field`-&gt;"$.my_array") from `my_table` where `id` = 1);
  </code></pre>
  
  <p>But when you go to use the variable, you do not get a result.</p>
  
  <pre><code>SELECT `json_field`-&gt;"$.my_array[@arrayLength - 1]" from `my_table` where `id` = 1;
  </code></pre>
  
  <p>Has anyone solved a similar problem with MySQL 5.7 yet?</p>