Introduction to Dgraph for SQL Users

GraphQL Syntax

If you are already familiar with GraphQL syntax, then this will be a quick review. GraphQL is a query language for APIs and a runtime for fulfilling those queries. With GraphQL, you describe your data, ask for what you want, and get predictable results.

The following code block shows how to describe the Post type in the GraphQL schema:

type Post {
  id: ID
  title: String!
}

You can then use the following query to fetch posts:

query {
  queryPost {
    id
    title
  }
}

Taking a brief peek into the syntax, you can see how GraphQL resembles a syntax you may be familiar with, JSON. This resemblance can be further seen in that the data returned from GraphQL is of a JSON type consisting of objects, property names, arrays, and scalars.

{
  "data":{
    "queryPost": [
      {
        "id": "0x5",
        "title": "If we’re going to win this fight, some of us might have to lose it."
      },
      {
        "id": "0x6",
        "title": "Is that the best you can do?"
      },
    ]
  }
}

GraphQL is a type-controlled environment. Types control requests along with their inputs and responses. Building a schema in GraphQL is nothing more than declaring types.

What is a GraphQL query? The GraphQL query is a typed request to a server that can parse and respond with data in a specific format. GraphQL can retrieve data like a SQL query, but goes beyond what you can do with a SQL query to provide an API for your app that replaces the need for a REST API, and greatly reduces the need for client-side parsing of query results.

How does this compare to SQL? A SQL query is a structured question that makes a request to a database to retrieve information or perform an action. They can be compared side by side for a quick understanding of the correlating syntax.

A side-by-side syntax comparison of SQL and GraphQL queries

A side-by-side syntax comparison of SQL and GraphQL queries

Mutations are GraphQL’s method for commanding a server application to make a change to the data in the graph. One of the main differences between a GraphQL mutation and a SQL action query is that the mutation handles both the action and the return of resulting data in a single round trip.

A side-by-side comparison between the SQL equivalent of a mutation, and a GraphQL mutation

A side-by-side comparison between the SQL equivalent of a mutation, and a GraphQL mutation

Both GraphQL queries and mutations accept inputs. These inputs form the filters, pagination, ordering rules, and data values when mutating. Inputs are also controlled by types. With Dgraph Cloud almost all inputs are generated from a user-supplied schema of types.

input: addPostInput {
  title: String!
  date: DateTime!
}

Together the types, queries, mutations, and inputs form the fundamental structure of GraphQL.