INSERT unless date is the same - sql

Is it possible (in Postgres) to do the following 2 INSERTs, or something that's logically equivalent (the proposed INSERTs don't work as they are, but maybe they can be slightly modified?):
CREATE TABLE IF NOT EXISTS table01(
userid int8 NOT NULL,
save date NOT NULL,
followers int4
);
CREATE UNIQUE INDEX ON table01 (userid,save);
INSERT 0:
INSERT INTO table01 (userid,save,followers) VALUES (%s,%s,%s)
ON CONFLICT (userid) DO INSERT INTO table01 (userid,save,followers) VALUES (%s,%s,%s)
WHERE table01.save!=save;
INSERT 1:
INSERT INTO table01 (userid,save,followers) VALUES (%s,%s,%s) WHERE table01.save!=save;
The logic is:
Try to insert a row
If there's a conflict of userid, then insert the row anyway UNLESS the date (save) is the same
Summary:
Are the 2 shown INSERTs (or something equivalent) possible?
Is it possible to do ON CONFLICT DO INSERT (just like one does ON CONFLICT DO UPDATE)?
Is it possible to do INSERT INTO WHERE (just like one does SELECT FROM WHERE)?

A simple insert would seem to do what you want:
INSERT INTO table01 (userid, save, followers)
VALUES (%s, %s, %s);
This will insert a new row unless the userid/save pair is already there. In that case, it would generate an error. If you don't want an error, you can use on conflict do nothing:
INSERT INTO table01 (userid, save, followers)
VALUES (%s, %s, %s)
ON CONFLICT (userid, save) DO NOTHING;

Related

SQL - Inserting into postgresql table produces error on semi-colon

I'm trying to insert some test data into a table to check the functionality of a web servlet, however, using pgAdmin4 to do the insert, I am running into an issue I'm not sure how to rectify. What I want to see is the last value (an image byte stream) is null for this test info. Here is my insert statement:
INSERT INTO schema.tablename("Test Title", "Test Content", "OldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
I get back:
ERROR: syntax error at or near ";"
LINE 1: ...ldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
^
********** Error **********
ERROR: syntax error at or near ";"
SQL state: 42601
Character: 122
I've tried removing the semi-colon just for kicks, and it instead errors on the close parenthesis. Is it an issue related to the null? I tried doing this without putting quotations around the null and I get back the same error but on the null instead of the semi-colon. Any help is appreciated, I am new to DBA/DBD related activities.
Related: Using PostgreSql 9.6
The insert statement usually has first part where you specify into which columns you want to insert and second part where you specify what values you want to insert.
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
You do not need to specify into which columns part only if you supply all values in the second part. If you have a table with seven columns you can omit the first part if in the second part you supply seven values.
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
drop table if exists my_table;
create table my_table (
id int not null,
username varchar(10) not null,
nockname varchar(10),
created timestamptz
);
INSERT INTO my_table (id, username) VALUES (1, 'user01');
You insert into columns id and username. The column created has default value specified so when you do not supply value in insert the default is used instead. Nickname and identification_number can accept null values. When no value is supplied NULL is used.
INSERT INTO my_table VALUES (2, 'user02', NULL, NULL, current_timestamp);
That is the same as the previous but here is omitted the fist part so you must supply values for all columns. If you did not you would get an error.
If you want insert multiple values you can use several statements.
INSERT INTO my_table (id, username, identification_number) VALUES (3, 'user03', 'BD5678');
INSERT INTO my_table (id, username, created) VALUES (4, 'user04', '2016-07-30 09:26:57');
Or you can use the postgres simplification for such inserts.
INSERT INTO my_table (id, username, nickname, identification_number) VALUES
(5, 'user05', 'fifth', 'SX59445'),
(6, 'user06', NULL, NULL),
(7, 'user07', NULL, 'AG1123');
At the beginning I have written that you can omit the first part (where you specify columns) only if you supply values for all columns in the second part. It is not completely true. In special cases when you have table that has nullable columns (columns that can contain NULL value) or you have specified DEFAUL values you can also omit the first part.
create sequence my_seq start 101;
create table my_table2 (
id int not null default nextval('my_seq'),
username varchar(10) not null default 'default',
nickname varchar(10),
identification_number varchar(10),
created timestamptz default current_timestamp
);
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
Result:
101 default NULL NULL 2016-07-30 10:28:27.797+02
102 default NULL NULL 2016-07-30 10:28:27.797+02
103 default NULL NULL 2016-07-30 10:28:27.797+02
When you do not specify values defaults are used or null. In the example above the id column has default value from sequence, username has default string "default", nickname and identification_number are null if not specified and created has default value current timestamp.
More information:
PostgreSQL INSERT

Using ##identity for consecutive inserts

I have this situation,
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT ##identidy
INSERT INTO TABLE2()...
The auto generated primary key has to be a foreign key in TABLE 2. How can I construct my second INSERT to have the value of ##identity?
This doesn't seem to work,
INSERT INTO TABLE1 (user_id, name) (##identity, 'ABC')
I get an error saying Must declare variable '##identidy'.
Cheers!!
1) you spelled ##identity wrong (##identidy)
2) You should create a local variable (#LastIdentity) to store the last inserted identity immediately after the first insert. Then use that variable as the input to the second INSERT:
DECLARE #LastIdentity int
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT #LastIdentity = ##identity
INSERT INTO TABLE2(...) VALUES (#LastIdentity, ...

Simulating UPSERT in presence of UNIQUE constraints

Simulating UPSERT was already discusssed before. In my case though, I have PRIMARY KEY and additional UNIQUE constraint, and I want upsert semantic with respect to primary key - replacing existing row if it exists, while checking the unique constraint.
Here's an attempt using insert-or-replace:
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s),
UNIQUE (name, s));
insert or replace into test values (1, "a", 0);
insert or replace into test values (1, "a", 0);
insert or replace into test values (2, "b", 0);
insert or replace into test values (2, "a", 0);
The last statement is replaces both rows. This is documented behavior of 'insert or replace', but not what I want.
Here is an attempt with "on conflict replace":
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s) on conflict replace,
UNIQUE (name, s));
insert into test values (1, "a", 0);
insert into test values (1, "a", 0);
I get "UNIQUE constraint failed" right away. The problem disappears if don't share column between both primary key and unique constraint:
drop table if exists test;
create table test (id INTEGER, name TEXT,
PRIMARY KEY (id) on conflict replace,
UNIQUE (name));
insert into test values (1, "a");
insert into test values (1, "a");
insert into test values (2, "b");
insert into test values (2, "a");
Here, I get constraint violation on the very last statement, which is precisely right. Sadly, I do need to share a column between constraints.
Is this something I don't understand about SQL, or SQLite issue, and how do I get the desired effect, except for first trying insert and then doing update on failure?
Can you try to apply the ON CONFLICT REPLACE clause to the UNIQUE constraint also?
create table test (id INTEGER, name TEXT,
PRIMARY KEY (id) on conflict replace,
UNIQUE (name) on conflict replace);
SQLite is an embedded database without client/server communication overhead, so it is not necessary to try to do this in a single statement.
To simulate UPSERT, just execute the UPDATE/INSERT statements separately:
c.execute("UPDATE test SET s = ? WHERE id = ? AND name = ?", [0, 1, "a"])
if c.rowcount == 0:
c.execute("INSERT INTO test(s, id, name) VALUES (?, ?, ?)", [0, 1, "a"])
Since SQLite 3.24.0, you can just use UPSERT.

