Skip to main content

GraphQL in LWC: Queries, Mutations, and When to Use Apex Instead

About Us
Published by yuliya.dzemidchuk
26 June 2026

GraphQL in Lightning Web Components: Queries, Mutations, Use Cases, Pros and Cons

 

Introduction

As Salesforce applications become more data-driven and interactive, retrieving and managing data efficiently becomes critical. Currently, there are several options for obtaining Salesforce data from Lightning Web Components. These include Lightning Data Service (LDS), UI API, Apex controllers, and REST APIs. Though these tools are reliable, they still involve multiple server requests or provide additional information that a component does not need.

GraphQL provides a modern alternative by allowing developers to request exactly the data they need in a single request. This means Lightning Web Components can get related data in a more efficient way, without having to rely on multiple endpoints or custom Apex methods.

In this article, we will explore:

  • GraphQL Queries
  • GraphQL Mutation Requests
  • Using GraphQL in Lightning Web Components
  • Common Use Cases
  • Pros and Cons

 

1. GraphQL Queries

GraphQL queries let developers specify exactly which objects and fields to return from Salesforce.  This enables the minimization of unnecessary data transfer. 

Example of the query that returns the Id, Name, and Industry fields for the first five Account records:

query GetAccounts {
    uiapi {
        query {
            Account(first: 5) {
                edges {
                    node {
                        Id
                        Name {
                            value
                        }
                        Industry {
                            value
                        }
                    }
                }
            }
        }
    }
}

 

Beyond basic field selection, the same query can filter, sort, paginate, and fetch related records.

Here's an example that retrieves five Technology accounts, sorted by Name:

query GetTechnologyAccounts {
  uiapi {
    query {
      Account(
        where: {
          Industry: {
            eq: "Technology"
          }
        }
        orderBy: {
          Name: {
            order: ASC
          }
        }
        first: 5
      ) {
        edges {
          node {
            Id
            Name {
              value
            }
            Industry {
              value
            }
          }
        }
      }
    }
  }
}

 

2. GraphQL Mutation Requests

Mutations are used to modify data while queries retrieve data. Mutations support standard CRUD operations: creating, updating, and deleting records.

Example of creating an Account:

mutation CreateAccount($input: AccountCreateInput!) {
  uiapi {
    AccountCreate(input: $input) {
      Record {
        Id
        Name {
          value
        }
      }
    }
  }
}

 

Updating an existing record:

mutation UpdateAccount($input: AccountUpdateInput!) {
  uiapi {
    AccountUpdate(input: $input) {
      Record {
        Id
        Industry {
          value
        }
      }
    }
  }
}

 

Note: Response capabilities vary depending on the Salesforce API version. Starting with Salesforce API v66.0, update mutations can return a Record object containing the fields requested in the response. Delete mutations return only the Id of the deleted record. 

Some of the limitations of GraphQL include the following:

  • Child records have to be created/updated separately through mutations since GraphQL does not allow updating parent and child records via mutations.
  • Mutations support the allOrNone parameter, which controls transaction behavior. By default, its value is true, so the entire transaction is rolled back, if any operation in the request fails.

Mutations simplify common data operations and can eliminate the need for simple Apex controllers. However, for the complex  business logic (multiple object updates, integrations, custom processing) Apex remains the preferred solution.

In Lightning Web Components, mutations are executed imperatively using executeMutation() rather than the @wire service.

 

3. Using GraphQL in Lightning Web Components

The lightning/graphql module is what connects LWC directly to the Salesforce GraphQL API. Developers define a GraphQL query using the gql template literal and execute it through the graphql wire adapter. 

Example:

import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/graphql';

const ACCOUNT_QUERY = gql`
query Accounts {
    uiapi {
        query {
            Account(first:5) {
                edges {
                    node {
                        Id
                        Name {
                            value
                        }
                    }
                }
            }
        }
    }
}
`;

export default class AccountList extends LightningElement {

    @wire(graphql, {
        query: ACCOUNT_QUERY
    })
    accounts;
}

 

Salesforce previously provided the lightning/uiGraphQLApi module for GraphQL query operations. The current lightning/graphql module is the newest version. It replaces lightning/uiGraphQLApi and is recommended for new development. It also provides new capabilities such as GraphQL mutations via executeMutation().

The GraphQL wire adapter behaves similarly to other wire adapters in LWC, providing reactive data updates whenever the query parameters change. Compared to Apex controllers, this approach typically requires less code while improving maintainability.

