0

I am running this bash script in order to connect to a PostgreSQL database, run some query, and simply check whether it returns an empty result or not. Then, I want to print out whether any rows were returned.

#!/bin/sh
DATABASE=dbname
USERNAME=user
HOSTNAME=somehost.com
export PGPASSWORD=password

queryResult () {
psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
SELECT * FROM myTable WHERE valueA > 5.0 OR valueB > 5.0;
IF @@ROWCOUNT > 0 THEN 1 ELSE 0;
SQL
}

valuesFound=$(queryResult)

echo $valuesFound

There are two issues I'm having with this:

1) It stores the result of the first query (SELECT * FROM myTable...) into valuesFound and prints it, and I don't want that. All I care about is whether the IF statement returns 1 or 0.

2) The second query (IF @@ROWCOUNT...) throws a syntax error: Syntax error at or near IF

2 Answers 2

3

I think that your script can be simplified by moving the logic to a unique statement:

queryResult () {
    psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
        SELECT CASE WHEN COUNT(*) = 0 THEN 0 ELSE 1 END
        FROM myTable 
        WHERE valueA > 5.0 OR valueB > 5.0;
    SQL
}

Or better yet, using EXISTS to avoid a potentially expensive aggregation:

queryResult () {
    psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
        SELECT CASE WHEN EXISTS (
            SELECT 1 FROM myTable WHERE valueA > 5.0 OR valueB > 5.0
        ) THEN 1 ELSE 0 END;
    SQL
}
Sign up to request clarification or add additional context in comments.

1 Comment

To anyone else who might have a similar question, edit the query as follows using the -t option in order to obtain only a tuple result: psql -h $HOSTNAME -U $USERNAME -d $DATABASE -t <<SQL ... SQL
1

IF @@ROWCOUNT > 0 THEN 1 ELSE 0; is T-SQL feature which PostgreSQL does not support.

The general solution could be:

myvar=$(psql -c "<SQL query>")
if [ -z "$myvar" ]; then
    # Do something when no data found
else
    # Data found, handle it
fi

1 Comment

psql returns 0 error code when no error happen, it is not related to data found or not!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.