How to skip exception raised in INSERT statement? - sql

When I run the following SQL code:
INSERT INTO table
(column1, column1)
SELECT column1, column2
FROM other_table
WHERE column2 = 'foo'
ON CONFLICT DO NOTHING;
I get
PG::CheckViolation: ERROR:
new row for relation "table" violates
check constraint "tables_column1_valid_first_char"
How can I skip rows violating that check constraint?
I tried
INSERT INTO table
(column1, column1)
SELECT column1, column2
FROM other_table
WHERE column2 = 'foo'
ON CONFLICT ON CONSTRAINT tables_column1_valid_first_char DO NOTHING;
But it fails with
PG::WrongObjectType: ERROR:
constraint in ON CONFLICT clause has no associated index
The constraint looks as following:
ADD CONSTRAINT tables_column1_valid_first_char
CHECK (SUBSTRING(text, 1,1) ~* '^[a-zàâçéèêëîïôûùüÿæœ]');

ON CONFLICT only deals with unique constraints, it doesn't work for check constraints (or foreign key constraints).
You need to exclude those rows by applying a WHERE clause:
INSERT INTO table (column1, column1)
SELECT column1, column2
FROM other_table
WHERE column2 = 'foo'
and SUBSTRING(column1, 1,1) ~* '^[a-zàâçéèêëîïôûùüÿæœ]'
ON CONFLICT DO NOTHING;

Related

update a table with serial primary key and another table with a referencing foreign key (postgres)

I have two tables with a primary key/foreign key relationship
primary key table:
create table table_one (
table_one_id_field serial,
field1 varchar (100) not null,
field2 varchar (100) not null,
constraint pk__table_one primary key (table_one_id_field)
);
create unique index ix_table_one one table_one (field1, field2)
foreign key table
create table table_two (
table_two_id int not null,
table_one_id_field int not null, -- the foreign key
field a int,
field b int,
constraint pk_table_two primary key (table_two_id)
constraint fk_table_two foreign key (table_one_id_field) references table_one (table_one_id_field)
);
I'm not sure what the best way is to update both of these tables. My first thought was to do something like this:
insert into table_one
(field1, field2)
values
('val1', 'val2')
on conflict (field1, field2) do nothing
returning table_one_id_field
and then to use the returned value to update table_two. However, if the conflict does exist, then the id is not returned. My second idea was to run the same query without a returning statement and then to run a select query
insert into table_one
(field1, field2)
values
('val1', 'val2')
on conflict (field1, field2) do nothing;
select table_one_id_field from table_one where field1 = 'val1' and field2 = 'val2'
but I'm not sure if that is the safest way to do it. Is there another best practice way to achieve this?
returning can't give you the id of a row that was not inserted, so selecting again after the insert seems like the relevant approach. You can do both operations at once with common table expressions:
with
params as (values('val1', 'val2')) v(field1, field2),
ins as (
insert into table_one (field1, field2)
select * from params
on conflict (field1, field2) do nothing
)
select t.table_one_id_field
from table_one t
inner join params p
on p.field1 = t.field1 and p.field2 = t.field2

Can you write SQL DELETE code the same as INSERTING a value?

Randomly decided to dive into some SQL reading.
Can I write a DELETE statement just like a INSERT statement?
example
INSERT TABLES table (column1, column2)
VALUES ('cell1', 'cell2);
DELETE FROM table (column1, column2)
WHERE ('value', 'value');
instead of
DELETE FROM table
WHERE column1 = 'value', column2 = 'value';
Neither of those statements is valid. You can write:
DELETE FROM table
WHERE column1 = 'value' and column2 = 'value';
Some databases allow:
DELETE FROM table
WHERE (column1, column2) = ('value', 'value');

Append columns to a table by selecting columns from another table

Alter Table table2 add ( select column1, column2, column3, column4 from table1 );
I need to append columns in an existing table, by selecting the columns of another table.
I get Error! Looking forward for a possible solution
First, to add four new columns to the table use the following syntax:
ALTER TABLE Table2
ADD column1 <datatype> <allow null>,
column2 <datatype> <allow null>,
column3 <datatype> <allow null>,
column4 <datatype> <allow null>
Where <datatype> is the type of data you'll be adding to the column and <allow null> is NULL if you want to allow null values is the column and NOT NULL if you do not want to allow null values in the column.
For example to add four columns of type nchar with a size of 10 that allow null values you would do the following:
ALTER TABLE Table2
ADD column1 [nchar](10) NULL,
column2 [nchar](10) NULL,
column3 [nchar](10) NULL,
column4 [nchar](10) NULL
Next, to insert your data from table1 into this table as brand new record you would use the following sql:
insert into table2 (column1, column2, column3, column4)
select column1, column2, column3, column4
from table1
Note: if any of the original columns in your table are set to NOT NULL and do not have have a default value this will fail and you will have to set values for those columns as well. You would do that by using a command similar to where you set a specific value for the column not allowing NULL values:
insert into table2 ( existingColumn, column1, column2, column3, column4)
select 'value to insert', column1, column2, column3, column4
from table1

INSERT INTO subtract 2 values

Is it possible for an INSERT query to subtract 2 values you have entered to create a 3rd value that can then be inserted into a table - if that makes sense...
e.g.
INSERT INTO table1 (column1, column2, column3)
VALUES ('50', '25', column1 - column2)
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', column1 - column2) from table1 where conditions)
This is a sample query! hope it helps!
Convoluted:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
(select 50 as column1,
25 as column2
) t
Since you can't reference other columns from the same SELECT clause, you have to do it as a subquery. I've also switched to using int literals rather than strings, because I can't make subtraction make sense in my head otherwise.
You could also do it using a Table Value Constructor:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
( VALUES (50, 25)
) AS t (column1, column2);
As indicated in my comment though, if the relationship should always hold, I'd build table1 as:
CREATE TABLE table1 (
column1 int not null,
column2 int not null,
column3 as column1 - column2
--More columns
)
Because that way, the column3 value is always correct.
You can create function that subtracts values and use this function in insert. This is the right way to do such things:
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', your_function() ) from table1 where conditions)
/
Using the "INSERT INTO" would do this:
INSERT INTO Table1Name (column1, column2, column3,)
(select 'X', 'Y', X - Y as Z)
Here is a link to SQL Authority with more examples of INSERT INTO
Another method would to be add a trigger to the table, where on insert of data, the third column would be updated with the difference of the first two columns.

Sql Query Create a new Table

Can anyone offered syntax for a sql query that takes an already created table and inserts some of the data into a new table with a new id(primary key)? So far I tried this
SELECT ((ID INT IDENTITY(1,1) PRIMARY KEY), column1, column2, column3)
INTO table_name
FROM table_name
I keep coming up with a syntax error.
SELECT column1, column2, column3
INTO table_name_new
FROM table_name_old
use like this
INSERT INTO newtable (column1, column2, column3)
SELECT (column1, column2, column3)
FROM table_name
INSERT INTO new_table
(Column1, Column2 . . . )
SELECT Column1, Column2 FROM old_table
Don't include the identity column (the primary key with the auto-generated numbers) in the insert list.
Just make it like below, Aa new id will be automatically created while inserting the record
insert into table1 (col1,col2,col3) select col1,col2,col3 from table2;
According to the documentation on MSDN, the IDENTITY property will transfer through with a SELECT INTO clause, but constraints will not. That means you can create a new table with an IDENTITY column if you include the original IDENTITY column from your source table, but the column in the new table won't be a primary key.
The sane way to do this is to use ALTER TABLE after the table is created, as #Kai has suggested.