Free, open courseware in graph theory and its applications

learngraphtheory.org Algorithms · Networks · Graph AI · Optimization
Graph Data

What Is a Graph Database? Graph vs Relational Databases Explained

A graph database stores relationships as first-class data instead of rebuilding them with joins. This guide explains how graph databases store and query connected data, compares them honestly with relational databases, and shows the same question written in SQL, Cypher, SPARQL and Gremlin.

18 Min Read Updated: December 2026 Intermediate Level
A whiteboard split in two: on the left, hand-drawn database tables linked by dashed foreign-key arrows; on the right, the same data redrawn as a graph of circled nodes joined by labelled arrows
Mohammed Islam Hadjoudj
Mohammed Islam Hadjoudj
Scientific Software Developer and Operations Research Engineer
MSc in Operations Research · BSc in Mathematics

1. What Is a Graph Database?

A graph database is a database that stores data as a graph: a set of nodes (also called vertices) connected by relationships (also called edges). A customer, a bank account, a web page or a machine part becomes a node. “Owns”, “links to”, “is part of” and “bought” become relationships. Both nodes and relationships can carry data, and the database is built to answer questions that move along the relationships, such as “who is connected to whom, through what, and how far away?”

Every database can store relationships in some form. What sets a graph database apart is that relationships are first-class data. In a relational database a relationship is implied by matching values in two columns, and the database rediscovers it with a join every time a query needs it. In a graph database the relationship is stored as an explicit record that points from one node to another, so following it is a direct step rather than a search.

That difference hardly matters when a query looks one or two steps away. It matters a great deal when a query must follow a chain of unknown length, such as a bill of materials, a chain of company ownership, a path through a computer network or a ring of fraudulent accounts. Those are the problems graph databases were designed for, and they are the reason the category grew from a niche into a standard part of the data stack, with an ISO query language of its own since 2024.

In one sentence: a graph database stores entities as nodes and connections as relationships, so queries that follow many connections run as a walk through the graph instead of a series of table joins.

This guide explains how graph databases work from the ground up: the two main data models, how relational databases handle the same data, what “index-free adjacency” really means, the main query languages, the graph algorithms that run inside the database, the products on the market, and how to decide between a graph and a relational database for your own project.

2. Two Data Models: Property Graphs and RDF

“Graph database” covers two families that grew up separately and still use different standards. Both are directed, labelled multigraphs in graph-theory terms: edges have a direction and a type, and two nodes can be joined by several edges of different types. If those terms are new, see our guides to directed vs undirected graphs and simple graphs vs multigraphs.

The labelled property graph

The labelled property graph is the model used by most products people call graph databases today. It has four building blocks:

Properties on relationships are the feature that makes the model so practical. A BOUGHT relationship can carry the date, price and channel of the purchase, which in a relational design would need a separate table.

RDF and the semantic web

The Resource Description Framework (RDF) is a W3C standard that represents everything as triples of the form subject, predicate, object, for example (Corvo Alloys, ships through, Halden Port). Every node and predicate is identified by a globally unique IRI, which lets datasets published by different organisations be merged simply by taking the union of their triples. RDF stores, often called triplestores, are queried with SPARQL, and they support ontologies and reasoning, which let the database infer new facts from rules. Wikidata, life-science knowledge bases and many government open-data portals are built on RDF.

The two models can express the same information, but they have different strengths. Property graphs feel natural to application developers and make it easy to attach data to edges. RDF shines when data from many sources must be integrated under shared vocabularies. RDF 1.2, the next revision of the standard, adds “triple terms” that let a statement be the subject of another statement, which narrows the gap with properties on edges. In the rest of this guide, “graph database” mainly means a property graph database, the kind used for most application and analytics work.

3. How Relational Databases Store Relationships

A relational database stores data in tables of rows and columns. A relationship between two rows is expressed by a foreign key: a column in one table whose value matches the primary key of a row in another table. A one-to-many relationship, such as a product and its maker, needs one foreign-key column. A many-to-many relationship, such as customers and the products they buy, needs a separate join table with one row per pair.

To follow a relationship, the query engine performs a join: it matches rows from two tables whose key values are equal. With an index on the key, each lookup is a search in a B-tree, which costs about O(log n) for a table of n rows. For questions that span a fixed, small number of tables, this is extremely efficient, and decades of query-optimiser research make relational databases very good at it.

The same supply-chain data stored two ways: on the left as relational tables linked by foreign keys and a join table, on the right as a property graph in which companies, a port and products are nodes joined by typed relationships
Figure 1. The same data as relational tables (left) and as a property graph (right). Foreign keys and join tables become explicit relationships.

