HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlMinor

can mysql cli exit with error if no records returned?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canerrorreturnedwithrecordsexitmysqlcli

Problem

I would like to execute a sql command in bash, and do something based on whether or not there was a result.

e.g.

$ LOOKUP=123; mysql -e \
    'SELECT id FROM table WHERE id='$LOOKUP dbname \
    && echo "Row $LOOKUP exists"
    || echo "Row $LOOKUP does not exists"


I can think of bodges (e.g. testing for ZLS) but wondered if there was a clean way?

Solution

Try changing the query to force a value

Instead of

SELECT id FROM table WHERE id=${LOOKUP}


you can use

SELECT COUNT(1) FROM table WHERE id=${LOOKUP}


Here is bash script to use that new query

LOOKUP=123
SQLSTMT="SELECT COUNT(1) FROM table WHERE id=${LOOKUP}"
RCOUNT=`mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}"`
if [ ${RCOUNT} -eq 0 ]
then
    echo "Row ${LOOKUP} exists"
else
    echo "Row ${LOOKUP} does not exist"
fi


Here is an alternative

LOOKUP=123
SQLSTMT="SELECT CONCAT('Row ',rcount,' ',IF(rcount=0,'Exists','Does Not Exist')) FROM (SELECT COUNT(1) rcount FROM rolando WHERE id=${LOOKUP}) A"
mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}" > /tmp/answer.txt
cat /tmp/answer.txt


Give it a Try !!!

Code Snippets

SELECT id FROM table WHERE id=${LOOKUP}
SELECT COUNT(1) FROM table WHERE id=${LOOKUP}
LOOKUP=123
SQLSTMT="SELECT COUNT(1) FROM table WHERE id=${LOOKUP}"
RCOUNT=`mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}"`
if [ ${RCOUNT} -eq 0 ]
then
    echo "Row ${LOOKUP} exists"
else
    echo "Row ${LOOKUP} does not exist"
fi
LOOKUP=123
SQLSTMT="SELECT CONCAT('Row ',rcount,' ',IF(rcount=0,'Exists','Does Not Exist')) FROM (SELECT COUNT(1) rcount FROM rolando WHERE id=${LOOKUP}) A"
mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}" > /tmp/answer.txt
cat /tmp/answer.txt

Context

StackExchange Database Administrators Q#12007, answer score: 3

Revisions (0)

No revisions yet.