brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mysql --safe-updates stops UPDATE and DELETE without a key or LIMIT

Mysql
~/tips/tip-database-mysql-safe-updates

mysql --safe-updates -u root -p

Starts the mysql client in a mode that refuses UPDATE and DELETE statements that could hit the whole table.

Everybody who types SQL by hand eventually runs a DELETE and forgets the WHERE clause. The mysql client can catch that for you.

mysql --safe-updates -u root -p

The manual explains that safe-updates mode helps when you might forget the WHERE clause. On connection the client runs a few settings for you: sql_safe_updates=1, sql_select_limit=1000 and max_join_size=1000000.

With sql_safe_updates on, an UPDATE or DELETE produces an error unless the WHERE clause uses a key column or the statement has a LIMIT. So this one fails:

DELETE FROM orders;
DELETE FROM orders WHERE note = 'test';

The second statement also fails if note has no index. This one works, because the primary key is used:

DELETE FROM orders WHERE id = 42;

The option also has the name --i-am-a-dummy, which is honest at least. You can change the limits, for example with --select-limit=500 and --max-join-size=10000.

The caveat is the extra limit on SELECT. With sql_select_limit=1000 every plain SELECT stops at 1000 rows, which can surprise you in an export or a count check. It is also a setting of this client session, not a protection of the server. Another client, an app or a script without the option can still run the full-table delete.

Further reading: MySQL manual: mysql client tips (safe-updates)

More Mysql tips FOR UPDATE SKIP LOCKED; mysql_config_editor set --login-path=shop \ SET PERSIST max_connections = 300; ALTER TABLE orders ADD COLUMN note VARCHAR(100), ALGORITHM=INSTANT; ALTER USER 'appuser'@'192.0.2.10' All Mysql tips (8) All topics

Link