Course contentsShow
← Web Development
Lesson 1537 of 2,98228. GraphQL FundamentalsFree lesson

Query Directives: @include and @skip

Conditionally include or exclude fields in your query response using built-in directives.

Query Directives: @include and @skip

You'll learn how to conditionally control which fields appear in your GraphQL query response without writing multiple queries.

The Core Idea

GraphQL's @include and @skip directives let you dynamically toggle fields on or off based on variable values. Instead of creating separate queries for different scenarios (like a detailed view vs. simplified view), you write one query that adapts based on conditions you pass at runtime.

Think of it like ordering a customizable meal: you tell the kitchen "include fries if I say yes, skip dessert if I'm on a diet" — all in one order, decided at the moment you place it.

How They Work

@include(if: Boolean) — The field appears in the response only if the condition is true.

@skip(if: Boolean) — The field is excluded from the response if the condition is true.

query GetUser($includeEmail: Boolean!, $skipAddress: Boolean!) {
  user(id: "123") {
    name
    email @include(if: $includeEmail)
    phone
    address @skip(if: $skipAddress)
  }
}

When you execute this query, you pass variables:

{
  "includeEmail": true,
  "skipAddress": false
}

Result: You get name, email, phone, and address. Change includeEmail to false and the email field vanishes from the response.

When to Use Them

Perfect for permission-based fields (show admin data only if user is admin), performance optimization (skip expensive nested data on mobile), or user preferences (detailed vs. compact view).

Key Takeaway: Use @include and @skip directives to write flexible, reusable GraphQL queries that adapt to runtime conditions without maintaining multiple query variants.