0
0
GraphqlComparisonBeginner · 3 min read

Include vs Skip Directive in GraphQL: Key Differences and Usage

In GraphQL, the @include directive includes a field only if a specified condition is true, while the @skip directive excludes a field if a specified condition is true. Both directives use a if argument to control whether a field or fragment is included in the query result.
⚖️

Quick Comparison

This table summarizes the main differences between the @include and @skip directives in GraphQL.

Aspect@include Directive@skip Directive
PurposeIncludes field if condition is trueSkips field if condition is true
Condition Argumentif: Boolean!if: Boolean!
Default BehaviorField excluded if if is falseField included if if is false
Use CaseAdd field only when neededRemove field when not needed
Logical RelationPositive conditionNegative condition
⚖️

Key Differences

The @include directive in GraphQL is used to conditionally add a field or fragment only when the if argument evaluates to true. This means if the condition is false, the field is omitted from the response entirely. It is useful when you want to add optional data based on some client-side logic.

On the other hand, the @skip directive works oppositely: it excludes a field or fragment when the if argument is true. If the condition is false, the field remains in the response. This directive is handy when you want to remove data conditionally.

Both directives accept a required Boolean argument named if. They cannot be used together on the same field because their conditions conflict. Choosing between them depends on whether you prefer to specify when to include or when to exclude a field.

⚖️

Code Comparison

graphql
query GetUser($showEmail: Boolean!) {
  user {
    id
    name
    email @include(if: $showEmail)
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": "alice@example.com" } } }
↔️

@skip Directive Equivalent

graphql
query GetUser($hideEmail: Boolean!) {
  user {
    id
    name
    email @skip(if: $hideEmail)
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": "alice@example.com" } } }
🎯

When to Use Which

Choose @include when you want to explicitly add a field only if a condition is true, making your query intent clear about adding optional data. Use @skip when you want to exclude a field based on a condition, which can be more intuitive if you think in terms of removing data.

In practice, @include is often preferred for adding optional fields, while @skip is useful for hiding sensitive or unnecessary data. Avoid using both on the same field to prevent confusion.

Key Takeaways

Use @include(if: Boolean) to add fields only when a condition is true.
Use @skip(if: Boolean) to remove fields when a condition is true.
Both directives control field presence dynamically in GraphQL queries.
Do not use @include and @skip together on the same field.
Choose the directive based on whether you think in terms of including or excluding data.