Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply every entry in column by a fixed number in SQL

Tags:

sql

In SQL, say I have a table of the following layout:

id    name      age
1     george    12
2     tom       14
3     charles   19
4     henry     21
5     fiona     12
6     kate      14
...

If I discover that I've made a terrible inputting mistake, and that everybody is actually twice their age, is there a way to multiply the age column by 2 in one sweep instead of needing to painstakingly go through the whole column and edit each age individually (pretend I have 500 entries so manual work is out of the question).

Is there a SQL solution?

like image 404
dplanet Avatar asked Aug 18 '12 23:08

dplanet


People also ask

How do I multiply all values in a column in SQL?

We are interested in x = a*b . Then, applying some math, we have: x = a * b -> log(x) = log(a * b) -> log(x) = log(a) + log(b) -> exp[log(x)] = exp[log(a) + log(b)] -> x = exp[log(a) + log(b)].

How do you multiply a number in SQL?

The SQL multiply ( * ) operator is used to multiply two or more expressions or numbers.

Is there a product function in SQL?

There is no PRODUCT set function in the SQL Standard. It would appear to be a worthy candidate, though (unlike, say, a CONCATENATE set function: it's not a good fit for SQL e.g. the resulting data type would involve multivalues and pose a problem as regards first normal form).

How do you multiply columns?

To multiply more than two columns in Excel, you can use the multiplication formulas similar to the ones discussed above, but include several cells or ranges. For example, to multiply values in columns B, C and D, use one of the following formulas: Multiplication operator: =A2*B2*C2. PRODUCT function: =PRODUCT(A2:C2)


2 Answers

It's really easy:

UPDATE table SET age=age*2
like image 169
mimicocotopus Avatar answered Oct 17 '22 23:10

mimicocotopus


Yes, run an update:

update theTable set age = age * 2

Depending on the settings in the database, you might not be allowed to run an update without a where (to protect against mistakes), then you would add a dummy comparison:

update theTable set age = age * 2 where 1 = 1
like image 24
Guffa Avatar answered Oct 18 '22 00:10

Guffa