Read Data with Queries
The most common use case of a backend is to read the stored data. Let’s take a look at a few use cases of example queries and how they would be formed in both GraphQL and SQL.
SQL uses keywords such as SELECT
, FROM
, WHERE
, to query data from the
backend. Conversely, with GraphQL being a typed system, there are not reserved
keywords that correspond to these SQL keywords. Instead, GraphQL has reserved
names. These reserved names
are types that are either already defined by specification or that will be
generated into the final schema by Dgraph.
Query data by type
With SQL, you use a SELECT
statement to request data, but with GraphQL, you
use a query block. For best practice, query blocks are named for later
reference. In this example, let’s name the GraphQL query block GET_POSTS
.
This name can be almost any name you want to use to uniquely reference this query.
SQL syntax:
SELECT ...
Similar GraphQL syntax:
query GET_POSTS { ... }
With both SQL and GraphQL, basic queries for data start with identifying the
type of data you want to fetch. SQL uses a FROM
statement with the table name.
In this example, you will use the posts
table. GraphQL uses a named root
block. To read multiple nodes of type Post, you need to use the queryPost
block, as in the following example:
SQL syntax:
SELECT
...
FROM
posts
Similar GraphQL syntax:
query GET_POSTS {
queryPost {
...
}
}
The field selection of both queries is very similar. The main difference is that in SQL, separating commas are required, but with GraphQL syntax commas aren’t required to separate fields - that is done with whitespace or line breaks. The standard way to lay out GraphQL syntax for readability is shown in the syntax example below.
The example below fills in the blanks (...
) in the syntax example above,
showing how you would fetch several fields from posts
. In SQL, this query
fetches fields from a posts
table; in GraphQL it fetches fields from all nodes
of type posts
:
SQL syntax:
SELECT
posts.id,
posts.title,
posts.date
FROM
posts
Similar GraphQL syntax:
query GET_POSTS {
queryPost {
id
title
date
}
}
Identity
The query above references id
, so you might wonder how a traditional SQL
database manages identity and how this is managed by Dgraph database. SQL
databases generally have IDs that are unique to each record within a table, so
no two posts would share an ID, but a post and an unrelated comment could share
the same ID because these IDs exist in different tables.
In contrast, Dgraph uses a universal ID (uid
) to uniquely identify nodes
within a dataset. So, in the example above, an ID can’t be shared by two posts,
and it would also never be shared by a post and a comment. To represent
potentially large IDs in fewer characters, Dgraph stores each uid
in
hexadecimal format.
In the next section, you’ll see how SQL and GraphQL approach filtering query results.