2

I am running some SQL queries from command line as follows:

cat my_query.sql | mysql --defaults-file=my_conf.cnf

I need to print column names whether the query returns any data or not. Currently when there is no data to return, i.e when query returns an empty result set this command does not print anything.

For example my query is:

-- id=-1 doesn't exist
SELECT col1, col2 FROM table WHERE id=-1

I need this query to return

col1    col2

Instead it returns nothing. Is it possible to do that using purely mysql and standard unix commands?

Thanks.

3
  • You could take the intended query and UNION ALL a "dummy" SELECT emulating an empty row after it. UNION results use the data types and column names of the first query of the UNION. Commented May 12, 2015 at 22:29
  • I guess you suggest to add a dummy SELECT like SELECT '',''. It would work but then it will add a new line and a few tab characters at the end of the results. It's not the cleanest solution but it might work. I was looking for a mysql command option to do that but there may not be one. Thanks. Commented May 12, 2015 at 22:42
  • Yes, it is not the ideal solution, but if you always have that, you know to always ignore the last line, or you could give your dummy SELECT some blatant "flag" values like '[cmdlinedummy]' for strings. Commented May 12, 2015 at 22:45

1 Answer 1

3

Adding a UNION ALL to a SELECT with "dummy"/blank data might work:

SELECT col1, col2 FROM table WHERE id=-1
UNION ALL
SELECT '', '' -- OR 0, 0 whatever is appropriate
;

I don't run queries from the command line, so this is assuming it normally would give you the column names if you had at least one row in the results.

Sign up to request clarification or add additional context in comments.

1 Comment

I used your idea and added this to remove the last line. "| sed '$ d' "

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.