Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MySQL check that file exists?

I have a table that holds relative paths to real files on HDD. for example:

SELECT * FROM images -->
id | path
1  | /files/1.jpg
2  | /files/2.jpg

Can I create a query to select all records pointing to non-existent files? I need to check it by MySql server exactly, without using an iteration in PHP-client.

like image 351
WindBridges Avatar asked Jun 19 '13 13:06

WindBridges


People also ask

How do you check if data already exists in MySQL database?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do I find a file in MySQL?

The default data directory location is C:\Program Files\MySQL\MySQL Server 8.0\data , or C:\ProgramData\Mysql on Windows 7 and Windows Server 2008. The C:\ProgramData directory is hidden by default.

Does MySQL have exists?

The EXISTS operator in MySQL is a type of Boolean operator which returns the true or false result. It is used in combination with a subquery and checks the existence of data in a subquery. It means if a subquery returns any record, this operator returns true.

What does exists do in MySQL?

The MySQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


1 Answers

I would go with a query like this:

SELECT id, path, ISNULL(LOAD_FILE(path)) as not_exists
FROM images
HAVING not_exists = 1

The function LOAD_FILE tries to load the file as a string, and returns NULL when it fails.

Please notice that a failure in this case might be due to the fact that mysql simply cannot read that specific location, even if the file actually exists.

EDIT:

As @ostrokach pointed out in comments, this isn't standard SQL, even though MySQL allows it, to follow the standard it could be:

SELECT *
FROM images
WHERE LOAD_FILE(PATH) IS NULL
like image 67
Matteo Tassinari Avatar answered Sep 20 '22 12:09

Matteo Tassinari