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

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

Related

SQL data truncation for date value

I'm having a hard time creating a simple table:
CREATE TABLE `csat` (
`csat_id` INT NOT NULL AUTO_INCREMENT,
`value` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`csat_id`)
);
CREATE TABLE `migrated` (
`migrated_id` INT NOT NULL AUTO_INCREMENT,
`title` INT,
`description` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`migrated_id`)
);
INSERT INTO csat
VALUES (1, 1, 2017-06-15);
INSERT INTO migrated
VALUES (1, 2, 2018-06-15);
I get the error:
Data truncation: Incorrect date value: '1996' for column 'month' at row 1
It seems like my date is in the right format:
https://www.w3schools.com/sql/func_mysql_date.asp
I'm also wondering why I need to specify a value on the csat_id, because I thought SQL would just put that in for me since its the primary key.
You have to wrap your date values in single quotation marks: '2017-06-15', not 2017-06-15. Right now, MySQL is evaluating this as 2017 minus 6 minus 15, which comes to 1996.
Also, when inserting, it's best to specify the columns you're inserting into. And if your column is set to AUTO_INCREMENT, you don't need to specify it:
INSERT INTO csat
(`value`, `month`)
VALUES
(1, '2017-06-15');
I would also consider changing your column names. Perhaps make "value" more descriptive (value of what?) And month is misleading, since it's actually a date-type column.
You haven't said which database server you're using, but generally speaking dates are inputted as strings.
You should try the following inserts;
INSERT INTO csat (`csat_id`, `value`, `month`)
VALUES (1, 1, '2017-06-15');
INSERT INTO migrated (`migrated_id`, `title`, `description`, `month`)
VALUES (1, 2, 2, '2018-06-15');
Also, you should specify which columns you're inserting into. This prevents data from being entered into the wrong fields, especially when schema changes occur.
SQL does auto increment primary key fields (if defined that way). However, you had to define it in your insert statements because you didn't specify the columns you were inserting to.
Try this instead;
INSERT INTO csat (`value`, `month`)
VALUES (1, '2017-06-15');
INSERT INTO migrated (`title`, `description`, `month`)
VALUES (2, 2, '2018-06-15');
I guess you missed the single qoutes (as per Sql standards) at first in your date and then while inserting even if the column is autoincrement you need to specify columns other than the autoincrement column so as to make sure the data you are inserting belongs to that specific column or not
Try this
INSERT INTO
csat(value,month) values
(1,'2017-06-15')

INSERT INTO with default values for a single column

I have a problem to insert the data into 1 table with 1 column
Name: user_id
Column: id
I am trying to add 1 line in this column with this query:
INSERT INTO user_id (id) VALUES ()
The problem is the above is invalid, I want the id take the last value id +1
This is not a syntax problem because this query works:
INSERT INTO user_id (id) VALUES (4)
So, I do not really know how to solve this problem.
Assuming the id column is defined as serial or identity you can specify a column list and set the column value to default:
insert into user_id (id) values (default);
This also works if you have more columns, e.g:
insert into users (id, firstname, lastname)
values (default, 'Arthur', 'Dent');
Or you can leave out the column list completely and request the default value(s) for all columns:
insert into user_id default values;
SQL supports the default values statement.
So this will work:
create table t (id serial primary key);
insert into t
default values;
The syntax is described in the documentation.

Upsert/on conflict with serial primary key

The upsert works using on conflict but the datatype of id is serial meaning I want to have it auto-generated/incremented. If I do the insert without specifying id the insert works fine.
The problem I have is combining the two. To get the key auto incremented I do not pass the id into the insert but if I do not pass id then the update will never fire. I cannot pass null to id as it is non-null field.
In below example - I run the query first time and it does insert and second time it does update but I cannot figure out how to pass 'nothing' to insert so the identity key still works on insert. I can put DEFAULT in the insert but then I cannot pass a real id value if there is one.
CREATE TABLE public.upsert_test
(
id INTEGER NOT NULL DEFAULT nextval('upsert_test_id_seq'::regclass),
name character varying(20) COLLATE pg_catalog."default",
description character varying(20) COLLATE pg_catalog."default",
CONSTRAINT upsert_test_pkey PRIMARY KEY (id)
)
INSERT INTO upsert_test (id, name, description)
VALUES (1, 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = 1;
You can change your query to use sequence functions like:
INSERT INTO upsert_test (id, name, description)
VALUES ((select nextval('upsert_test_id_seq')), 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = (select currval('upsert_test_id_seq'));
Note this may not be threadsafe, for eg if second call to this sql is executed before select currval('upsert_test_id_seq') in first call, then the update may fail in first query.
Update after more information from op
You can change the query to like this:
INSERT INTO upsert_test (id, name, description)
VALUES (COALESCE(:YOUR_ID_PARAM, (select nextval('upsert_test_id_seq'))), 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = :YOUR_ID_PARAM;
Note I added the coalesce function so if your parameter is null then use sequence nextval. Also, the update now also uses your parameter.

NULL constraint after attribute in CREATE TABLE?

I'm new to SQL and I'm trying to figure out what this NULL is doing. Here a simple example:
CREATE TABLE test (
bla VARCHAR NULL
);
So I tried to figure out wether this is set to be the default value, but it is null as default wether I put it there or not, right?
Also I wondered if it has to stay null (for whatever reason) but when I tried to insert a value it was possible anyway. So does it do anything?
From CREATE TABLE:
NULL
The column is allowed to contain null values. This is the default.
You could write:
INSERT INTO test(bla)
VALUES (NULL);
-- it holds NULL
INSERT INTO test(bla)
VALUES (default);
-- it holds NULL
INSERT INTO test(bla)
VALUES ('a');
-- it holds 'a'
You could also omit column:
CREATE TABLE test2(bla VARCHAR NULL, col2 INT NOT NULL);
INSERT INTO test2(col2) VALUES (1);
-- it contains NULL, 1
If you specify column as:
CREATE TABLE test(bla VARCHAR NOT NULL);
INSERT INTO test(bla) VALUES (NULL);
-- error
EDIT:
You don't have to specify NULL explicitly.
CREATE TABLE test(bla VARCHAR);
is the same as:
CREATE TABLE test (bla VARCHAR NULL);
You are parameterizing the column can be NULL

sql not null property error

I have a sql table and here is my column which gives error. When I try to add a new record which has null active_status to this table, It gives "not-null property references a null or transient value" error. Is there any idea?
active_status character varying(30) NOT NULL DEFAULT 'NEW'::character varying,
EDIT: I have created a new simple table;
CREATE TABLE mytable
(
"MyData" character varying(30) NOT NULL DEFAULT 'NEW'::character varying,
CONSTRAINT mytable_pkey PRIMARY KEY ("MyData" )
)
WITH (
OIDS=FALSE
);
ALTER TABLE mytable
OWNER TO postgres;
When I try to insert a string, it runs fine;
insert into mytable values('ssss');
But when I try to insert a null value it gives error;
insert into mytable values(null);
ERROR: null value in column "MyData" violates not-null constraint
SQL state: 23502
With this statement:
insert into mytable values(null);
you explicitely requested to insert a NULL value into the column MyData and therefor you get the error message.
If you want to use the default value, you need to tell the DBMS to do so:
insert into mytable values (default);
Btw: it is much better coding style to always specify the columns in the insert statement:
insert into mytable ("MyData") values (null);
And another thing: you should avoid using quoted identifiers ("MyData" vs. MyData) , they simply are more trouble than it's worth it.
You need to first create the column with NULL constraint. Update all rows for that column with the default values. Alter the column to have Not Null constraint