Introduction to Dgraph for SQL Users

Count Results

As a SQL user, you are accustomed to how SQL counts results: rows of data are counted with a COUNT function in a SELECT statement; with an asterisk * used to count all rows, or a column name specified to skip rows where that column is null. You can do the same thing with GraphQL using Dgraph’s aggregate queries to count every node of the specified type without returning the full dataset. And, you can skip nodes with null data for a particular field by adding filters to aggregate queries, as shown below:

SQL syntax:

SELECT
  COUNT(*)
FROM posts

Similar GraphQL syntax:

query COUNT_POSTS {
  aggregatePost {
    count
  }
}

SQL syntax:

SELECT
  COUNT(posts.title)
FROM posts

Similar GraphQL syntax:

query COUNT_POST_TITLES {
  aggregatePost(filter: {
    has: title
  }) {
    count
  }
}

It’s important to note that with GraphQL, it is possible to count nested edges as well. Any edge that references a list generates an additional field for the aggregate of the field name. This field takes the form <field name>Aggregate. With SQL, this would be similar to doing a join and counting non-null rows.

query COUNT_PERSONS_POSTS {
  queryPerson {
    username
    authoredPostsAggregate {
      count
    }
  }
}

Note: To learn more about Dgraph’s support for count queries, and other aggregate queries, see Aggregate Queries in the Dgraph documentation.