Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a row could be deleted in MySQL

Is there a way I can check if a row potentially could be deleted? That it for example is not currently connected through restricted foreign keys to anything else.

Reason: I am making an admin page with all the users in the system listed. They can always be disabled, but they may also be deleted. However they can only be deleted if they are not connected to anything critical. And I would like to not having to check that manually if it can be done easily in the database.

Note: I do not want to actually delete any user. I just want to display to the admin that a user could be deleted.

like image 551
Svish Avatar asked Sep 14 '10 18:09

Svish


People also ask

Is deletion possible in MySQL?

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE .

How do I DELETE a specific row in MySQL?

To delete rows in a MySQL table, use the DELETE FROM statement: DELETE FROM products WHERE product_id=1; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.

Why DELETE is not working in MySQL?

Solution. By default, MySQL workbench is started in safe mode, and can't update or delete, without a “WHERE” condition, see the error message. To fix it, in menu, selects “Edit” -> “Preferences” -> “SQL Queries”, uncheck the “Safe Updates” checkbox. Done, try reconnect and issue the delete command again.


2 Answers

You could try deleting it as part of a transaction, and then roll back the transaction if it succeeds. BUT, I guess the immediate followup question is, why wouldn't you know in the first place if you could delete the row or not?

like image 60
GrandmasterB Avatar answered Sep 21 '22 20:09

GrandmasterB


You could use a view to sum up the number of dependencies without having to worry about storing the data & keeping it current. When the number of dependencies is zero, make the delete option available in the UI...

like image 39
OMG Ponies Avatar answered Sep 19 '22 20:09

OMG Ponies