I am trying to run the following insert statement using pgadmin3:
INSERT INTO device
VALUES
(12345,
'asdf',
'OY8YuDFLYdv',
'2',
'myname',
'2013-04-24 11:30:08',
Null,Null)
But I keep getting the following error message:
ERROR: invalid input syntax for integer: "asdf"
LINE 4: 'asdf',
^
********** Error **********
ERROR: invalid input syntax for integer: "asdf"
SQL state: 22P02
Character: 42
Here's the table definition:
CREATE TABLE device
(
device_id integer NOT NULL DEFAULT nextval('device_device_id_seq'::regclass),
userid integer NOT NULL,
description character varying(255),
password character varying(255) NOT NULL,
user_id integer NOT NULL,
createdname character varying(255),
createddatetime timestamp without time zone,
updatedname character varying(255),
updateddatetime timestamp without time zone,
CONSTRAINT device_pkey PRIMARY KEY (device_id )
)
WITH (
OIDS=FALSE
);
ALTER TABLE device
OWNER TO appadmin;
Can you tell me where I'm going wrong? I've tried changing the single quotes to double quotes but that didn't help.
I don't want to have to list all the column names in the INSERT if I dont have to.
Thanks.
Apparently you're expecting the INSERT to skip device_id since it is the primary key and has a default that comes from a sequence. That's not going to happen so PostgreSQL thinks you mean this:
insert into device (device_id, userid, ...)
values (12345, 'asdf', ...);
If you insist on not listing your columns explicitly (and making the people that get to maintain your code suffer needlessly) then you can specify DEFAULT in the VALUES to tell PostgreSQL to use the PK's default value; from the fine manual:
INSERT INTO table_name [ ( column_name [, ...] ) ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
[ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
[...]
DEFAULT
The corresponding column will be filled with its default value.
For example:
INSERT INTO device
VALUES
(DEFAULT,
12345,
'asdf',
...
But really, you should just specify the columns to make the SQL easier to understand and more robust when the schema changes.
Related
I have a table with two columns conversation_id which is a text field and then participants which is a jsonb column. I am trying to insert one dimensional values to the jsonb column using the insert statement like below -
INSERT INTO public.conversations(conversation_id, participants)
VALUES ('123456', '{"14160000000","17780000000"}');
I get an error
Syntax error at or near "{"
Create table script:
create table conversations
(
id uuid not null,
conversation_id text UNIQUE PRIMARY KEY not null,
participants jsonb not null,
created_at timestamp with time zone,
updated_at timestamp with time zone,
avatar_url varchar(500),
last_message varchar(32000)
)
The JSON array is syntactically wrong, it should use brackets:
'["14160000000","17780000000"]'
Table Structure:
Old Table Structure:
New Table Structure:
Query:
INSERT INTO hotel (id, name, hotel_type, active, parent_hotel_id)
SELECT id, name, hotel_type, active, parent_hotel_id
FROM dblink('demopostgres', 'SELECT id, name, hotel_type, active, parent_hotel_id FROM hotel')
AS data(id bigint, name character varying, hotel_type character varying, active boolean, parent_hotel_id bigint);
Following error occurs:
ERROR: null value in column "created_by" violates not-null constraint
DETAIL: Failing row contains (1, Test Hotel, THREE_STAR, t, null,
null, null, null, null, null). SQL state: 23502
I tried to insert other required columns
Note: created_by as Jsonb
created_by = '{
"id": 1,
"email": "tes#localhost",
"login": "test",
"lastName": "Test",
"firstName": "Test",
"displayName": "test"
}'
created_date = '2020-02-22 16:09:08.346'
How can I pass default values for created_by and created_date column while moving data from the old table?
There are several choices.
First the INSERT is failing because the field is NOT NULL. You could ALTER TABLE(https://www.postgresql.org/docs/12/sql-altertable.html)as to unset that for the import, update the fields with values and the reset NOT NULL.
ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL
Two, as #XraySensei said you could add DEFAULT values to the table using ALTER TABLE:
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
action [, ... ]
ALTER [ COLUMN ] column_name SET DEFAULT expression
Third option is to embed the defaults into the query:
create table orig_test(id integer NOT NULL, fld_1 varchar, fld_2 integer NOT NULL);
insert into orig_test(id, fld_1, fld_2) values (1, 'test', 4);
insert into orig_test(id, fld_1, fld_2) values (2, 'test', 7);
insert into default_test (id, fld_1, fld_2) select id, fld_1, fld_2 from orig_test ;
ERROR: null value in column "fld_3" violates not-null constraint
DETAIL: Failing row contains (1, test, 4, null).
insert into default_test (id, fld_1, fld_2, fld_3) select id, fld_1, fld_2, '06/14/2020' AS fld_3 from orig_test ;
INSERT 0 2
insert into hospital_image
select 'HospitalImage',
lo_from_bytea(1,decode('/9j/4AAQSkZJRgABAQEA3ADcAAD','base64')),
'jpg',
'123'
where not exists (select null from pg_largeObject where loid=1);
CREATE TABLE hospital_image (
key character varying(30) NOT NULL,
image oid NOT NULL,
mime_type character varying(30) NOT NULL,
version numeric(8,0) NOT NULL,
CONSTRAINT
pk_hospital_image PRIMARY KEY (key)
) WITH ( OIDS=FALSE );
ALTER TABLE
hospital_image OWNER TO postgres;
Here in the above Statement we are supplying the loid manually as 1. Instead we want to get the loid dynamically using lo_create(0). When I use lo_create(0) as per the Postgres docs, Iget an exception.
I used both lo_creat(-1) and lo_create(0). Both doesn't work. It is saying loid exists already. how to use the above functions in my query.
My SQL statement for including a variable OID is:
INSERT INTO hospital_image (key, image, mime_type, version)
VALUES ('MainLogoImage99999',
lo_from_bytea(lo_create(0),
decode('/9j4AAQSkZJRgABAQEA3ADcAAD',
'base64')),
'jpg',
123);
The error message is:
ERROR: duplicate key value violates unique constraint "pg_largeobject_metadata_oid_index"
SQL state: 23505
Detail: Key (oid)=(34773) already exists.
Both lo_creat(-1) (the argument doesn't matter) and lo_create(0) will create a new large object and return its OID.
lo_create(-1) is the same as lo_create(4294967295) – OIDs are unsigned 4-byte integers.
lo_from_bytea also creates a new large object, so if you pass it the result from lo_create, it complains that it cannot create a large object with the same number again.
Just pass 0 instead of lo_create(0) as the first argument to lo_from_bytea.
I have this postgrse code:
CREATE TABLE IF NOT EXISTS config_change_log
(
id serial primary key,
last_config_version varchar(255) NOT NULL,
is_done Boolean NOT NULL DEFAULT '0',
change_description varchar(255),
timestamp timestamp default current_timestamp
);
INSERT INTO config_change_log(last_config_version, is_done, change_description )
VALUES("5837-2016-08-24_09-12-22", false, "{ 'key':'value'}");
and I get this error:
psql:createConfigChangeLog.sql:11: ERROR: column "5837-2016-08-24_09-12-22" does not exist
LINE 2: VALUES("5837-2016-08-24_09-12-22", false, "{ 'key':'value'}"...
how can it be? it's a value not a column.postgr
Use single quotes for string constants
INSERT INTO config_change_log(last_config_version, is_done, change_description )
VALUES('5837-2016-08-24_09-12-22', false, '{ ''key'':''value''}');
Also you can escape single quotes in data by doubling them
SQL FIDDLE DEMO
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