SQL Server graph features

Posted: (EET/GMT+2)

 

SQL Server 2017 introduced native graph features, which are a way to model relationships between entities. You can use it to represent networks, hierarchies, or connections that would otherwise need many joined tables.

To get started, create node and edge tables:

CREATE TABLE Person (
  ID INT PRIMARY KEY,
  Name NVARCHAR(100)
) AS NODE;

CREATE TABLE Friends AS EDGE;

Now you can insert data and connect nodes using edge references:

INSERT INTO Person VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');

INSERT INTO Friends ($from_id, $to_id)
VALUES ((SELECT $node_id FROM Person WHERE ID = 1),
        (SELECT $node_id FROM Person WHERE ID = 2));

To query relationships, use the MATCH syntax:

SELECT p1.Name AS Person, p2.Name AS Friend
FROM Person p1, Friends f, Person p2
WHERE MATCH(p1-(f)->p2);

The result shows "Person: Alice; Friend: Bob". You can chain relationships to traverse deeper levels, and mix graph and relational queries in the same T-SQL statement.

Happy querying!