Return inserted values from 'insert' query - javascript

I have simple table and I need to insert in to it values from array, but only values which are not exists in table and return from query inserted values, how I can do this?
I have next query, but it just inserts values:
INSERT INTO my_table(id, card_id, size)
VALUES ${myArray.map(item => `($${addDbValue(item.id, dbValues)},
$${dbValues.push(item.card_id)}::int, '24')`)}
`, dbValues)
unique is card_id

You seem to want on conflict and returning:
insert into my_table(id, card_id, size)
values (?, ?, ?)
on conflict (card_id) do nothing
returning *
The query inserts the new row, and returns the entire row (including columns that were not initially given for insert). If a row already exists with the same card_id, the insert is not performed (for this to work, you need a unique index or constraint on card_id).
Note that you should be using query parameters (as shown above) rather than concatenating variables in the query string. Have a look at the parameterized query feature of your client.

Related

How to Check if value exists in sql column?

I want Chack If Value exists in coulmn, If value exist do not insert to table.
If not exist insert to table a new data.
I tried this but not works..
my code in node.js
`
//add new meeting
async function addNewMeeting(meeting: Meeting): Promise<Meeting>{
const sql = `INSERT INTO meetings Values (
DEFAULT,
${meeting.meeting_code},
'${meeting.meeting_start_date}',
'${meeting.meeting_end_date}',
'${meeting.meeting_description}',
'${meeting.meeting_room}'
)`;
const result:OkPacket = await dal.execute(sql);
meeting.id = result.insertId;
return meeting;
}
`
I tried to chack if the value - '2022-10-15 07:03:42' exist or not.
If not exists insert to table a new data.
if exist send a error that cannot insert a new meeting because there is already meeting at this time.
thanks :)
You can solve this at the SQL level by using the keyword UNIQUE when defining that column in the table. This will prevent you from being able to insert duplicate values.
SQL UNIQUE
Note that this will throw an error and depending on the package you are using to connect to your database, you might need some error handling.
Alternatively in your javascript you can select all values in the column that should be unique, and then only proceed with the insertion code if there is not a match.

How to dynamically select columns from a given table in snowflake stored procedure?

I am trying to create a procedure that choose columns dynamically from two table. I have already hardcoded query which works fine.
#Existing query
create table mydb.result_table as
select
t1.id,
t1.name,
t1.place,
t1.product
t1.prize
t2.id,
t2.name,
t2.place,
t2.product,
t2.prize
from source_db.source_table t1
full outer join target_db_target_table t2 on
t1.id=t2.id and t1.name=t2.name
where t1.place<>t2.place
Now i need to create a procedure which basically select column dynamically from given table name and join both with given keys
so something like below
CREATE OR REPLACE PROCEDURE result(source_db varchar, source_table VARCHAR, targt_db varchar, target_table VARCHAR, key_join varchar<not sure can pass list>, filter_col varchar )
returns string not null
language javascript
as
$$
var query= `create table mydb.result_table as
select
t1.<all columns from source_db and source_table>
t2.<all columns from targt_db and target_table >
from <source_db and source_table> as t1
full outer join <target_db_target_table> as t2
on <key_join> where <t1.filter_col <> t2.filter_col>
`
return 'success';
$$;
i don't see example of selecting columns dynamically for this kind of use case.
Any solution to this?
You need to query the information schema for the list of columns in each table and use the result to dynamically build your SQL statement.
You also need to be aware of the same column name existing in multiple tables as you obviously can’t have the same column appearing multiple times in a table - so you’ll need to dynamically rename columns as appropriate
Just query the INFORMATION_SCHEMA.COLUMNS view to access the table's columns and then you can build your query dynamically:
https://docs.snowflake.com/en/sql-reference/info-schema/columns.html

How to conditionally insert into mariadb based on if the entry already exists

I have the following:
Table with ID, title, userid
At the moment I have logic that when a certain media is viewed it is entered into the database in order to store view history.
Now, I am trying to prevent duplicate entries from being inserted. This is the code that I have tried and it is still duplicating entries.
dataAccessor.viewers = {
add: ({ courseId, viewerOid }) => {
const query =
"IF NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?) INSERT INTO course_video_viewers (course_id, azure_oid) VALUES (?, ?)";
const inputs = [courseId, viewerOid];
return sendQueryAndReturnResultsAsPromise(query, inputs);
}
};
Looks like you should have a unique index on course_id,azure_oid That would prevent duplicates from being inserted. Then you can run insert ignore into course_video_viewers... and it will internally drop the record if it exists and reinsert it.
The best thing to do is to add a unique constraint in the table for the combination of the columns course_id and azure_oid:
ALTER TABLE course_video_viewers
ADD CONSTRAINT un_con_video_view
UNIQUE (course_id, azure_oid);
If you can't alter the table's definition you can use a INSERT ... SELECT statement:
INSERT INTO course_video_viewers (course_id, azure_oid)
SELECT ?, ?
FROM dual
WHERE NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?)
You may omit FROM dual if your version of MySql is 5.7+.

How can I INSERT new values and values from an already existing table?

I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.
The INSERT INTO statement works like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
While the INSERT INTO SELECT works like this:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
What I'm trying to do is add new values while also adding values that I already have stored in another table.
con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")
From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten.
How can I do this? Add a VALUES statement before SELECT?
I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.
What I want to replace:
vehicleType -> "players"
vehicleModel -> vehicleCreate.model
vehicleOwner -> playerID FROM players table
vehicleSpawnX -> pos.x
vehicleSpawnY -> pos.y
vehicleSpawnZ -> pos.z
Thanks!
It's not possible... But you can select data and store that on variables, then you will store it in another table
You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.
So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:
insert into pairs (playerId1, playerId2)
select p1.playerId, p2.playerId
from players p1 join
players p2
on p1.name = ? and p2.name = ?;
The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.

is - select * from empty table possible?

On my website I am trying to select 2 tables - tableB of which might be empty, so its not returning any results at all when tableB is empty. I hope I am explaining this properly. Any suggestions?
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA, tableB", [], renderFunc,
curatio.webdb.onError);
});
}
basically TableA has e.g. Name and Surname columns and TableB has e.g. Address details. But sometimes there is no address, and then I cannot get anything to display.
I need to basically ignore tableB if it's empty.
If tableA and tableB have the same schema, you can do something like this:
SELECT * FROM tableA
UNION
SELECT * FROM tableB
However, if they don't have the same schema, you will have to do something smarter to get the union to work.
Although your query doesn't hint at this, I still think you are probably looking for a LEFT JOIN, because I'm assuming you want to link data from two tables by a common value in a column from table B (known as the foreign key).
This query selects values of the first table, even when there's no matching data in the join table:
SELECT *
FROM `tableA` `a`
LEFT JOIN `tableB` `b`
ON `b`.`someReferenceColumnToTableA` = `a`.`theReferredColumn`
Again, this assumes you meant to join two tables by some common value, for instance:
person (table A):
- id
- name
phonenumber (table B):
- id
- person_id // this is the foreign key to table A that "links" the data
- phonenumber
If you were to use a regular JOIN (also known as INNER JOIN) then only rows are returned for when both tables have matching data.
What your original query did, however, was (implicitly) CROSS JOIN all data from both tables. Given your question edit, I hardly think this is what you were actually after.
What you are performing there is called a Cross-Product of those two tables. A cross-product is essentially every row of tableA with every row of tableB. Since tableB has no rows, the cross-product has no rows. If you want all rows of both tables, use 2 queries. I would recommend reading a basic SQL tutorial.
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA UNION ALL SELECT * FROM tableB", [], renderFunc,
curatio.webdb.onError);
});
}
It will best to explicitly use the column names in both select rather then using the *.

Categories