What is equivalent of isNullOrEmpty in Postgresql select command? - postgresql

select complaintno from complaintprocess where endtime='';
It Is Not Working
In complaintprocess table endtime datatype is timestamp without time zone.
Here I want to get one of the column in complaintprocess where endtime is empty.

You could not store '' as timestamp. I suspect that by blank you mean NULL value.
SELECT CAST('' AS timestamp);
-- ERROR: invalid input syntax for type timestamp: ""
To filter them you could use:
SELECT complaintno
FROM complaintprocess
WHERE endtime IS NULL;

Related

How to query by time in postgresql

device_id
device_created_at
10e7983e-6a7b-443f-b0fe-d5e6485a502c
2022-08-10 20:55:16.695
i have a table where my date/time is of form: 2022-08-10 20:55:16.695 This is a timestampped object. I tried the following query but didn't return any rows:
select * from device where to_char(device_created_at,'YYYY-MM-DD HH24:MI:SS.FFF') = '2022-08-10 20:55:16.695'
The type of device_created_at is "timestamp without time zone"
How do i query based on timestamp in postgressql?
Try comparing timestamp values in place of strings:
SELECT *
FROM device
WHERE device_created_at = CAST('2022-08-10 20:55:16.695' AS TIMESTAMP)
Check the demo here.

SQL Error [22P02]: ERROR: invalid input value for enum tableName.date_unit: ""

I got this error when I try to get the list of all rows on my table. This only happens because I include one of the column in the SELECT. The column itself is an enum column and I wanna use COALESCE for the column in case it meets a null value.
This is a simplication of my code
SELECT id,
user_id,
coalesce(date_unit, '') date_unit
FROM table_name
WHERE user_id = $1
I got this error when I try to run it
SQL Error [22P02]: ERROR: invalid input value for enum table_name.date_unit: ""
This is the error when I run it using SQLX On Golang
Pq: invalid input value for enum table_name.date_unit: \"\"
date_unit itself is an enum which has restricted values. It only accepts day and month as value in the table. But lots of rows have null value in date_unit.
I wanna convert it to "" or empty string if date_unit value is null.
Is there a problem with the COALESCE with enum values? How should I use COALESCE to work with what I wanna do?
The answer is found in the comment section of the question.
To officiate it, as date_unit is not a string type, it cannot be returned when querying (invalid data type). As such, when querying, we should convert date_unit to string type.
This can be done using the query:
SELECT id,
user_id,
COALESCE(date_unit::text, '')
FROM table_name
WHERE user_id = $1
SELECT id,
user_id,
coalesce(date_unit, '')
FROM table_name
WHERE user_id = $1

tsql convert string into date when possible

I've got a column to import into an Azure SQL DB that is supposed to be made of dates only but of course contains errors.
In TSQL I would like to do something like: convert to date if it's possible otherwise null.
Does anyone know a statement to test the convertibility of a string into a date?
use TryCast or Isdate
select
try_Cast('test' as date)
select try_Cast('4' as date)
select case when ISDATE('test')=1 then cast('test' as date) else null end
TryCast will fail if the expression is not in expected format ..ie.,if the explicit conversion of expression is not permitted
select
try_cast( 4 as xml)
select try_Cast(4 as date)
You could use TRY_PARSE:
Returns the result of an expression, translated to the requested data type, or null if the cast fails. Use TRY_PARSE only for converting from string to date/time and number types.
SELECT TRY_PARSE('20129901' AS DATE)
-- NULL
Additionaly you could add culture:
SELECT TRY_PARSE('10/25/2015' AS DATE USING 'en-US')
And importing:
INSERT INTO target_table(date_column, ...)
SELECT TRY_PARSE(date_string_column AS DATE) ...
FROM source_table
...

How to convert a '' to NULL in postgreSQL

I have a postgreSQL table which accepts date in yyyy-mm-dd format and it is not accepting if the incoming date format is ''(no date). There could be some instances when '' gets passed as date. Could anyone help me write a function which checks if the incoming date is '' and then replaces it with NULL and then adds it to the db.
Use nullif()
insert into the_table (the_date_column)
values (nullif(?, ''))
Or for an update
update the_table
set the_date_column = nullif(?, '');
You could use a case expression to check for this. I'm using :arg to represent the inputting string - change it according to the programming language you're using:
INSERT INTO mytable
(my_date_col)
VALUES (CASE LENGTH(:arg) WHEN 0 THEN NULL ELSE TO_DATE(:arg, 'yyyy-mm-dd' END)

Extract year from date within WHERE clause

I need to include EXTRACT() function within WHERE clause as follow:
SELECT * FROM my_table WHERE EXTRACT(YEAR FROM date) = '2014';
I get a message like this:
pg_catalog.date_part(unknown, text) doesn't exist**
SQL State 42883
Here is my_table content (gid INTEGER, date DATE):
gid | date
-------+-------------
1 | 2014-12-12
2 | 2014-12-08
3 | 2013-17-15
I have to do it this way because the query is sent from a form on a website that includes a 'Year' field where users enter the year on a 4-digits basis.
The problem is that your column is of data type text, while EXTRACT() only works for date / time types.
You should convert your column to the appropriate data type.
ALTER TABLE my_table ALTER COLUMN date TYPE date;
That's smaller (4 bytes instead of 11 for the text), faster and cleaner (disallows illegal dates and most typos).
If you have non-standard format add a USING clause with a conversion expression. Example:
Alter character field to date
Also, for your queries to be fast with a plain index on date you should rather use sargable predicates. Like:
SELECT * FROM my_table
WHERE date >= '2014-01-01'
AND date < '2015-01-01';
Or, to go with your 4-digit input for the year:
SELECT * FROM my_table
WHERE date >= to_date('2014', 'YYYY')
AND date < to_date('2015', 'YYYY');
You could also be more explicit:
to_date('2014' || '0101', 'YYYYMMNDD')
Both produce the same date '2014-01-01'.
Aside: date is a reserved word in standard SQL and a basic type name in Postgres. Don't use it as identifier.
This happens because the column has a text or varchar type, as opposed to date or timestamp. This is easily reproducible:
SELECT 1 WHERE extract(year from '2014-01-01'::text)='2014';
yields this error:
ERROR: function pg_catalog.date_part(unknown, text) does not exist
LINE 1: SELECT 1 WHERE extract(year from '2014-01-01'::text)='2014';
^ HINT: No function matches the given name and argument types. You might need to add explicit type casts.
extract or is underlying function date_part does not exist for text-like datatypes, but they're not needed anyway. Extracting the year from this date format is equivalent to getting the 4 first characters, so your query would be:
SELECT * FROM my_table WHERE left(date,4)='2014';