Introducing GROQ-powered Webhooks
NEWS · July 12th 2021

Logical AND, Logical OR, Logical NOT in GROQ

In the latest episode of Kap & Lauren learn GROQ - Part 6, we learned how to use the logical AND, the logical OR, and the logical NOT to really fine-tune our queries.

Lauren Etheridge

Lauren is a Developer Relations Specialist at Sanity.

Kapehe

Kapehe is a Developer Relations Specialist at Sanity.

In Kap & Lauren Learn GROQ - Part 6, we delved into the world of logical and comparison operators and space travel. We both agreed that we preferred exploring space over the bottom of the sea, astronauts && international space station == YAY! while giant sea monsters || giant squid == No Way!

Logical Operators

Logical operators such as AND [&&], OR [||], and NOT [!] are common booleans that evaluate to true, false, or null.

AND operator - &&

The [&&] operator evaluates true when both sides of the expression are true:

*[_type == "product" && "chocolate" in tags]

Using the e-commerce sample dataset, we filtered the document type product and used the && operator to filter through the tags and find only the candy that is tagged as chocolate. In this query, the && declares that the candy must be a product and it must also have a chocolate tag. In other words, both sides must be true.

OR operator - | |

The [||] is a bit more flexible in that only one side of the expression needs to be satisfied in order to evaluate true:

*[_type == "product" && "Liquorice" in tags || "Strange" in tags]{
  tags
}

The OR operator in the above query allowed Kap & I to return all candy that was tagged as Liquorice or Strange. If the candy had at least one of these tags, the expression would evaluate as true.

Gotcha

Case/Capitalization: In the e-commerce sample dataset, the tags were case sensitive and if the title was capitalized, it must be capitalized in the query.

NOT operator - !

The [!] operator is a negation and evaluates to true when the value is not a part of the specified parameter:

*[_type == "product" && !(_id in path("drafts.**"))]

The filter in the above query is looking for all documents in the product type that are not in drafts. In other words, all candy products that have been published.

If you missed the stream, you can watch Kap & Lauren learn GROQ - Part 6 on YouTube. Follow us on Twitch and tune in for another episode of Kap & Lauren learn GROQ, we hope to see you there!