INSERT + SELECT data type mismatch on similar fields - sql

I'm running the following SQLite workaround to add a primary key to a table that did not have one. I am getting a datatype mismatch on
INSERT INTO cities
SELECT id, name FROM old_cities;
However, the fields have exactly the same type. Is it possible that his happens due to running the queries from DbBrowser for SQLite?
CREATE table cities (
id INTEGER NOT NULL,
name TEXT NOT NULL
);
INSERT INTO cities (id, name)
VALUES ('pan', 'doul');
END TRANSACTION;
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE cities RENAME TO old_cities;
--CREATE TABLE cities (
-- id INTEGER NOT NULL PRIMARY KEY,
-- name TEXT NOT NULL
--);
CREATE TABLE cities (
id INTEGER NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (id)
);
SELECT * FROM old_cities;
INSERT INTO cities
SELECT id, name FROM old_cities;
DROP TABLE old_cities;
COMMIT;

You have defined the column id of the table cities to be INTEGER, but with this:
INSERT INTO cities (id, name) VALUES ('pan', 'doul');
you insert the string 'pan' as id.
SQLite does not do any type checking in this case and allows it.
Did you mean to insert 2 rows each having the names 'pan' and 'doul'?
If so, you should do something like:
INSERT INTO cities (id, name) VALUES (1, 'pan'), (2, 'doul');
Later you rename the table cities to old_cities and you recreate cities but you do something different: you define id as INTEGER and PRIMARY KEY.
This definition is the only one that forces type checking in SQLite.
So, when you try to insert the rows from old_cities to cities you get an error because 'pan' is not allowed in the column id as it is defined now.

Related

Is it possible to store a query in a variable and use that variable in Insert query? "#countrid =SELECT id FROM COUNTRIES WHERE description = 'asdf';"

So I've been going through SQL migrations to insert data in a SEQUENTIAL manner specifically from parent to child.
I've inserted data in the parent table. Now I've to store the primary key value of that
specific row (WHERE condition is defined in query for reference " where description = '1234'") in a variable.
And while inserting data to the child table I've to use that primary key value stored in a variable in place of a foreign key column("country_code_id") of the child table.
I'm using Postgresql
CREATE TABLE Countries
(
id SERIAL,
description VARCHAR(100),
CONSTRAINT coutry_pkey PRIMARY KEY (id)
);
CREATE TABLE Cities
(
country_code_id int ,
city_id int,
description VARCHAR(100),
CONSTRAINT cities_pkey PRIMARY KEY (city_id),
CONSTRAINT fk_cities_countries FOREIGN KEY (country_code_id) REFERENCES Countries (id)
);
INSERT INTO COUNTRIES (description) VALUES('asdf');
#countrid = SELECT id FROM COUNTRIES WHERE description = 'asdf';
INSERT INTO cities VALUES (countrid, 1 , 'abc');
SQL does not have variables. The normal way to do this is to use INSERT ... RETURNING:
INSERT INTO countries (description) VALUES ('1234')
RETURNING id;
This will return the automatically generated primary key. You store that in a variable on the client side and run a second statement:
INSERT INTO cities (country_code_id, city_id, description)
VALUES (4711, 1, 'abc');
where 4711 is the value returned from the first statement. To avoid hard-coding the value, you can use a prepared statement, which also will boost performance.
An alternative, more complicated, solution is to run both statements in a single statement using a common table expression:
WITH country_ids AS (
INSERT INTO countries (description) VALUES ('1234')
RETURNING id
INSERT INTO (country_code_id, city_id, description)
SELECT id, 1, 'abc'
FROM country_ids;

Oracle if value to be inserted in foreign key is -1, insert null instead

I have a xml script I'm reading from to populate my database with data. One of the nodes in the xml file don't have a idDirector field (the nodes are movies) and so the xml reads a -1 as idDirector and then my stored procedure tries to insert -1 into the fk field and this makes my database returna constraint error : director -1 doesn't exist in Director table. How can I make it so it inserts null instead and make my fk field nullable?
CREATE TABLE Film (
PRIMARY KEY (idFilm),
FOREIGN KEY (idDirector) REFERENCES Director
);
Thank you
Looks like CASE to me, e.g.
insert into film (id_film, id_director)
select id_film,
case when id_director = -1 then null
else id_director
end
from ...
Will it work? Yes:
SQL> create table director (id number primary key);
Table created.
SQL> create table film (id number primary key, id_director number references director);
Table created.
SQL> insert into director values (100);
1 row created.
Inserting -1 fails:
SQL> insert into film (id, id_director) values (1, -1);
insert into film (id, id_director) values (1, -1)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0065885) violated - parent key not
found
Inserting NULL works:
SQL> insert into film (id, id_director) values (1, null);
1 row created.
SQL>

How can I insert a row that references another postgres table via foreign key, and creates the foreign row too if it doesn't exist?

