
Table of Contents
- 1. What Is a Graph Database?
- 2. Two Data Models: Property Graphs and RDF
- 3. How Relational Databases Store Relationships
- 4. Inside a Graph Database: Index-Free Adjacency
- 5. Query Languages: Cypher, GQL, SPARQL and Gremlin
- 6. A Worked Example: One Question, Four Languages
- 7. Graph Algorithms Inside the Database
- 8. Where Graph Databases Shine
- 9. Popular Graph Databases Compared
- 10. Pitfalls and Limits
- 11. Graph vs Relational: How to Choose
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:
- Nodes, the entities.
- Labels on nodes, such as
CompanyorProduct, which group nodes into types. A node can have several labels. - Relationships, which always have a start node, an end node, a direction and exactly one type, such as
MAKESorPART_OF. - Properties, key-value pairs stored on nodes and on relationships, such as a company’s name or the quantity of a part in an assembly.
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 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.
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.
- Cypher, created at Neo4j and opened up as openCypher in 2015, uses ASCII-art patterns:
(a)-[:KNOWS]->(b)means a nodeawith aKNOWSrelationship pointing to a nodeb. It is supported by Neo4j, Memgraph, FalkorDB, Amazon Neptune, Apache AGE for PostgreSQL and others. - GQL (ISO/IEC 39075, published in April 2024) is the first new ISO database language since SQL. It standardises property-graph querying and borrows its pattern syntax heavily from Cypher. Its companion, SQL/PGQ (part 16 of SQL:2023), lets a relational database define a property graph over existing tables and query it with the same patterns inside SQL.
- SPARQL is the W3C query language for RDF. Queries are sets of triple patterns, and property paths such as
ex:partOf*express variable-length traversals. - Gremlin, part of Apache TinkerPop, is a traversal language rather than a pattern language: you write the walk step by step, for example
g.V().out('KNOWS'). It runs on JanusGraph, Amazon Neptune, Azure Cosmos DB and other TinkerPop-enabled systems.
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:
- Pathfinding: shortest paths with Dijkstra, A* and Yen’s
kshortest paths, for routing, logistics and “how is X connected to Y?” questions. - Centrality: degree, betweenness and PageRank, for finding influential accounts, critical suppliers or single points of failure.
- Community detection: Louvain, Leiden and label propagation, for customer segments, fraud rings and topic clusters.
- Connectivity: connected components, for entity resolution and for spotting isolated clusters of accounts.
- Similarity and link prediction: Jaccard similarity, node similarity and Adamic-Adar scores, for recommendations and for predicting missing relationships.
- Node embeddings: node2vec, FastRP and graph neural networks, which turn each node into a vector that machine-learning models can use.
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:
- Fraud detection. Fraud rings share phone numbers, devices, addresses and cards across many synthetic identities. Each account looks normal on its own, but in a graph the ring appears as a dense cluster of shared attributes. Banks and payment companies combine real-time pattern queries with community detection and centrality scores.
- Recommendations. “People who bought this also bought” is a two-hop traversal: from a product to its buyers and on to their other purchases. Graphs make it easy to add context such as categories, sessions and social connections.
- Knowledge graphs and AI. Enterprise knowledge graphs connect products, people, documents and policies. They are increasingly used as the memory behind LLM applications, as described in our GraphRAG guide. Many graph databases now store vector embeddings next to the graph, so one query can combine semantic search with traversal.
- Network and IT operations. Data centres, telecom networks and cloud deployments are graphs of devices, services and dependencies. Impact analysis, the question “what breaks if this switch fails?”, is a reachability query.
- Identity and access management. Users belong to groups that hold roles that grant permissions on resources. Answering “can this user reach this file, and through which path?” is a traversal, and so is finding unexpected attack paths, a topic covered in our guide to graph theory in cybersecurity.
- Supply chains and master data. Bills of materials, supplier tiers and ownership structures are deep hierarchies and networks, exactly the shape that recursive SQL handles least gracefully.
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.
| System | Data model and design | Query languages | Notable for |
|---|---|---|---|
| Amazon Neptune | Managed property graph and RDF | Gremlin, openCypher, SPARQL | Fully managed on AWS, with a separate analytics engine |
| Apache AGE | Property graph inside PostgreSQL | openCypher within SQL | Graph queries next to existing relational tables |
| ArangoDB | Multi-model: documents, key-value and graphs | AQL | One engine for document and graph workloads |
| FalkorDB | Property graph stored as sparse matrices | openCypher | Linear-algebra query engine, low-latency GraphRAG use |
| JanusGraph | Property graph on Cassandra, HBase or ScyllaDB | Gremlin | Open-source and horizontally scalable |
| Memgraph | In-memory property graph | Cypher | Streaming data and real-time analytics |
| NebulaGraph | Distributed, shared-nothing property graph | nGQL, openCypher subset | Very large graphs spread across many machines |
| Neo4j | Native property graph | Cypher, aligned with GQL | The most widely used graph database, large ecosystem |
| TigerGraph | Native, distributed, massively parallel | GSQL | Deep-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.
- Supernodes. A node with millions of relationships, such as a country, a popular hashtag or a default “unknown” value, makes every traversal through it explode. Filter by relationship type and direction early, and remodel when one node starts to collect most of the edges.
- Partitioning is hard. Splitting a graph across machines so that few relationships cross between them is the balanced graph partitioning problem, which is NP-hard. Every traversal that crosses a partition costs a network round trip, so distributed graph databases rely on heuristics related to minimum cuts, replication and careful data modelling.
- Aggregations and reports. Summing sales by month across millions of rows is what relational and columnar databases do best. Graph databases can do it, but it is rarely their strength.
- Modelling mistakes. Storing as a property what should be a node (for example a city name repeated on thousands of customers) hides the connections the graph was meant to expose. Storing as a node what is only an attribute adds hops for nothing.
- Skills and tooling. SQL is universal. Cypher, Gremlin and SPARQL are learned skills, and reporting tools, ORMs and data pipelines still assume tables. GQL and SQL/PGQ should narrow this gap over time.
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.
| Criterion | Relational database | Graph database |
|---|---|---|
| Data model | Tables, rows and foreign keys | Nodes, relationships and properties |
| Relationships | Rebuilt with joins at query time | Stored as explicit records |
| Schema | Fixed in advance, changed by migration | Flexible, new relationship types at any time |
| Cost of one hop | An index lookup, about log n | Following a pointer, independent of database size |
| Variable-depth queries | Recursive CTEs, verbose and hard to tune | Native patterns such as *1..5 |
| Aggregates and reports | Excellent | Adequate |
| Standards and tooling | SQL, mature and universal | GQL, Cypher, SPARQL, Gremlin, still maturing |
| Typical uses | Transactions, accounting, reporting | Fraud, recommendations, networks, knowledge graphs |
A graph database is likely to pay off when:
- the important questions follow relationships several steps deep, or to a depth you cannot fix in advance;
- the schema keeps changing because new kinds of relationships keep appearing;
- you need graph algorithms such as PageRank, community detection or shortest paths on live data;
- the answer to a question is a path, and users need to see that path.
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.