I have a table with 2 columns:
CREATE TABLE Numbers(
col1 float,
col2 float
);
INSERT INTO Numbers(col1, col2)
VALUES('0.6', '1.5'),('2.7', '1.8');
How can I create a third column with the sum of col1 and col2?
First, create col3 using the ALTER TABLE command.
Then update it with the sums.
UPDATE numbers SET col3 = col1 + col2;
I would suggest a calculated column - that way if col1 or col2 are updated, col3 will automatically reflect the correct value; storing mutable data is gnerally not a good idea as it easily leads to inconsistencies.
alter table Numbers add column col3 float as (col1 + col2) stored;
Side note - float is rarely the correct choice of data type, probably you should be using a decimal.
Select *, col1 +col2 as col3 from numbers
Related
I have a database table. That table has 4 columns. In 3 columns members(values) want to access the 4th column value.
So here i don't want to write same query for every member. I want to write only single query. So is it possible with single query? If possible how I can know which column has given those result set?
select 4thcolumn from tablename where lstcolumn=?1 or 2ndcolumn=?2 or 3rdcolumn=?3;
Using OR is a solution (but that requires you to repeat the parameter three times):
SELECT col4 FROM mytable col1 =:myvalue OR col2 =:myvalue OR col3 = :myvalue;
One solution to shorten the query (and pass a unique parameter) is to use IN:
SELECT col4 FROM mytable WHERE :myvalue IN (col1, col2, col3)
If you want to know which column matched, then this gets longer. In MySQL you can do:
SELECT
col4,
col1 = :myvalue is_col1,
col2 = :myvalue is_col2,
col3 = :myvalue is_col3
FROM mytable
WHERE :myvalue IN (col1, col2, col3)
This adds three columns in the result set: is_col1, is_col2, is_col3; the column(s) that matched will have value 1, other(s) will show 0.
My database is in MySQL
I have a table, let's say of 4 columns.
I would like to know if it's possible, and how to implement the following: fill the 4th column according to the value of the column 2 and column 3
In Excel I have a formula, let's give an example: if column2 value is set to "grey" and column3 value is set to "car", then column 4 value should be set to "super"
I just say this as an example.
My real formula in Excel looks like this: =IF(K4=4;"Maximal";IF(K4>4;"Maximal";IF(K4=3;"Important";IF(K4>3;"Important";IF(K4=2;"Limited";IF(K4>2;"Limited";IF(K4=1;"Forgettable";IF(K4>1;"Forgettable";"error"))))))))
However I want to do it in SQL.
I was thinking of creating my table until the column 3, set column 4 to NULL or empty, then open a GUI written in Java and maybe there do a piece of code to automatically fill the column 4 according to what is in column 2 and column 3 (these values will be choosable via Choicelist).
But if there is a way to do it directly in SQL, I am interested
Thx a lot in advance for your help.
regards
Yes. you can easily update your NULL-values according to some requirements for the other values in other columns of a particular row with the Update statement
UPDATE <tablename>
SET <column> = 'value'
WHERE <condition>
The only drawback here might be that you have to create an update statement for each of the combinations of your values in column2 and column3. (however, it's not much work for your amount of conditions).
I created an example (demo):
Creating a table in SQL according to your example could look like this,I used a temporary one for the sake of an example:
CREATE GLOBAL TEMPORARY TABLE demoTable (
"Col1" VARCHAR2(50 BYTE) NOT NULL,
"Col2" VARCHAR2(50 BYTE) NOT NULL,
"Col3" VARCHAR2(50 BYTE) NOT NULL,
"Col4" VARCHAR2(50 BYTE) DEFAULT NULL
)
ON COMMIT PRESERVE ROWS
I also inserted some dummy data:
INSERT INTO demoTable VALUES ('Charles', 'grey', 'car', NULL);
INSERT INTO demoTable VALUES ('Alice', 'grey', 'bike', NULL);
INSERT INTO demoTable VALUES ('Bob', 'red', 'car', NULL);
The result:
Now, create the update statements like this, for example:
UPDATE demoTable dt
SET dt."Col4" = 'super'
WHERE dt."Col2" = 'grey' AND dt."Col3" = 'car';
The result
You can try like this;
select * from mytable
COL1 COL2
---- --------------------
0 -
1 -
2 -
3 -
4 -
4 record(s) selected.
update mytable Set Col2 =
Case
When Col1<1 Then 'error'
When Col1=1 Then 'Forget'
When Col1=2 Then 'Limited'
When Col1=3 Then 'Important'
When Col1=4 Then 'Maximal'
End"
select * from mytable"
COL1 COL2
---- --------------------
0 Error
1 Forget
2 Limited
3 Important
4 Maximal
4 record(s) selected.
You can create a sql function, lets say udfGetColumn4Value taking in the column2, column3 as parameters to it and return a value.
Now you can run a select column2, column3, udfGetColumn4Value(column2, column3) from table or a query as desired. Hope this helps.
You were not very precise regarding which DBMS you're using. And also about the exact logic behind using your two columns.
Still here comes a probable SQL-Server solution, where I have taken one statement using CASE WHEN with your example and concatenated your two columns col2 and col3 (you can apply your further logic of here) otherwise:
UPDATE TableName
SET Col4 = CASE WHEN col2 = 'red' AND col3 = 'car' THEN 'super' ELSE col2 + col3 END;
You should replace col2 + col3 with your further logic.
Seems that a simple UPDATE-Query could address your problem:
update things set result = "super" where thing = "car" and color = "grey";
The where-clause does what you desire to do by saying
fill the column 4 according to what is in column 2 and column 3
I created a test table here on turorialspoint, there you can check if it fits your needs.
I have several columns in a MySQL database that I would like to add and store in another column:
column1 column2 column3 subtotal
10 10 10 30
Is there a way to accomplish this?
update yourtable set subtotal = col1 + col2 + col3
If you simply update subtotal, you have to maintain its value - ie every time one of the other columns is updated, your code has to remember to update subtotal too.
There are two ways to address this issue:
Create a trigger that fires when the row is updated. This option requires database "kung fu" and isn't immediately obvious to anyone else looking at the table the the trigger exists
Create a VIEW that does the calculation
I think option 2 is the best approach.
Here's how you code a view.
create view mytable_totalled as
select col1, col2, col3, col1 + col2 + col3 as subtotal
from mytable
Once created, the view can be used just like a table (with a few caveats), but you can certainly do any kind of select on it. The new column is calculated on the fly when selected
How about this?
UPDATE tableName SET subtotal = (column1 + column2 + column3)
Update 1
If you really don't need subtotal column in table just use query as
SELECT *, (column1 + column2 + column3) as subtotal
FROM tableName
Demo
Well if this is just a one time deal you could do an update query like so:
UPDATE MyTable set subtotal = (column1 + column2 + column3)
If you want it to be calculated on insert, you could have a calculated column.
I would personally just wait until you need it to calculate it so that information that could easily be derived from your data isn't bloating your DB.
I want to know if this is possible without a procedure or server side calls into the database.
I am trying to insert values into a table based on a select, and other values that will be provided from the server.
The select statement will return more than one result.
I am aware of the existence of INSERT SELECT, but is there any SELECT INSERT ? or a way to insert based on the results of a select ?
thank you
Not really sure what seems to be the problem.
You can do like this:
INSERT INTO table (columns)
SELECT
column or column expression1,
column or column expression2,
…
constant or constant expression1,
constant or constant expression2,
…
FROM a set of tables/joins
WHERE …
Not necessarily in that order (columns, then constants), no. You can mix columns with constants any way you like, just follow the order of the columns you are inserting into.
Was that what you were asking about?
I don't see why an
INSERT INTO yourtable(col1, col2, col3)
SELECT col1, col2, col3
FROM yourothertable
doesn't work for you. But you could always do a SELECT INTO #temptable to save your query in a temporary table and then you could INSERT that data or manipulate it prior to inserting. This is just a long way around the original idea, though.
Am I misunderstanding your questions?
Yes. Use this query:
INSERT INTO FOO (oof, rab) SELECT (foo, bar) FROM BAR;
I think you can do this:
INSERT INTO targetTable (col1, col2, col3)
SELECT col1, col2, col3 FROM sourceTable
UNION ALL
SELECT 'something' AS col1, 'something else' AS col2, 'yet something else' AS col3 FROM DUAL;
I have two scenarios represented below, SCENARIO 1 works as well as SCENARIO 2 but are both those SCENARIOS achieving the Same Objective, Note in both Scenario's otherTbl is static
SCENARIO 1
CREATE TABLE `tbl`(
col1 VARCHAR(255),
PRIMARY KEY(col1)
) ENGINE='InnoDb';
Here is my set of queries that I run previously that make sense and run fine.
#Create an exact copy of the `tbl`
CREATE TEMPORARY TABLE `tmp_tbl`( .. SAME AS `tbl` .. );
#Add grouped records from another table into `tmp_table`
INSERT INTO tmp_tbl SELECT col1 FROM otherTbl GROUP BY col1;
#Delete the tables that donot exist any more int the `otherTbl`
DELETE FROM tbl WHERE tbl.col1 NOT IN (SELECT col1 FROM tmp_tbl);
SCENARIO 2
In this scenario the difference is only of the columns, As you can see all of them are primary Keys
CREATE TABLE `tbl`(
col1 VARCHAR(255),
col2 VARCHAR(255),
col3 VARCHAR(255),
PRIMARY KEY(col1, col2, col3)
) ENGINE='InnoDb';
Here are the new set of Queries
#Create an exact copy of the `tbl`
CREATE TEMPORARY TABLE `tmp_tbl`( .. SAME AS `tbl` .. );
#Add grouped records from another table into `tmp_table`
INSERT INTO tmp_tbl
SELECT col1, col2, col3 FROM otherTbl GROUP BY col1, col2, col3;
#Delete the tables that donot exist any more int the `otherTbl`
DELETE FROM tbl WHERE NOT EXISTS(SELECT col1, col2, col3 FROM `tmp_tbl`);
The question simply is, Do they achieve the same conclusion HENCE if we replace the delete query from NOT IN to NOT EXISTS in SCENARIO 1 it will still work the same way.
******SIMPLE VERSION******
Is:
DELETE FROM `tbl` WHERE tbl.col1 NOT IN (SELECT col1 FROM tmp_tbl);
Equall To:
DELETE FROM `tbl` WHERE NOT EXISTS(SELECT col1 FROM `tmp_tbl`);
I haven't tested it, but they are most likely not equivalent. The NOT EXISTS form would make sense if used with a correlated subquery. But your subquery doesn't contain any reference to the outer query, so probably the second form won't delete any rows at all.
Also, presence of NULLs in the table may make these two forms act very differently.
These two queries should, to my knowledge, achieve the same results (since the query checks for the same data - only the second one does it in a more elegant manner maybe).