While GROQ is nominally similar to GraphQL, there are subtle differences. Here's a quick run down of the similarities and differences, so that you can understand the reasons for GROQs existence, and some of it’s use-cases, before using it yourself
- Both use declarative Queries - Clients express their data requirements in a structured format without needing to specify how the data should be fetched or manipulated.
- Both have strong typing: Both GraphQL and GROQ have strong typing systems. They enforce strict data types, allowing clients to have confidence in the shape and structure of the data they receive. This improves the developer experience and reduces the chances of runtime errors caused by type mismatches.
- Both use schema definitions: Both GraphQL and GROQ rely on a schema to define the structure and types of the available data. GraphQL schemas describe the types, fields, and relationships between entities, while GROQ schemas define the structure and expected values of structured content documents.
- GraphQL can be used with any data source - It just needs to be mapped in the backend
- GROQ only works with Sanity, however it can nominally work with any collection of JSON documents.
- GraphQL allows clients to specify the data they want, but it always is returned in the same structure.
- GROQ allows clients to specify the data, but also allows projections so that data can be manipulated before being returned to the client
A simple way to look at it is that GraphQL is a pre-made sandwich that you can pick off a supermarket shelf, and GROQ is a sandwich from Subway* where the finer details can be controlled.
*Other deli’s are available
In the GraphQL shop (supermarket) you have a selection of sandwiches you can pick from, but they are always the same.
With GROQ (Subway) you ask for the sandwich you would like, and then you receive the complete one, with no need to go home and assemble it 😋