Skip to main content
Backend & APIs

GraphQL Queries, Mutations & Schemas

Production

GraphQL Query language, mutations, fragments, variables, directives, type definitions, and subscription patterns.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

GraphQL Queries, Mutations & Schemas Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (15 Total Commands).

15+ Verified Recipes
Query with Variablesquery, @include
query GetUser($id: ID!, $includePosts: Boolean = true) { user(id: $id) { id name posts @include(if: $includePosts) { title slug } } }

Structured client query requesting exact nested fields with conditional directive.

Mutationsmutation
mutation CreateArticle($input: ArticleInput!) { createArticle(input: $input) { id title createdAt } }

Perform write mutation and return newly generated record fields.

Reusable Fragmentsfragment ... on Type
fragment UserPreview on User { id displayName avatarUrl } query { users { ...UserPreview } }

Define reusable field set across multiple client components.

Schema Definition (SDL)type Query, union
type Query { user(id: ID!): User search(term: String!): [SearchResult!]! } union SearchResult = User | Article

Define schema entrypoints and polymorphic union types.

Real-Time Subscriptionssubscription
subscription OnNewMessage($channelId: ID!) { messageAdded(channelId: $channelId) { id content sender { name } createdAt } }

Subscribe to server-sent WebSocket events for real-time bidirectional message streaming.

Cursor-Based PaginationPageInfo, cursor
input PaginationInput { first: Int = 20 after: String } type PageInfo { hasNextPage: Boolean! endCursor: String }

Relay specification cursor pagination schema definition for high-volume infinite scroll APIs.

Cache Control Directives@cacheControl
directive @cacheControl(maxAge: Int, scope: CacheControlScope) on FIELD_DEFINITION | OBJECT type Query { popularPosts: [Post] @cacheControl(maxAge: 300) }

Declare edge CDN and reverse-proxy caching policies directly inside the schema definition.

DataLoader BatchingDataLoader
const userLoader = new DataLoader(async (userIds) => { const users = await db.users.findMany({ where: { id: { in: userIds } } }); return userIds.map(id => users.find(u => u.id === id)); });

Batch and deduplicate database requests across resolver invocations solving the GraphQL N+1 problem.

Polymorphic Unionsunion
union SearchResult = User | Article | Comment type Query { search(query: String!): [SearchResult!]! }

Define heterogeneous polymorphic union schemas returning distinct object types from a single query.

Interface Contractsinterface, implements
interface Node { id: ID! } type User implements Node { id: ID! name: String! }

Guarantee shared field contracts across disparate object types using abstract schema interfaces.

Apollo Server SetupApolloServer
const server = new ApolloServer({ schema, plugins: [ApolloServerPluginInlineTrace(), responseCachePlugin()] });

Initialize production Apollo Server instance with query tracing metrics and response cache plugin.

Schema Introspection__schema
query IntrospectionQuery { __schema { types { name kind description } } }

Introspect complete type system and documentation for client code generators and tooling.

Batch Mutationsmutation, [UpdateUserInput!]
mutation BatchUpdateUsers($inputs: [UpdateUserInput!]!) { updateUsers(inputs: $inputs) { id status } }

Perform multi-record batch mutations within a single HTTP POST request.

Conditional Directives@include, @skip
query DynamicQuery($withComments: Boolean!) { post(id: "123") { title comments @include(if: $withComments) { text } } }

Dynamically include or omit subtree fields based on runtime Boolean variables.

Type-Safe Enumsenum
enum OrderStatus { PENDING PROCESSING COMPLETED CANCELLED }

Enforce strict enumerations preventing invalid state strings in arguments and responses.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

GraphQL Queries, Mutations & Schemas: Command Groups & Quick Index

15 indexed entries across 15 sections
Query with Variables1 items
Mutations1 items
Reusable Fragments1 items
Schema Definition (SDL)1 items
Real-Time Subscriptions1 items
Cursor-Based Pagination1 items
Cache Control Directives1 items
DataLoader Batching1 items
Polymorphic Unions1 items
Interface Contracts1 items
Apollo Server Setup1 items
Schema Introspection1 items
Batch Mutations1 items
Conditional Directives1 items
Type-Safe Enums1 items

Highlighted Flags & Syntax Examples in GraphQL Queries, Mutations & Schemas

query GetUser($id: ID!, $includePosts: Boolean = true) { user(id: $id) { id name posts @include(if: $includePosts) { title slug } } }

Structured client query requesting exact nested fields with conditional directive.

Flags: query, @include
mutation CreateArticle($input: ArticleInput!) { createArticle(input: $input) { id title createdAt } }

Perform write mutation and return newly generated record fields.

Flags: mutation
fragment UserPreview on User { id displayName avatarUrl } query { users { ...UserPreview } }

Define reusable field set across multiple client components.

Flags: fragment ... on Type
type Query { user(id: ID!): User search(term: String!): [SearchResult!]! } union SearchResult = User | Article

Define schema entrypoints and polymorphic union types.

Flags: type Query, union

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for GraphQL Queries, Mutations & Schemas.

How does GraphQL solve Over-fetching and Under-fetching?

In REST, endpoints return fixed payloads (over-fetching unneeded fields) or require multiple round-trips to separate endpoints (under-fetching). In GraphQL, the client defines the exact shape of the response in a single request.

What is the DataLoader pattern in GraphQL backend servers?

DataLoader is a utility that batches individual resolver database queries together into a single 'WHERE id IN (...)' query and caches results, eliminating N+1 database queries across nested GraphQL fields.

What is the GraphQL N+1 problem and how does DataLoader solve it?

If a query requests 50 authors and each author's books, a naive resolver fires 1 query for authors followed by 50 individual queries for each author's books (51 queries total). Facebook's DataLoader library queues all individual book requests within a single tick of the event loop and consolidates them into a single 'SELECT * WHERE author_id IN (...)' batch query.

What is the difference between cursor-based pagination and offset-based pagination in GraphQL?

Offset-based pagination ('limit' and 'offset') suffers from performance degradation on deep offsets and skips or duplicates records when rows are inserted or deleted during paging. Cursor-based pagination uses an opaque pointer (like a base64 encoded timestamp or ID) with 'WHERE id > cursor LIMIT 20', maintaining steady index seek performance.

Why should GraphQL schema introspection be disabled in production environments?

Schema introspection exposes your entire internal data schema, relations, deprecated fields, and business logic to external parties. Malicious actors use introspection to discover unpublished mutations, sensitive entities, or exploit query depth complexity vulnerabilities.

How does GraphQL handle caching compared to RESTful HTTP caching?

Because all GraphQL queries are typically HTTP POST requests sent to a single endpoint (/graphql), standard HTTP reverse-proxies and CDNs cannot cache them by default URL keys. Solutions include persisted queries (hashing query strings into GET URLs) or Apollo Client normalized in-memory caching keyed by '__typename:id'.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets