What is the best SQL query to populate an existing column on table A with a similar column from table B? - sql

Let's say I have an existing table A with a column called contact_name and a ID column id as the primary key.
All the rows in A have the name value as "NULL" right now.
Another table B has different columns, but one of which is contact_name, and another is ref_id.
Each ref_id in B corresponds to a value of id in A, and there may be multiple rows in B that share the same value for ref_id (meaning they all correspond to a single entry in A).
Let me set up an example:
Table A
id | contact_name
1 | [NULL]
2 | [NULL]
Table B
ref_id | contact_name
1 | "John"
2 | "Helen"
2 | "Alex"
Note there are theoretically other values in each table but for the sake of brevity I'm just showing the values I'm interested in using.
I want to populate contact_name in table A with the first entry of the corresponding contact_name in B, where B.(first)ref_id = A.id, without adding any rows or editing the rest of the rows in either table. That is, I want A in my example to now be:
id | contact_name
1 | "John"
2 | "Helen"
Again, note how the first contact_name value, "Helen", in B is selected, not any other subsequent one, like "Alex".

The MERGE function is made for this. Give it a try:
MERGE INTO TABLEA a USING (
SELECT b.REF_ID, b.CONTACT_NAME
FROM TABLEB) b
ON (a.ID = b.REF_ID)
WHEN MATCHED THEN
UPDATE SET
a.CONTACT_NAME = b.CONTACT_NAME
WHERE a.CONTACT_NAME IS null;

You could try using Five, a low-code development environment that lets you manage your MySQL database, and build a web application on top of it.
Whenever You can add a new column in a Table, Five will give you a prompt where you can use a query to populate that particular column.
Here are the steps:
Import your existing MySQL database into Five
Add a new column to your database.
Five will prompt you to fill in values for the new column. Five gives you four options:
A. you can leave the new column empty,
B. assigned a Default value,
C. Copy Values to an existing field
D. Write a custom query.
Refer to This Screenshot to get an idea how things look inside Five
Hope this helps!
Disclaimer: I work for Five

Related

insert and update from table a to table b by combining 2 column from table a in postgres

I have 2 tables name Table A and Table B
"Table A has 10 columns named ta1, ta2, ta3...ta10"
"Table b has 2 columns name id (PK,AI) and tb1"
My requirement is to combine "ta3" and "ta4" from table A initially,
or it will check for the "tb1" column whether any same data is available, if available do nothing else insert the new data.(if a new row is added in the ta3 or ta4, it should be added to the 2nd table column named tb1)
I have checked other functions in the for combining the data from ta3 and ta4 by using the "unnest" function, but if I use that, I'm getting stuck in the insert, as it will insert on each query rather than checking whether any data is there or not.
any solution on this legends.
simply I just want to combine 2 column from 1st table and store it in a column on 2nd table, but in 2nd table's column it should be only distinct values taken from both of those 1st table columns. this should automatically check for the values in the column of 2nd table and compare that with the new one and if there is change the insert else neglect. I hope my question is clear.
Table1
Table 2
new table-1
Expected table-2

Generate new ID for every new combination of column 1 and column 2

