polvoazul
polvoazul

Reputation: 2528

Can a table have a value associated to IT?

Kind of like a static variable in an analogy to classes.

For example, lets say i have a table for keeping people. Then for each row I have a bunch of columns: age, sex, name... But I would like a value to be associated to the table itself, lets say, minimum allowed age = 18. Then, whenever I would add a new person I would check if their age is bigger than Table.minimum_allowed_age. This way I could easely change that value, without beign hard coded anywhere.

The only way I can do it now is by creating a (very ugly) ENUM column that has only one option, 18, and then every row has it. This is obviously not the way to do it, especially if you want to change that value often (which is my case in my application).

Upvotes: 0

Views: 60

Answers (3)

Dude
Dude

Reputation: 583

Static variables are technically globals. How about using another table to store global properties?

A string for the primary key, another string that is CAST to an integer in a nested query fetching the value would work.

You might as well use an integer value if sufficient or several, differently-typed maybe-NULL columns if you want type safety (you may COALESCE and CAST the result to a string for a fully generic string->string view).

For globals that are associated with tables you could establish an appropriate convention, e.g. prefixing the key with the table name and some separator.

Upvotes: 1

user149341
user149341

Reputation:

Not really. Some database servers let you attach a few bits of metadata to a table (e.g, the AUTO_INCREMENT value in MySQL, or the COMMENT field in various SQL databases), but they are not suitable for general-purpose data storage.

In your case, the value that you're describing (minimum allowed age) isn't a property of the table at all -- it's a property of your application logic. If it's going to be constant over the long term, write it as a constant in your code; if it will be changed more often, create a separate table which stores configuration key/value pairs for the whole application.

Upvotes: 2

vinodhrajagopal
vinodhrajagopal

Reputation: 153

You can try writing insert triggers. Inside the trigger code,you can check if the minimum age is 18 and if not, you can set it to 18.

Upvotes: 0

Related Questions