G
G
garasevn2021-02-22 11:09:00
PostgreSQL
garasevn, 2021-02-22 11:09:00

How to design a database with dynamic fields?

I want to implement storage of the user's investment portfolio (A user's portfolio can store a variable number of shares). What would be the right decision? Do I need to use Json files to store this portfolio?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-02-22
@garasevn

Simplified version:

CREATE TABLE users (
  id serial primary key,
  	name varchar(255)
);

INSERT INTO users VALUES (1, 'John'), (2, 'Sarah');

CREATE TABLE shares (
  id varchar(12) primary key,
  	price numeric
);

INSERT INTO shares VALUES ('TSLA', 781.30), ('AAPL', 105.00);

CREATE TABLE user_shares (
  user_id int,
  	share varchar(12),
  	count int
);

INSERT INTO user_shares VALUES (1, 'TSLA', 5), (2, 'AAPL', 1);

SELECT 
  users.*,
  shares.*,
  user_shares.count,
  user_shares.count * shares.price total
FROM user_shares
JOIN users ON user_shares.user_id = users.id
JOIN shares ON user_shares.share = shares.id
;

PostgeSQL fiddle

D
Dr. Bacon, 2021-02-22
@bacon

You need to learn the basics of relational databases, because here you need not "dynamic fields", but a relationship, this is basic knowledge.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question