Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql insert null value on query

Tags:

In my php code query, i got some error when i will place a null value into the table. The column names "number1","number2", and "number3" are integers and can have a null value.

if there is no null value, the query works

query is like this insert into table(number1,number2,number3) values (1,2,3);

but when I leave a blank value on the input form on the PHP,

for example I will not place value for column "number2", the query will look like this.

insert into table(number1,number2,number3) values (1,,3);

it says ERROR: syntax error at or near "," SQL state: 42601

Does anybody have an idea how to solve this?

this query is likely to be the solution but is there any other way? insert into table(number1,number2,number3) values (1,null,3);

because i got so many variables like that and am a bit lazy to place some conditions like when that variable returns a blank value then value="null"

like image 900
huddreth Avatar asked Mar 20 '15 08:03

huddreth


People also ask

How do you add NULL values?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL); To understand the above syntax, let us first create a table.

How do I INSERT a NULL value in a NOT NULL column?

Code Inspection: Insert NULL into NOT NULL column You cannot insert NULL values in col1 and col2 because they are defined as NOT NULL. If you run the script as is, you will receive an error. To fix this code, replace NULL in the VALUES part with some values (for example, 42 and 'bird' ).

Can we INSERT NULL in integer column in PostgreSQL?

An integer column can be null, but '' is an empty string not null. The right syntax for a null integer (or any other sql type) is null .

How do I use NULL in PostgreSQL?

The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different from a zero value or a field that contains spaces.


1 Answers

You insert NULL value by typing NULL:

INSERT INTO table(number1,number2,number3) VALUES (1,NULL,3); 

If you have a variable and when that variable is empty you want to insert a NULL value you can use NULLIF with the variable enclosed in single quotes to prepare for that (this is somewhat dirty solution as you have to treat the variable as an empty string and then convert it to integer):

INSERT INTO table(number1,number2,number3) VALUES (1,NULLIF('$var','')::integer,3); 
like image 150
Simo Kivistö Avatar answered Sep 28 '22 08:09

Simo Kivistö