I am new to Oracle and I want to check if particular primary key value is present or not. If value exists then just update the entire row .If value is not present, then insert new row.
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Code above works on MySql. How to achieve the same in Oracle 10g? Can anyone please help?
Look up the SQL standard MERGE statement, which is supported by (more recent versions of) Oracle. This will work with other DBMS than Oracle too.
Related
I have the following sql code:
UPDATE google_calendar_accounts SET google_refresh_token="d",google_org_token="d" WHERE userID=5;
IF ROW_COUNT()=0 THEN
INSERT INTO google_calendar_accounts (userID,google_refresh_token,google_org_token) VALUES (5,"d","d"); END IF
and I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
I am using mariadb 10.1.14
In spite the comment suggesting to do INSERT ... ON DUPLICATE KEY UPDATE ..., There may be a reason to do the update first, and insert just if there was no row affected, like the OP tried: this way auto increment won't be increased in vain.
So, a possible solution to the question may be using insert from select with a condition where row_count()=0
For example:
--first query
UPDATE google_calendar_accounts
SET google_refresh_token='d',google_org_token='d'
WHERE userID=5;
--second query use the affected rows of the previous query
INSERT IGNORE INTO google_calendar_accounts (userID,google_refresh_token,google_org_token)
SELECT 5,'d','d' WHERE ROW_COUNT()=0
BTW: I've added IGNORE to the insert query for a case there was a row match to the update condition but it wasn't updated since all columns was identical to the updated, like in the case before the update there was already row 5,'d','d'.
In such case, if the 5 is primary or unique key the query won't fail.
I want to insert a row if it doesn't already exist. If it does already exist, I want to get it's primary key.
Can this be done without using two queries, for instance using a UNIQUE constraint on the columns and ON CONFLICT ... TELL ME THE CONFLICTING ROWID?
Please note that I don't have experience with SQLite. However, after perusing the online documentation, I don't believe that it supports data-change table references, so no, this isn't possible.
My reccommendation is to write your INSERT in such a way that it won't fail if the row exists - it just won't insert a row. Something like this:
INSERT INTO destinationTable (colA, colB)
(SELECT :colAValue, :colBValue
WHERE NOT EXISTS (SELECT '1'
FROM destinationTable
WHERE uniqueColumn = :uniqueColumn))
This works because the selection won't return a row if it already exists. You can then either look at the return code/state to see if it INSERTed a row, or just SELECT with the unique column, to get the identity column.
DON'T rely on your constraint to catch this. Constraints are to catch application errors, and this is solely a business/implementation detail.
In a word, no. You can't, with SQLite, either INSERT data or, on some condition, SELECT it.
Other SQL engines might allow it, but SQLite can't.
What you can do is INSERT OR IGNORE, which will just not bring up an error. See http://sqlite.org/lang_conflict.html
I have inserted a row with some data in a table where a primary key is present. How would one "SELECT" the primary key of the row one just inserted?
I should have been more specific and mentioned that I'm currently
using SQLite.
For MS SQL Server:
SCOPE_IDENTITY() will return you the last generated identity value within your current scope:
SELECT SCOPE_IDENTITY() AS NewID
For SQL Server 2005 and up, and regardless of what type your primary key is, you could always use the OUTPUT clause to return the values inserted:
INSERT INTO dbo.YourTable(col1, col2, ...., colN)
OUTPUT Inserted.PrimaryKey
VALUES(val1, val2, ....., valN)
SQL Server:
You can use ##IDENTITY. After an insert statement, you can run:
select ##identity
This will give you the primary key of the record you just inserted. If you are planning to use it later, I suggest saving it:
set #MyIdentity = ##identity
If you are using this in a stored procedure and want to access it back in your application, make sure to have nocount off.
For MySQL, use LAST_INSERT_ID()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
You should also be able to start a transaction, insert the row, and select the row using some field that has a unique value that you just inserted, like a timestamp or guid. This should work in pretty much any RDBMS that supports transactions, as long as you have a good unique field to select the row with.
If you need to retrieve the new index in MS SQL when there are triggers on the table then you have to use a little workaround. A simple OUTPUT will not work. You have to do something like this (in VB.NET):
DECLARE #newKeyTbl TABLE (newKey INT);
INSERT INTO myDbName(myFieldName) OUTPUT INSERTED.myKeyName INTO #newKeyTbl VALUES('myValue'); " & _
SELECT newKey FROM #newKeyTbl;"
If using .NET, then the return value from this query can be directly cast to an integer (you have to call "ExecuteScalar" on the .NET SqlCommand to get the return).
For SQLite:
SELECT [Column_1], [Column_2],... [Column_n]
FROM [YourTable]
WHERE rowid = (SELECT last_insert_rowid())
whereas:
Column_1, Column_2,... Column_n: are the primary key of YourTable.
If you'd created YourTable with primary key replaced rowid (i.e. one column pk defined as INTEGER PRIMARY KEY) you just use:
SELECT last_insert_rowid()
Which is a common case.
Finally, this wont work for WITHOUT_ROWID tables.
Please Check:
https://www.sqlite.org/lang_corefunc.html#last_insert_rowid
For PostgreSQL,
INSERT INTO tablename (col1, col2, ...)
VALUES (val1, val2, ...)
RETURNING idcol;
The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed.
https://www.postgresql.org/docs/current/sql-insert.html
For Postgresql:
SELECT CURRVAL(pg_get_serial_sequence('schema.table','id'))
Source: PostgreSQL function for last inserted ID
select MAX(id_column) from table
That, in theory, should return you that last inserted id. If it's a busy database with many inserts going on it may not get the one you just did but another.
Anyhow, an alternative to other methods.
How should my SQL-Statement (MS-SQL) look like if I wan't to insert a row into a table, which contains only one column with the autogenerated id?
Following two queries won't work:
INSERT INTO MyTable (MyTableId) VALUES (Null)
-- or simply
INSERT INTO MyTable
Thx for any tipps.
sl3dg3
INSERT INTO MyTable (MyTableId) VALUES (Null) implicitly tries to insert a null into the identity column, so that won't work as identity columns may never be nullable and without a SET option you cannot insert an arbitrary value anyway, instead you can use:
INSERT INTO MyTable DEFAULT VALUES
For completeness' sake, the SQL standard and most databases support the DEFAULT VALUES clause for this:
INSERT INTO MyTable DEFAULT VALUES;
This is supported in
CUBRID
Firebird
H2
HSQLDB
Ingres
PostgreSQL
SQLite
SQL Server (your database)
Sybase SQL Anywhere
If the above is not supported, you can still write this statement as a workaround:
INSERT INTO MyTable (MyTableId) VALUES (DEFAULT);
This will then also work with:
Access
DB2
MariaDB
MySQL
Oracle
For more details, see this blog post here:
http://blog.jooq.org/2014/01/08/lesser-known-sql-features-default-values/
I want to add a row using SQLs INSERT statement. Is it possible that as part of this statement I can somehow get the value of the column userId which I don't update but is the AUTO_INCREMENT primary key. I need this value to update another table, however I can't follow the Insert statement immediately with a SELECT statement as there is no other unique identifier in the table on which to select.
INSERT INTO objectUrl(disp_name, loggedIn) VALUES('please change this', true)
Is it possible to get the row number (column name userId) and if so how do you do it?
In MySQL it's called LAST_INSERT_ID(). I believe to be technically correct, the two statements should be wrapped in a transaction so that some other INSERT doesn't mess up what ID you get back.
In SQL Sever you have IDENT_CURRENT(‘tablename’) which will only grab it from that table (still need a transaction to be safe). You could also use SCOPE_IDENTITY() which theoretically will always return the one you expect as long as you aren't doing something weird with your connection.
For MySQL you have:
select last_insert_id()