I have a PostgreSQL query that won't execute properly when I look for empty strings. I've tried escaping single quotes with the backslash, I've tried double quotes, nothing seems to work. Ideas? I need to look for empty strings because my script doesn't do what I need it to do when it finds empty strings in my dataset.
this_query = """
copy(SELECT phone_number from mytable WHERE phone_number is not null and phone_number != '''' ORDER BY random() LIMIT 25)
to stdout csv header;
"""
Without the empty string phrase (phone_number != ''''), the query will work when I execute:
THIS_COMMAND = "psql -h hostname -d dbname -c '{query}' > {file_name}"
command = THIS_COMMAND.format(query=this_query, file_name=a_file_name)
os.system(command)
ATTN: After reviewing answers below, I experimented and found this to work:
phone_number != '\"'\"''\"'\"'
There are ways to make this work with the quotes.
EDIT: Cross-referencing this UNIX-shell quoting answer: The quotes need to both escaped for Python and sh/bash (presumably). So for sh this needs to be '"'"''"'"', but then the " characters need to be escaped for Python, giving '\"'\"''\"'\"'. Phew!
this_query = """
copy(SELECT phone_number from mytable WHERE phone_number is not null and phone_number != '\"'\"''\"'\"''\"'\"''\"'\"' ORDER BY random() LIMIT 25) to stdout csv header;
"""
But to give another approach, have you considered checking for character_length(phone_number) > 0 ?
Ref: https://www.postgresql.org/docs/9.1/functions-string.html
e.g.:
SELECT phone_number FROM mytable WHERE phone_number IS NOT NULL AND character_length(phone_number) > 0
But maybe it's better to clean the data?
UPDATE mytable SET phone_number = NULL WHERE character_length(trim(phone_number)) = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With