TransWikia.com

How to pull data from an array using SQL

Stack Overflow Asked by Sarah on September 29, 2020

If I have a string column with the following data:

+-------+----------------------------+
| Row # |        Array Column        |
+-------+----------------------------+
|     1 | {apple;coconut;mango}      |
|     2 | {coconut;pear;grapes}      |
|     3 | {strawberry;mango;coconut} |
|     4 | {}                         |
|     5 | {january}                  |
+-------+----------------------------+

How can I pull out only the rows that have mango or nothing in it?

Result:

+-------+----------------------------+
| Row # |        Array Column        |
+-------+----------------------------+
|     1 | {apple;coconut;mango}      |
|     3 | {strawberry;mango;coconut} |
|     4 | {}                         |
+-------+----------------------------+

One Answer

If the column is a string and not an actual array.

SELECT * 
FROM YourTable 
WHERE ArrayColumn='{}' 
OR ArrayColumn like '%mango%'

If the column is indeed an array

SELECT * 
FROM YourTable 
WHERE size(ArrayColumn)=0
OR array_contains(ArrayColumn,'mango')

Answered by Gabriel Durac on September 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP