0

I am trying to alter a table to add an additional column and populate the new column based on another column. For example I have a table that looks like this:

+----+------------+----------+
| id | username   | role     |
+----+------------+----------+
| 1  |    foo     | admin    |
+----+------------+----------+
| 2  |    bar     | operator |
+----+------------+----------+

I want to add a column named tenant and based on the value in role column populate the value inside tenent:

+----+------------+----------+--------------+
| id | username   | role     | permissions  |
+----+------------+----------+--------------+
|  1 |    foo     | admin    |      *       |
+----+------------+----------+--------------+
|  2 |    bar     | operator |   limited    |
+----+------------+----------+--------------+

Is there a MySQL query that can be performed or will I need to create a script to do this?

3
  • 1
    Possibly a generated column would be better for this. Commented Apr 13, 2022 at 10:11
  • Have you looked at the CASE statement? <softwaretestinghelp.com/mysql-case-statement/#MySQL_CASE_Syntax> Commented Apr 13, 2022 at 10:14
  • I want to add a column named tenant - your desired results have a column permissions. What happened to Tenant? Commented Apr 13, 2022 at 10:21

1 Answer 1

2

Consider using a generated column, something like the following. That way, when you update the role, the Permissions will automatically be correct:

alter table MyTable add column Permissions varchar(10) generated always as 
  (case when role='admin' then '*' else 'limited' end);
Sign up to request clarification or add additional context in comments.

Comments

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.