The trouble starts with recursive or variable-length questions. “Which finished products contain this part, at any depth?” cannot be answered by a fixed number of joins, because nobody knows in advance how deep the bill of materials goes. Standard SQL handles this with a recursive common table expression (WITH RECURSIVE), which repeats a join until no new rows appear. It works, and modern engines run it well, but the query becomes harder to write, harder for the optimiser to estimate, and slower as the depth and fan-out grow, because every step is again a join against a whole table.

There is also a modelling cost. In a relational schema, a new kind of relationship usually means a new table or a new foreign-key column, plus a migration. In a property graph, it is simply a new relationship type, which can be added to the data without changing the existing nodes.

4. Inside a Graph Database: Index-Free Adjacency

The defining idea of a native graph database is index-free adjacency: every node holds direct references to its neighbouring relationships, and every relationship holds direct references to its start and end nodes. Moving from a node to its neighbours means following stored pointers, not looking up a global index.

In graph-theory terms, the storage engine keeps an adjacency list on disk and in memory. Neo4j’s classic record format, for example, stores nodes and relationships in fixed-size records. A node record points to its first relationship, and each relationship record links to the next relationship of each of its two endpoints, forming a linked list per node. Because the records have a fixed size, the position of record number i is computed by multiplication rather than searched for.

Two ways to take one hop from a customer to the products they bought: a relational engine searches a B-tree index on the join table at a cost of about log n per lookup, while a native graph engine follows a pointer stored in the node record at a cost that depends only on the node’s own relationships
Figure 2. One hop in each engine. A join searches an index whose size grows with the whole table; index-free adjacency follows pointers whose number depends only on the node’s own degree.

The consequence is about where the cost of a query comes from. Expanding one node costs time proportional to its degree, the number of relationships it has, and does not depend on how large the whole database is. A traversal that visits m relationships costs roughly O(m), whether the graph holds a thousand nodes or a billion. A join-based plan pays an index search for every step, and if the optimiser picks a hash join instead, it may read entire tables to answer a question about a handful of rows.

Two qualifications keep this honest. First, the per-hop advantage over an indexed join is roughly a factor of log n, which is real but modest. The big wins come from deep, branching traversals and from queries whose depth is not known in advance, where a relational plan has to repeat joins step by step. Second, not every graph database is native. Many store the graph on top of another engine, such as a key-value store, a wide-column store or a relational database, and translate traversals into lookups. Others, such as FalkorDB, represent the graph as sparse adjacency matrices and evaluate queries with linear algebra. Surveys of the field show that these designs can be just as fast in practice. What users should care about is measured performance on their own queries, not the label “native”.

Graph databases also differ in their workload. Transactional (OLTP) graph databases serve many small reads and writes with ACID guarantees, like an operational relational database. Analytical engines load a graph into memory to run whole-graph algorithms such as PageRank or community detection. Many products now offer both, often as a transactional store plus an in-memory analytics library.

5. Query Languages: Cypher, GQL, SPARQL and Gremlin

SQL describes the rows you want from tables. Graph query languages describe the patterns you want to find in a graph. Four languages matter today.

Some products add their own languages, such as AQL in ArangoDB, GSQL in TigerGraph and nGQL in NebulaGraph, and most of them are moving toward GQL compatibility. The best way to see the differences is to ask the same question in each language.

6. A Worked Example: One Question, Four Languages

Take a small supply chain, the same one used in our GraphRAG guide. All names are fictional. Corvo Alloys ships everything through Halden Port and makes an aluminium housing. The housing is part of a C7 controller board, made by Brisa Electronics, and the board is part of the P200 pump, made by Tarn Industrial. Brisa also makes an S3 pressure sensor that goes into the same pump. Two customers, Vela Water Utility and Ostra Farms, buy the P200.

The question is a classic multi-hop one:

“If Halden Port closes, which customers lose a product, and which product?”

The relational version

A natural relational schema has a table for companies, ports and products, a foreign key from each product to its maker, and join tables for shipping routes, the bill of materials and purchases.

CREATE TABLE company       (id INT PRIMARY KEY, name TEXT);
CREATE TABLE port          (id INT PRIMARY KEY, name TEXT);
CREATE TABLE product       (id INT PRIMARY KEY, name TEXT,
                            maker_id INT REFERENCES company(id));
CREATE TABLE ships_through (company_id INT REFERENCES company(id),
                            port_id    INT REFERENCES port(id));
CREATE TABLE part_of       (part_id     INT REFERENCES product(id),
                            assembly_id INT REFERENCES product(id));
