SQL Replace String NULL with a NULL Value - tsql

I have a database table that has a string value that literally says "NULL", it's not an actual NULL value, it's literally a string that says "NULL" (without the ").
I want to replace this the string value "NULL" with an actual null value.
This is what I tried to use but it replaces the entire column with NULL values, even when the string value isn't "NULL".
replace([col_1],'NULL',NULL) as [col_1]
Any Suggestions?

NullIf looks suitable:
select Col, NullIf( Col, 'NULL' ) as NullifiedCol
from ( values ( '' ), ( 'Hello' ), ( 'NULL' ), ( 'Mmm, NULLBerries!' ) ) as Ph( Col );
As for the result you are seeing, from replace: "Returns NULL if any one of the arguments is NULL."

Figured out how to do this, instead of using the replace function, I used a case statement.
case
when [col_1] = 'NULL' then NULL
else [col_1]
end as [col_1]

Related

PostgreSQL - Comparison operator with character varying - Exclude values

I want to query a PostgreSQL table with comparison operators. This table have two character varying columns.
Table
CREATE TABLE IF NOT EXISTS test.test
(
scope character varying COLLATE pg_catalog."default",
project_code character varying COLLATE pg_catalog."default"
)
Values
INSERT INTO test.test(scope, project_code) VALUES (NULL, 'AA');
INSERT INTO test.test(scope, project_code) VALUES ('A', 'AA');
When I wan't to query values with a project_code = 'AA' and a scope = 'A', I write:
SELECT * FROM test.test WHERE project_code LIKE 'AA' AND scope LIKE 'A';
It returns me one row, result is ok.
But when I try to query values with a project_code = 'AA' and scope with any other values than 'A', I write:
SELECT * FROM test.test WHERE project_code LIKE 'AA' AND scope NOT LIKE 'A';
It doesn't return me any results. But I have a row who match this. How to explain this and how to write this query ?
I try other comparaison operators <> and !=, same result. I'm using PostgreSQL 13.6.
You need to use a NULL safe comparison operator. The SQL standard defines the is not distinct from operator as the NULL safe version of <> and Postgres supports this:
SELECT *
FROM test.test
WHERE project_code = 'AA'
AND scope IS DISTINCT FROM 'A';
NULL in most operations will return NULL. For example
SELECT NULL LIKE 'A', NULL NOT LIKE 'A'
returns (NULL, NULL). Probably handling the NULL case specifically helps:
SELECT
*
FROM
test.test
WHERE
project_code LIKE 'AA'
AND (scope IS NULL OR scope NOT LIKE 'A')
The solution offered by #a_horse_with_no_name is more elegant; this solution may be interesting when using "wildcards" in the LIKE operator.
select null like 'a' is true; --return false
select null not like 'a' is true; --return false
select null like 'a'; --return null
select null not like 'a' ; --return null
https://www.postgresql.org/docs/current/functions-matching.html.
If pattern does not contain percent signs or underscores, then the
pattern only represents the string itself; in that case LIKE acts like
the equals operator. An underscore (_) in pattern stands for (matches)
any single character; a percent sign (%) matches any sequence of zero
or more characters.

Check if value is not null and not empty in a select query

I have created a function in Postgresql and specified the returned type as TABLE (id uuid, data boolean).
This is the code that I have tried:
BEGIN
RETURN QUERY SELECT table.id, (table.data <> '') as data FROM table;
END
But it will return NULL for "data" when data is NULL in the table. I was expecting it to return FALSE.
Data column is storing a JSON and I am trying to check if the stored value is not null and not empty
How can I make this code work?
Use is distinct from to use a null-safe comparison:
SELECT table.id, table.data is distinct from '' as data
FROM table;
Another option is to treat an empty string like null:
SELECT table.id, nullif(table.data, '') is not null as data
FROM table;

Insert a string into a bytea column

I want to insert text data into a Postgres bytea column using the concat function or the || operator. I am getting an error
column "name" is of type bytea but expression is of type text
create table test(
name bytea
);
insert into test(name) values(concat('abac-' , 'test123'));
insert into test(name) values('aa' || 'bb');
I am executing the insert inside a stored procedure. If want to add the argument like
(concat('abac-' , row.name , 'test123'));
How do I do it?
Perform a type cast after concatenating the values:
INSERT INTO test (name)
VALUES (CAST('abac-' || row.name || 'test123' AS bytea));
Note: The difference between || and concat is how they behave with NULLs.
You need to cast both strings to bytea, for example:
insert into test(name) values('aa'::bytea || 'bb'::bytea);

Declare a column of type 'not-null-string' array in PostgreSQL

Using PostgreSQL 9.6 I can create a column with type 'not-null-array of string' with:
CREATE TABLE example (
foo TEXT[] NOT NULL
);
but this allows the elements to be null, i.e I can do:
INSERT INTO example VALUES('{NULL}')
Is there a way to instead create a column with type 'not-null-array of not-null-string'? I'd like something like this:
CREATE TABLE example (
foo (NOT NULL TEXT)[] NOT NULL
);
but it's not syntactically valid. Is there a valid way to express this?
Simpler since pg 9.5, with the addition of array_position()
CREATE TABLE example (
foo TEXT[] NOT NULL check (array_position(foo, null) is null)
);
You might also want to check for an empty array:
CREATE TABLE example (
foo TEXT[] NOT NULL check (foo <> '{}' and array_position(foo, null) is null)
);
Use the function:
create or replace function are_elements_not_null(arr anyarray)
returns boolean language sql immutable
as $$
select bool_and(elem is not null)
from unnest(arr) as elem
$$;
in a check constraint:
create table example(
foo text[] check(are_elements_not_null(foo))
);
insert into example values
(array[null]);
ERROR: new row for relation "example" violates check constraint "example_foo_check"
DETAIL: Failing row contains ({NULL}).
Note that the column still may be null or may contain an empty array. If you want to exclude these cases expand the definition in the way:
create table example(
foo text[] check(are_elements_not_null(foo) and foo <> '{}') not null
);

Append text to column data in PostgreSQL if columns initial value is null

Append text to column data in PostgreSQL if columns initial value is null.
Its not altering value.
It's pretty unclear what you are trying to achieve, but:
If the column's value is null you can't "append" a value to it because any expression involving null yields null ( null||'foo' is null). In this case you just replace the null value with the new value:
update the_table
set the_column = 'new value'
where the_column is null;
If with "initial value is null" you mean if the "current value is an empty string", then you would do something like this:
update the_table
set the_column = the_column || 'this will be appended'
where the_column = '';
Which is identical to:
update the_table
set the_column = 'this will be appended'
where the_column = '';
null and '' are different things
Another option is to use the concat() function which will implicitly treat null values as empty strings:
update the_table
set the_column = concat(the_column, 'this will be appended')
where ...