Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about multiplying columns in SQL

Tags:

sql

database

I was wondering if it was possible to multiply two columns and if so how would this take place

Suppose I have a table

a    b
1    4
2    5
3    6

Could I do something like

SELECT a *b from table

Would this multiply the contents row by row then store it in a new column

Are these result right

4
10
18
like image 787
Steffan Harris Avatar asked Mar 29 '11 01:03

Steffan Harris


People also ask

How do I multiply multiple columns in SQL?

All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query.

How do I find multiple columns in SQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Does SQL do multiplication?

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

How do I create multiple columns in SQL?

You can add multiple columns to an SQL table using the ALTER TABLE syntax. To do so, specify multiple columns to add after the ADD keyword. Separate each column you want to add using a comma.


3 Answers

That query would multiply the values, but it wouldn't "store it in a new column" To store it you would have to issue an update statement.

Assuming you add a new column ("c") to your table you could do:

update table 
  set c = a * b

If all you need is the new column in a result set, without modifying the underlying table you could:

select a, b, (a*b) as c from table
like image 137
NotMe Avatar answered Sep 28 '22 03:09

NotMe


Yes you can perfectly do that.

update

To clarify: The query and output you mentioned in your question are correct.

like image 27
Alp Avatar answered Sep 28 '22 02:09

Alp


Rather than storing a calculated column in a base table, consider a viewed table:

CREATE VIEW MyView
AS
SELECT a, b, 
       a * b AS my_calc
  FROM MyTable;
like image 32
onedaywhen Avatar answered Sep 28 '22 01:09

onedaywhen