Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can I add values into a column conditionally in mysql via a query (heidisql)?

I’m having trouble inserting values conditionally into a column via a query. I am trying to add the following: low, med, high into a new column called income_level which is based on the value in column income. What i wish to query:

INSERT INTO chile

VALUE (‘low_income’ if income < 10000, ‘medium_income’ if income BETWEEN 10000 AND 100000, ‘high_income’ if income >100000)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Current state of the table

ID income
1 7000
2 15000

Wished state of the table

ID Income Income_level
1 7000 low_income
2 15000 medium_income
3 110000 high_income

I have been searching around stackoverflow and searching for an answer but haven’t found a applicable solution that I could’ve used.

>Solution :

I suggest making income_level a generated column, so you don’t have to insert a value. Also you don’t have to worry if you update the income that the income_level becomes out of sync.

ALTER TABLE chile ADD COLUMN income_level VARCHAR(20)
  GENERATED ALWAYS AS (CASE WHEN income < 10000 THEN 'low_income'
                            WHEN income > 100000 THEN 'high_income'
                            ELSE 'medium_income' END);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading