Introduction to Dgraph for SQL Users

Combine Related Data

In GraphQL, combining data is often called “traversing a graph”. In SQL, you combine data from various tables using a process called “joining tables”.Traversing a graph is where the GraphQL syntax really starts to show its advantages in terms of simplicity. When your app consumes data with deep traversals, you will find that the syntax is not only easier to write, but also the data is easier to consume in a nested ‘graph-like’ result. Additionally, you can traverse a graph as-needed without having to prepare your database for such traversals by adding a large number of joins to your database.

With SQL, the more tables that get joined together, the wider the results table can become. This is because the results from a SQL join produce a flattened table.

With GraphQL, combining related data is achieved by adding the edge object as a field. It is invalid syntax to add an edge when no fields are selected from that edge object. The more nested edges that are added, the deeper the results objects can become.

SQL syntax:

SELECT
  posts.id,
  posts.title,
  people.id,
  people.username
FROM
  posts
  LEFT JOIN people
    ON posts.author = people.id

Similar GraphQL syntax:

query POSTS_WITH_AUTHORS {
  queryPost {
    id
    title
    author {
      username
    }
  }
}

SQL syntax:

SELECT
  posts.id,
  posts.title,
  comments.id,
  comments.text,
  people.id,
  people.username
FROM
  posts
  LEFT JOIN comments
    ON comments.on_post=posts.id
  LEFT JOIN people
    ON comments.author=people.id

Similar GraphQL syntax:

query POSTS_W_COMMENTS_AUTHORS {
  queryPost {
    id
    title
    comments {
      id
      text
      author {
        username
      }
    }
  }
}

The following example starts to really show how a complex join with a filtered sub-query can be simpler with GraphQL’s typed syntax. And, GraphQL’s query responses are easier for you to read and for your app to parse because they are formatted as JSON-style nested lists, rather than a flattened table.

SQL syntax:

SELECT
  posts.id,
  posts.title,
  post_auth.id,
  post_auth.username,
  comnt_auth.id,
  comnt_auth.username
FROM
  posts
  LEFT JOIN people post_auth
    ON posts.author = post_auth.id
  LEFT JOIN comments
    ON comments.on_post=posts.id
  LEFT JOIN (
      SELECT
        people.id,
        people.username
      FROM
        people
      WHERE
       people.username="jarvis"
    ) comnt_auth
    ON comments.author=comnt_auth.id

Similar GraphQL syntax:

query POSTS_W_AUTH_COMNT_W_AUTH {
  queryPost {
    id
    title
    author {
      username
    }
    comments {
      id
      text
      author(filter: { username: { eq: "jarvis" } }) {
        username
      }
    }
  }
}