Monday, 15 March 2010

sql - Set value of column based on another column in Postgres? -


I am working with Postgear 9.1 and I have added a new Boolean column to my table:

  ALTER TABLE frontend_item ADD COLUMN is_generic BOOLEAN;  

The value of this column will be based on the value of the second column, code . If there are 10-11 characters aa of code , the value of is_generic should be TRUE . Otherwise it should be incorrect (or empty, if it has not yet been set).

My question is, how can I do this in postgres? I am able to work on some individual components using Docs:

  UPDATE frontend_item SET is_generic ...  

And then I know that I The substrings of code can be found as follows:

  substrings (code from 2 to 10)  

But how can I The substrings can turn on a boolean, and then UPDATE statement

  UPDATE frontend_item SET is_generic = (substring (code from 2 to 10) = 'AA');  

But do you really need unnecessary columns? You can just keep using the expression substrings (code 10 to 2) , which is more reliable in the face of possible updates in the table. The cost for the function is low and keeping the table short is a benefit for overall performance.

Unnecessary storage is rarely a good idea only for special adaptation.

BTW, a low verbose postgate variant is similar:

  substr (code, 10, 2)  


No comments:

Post a Comment