Search code examples
mysqlsqlexport-to-csv

Prevent file creation if query returns no data


I have a job that runs every night which executes a query and exports the result of that query into a .csv file.

Here is an example of what I mean:

SELECT Your_Column_Name
FROM Your_Table_Name
INTO OUTFILE 'Filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

My question is: is there any way to prevent the file creation if the query returns a total rowcount of 0 without having to execute the query twice? Once to count the row and twice to create the file?


Solution

  • No, there's no way to prevent creation of the file without writing a little more code.

    You don't necessarily need to count the rows, if all you want to know is whether there are zero rows or more than zero rows.

    SELECT 1 FROM Your_Table_Name LIMIT 1
    

    This will return 1 row if there are any matching rows, or else it will return zero rows. If you're concerned that counting all matching rows is too slow, then this will return more quickly.