CREATE TABLE buys          (customer_id INT REFERENCES company(id),
                            product_id  INT REFERENCES product(id));

Because a part can sit any number of levels deep inside a product, the query needs a recursive common table expression. The first branch finds the products made by companies that ship through the port. The second branch repeatedly climbs the bill of materials from a part to the assembly that contains it.

WITH RECURSIVE affected(product_id) AS (
    -- products made by companies that ship through the port
    SELECT p.id
    FROM port pt
    JOIN ships_through st ON st.port_id = pt.id
    JOIN product p        ON p.maker_id = st.company_id
    WHERE pt.name = 'Halden Port'
  UNION
    -- every assembly that contains an affected part
    SELECT po.assembly_id
    FROM part_of po
    JOIN affected a ON po.part_id = a.product_id
)
SELECT DISTINCT c.name AS customer, p.name AS product
FROM affected a
JOIN buys b    ON b.product_id = a.product_id
JOIN company c ON c.id = b.customer_id
JOIN product p ON p.id = a.product_id;

The recursion finds three affected products (the housing, the C7 board and the P200 pump), and the final join returns two rows: Vela Water Utility and Ostra Farms, both losing the P200 pump. The query is correct and portable, but its shape has little to do with the question. Six joins and a recursion express what is, in the end, a single path.

Cypher

In a property graph, makers, shipping routes, components and purchases are all relationships. The query draws the path directly. The quantifier *0.. means “zero or more PART_OF hops”, so a customer who buys the affected part itself is found as well as one who buys a product that contains it.

MATCH (:Port {name: 'Halden Port'})<-[:SHIPS_THROUGH]-(:Company)
      -[:MAKES]->(:Product)-[:PART_OF*0..]->(p:Product)
      <-[:BUYS]-(c:Company)
RETURN DISTINCT c.name AS customer, p.name AS product;

The result is the same two rows. In GQL the pattern is almost identical. The main visible difference is the quantifier, written -[:PART_OF]->{0,} after the edge pattern.

SPARQL

As RDF triples, each fact is one statement, and the property path ex:partOf* plays the same role as Cypher’s variable-length pattern.

PREFIX ex: <http://example.org/>

SELECT DISTINCT ?customer ?product WHERE {
  ?supplier ex:shipsThrough ex:HaldenPort .
  ?supplier ex:makes        ?part .
  ?part     ex:partOf*      ?product .
  ?customer ex:buys         ?product .
}

Gremlin

Gremlin describes the walk itself: start at the port, step backwards along SHIPS_THROUGH, forwards along MAKES, then repeatedly along PART_OF, and finally backwards along BUYS. Placing emit() before repeat() keeps the starting part as well as every assembly reached from it.

g.V().has('Port', 'name', 'Halden Port').
  in('SHIPS_THROUGH').out('MAKES').
  emit().repeat(out('PART_OF')).
  in('BUYS').dedup().values('name')

All four queries return Vela Water Utility and Ostra Farms. On five rows of data the relational engine is just as fast. The difference appears at scale: with millions of parts and deep, branching assemblies, the graph engine touches only the relationships along the paths it explores, while the recursive SQL repeats a join against the full part_of table at every level. Just as important, the graph query can be read aloud as the question it answers, which makes it easier to write, review and change.

7. Graph Algorithms Inside the Database

Pattern queries answer questions about specific nodes. Many of the most valuable questions are about the whole graph: which accounts are most central in a payment network, which customers form tight communities, which products are similar because the same people buy them. Those questions need graph algorithms, and most graph platforms now ship a library of them that runs next to the data, such as the Neo4j Graph Data Science library, Memgraph MAGE, Neptune Analytics and TigerGraph’s graph data science library.

The core algorithm families are the same ones taught in any graph theory course, and you can run each of them step by step in our visualizers:

Running these algorithms inside the database avoids exporting the graph to another system, and the results can be written back as properties, for example a pagerank score on every account, which ordinary queries can then filter and sort on.

8. Where Graph Databases Shine

Graph databases earn their place when the value of the data lies in its connections. The most common production uses are:

9. Popular Graph Databases Compared

The market is broad, and products differ more in architecture and query language than in features. The table lists widely used systems in alphabetical order. It describes, it does not rank, and the right choice depends on your workload, scale and existing stack.

