Database design for friends relationships

Ilya Mihaylov 1 Reputation point
2020-08-18T13:06:15.097+00:00

Hallo! Can you help me design database for friends social relations with 1000 requests per second. Bob->Mary John->Bob Serg->Francis Francis->Bob Result: Bob->Francis->Serg Thanks.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,597 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,726 Reputation points
    2020-08-18T15:02:25.077+00:00

    Hi Ilya,

    It is not exactly clear what is your complete scenario.

    Please take a look at the hierarchy data type in MS SQL Server:

    1 person found this answer helpful.
    0 comments No comments

  2. Tom Phillips 17,721 Reputation points
    2020-08-18T18:51:07.967+00:00

    A "person" can have many friends, and the same "person" can be friends to multiple people.

    So you need to have a "person" table and a "relationship" table which links fromPerson -> toPerson.

    0 comments No comments

  3. MelissaMa-MSFT 24,186 Reputation points
    2020-08-19T02:19:22.75+00:00

    Hi IlyaMihaylov,

    SQL Server offers Graph Database capabilities to model many-to-many relationships which is applied to SQL Server 2017 and later.
    Graph processing with SQL Server and Azure SQL Database

    Please refer one example in below link and check whether it is helpful to you:

    DROP TABLE IF EXISTS Person;  
    GO  
    CREATE TABLE Person (  
      ID INT IDENTITY PRIMARY KEY,  
      Name VARCHAR(50) NOT NULL  
    ) AS NODE;  
    INSERT INTO Person (Name) VALUES  
    ('Mary'),  
    ('Bob'),  
    ('John'),  
    ('Francis'),  
    ('Serg')  
      
    DROP TABLE IF EXISTS Friendof;  
    GO  
    CREATE TABLE Friendof AS EDGE;  
    INSERT INTO Friendof ($from_id, $to_id) VALUES (  
      (SELECT $node_id FROM Person WHERE ID = 1),   
      (SELECT $node_id FROM Person WHERE ID = 2));  
    INSERT INTO Friendof ($from_id, $to_id) VALUES (  
      (SELECT $node_id FROM Person WHERE ID = 2),   
      (SELECT $node_id FROM Person WHERE ID = 3));  
    INSERT INTO Friendof ($from_id, $to_id) VALUES (  
      (SELECT $node_id FROM Person WHERE ID = 5),   
      (SELECT $node_id FROM Person WHERE ID = 4));  
    INSERT INTO Friendof ($from_id, $to_id) VALUES (  
      (SELECT $node_id FROM Person WHERE ID = 4),   
      (SELECT $node_id FROM Person WHERE ID = 2));  
    

    18916-select.png

    SHORTEST_PATH (Transact-SQL)

    Please find complete code in attached txt file.
    20058-friend.txt

    If the response helped, do "Accept Answer" and upvote it.

    Best regards
    Melissa

    0 comments No comments