Search code examples
sqlalter

Why isn't ALTER TABLE (adding a column) working in this SQL code?


Suppose I have a table (called numbers) like this

A B
1 3
4 4
5 5

I want to create a new column, C, which consists of values A / B. I.e. something that looks like:

A B C
1 3 0.33
4 4 1
5 5 1

I try this code but it doesn't work. Does anyone know why?

ALTER TABLE numbers ADD C VARCHAR(50) NOT NULL INSERT INTO numbers (C) VALUES (A / B)


Solution

  • It sounds like you want a generated column. The syntax varies, depending on the database, but it is often something like this:

    ALTER TABLE numbers ADD C VARCHAR(50) GENERATED ALWAYS AS (A / B);
    

    Why you are doing an arithmetic operation and then storing the value as a string is a mystery to me, but it is allowed.

    Here is a db<>fiddle, which happens to use MySQL.