SystemData model and designQuery languagesNotable for
Amazon NeptuneManaged property graph and RDFGremlin, openCypher, SPARQLFully managed on AWS, with a separate analytics engine
Apache AGEProperty graph inside PostgreSQLopenCypher within SQLGraph queries next to existing relational tables
ArangoDBMulti-model: documents, key-value and graphsAQLOne engine for document and graph workloads
FalkorDBProperty graph stored as sparse matricesopenCypherLinear-algebra query engine, low-latency GraphRAG use
JanusGraphProperty graph on Cassandra, HBase or ScyllaDBGremlinOpen-source and horizontally scalable
MemgraphIn-memory property graphCypherStreaming data and real-time analytics
NebulaGraphDistributed, shared-nothing property graphnGQL, openCypher subsetVery large graphs spread across many machines
Neo4jNative property graphCypher, aligned with GQLThe most widely used graph database, large ecosystem
TigerGraphNative, distributed, massively parallelGSQLDeep-link analytics on very large graphs

Relational vendors have moved too. Oracle Database, SQL Server and Google Spanner offer graph features, and SQL/PGQ brings property-graph patterns to SQL itself. For many teams the first graph query will run inside a database they already have.

10. Pitfalls and Limits

Graph databases are powerful, but they are not a free upgrade. The common problems are predictable.

Before migrating, benchmark your real queries on realistic data in both engines. Many teams keep their system of record in a relational database and maintain a graph copy for the queries that need it.

11. Graph vs Relational: How to Choose

The two models are complementary. The table summarises the trade-offs.

CriterionRelational databaseGraph database
Data modelTables, rows and foreign keysNodes, relationships and properties
RelationshipsRebuilt with joins at query timeStored as explicit records
SchemaFixed in advance, changed by migrationFlexible, new relationship types at any time
Cost of one hopAn index lookup, about log nFollowing a pointer, independent of database size
Variable-depth queriesRecursive CTEs, verbose and hard to tuneNative patterns such as *1..5
Aggregates and reportsExcellentAdequate
Standards and toolingSQL, mature and universalGQL, Cypher, SPARQL, Gremlin, still maturing
Typical usesTransactions, accounting, reportingFraud, recommendations, networks, knowledge graphs

A graph database is likely to pay off when:

A relational database is usually the better choice when the data is naturally tabular, most queries filter and aggregate rows, relationships are shallow and stable, or strict reporting and tooling requirements favour SQL. Many successful systems use both, with the relational database as the system of record and a graph for the connected questions.

Whichever you choose, the ideas underneath are the same graph theory: adjacency lists, traversals, shortest paths, centrality and communities. Understanding those algorithms is the best preparation for working with connected data in any database.

Interactive visualizers: Bidirectional BFS, Yen's K shortest paths, Transitive closure (Warshall), PageRank, Louvain community detection, Connected components, Node similarity (Jaccard) and Link prediction (Adamic-Adar), each run step by step on a graph you can edit.

Frequently Asked Questions

What is a graph database in simple terms?

A graph database stores data as nodes, such as people, accounts or products, and relationships between them, such as “owns”, “bought” or “is part of”. Relationships are stored as data in their own right, so questions that follow many connections, like “who is connected to this account within three steps?”, are answered by walking the graph rather than by joining tables.

What is the difference between a graph database and a relational database?

A relational database stores data in tables and rebuilds relationships at query time with joins on foreign keys. A graph database stores each relationship as an explicit record that points from one node to another. Relational databases excel at tabular data, aggregation and reporting; graph databases excel at deep, variable-length and highly connected queries.

Is a graph database faster than SQL?

For queries that follow many relationships, especially to a depth that is not known in advance, a graph database is usually faster, because each hop follows a stored reference instead of searching an index or joining whole tables. For filtering, sorting and aggregating large numbers of rows, a relational database is usually as fast or faster. The only reliable answer comes from benchmarking your own queries.

What query language do graph databases use?

Property graph databases mostly use Cypher or the ISO standard GQL, published in 2024, which borrows Cypher’s pattern syntax. RDF triplestores use the W3C standard SPARQL. Apache TinkerPop systems use Gremlin, and some products have their own languages, such as AQL, GSQL and nGQL. SQL/PGQ adds graph pattern matching to SQL itself.

Can PostgreSQL be used as a graph database?

Yes, to a degree. Recursive common table expressions let plain SQL follow relationships of any depth, and the Apache AGE extension adds openCypher queries over graphs stored inside PostgreSQL. This works well for moderate graphs and mixed workloads. For very deep traversals, heavy graph algorithms or very large connected datasets, a dedicated graph database is usually more efficient.

Further Exploration

See Graph Queries Run, Step by Step

Traversals, shortest paths, PageRank and community detection are what graph databases execute under the hood. Watch each of them work on a graph you build yourself.

Open the Visualizer