In Postgres, is there a way to atomically insert a row into a table, where one column references another table, and we look up to see if the desired row exists in the referenced table and inserts it as well if it is not?
For example, say we have a US states table and a cities table which references the states table:
CREATE TABLE states (
state_id serial primary key,
name text
);
CREATE TABLE cities (
city_id serial,
name text,
state_id int references states(state_id)
);
When I want to add the city of Austin, Texas, I want to be able to see whether Texas exists in the states table, and if so use its state_id in the new row I'm inserting in the cities table. If Texas doesn't exist in the states table, I want to create it and then use its id in the cities table.
I tried this query, but I got an error saying
ERROR: WITH clause containing a data-modifying statement must be at the top level
LINE 2: WITH inserted AS (
^
WITH state_id AS (
WITH inserted AS (
INSERT INTO states(name)
VALUES ('Texas')
ON CONFLICT DO NOTHING
RETURNING state_id),
already_there AS (
SELECT state_id FROM states
WHERE name='Texas')
SELECT * FROM inserted
UNION
SELECT * FROM already_there)
INSERT INTO cities(name, state_id)
VALUES
('Austin', (SELECT state_id FROM state_id));
Am I overlooking a simple solution?
Here is one option:
with inserted as (
insert into states(name) values ('Texas')
on conflict do nothing
returning state_id
)
insert into cities(name, state_id)
values (
'Dallas',
coalesce(
(select state_id from inserted),
(select state_id from states where name = 'Texas')
)
);
The idea is to attempt to insert in a CTE, and then, in the main insert, check if a value was inserted, else select it.
For this to work properly, you need a unique constraint on states(name):
create table states (
state_id serial primary key,
name text unique
);
Demo on DB Fiddlde
You can force the insert statement to return a value:
WITH inserted AS (
INSERT INTO states (name)
VALUES ('Texas')
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.NAME
RETURNING state_id
)
. . .
The DO UPDATE SET forces the INSERT to return something.
I notice that you don't have a unique constraint, so you also need that:
ALTER TABLE states ADD CONSTRAINT unq_state_name
UNIQUE (name);
Otherwise the ON CONFLICT doesn't have anything to work with.

SQL datable query to insert multiple column values

How to add multiple values in a single column of table in SQL? My table looks like this:
Create table emp
(
id number(5),
name varchar(25),
phone varchar(25)
);
Now I want to add values and multiple phones in the phone column. How to do that? I tried using
insert into emp values (id, name, phone)
values (1, lee, (23455, 67543));
but this is not working
Use two insert statements instead
insert into emp values (id, name,phone) values (1,'lee','23455');
insert into emp values (id, name,phone) values (1,'lee','67543');
or If you want to store both the values in single row
insert into emp values (id, name,phone) values (1,'lee','23455,67543');
Here table is not normalised. You either need to store Phone Number info in separate table or use two different column in same table.
Try changing you table design like this.
EMP table
CREATE TABLE emp
(
emp_id INT IDENTITY(1, 1) PRIMARY KEY,
name VARCHAR(25)
);
PhoneNumber Table
CREATE TABLE PhoneNumber
(
phoneno_id INT IDENTITY(1, 1),
emp_id INT,
Phone_Number int,
Cell_Number Int,
FOREIGN KEY (emp_id) REFERENCES emp(emp_id)
)
Note : Auto increment syntax may differ based on the database you are using.
The proper and only real well-designed way to do this in a relational setting is to use a separate table for your phones (this is in SQL Server specific syntax - it might be slightly different, depending on which concrete database system you're using):
Create table emp
(
id INT PRIMARY KEY,
name varchar(25)
)
create table phone
(
phoneId INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
empid INT NOT NULL,
phone varchar(25) NOT NULL,
CONSTRAINT FK_Phone_Emp
FOREIGN KEY(empid) REFERENCES dbo.emp(id)
);
and then you insert the employee data into emp :
insert into emp(id, name)
values (1, lee);
and the phones into phone:
insert into phone(empid, phone) values(1, 23455);
insert into phone(empid, phone) values(1, 67543);
With this setup, you have proper normalization for the database, and you can store as many phones as you like, for each employee.

Storing a database reference within the database

I want to be able to label the database with a single value, i.e its name, from within the database instead of my application, since it will always be one ID per database. For example, something like this:
DATABASE_A.sql
-- Database Name Table
CREATE TABLE database (
name VARCHAR(10) NOT NULL UNIQUE,
);
CREATE TABLE item (
id SERIAL PRIMARY KEY,
name VARCHAR(10) NOT NULL UNIQUE,
);
Insert Into database (name) values ('A');
DATABASE_B.sql
-- Database Name Table
CREATE TABLE database (
name VARCHAR(10) NOT NULL UNIQUE,
);
CREATE TABLE item (
id SERIAL PRIMARY KEY,
name VARCHAR(10) NOT NULL UNIQUE,
);
Insert Into database (name) values ('B');
This is because when they are combined and stored on a SOLR search server their ID is a combination of their database name and their item ID, such as this:
SOLR ITEM ID's
A1
A2
A3
B1
Is it ok to have a single table to define the prefix so that when I do the look up from my SQL website to SOLR I can just do the following query:
database (name) + item (id) = SolrID
I'd be more inclined to build a procedure in each database that contained the database ID, for example:
CREATE OR REPLACE FUNCTION solrid(IN local_id INTEGER, OUT result TEXT) AS $$
DECLARE
database_id TEXT := 'A';
BEGIN
result := database_id || local_id::TEXT;
END;
$$ LANGUAGE PLPGSQL;
Then you could write your select statement like:
SELECT solrid(id), name FROM item;
which seems to be a cleaner solution.