Introduction to Dgraph for SQL Users

Paginate Results

While more and more apps developed are Single Page Applications (SPA) and a single GraphQL query can retrieve all of the data for the entire page at once, there are use cases when your app may need to be able to paginate through data.

In SQL, pagination is not standardized across the various SQL implementations. MySQL and PostgreSQL implement pagination with the LIMIT and OFFSET keywords that determine the number of query results to return and the offset, respectively.

In GraphQL, pagination is achieved by using first (similar to SQL’s LIMIT) and offset parameters, as shown below:

SQL syntax:

SELECT id
FROM posts
LIMIT 10

Similar GraphQL syntax:

query FIRST_10_POSTS {
  queryPost( first: 10 ) {
    id
  }
}

SQL syntax:

SELECT id
FROM posts
LIMIT 10
OFFSET 20

Similar GraphQL syntax:

query FIRST_10_POSTS {
  queryPost(
    first: 10
    offset: 20
  ) {
    id
  }
}

Your app might have a use case where you need to get a single matched item. While restrictions on the schema can prevent a filter from matching multiple items, another common query will add a filter with a limit of 1. With SQL, all results are returned in row-based lists. So, even if the results are limited to a single row, it will still return the single row in a list.

In GraphQL, results can be returned as either lists, objects, or scalars. If an app works with a single result item, it’s easier to work with the result if it’s returned as an object, rather than a list with a single item.

To manage queries against typed nodes (or objects) with GraphQL, Dgraph generates an additional root query for each type that contains an id field. To get a single node by id, you can use the get<Type> query. You can see how SQL and GraphQL handle this differently in the example below:

SQL syntax:

SELECT id, title
FROM posts
WHERE id="1"
LIMIT 1

Similar GraphQL syntax:

query GET_POST_BY_ID {
  getPost(id: "0x1") {
    id title
  }
}

In the next section we will look at the real strength of querying data with GraphQL compared to SQL: combining related data across nodes.