Note: The graphql wire adapter is used only for GraphQL read operations. But GraphQL mutations are executed imperatively using the executeMutation() function from the lightning/graphql module.

 

4. Use Cases

GraphQL is particularly useful for components that need information from multiple related Salesforce objects. Common use cases include:

  • Dashboard Components. Dashboards tend to pull from Accounts, Opportunities, Cases and Contacts all at once. One GraphQL query covers it instead of a separate call for each.
  • Record Detail Pages. Instead of making multiple server calls for related lists, GraphQL can retrieve a parent record together with its child records.
  • Complex Data Tables. Large tables displaying related information benefit from GraphQL by requesting only the fields that are actually visible.
  • Mobile Applications. Reducing network traffic is especially important for mobile users. GraphQL minimizes payload size by returning only requested data.
  • Replacing Multiple Apex Calls. Several Apex calls for retrieving related information can be substituted by one GraphQL call.

 

5. Pros and Cons

GraphQL offers several advantages for Lightning Web Components:

  • Retrieves only the required fields.
  • Reduces unnecessary network traffic.
  • Supports multiple related objects in a single request.
  • Simplifies frontend development.
  • Reduces the need for simple Apex controllers.

Despite its advantages, GraphQL is not intended to replace Apex completely. Some limitations include:

  • Not every Salesforce feature is currently available through the GraphQL API.
  • Complex business logic still requires Apex.
  • Large nested queries can become difficult to maintain.
  • Poorly designed queries may negatively impact performance.
  • Child relationship creation and updates are not currently supported in mutations.
  • Some mutation response capabilities depend on the Salesforce API version. 

 

Conclusion

GraphQL allows developers to retrieve and process data efficiently using Lightning Web Components. Fewer requests, smaller payloads, less Apex code to write and maintain.

Apex isn't going anywhere though: complex logic, multi-object transactions and gaps in the GraphQL API still need it. Knowing when to use which is what matters in practice.


Hanna Pestava
Salesforce Developer
image
Expertise
Question to the expert
image

We have available resources to start working on your project within 5 business days

1 UX Designer

image

1 Admin

image

2 QA engineers

image

1 Consultant

image
Related Articles
All articles
image
Is Salesforce Winning the Public Sector Race?
An analysis of Salesforce's rapid expansion into the U.S. public sector, tracing its path from cautious early government licensing deals in the 2010s through the launch of Government Cloud in 2012, its pivotal role in COVID-19 vaccine rollouts, and its 2025–2026 push into military and intelligence work via Agentforce and Missionforce. The piece covers major 2026 contracts — including a $5.6 billion Army deal, a $1.6 billion VA agreement, and Pentagon Impact Level 5 authorization — alongside real-world case studies like California's REAL ID processing and the UK's NHS back-office operations. It also examines the structural obstacles still facing Salesforce and other vendors in government tech: legacy IT systems decades old, outdated federal procurement rules, budget constraints, and organizational caution around AI adoption, plus the competitive pressure from Palantir, Microsoft, and Oracle in the race for public sector AI spending.
28 August 2026
image
Why Your Salesforce Flows Are Agentforce's Biggest Problem
This article argues that the most underestimated risk in Agentforce deployments isn't data quality — it's the automation layer: years of overlapping Flows, Process Builder processes, Apex triggers, and managed package logic that no one has reviewed end-to-end. It explains why AI agents inherit automation complexity without the tribal knowledge human admins carry, why technical debt only becomes visible after an agent hits it in production, and why a clean demo is no indicator of production readiness. The article closes with a concrete, tool-by-tool inventory approach using Flow Trigger Explorer, Salesforce Optimizer, Setup Audit Trail, Apex Debug Logs, Agent Builder, and Health Check — scoped to the specific processes the agent will actually use rather than the whole org.
23 July 2026
image
How to Wire Multiple Salesforce Projects in One Org Without Breaking Everything
This article maps the real integration patterns that emerge when multiple Salesforce projects — both managed packages and unpackaged code — share a single org. It covers four concrete patterns: attaching custom triggers to package-owned objects, calling global members exposed by managed packages, writing directly into another project's objects, and runtime-guarded reads of package data. It then addresses access control for authenticated and guest users, including the Master-Detail wall and the without sharing elevation pattern. The piece closes with eight concrete risks (compile-time dependencies that block uninstall, upgrade coupling, silent cascade failures, access invisible to admins) and six actionable recommendations for keeping cross-project coupling manageable.
08 July 2026