I would like to generate a new ID number for every new combination of column 1 and column 2.
For example:
ID | column 1 | column 2
1 | peter | blue
2 | mark | red
1 | peter | blue
As there will be new rows added over time, with new values, this should be able to auto-update.
I tried DENSE_RANK(), which seemed to work. But it gave an error when I put it as a statement in a calculated column, so I guess this is not possible? (Still very new to SQL).
Thanks for any help!
Error message: #1901 - Function or expression 'dense_rank()' cannot be
used in the GENERATED ALWAYS AS clause of `ProductIdentifier
EDIT:
What I basically want is to link a row to another table based on the 2 columns. I could also concatenate the two columns of course, but I read somewhere that doing this with string will be slower. It will ultimately be a big table with currently 200.000+ rows and growing to millions. Is this something I could/should do?
I don't understand. If you want column1/column2 to be unique, then they should be in their own table:
create table t12 (
t12_id int auto_increment primary key,
column1 int,
column2 int,
unique (column1, column2)
);
This gives you the unique value for the pair that you seem to want.
You can't use window functions in a generated column, as you found out. You can, however, compute the information on the fly in a view:
create view myview as
select id, column1, column2, dense_rank() over(order by column1, column2) rn
from mytable
Then you can query the view instead of the table, like:
select * from myview;

Adding column to sqlite database and distribute rows based on primary key

I have some data elements containing a timestamp and information about Item X sales related to this timestamp.
e.g.
timestamp | items X sold
------------------------
1 | 10
4 | 40
7 | 20
I store this data in an SQLite table. Now I want to add to this table. Especially if I get data about another item Y.
The item Y data might or might not have different timestamps but I want to insert this data into the existing table so that it looks like this:
timestamp | items X sold | items Y sold
------------------------------------------
1 | 10 | 5
2 | NULL | 10
4 | 40 | NULL
5 | NULL | 3
7 | 20 | NULL
Later on additional sales data (columns) must be added with the same scheme.
Is there an easy way to accomplish this with SQLite?
In the end I want to fetch data by timestamp and get an overview which items were sold at this time. Most examples consider the usecase to add a complete row (one record) or a complete column if it perfectly matches to the other columns.
Or is sqlite the wrong tool at all? And I should rather use csv or excel?
(Using pythons sqlite3 package to create and manipulate the DB)
Thanks!
Dynamically adding columns is not a good design. You could add them using
ALTER TABLE your_table ADD COLUMN the_column_name TEXT
the column, for existing rows would be populated with nulls, although you could specify a DEFAULT value and the existing rows would then be populated with that value.
e.g. the following demonstrates the above :-
DROP TABLE IF EXISTS soldv1;
CREATE TABLE IF NOT EXISTS soldv1 (timestamp INTEGER PRIAMRY KEY, items_sold_x INTEGER);
INSERT INTO soldv1 VALUES(1,10),(4,40),(7,20);
SELECT * FROM soldv1 ORDER BY timestamp;
ALTER TABLE soldv1 ADD COLUMN items_sold_y INTEGER;
UPDATE soldv1 SET items_sold_y = 5 WHERE timestamp = 1;
INSERT INTO soldv1 VALUES(2,null,10),(5,null,3);
SELECT * FROM soldv1 ORDER BY timestamp;
resulting in the first query returning :-
and the second query returning :-
However, as stated, the above is not considered a good design as the schema is dynamic.
You could alternately manage an equivalent of the above with the addition of either a new column (to also be part of the primary key) or by prefixing/suffixing the timestamp with a type.
Consider, as an example, the following :-
DROP TABLE IF EXISTS soldv2;
CREATE TABLE IF NOT EXISTS soldv2 (type TEXT, timestamp INTEGER, items_sold INTEGER, PRIMARY KEY(timestamp,type));
INSERT INTO soldv2 VALUES('x',1,10),('x',4,40),('x',7,20);
INSERT INTO soldv2 VALUES('y',1,5),('y',2,10),('y',5,3);
INSERT INTO soldv2 VALUES('z',1,15),('z',2,5),('z',9,25);
SELECT * FROM soldv2 ORDER BY timestamp;
This has replicated, data-wise, your original data and additionally added another type (column items_sold_z) without having to change the table's schema (nor having the additional complication of needing to update rather than insert as per when applying timestamp 1 items_sold_y 5).
The result from the query being :-
Or is sqlite the wrong tool at all? And I should rather use csv or excel?
SQLite is a valid tool. What you then do with the data can probably be done as easy as in excel (perhaps simpler) and probably much simpler than trying to process the data in csv format.
For example, say you wanted the total items sold per timestamp and how many types were sold then :-
SELECT timestamp, count(items_sold) AS number_of_item_types_sold, sum(items_sold) AS total_sold FROM soldv2 GROUP by timestamp ORDER BY timestamp;
would result in :-

sql add id column in a table

Hi I have a table with
name
a
b
c
d
need to add a id column starting from mid number and want in sql
name ID
a 10262
b 10623
c 10624
d 10625
You won't be able to add an auto-incrementing Primary Key ID column if there's already data in the table without copying the data, dropping the table and recreating it. However, if there's no data you can just add those columns through SQL's Table Editor. Right click any table in SQL Server and click on "Design"; that will get you to the Table Editor. When you declare any Primary Key you can set it's "seed" value, which is the number that it will initially start with; in your case, your seed would be 10262, based on your original post.

SQL Command to copy data from 1 column in table and 1 column in another table into a new table?

I had to make a new table to get the Include statement working in Entity Framework since EF was looking for a table called be_PostTagbe_Posts. I was using EF Code First from DB. But now the question is about SQL. I added one row of data and now the include works. But what I am looking for is a SQL command that can copy data from 1 column in 1 table and 1 column in another into the new be_PostTagbe_Posts table. In the be_Posts table I need the data in PostRowID to go into be_Posts_PostRowID and PostTagId to go into be_PostTag_PostTagID. Both be_PostTag_PostTagID and be_Posts_PostRowID are in the new be_PostTagbe_Posts table. I am not very good with SQL so not sure how to do this.
Edit: Thanks for the answers. I tried 2 separate queries but only data was inserted into the the be_PostTag_PostTagID while be_PostTag_PostRowID remained null.
And I tried this query which returned The multi-part identifier "be_PostTag.PostID" could not be bound.
INSERT INTO be_PostTagbe_Posts(be_PostTag_PostTagID, be_Posts_PostRowID)
SELECT be_PostTag.PostTagID, be_Posts.PostRowID
WHERE be_PostTag.PostID = be_Posts.PostID
EDIT:
This only inserted half the data - even 2 inserts leave one column null
INSERT INTO be_PostTagbe_Posts (be_Posts_PostRowID)
SELECT PostRowID FROM be_Posts;
INSERT INTO be_PostTagbe_Posts (be_PostTag_PostTagID)
SELECT PostTagID FROM be_PostTag;
And yet management studio tells me the query executed successfully but one column is still null. Weird.
Here are screenshots of the tables:
SELECT PostTagID AS be_PostTag_PostTagID, PostRowID AS be_Posts_PostRowID
INTO be_PostTagbe_Posts
FROM be_PostTag
Inner JOIN be_Posts
ON be_PostTag.PostID=be_Posts.PostID
That command created the new table with the 2 columns populated.
If i understand you ,you want to Copy Table Z's Column A to Table X And Table Z's Column B to Table Y.
If it is so, According to your question it is not clear about Table Structure of TableX and TableY
Assuming TableX And TableY to single ColumnTable [Apart from IdentityColumn] our query will be
INSERT INTO TableX
SELECT ColumnA FROM TableZ
INSERT INTO TableY
SELECT ColumnB FROM TableZ
Rest put your Entire Structure of Table To Get More Help Because These query are on Assumptions
There's not enough information in your question to give you a working example, but this would be the general syntax for INSERTing into a different table using a query SELECTing from two other tables.
INSERT INTO destination_table(wanted_value_1, wanted_value_2)
SELECT table_1.source_field_1, table_2.source_field_1
WHERE table_1.matching_field = table_2.matching_field
There has to be some sort of relationship between the two tables for the WHERE clause to work in that statement. I'm guessing based the little information you provided that there is a PostRowID field somewhere in the table that contains the tags such that your data would look similar to this in the tag table:
PostRowID PostTagID
--------- ---------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
4 4
It sounds like you should use two sql statements:
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`)
select `PostTagID` from POSTTAGIDTABLE
and
Insert into `be_PostTagbe_Posts` (`be_Posts_PostRowID`)
select `PostRowID` from POSTTAGIDTABLE
unless the items have some sort of relationship, then if you have a select statement that will select the merged data in two columns you can just do
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`,`be_Posts_PostRowID`)
(select statement that selects the two items)