7

I have a SQL column that contains JSON such as this

{
"tags":[
{"id":11,"x":99.12343123213,"y":88.123232},
{"id":12,"x":99.12343123213,"y":88.123232},
{"id":13,"x":99.12343123213,"y":88.123232}
]
}

I am trying to find a record with the value of '13', however the number of objects may vary. I know that i could use code similar to:

select * from Logs WHERE JSON_VALUE([log],'$.tags[0].id') LIKE '13'

Unfortunately, the number of objects in the array could be any number. How could I search through every object in my array for the value?

I am aware I could search through the string for the value of '%"id":13,%', however this seems like a messy solution.

2
  • What variety of SQL are you using? Commented Feb 17, 2019 at 1:14
  • SQL Server 2017 Commented Feb 17, 2019 at 1:16

1 Answer 1

10

You can use OPENJSON to extract the id values from your JSON objects and CROSS APPLY that to your logs table, selecting only rows that have an id value in the JSON object of 13:

SELECT logs.*
FROM logs
CROSS APPLY OPENJSON([log], '$.tags') WITH (id INT '$.id')
WHERE id = 13

Demo on dbfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

how can I use this for mariadb?
This is SQL server specific. I suggest asking a new question as the solution would be quite different for MariaDB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.