0

I want to store a table for variables with table definition like below

variable
--------
id           int
var_type     int  0: number, 1: string, 2: json
var_name     int
var_value    ??? varchar or jsonb?

If I use varchar, how to store the json type variable and if, I am using jsonb how to store the int and string?

The example json value that is stored,

[{"name": "Andy", "email" : "[email protected]"},{"name": "Cindy", "email" : "[email protected]"}]

TIA

Beny

2
  • 1
    Variable types aren't really a thing relational schemas are good at. Try to avoid it if possible. Why not simply having a name and an email column with appropriate types each? Commented Feb 7, 2021 at 5:26
  • the idea is to have a variable that can be number, string or json (array). the example of name and email aboce is just an example. it can be anything, [{'first_name' : 'Andy', 'last_name' : 'Robertson'}, {'first_name' : 'Cindy', 'last_name' : 'McGill'}]. Commented Feb 7, 2021 at 7:08

1 Answer 1

1

When you have data and you don't know the structure, use a single jsonb column. JSON can handle strings, numbers, and more JSON.

{
  "string": "basset hounds got long ears",
  "number": 23.42,
  "json": [1,2,3,4,5]
}

Don't try to cram them all into a single array. Put them in separate rows.

However, your example feels like its avoiding designing a schema. JSONB is useful, but overusing it defeats the point of a relational database.

create table people (
  id bigserial primary key,

  // Columns for known keys which can have constraints.
  name text not null,
  email text not null,

  // JSONB for extra keys you can't predict.
  data jsonb
)

Use the JSON operators to query individual pairs.

select
  name, email, data->>'favorite dog breed'
from some_table
Sign up to request clarification or add additional context in comments.

5 Comments

thank you for your explanation. The thing is that name and email are there not because they are permanently there. Another JSON type variable is [{'first_name' : 'Andy', 'last_name' : 'Robertson'}, {'first_name' : 'Cindy', 'last_name' : 'McGill'}].
if I stored as varchar, How can I cast this varchar to this json where var_type is json?
@BenySetiawan Don't store it as varchar, use a single jsonb column for everything.
@BenySetiawan Here's an example. Again, I advise you consider a more traditional table structure before slapping everything into jsonb.
Thanks a lot @Schwern. I follow your suggestion that I move the important thing to a field and only leave unstructured fields in the jsonb field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.