Conditional composite key in MySQL?

So I have this table with a composite key, basically 'userID'-'data' must be unique (see my other question SQL table - semi-unique row?)
However, I was wondering if it was possible to make this only come into effect when userID is not zero? By that I mean, 'userID'-'data' must be unique for non-zero userIDs?
Or am I barking up the wrong tree?
Thanks
Mala
SQL constraints apply to every row in the table. You can't make them conditional based on certain data values.
However, if you could use NULL instead of zero, you can get around the unique constraint. A unique constraint allows multiple entries that have NULL. The reason is that uniqueness means no two equal values can exist. Equality means value1 = value2 must be true. But in SQL, NULL = NULL is unknown, not true.
CREATE TABLE MyTable (id SERIAL PRIMARY KEY, userid INT, data VARCHAR(64));
INSERT INTO MyTable (userid, data) VALUES ( 1, 'foo');
INSERT INTO MyTable (userid, data) VALUES ( 1, 'bar');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');
So far so good, now you might think the following statements would violate the unique constraint, but they don't:
INSERT INTO MyTable (userid, data) VALUES ( 1, 'baz');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'foo');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');

DB2 Temp Tables: Not storing or not retrieving information

I'm an MSSQL guy, but I'm working on a DB2 query that needs to create a temp table, insert into it, and do stuff with it. As a much-shortened test, I'm using the following query, which is providing the same result..
declare global temporary table tt_testingSyntax (id int);
insert into session.tt_testingSyntax (id) values (1);
insert into session.tt_testingSyntax (id) values (2);
insert into session.tt_testingSyntax (id) values (3);
insert into session.tt_testingSyntax (id) values (4);
select * from session.tt_testingSyntax;
Zero rows are returned. Why would that be? I've created the tablespace and verified the table is in scope throughout the query.
Try:
declare global temporary table tt_testingSyntax (id int)
ON COMMIT PRESERVE ROWS NOT LOGGED;
insert into session.tt_testingSyntax (id) values (1);
insert into session.tt_testingSyntax (id) values (2);
insert into session.tt_testingSyntax (id) values (3);
insert into session.tt_testingSyntax (id) values (4);
select * from session.tt_testingSyntax;
There are two options...ON COMMIT DELETE ROWS (the default) or ON COMMIT PRESERVE ROWS.
I ended up unknowingly having access to create my own tables (i.e. for user X, I could create X.temp1). Since this query need only be run once, this works fine. Thanks.