Mysql error safe update mode

Из данного материала Вы узнаете, как исправить ошибку «Error Code: 1175. You are using safe update mode» в MySQL Workbench, а также причины ее возникновения

Приветствую Вас на сайте Info-Comp.ru! Сегодня мы рассмотрим ситуацию, когда в среде MySQL Workbench при выполнении запроса на обновление (UPDATE) или удаление (DELETE) возникает ошибка «Error Code: 1175. You are using safe update mode». Мы поговорим о причинах возникновения этой ошибки, а также о том, как устранить эту ошибку.

Ошибка в MySQL Workbench «Error Code: 1175»

Содержание

  1. Причины возникновения ошибки «Error Code: 1175» в MySQL Workbench
  2. Как исправить ошибку «Error Code: 1175» в MySQL Workbench
  3. Исходные данные
  4. Способ 1 – Отключение режима безопасных обновлений
  5. Способ 2 – Использование в условии первичного ключа
  6. Способ 3 – Использование оператора LIMIT

Данная ошибка в основном возникает, если Вы хотите обновить или удалить абсолютно все записи из таблицы, при этом вообще не указывая условие WHERE, или Вы указываете условие WHERE, но в нем нет предиката с участием первичного ключа.

Дело в том, что по умолчанию в MySQL включен режим «Безопасных обновлений» – Safe Updates Mode.

Данный режим предполагает обязательное использование в условии WHERE первичного ключа или указание оператора LIMIT.

Сделано это для того, чтобы уберечь начинающих от случайных изменений данных в таблицах во время операций UPDATE или DELETE, так как иногда некоторые пользователи просто забывают написать условие WHERE и запускают запрос на выполнение, и тем самым вносят изменения абсолютно во все записи таблицы, что достаточно часто не является их целью.

Заметка! Установка MySQL 8 на Windows 10.

Как исправить ошибку «Error Code: 1175» в MySQL Workbench

Данную ошибку достаточно легко устранить, так как это всего лишь ограничение, реализованное в целях безопасности.

Давайте рассмотрим способы устранения ошибки «Error Code: 1175» в MySQL Workbench.

Исходные данные

Для начала, чтобы было нагляднее, давайте я покажу, какие исходные данные будут использоваться в примерах.

   
   CREATE TABLE goods (
       product_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
       product_name VARCHAR(100) NOT NULL,
       price NUMERIC(18,2) NULL
   );

   INSERT INTO goods (product_name, price)
      VALUES ('Системный блок', 50),
             ('Клавиатура', 30),
             ('Монитор', 100),
             ('Планшет', 150),
             ('Смартфон', 100);

   SELECT * FROM goods;

Скриншот 1

Заметка! Начинающим программистам рекомендую почитать мою книгу «SQL код», которая поможет Вам изучить язык SQL как стандарт, в ней рассматриваются все базовые конструкции языка SQL, приводится много примеров и скриншотов.

И допустим, у нас появилась задача обновить столбец price у всех записей этой таблицы. Давайте попытаемся это сделать, написав следующий запрос.

   
   UPDATE goods SET price = price + 10;

Скриншот 2

Как видите, у нас возникла ошибка «Error Code: 1175. You are using safe update mode», а данные нам все равно нужно обновить, поэтому давайте исправим эту ситуацию.

Курс по SQL для начинающих

Заметка! Что такое SQL. Назначение и основа.

Способ 1 – Отключение режима безопасных обновлений

Самым очевидным способом решения проблемы является отключение режима безопасных обновлений.

Например, для отключения этого режима на время сеанса можно использовать следующую инструкцию.

   
   SET SQL_SAFE_UPDATES = 0;

Или зайти в настройки MySQL Workbench «Edit -> Preferences -> SQL Editor» и снять галочку «Save Updates», тем самым режим безопасных обновлений будет отключен насовсем (чтобы изменения вступили в силу, необходимо перезапустить MySQL Workbench, т.е. переподключиться к MySQL Server).

Скриншот 3

Однако, так как по умолчанию данный режим все-таки включен, значит, это рекомендуют сами разработчики MySQL, и отключать его не советуют. Поэтому стоит посмотреть на следующие способы решения данной проблемы.

Способ 2 – Использование в условии первичного ключа

Чтобы не трогать сам режим, мы можем просто выполнить требования, которые накладывает данный режим.

Например, в условии WHERE использовать ключ. Для решения нашей задачи мы можем указать product_id > 0.

   
   UPDATE goods SET price = price + 10
   WHERE product_id > 0;

   SELECT * FROM goods;

Скриншот 4

Мы видим, что запрос успешно выполнился, и все записи обновлены.

Заметка! ТОП 5 популярных систем управления базами данных (СУБД).

Способ 3 – Использование оператора LIMIT

Также можно указать оператор LIMIT, чтобы ограничить строки для обновления, при этом в параметре LIMIT указать число, которое будет больше количества строк в таблице.

   
   UPDATE goods SET price = price + 10
   LIMIT 1000;

   SELECT * FROM goods;

Скриншот 5

В данном случае также запрос выполнился успешно.

На сегодня это все, надеюсь, материал был Вам полезен, пока!

MySQL ERROR code 1175 is triggered when you try to update or delete a table data without using a WHERE clause.

MySQL has a safe update mode to prevent administrators from issuing an UPDATE or DELETE statement without a WHERE clause.

You can see if safe update mode is enabled in your MySQL server by checking the global variable sql_safe_updates.

Check the global variable using the SHOW VARIABLES statement as follows:

SHOW VARIABLES LIKE "sql_safe_updates";

--   +------------------+-------+
--   | Variable_name    | Value |
--   +------------------+-------+
--   | sql_safe_updates | ON    |
--   +------------------+-------+

The example above shows that sql_safe_updates is turned ON, so an UPDATE or DELETE statement without a WHERE clause will cause the error 1175.

Here’s an example UPDATE statement that causes the error:

mysql> UPDATE books SET title = "Stardust";

ERROR 1175 (HY000): You are using safe update mode and you tried 
to update a table without a WHERE that uses a KEY column. 

To fix the error, you can either disable the safe update mode or follow the error description by adding a WHERE clause that uses a KEY column.

You can use the SET statement to disable the safe update as shown below:

SET SQL_SAFE_UPDATES = 0;

Now you should be able to execute an UPDATE or DELETE statement without a WHERE clause.

If you want to turn the safe update mode back on again, you can SET the global variable to 1 as shown below:

SET SQL_SAFE_UPDATES = 1;

If you’re using MySQL Workbench to manage your database server, then you can disable the safe update mode from the Preferences menu.

Click on Edit -> Preferences for Windows or MySQLWorkbench -> Preferences for Mac.

Then click on SQL Editor tab and uncheck the Safe updates feature:

Keep in mind that updating or deleting a table without a WHERE clause will affect all rows in that table.

The safe update mode is added to prevent accidental change that can be fatal.

It’s okay if you’re testing with dummy data, but please be careful with real data 👍

If you try to update a row in the MySQL database by using Workbench without specifying Key column in the WHERE clause you will get the following error:

Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.

Error Code 1175 is telling you that you are in the safe mode, this is mode is enabled by default in MySQL Workbench, and it helps you prevent some unintentional updates to the database. This is a client-side setting (the same as --safe-updates in the mysql client) so there’s not much you can do to disable it on the server-side.

There are few ways you can fix this, but I would not recommend you disabling it permanently, it’s better to disable it, execute your update statement and then enable this setting again.

ErrorCode 1175 Safe Update Mode Fix

How to fix Error Code 1175

The simple fix is to disable this setting with an SQL statement, then execute the UPDATE statement and then enable it again:

-- disable safe update mode
SET SQL_SAFE_UPDATES=0;
-- execute update statement
UPDATE table SET column='value';
-- enable safe update mode
SET SQL_SAFE_UPDATES=1;

There is another way to disable this mode permanently in MySQL Workbench (I do not recommend you disable this mode entirely, it’s better to use the previous approach to the temporary disable the safe update mode)

Disable Safe Update Mode

To permanently disable safe update mode in MySQL Workbench 8.0 you should do the following:

  1. Go to Edit —> PreferencesMySQL Workbench Edit Preferences Menu
  2. Click "SQL Editor" tab and uncheck «Safe Updates» (rejects UPDATEs and DELETEs with no restrictions) check boxMySQL Workbench SQL Editor Safe Update
  3. Query —> Reconnect to Server

In this way, you will permanently disable the Safe Update mode, so all of your updates and deletes can be executed without specifying WHERE clause at all. Be careful, you can delete all data from the table in this case.

P.S. this is just a reminder for myself on how to disable this setting, I am tired of googling it every time I need to update something directly in the database (I would not recommend doing it either, but sometimes you have to).

Oops!! Stuck with MySQL Workbench Error Code 1175? We can help you in fixing it. 

MySQL Workbench Error Code 1175 occurs mainly when trying to UPDATE without a WHERE clause while operating in ‘safe update mode’.

At Bobcares, we often get requests to fix MySQL Benchmark errors, as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix MySQL Workbench Error Code 1175 for our customers.

Why MySQL Workbench Error Code 1175 occur?

The UPDATE, DELETE commands and WHERE clause is to be executed very carefully when dealing with the database. Even a mild mishandling can cause data corruption.

In order to prevent such situations, we can stop the execution of queries without a key field condition.

When, the safe_updates_option is turned ON and when we execute a DELETE query, this will result in  ‘Error Code 1175’. Another reason for this error to occur is running UPDATE without a WHERE key in safe update mode.

How we fix this error?

Recently, one of our customers approached us saying that he is getting Error Code 1175 while executing a DELETE query. When we checked we found that the safe update option is turned ON. So we set a safe update option OFF.

SET sql_safe_updates=0;

Then we tried deleting the records from the table he mentioned using:

DELETE FROM TableA

This deleted the table successfully.

We also handled a situation where the customer approached us saying that he wants to disable sql_safe_updates option as he is getting an error like the one shown below:

 MySQL Workbench Error Code 1175

The customer said, he doesn’t know from where he has to disable it in GUI. So our Support Engineers asked him to follow the steps below for disabling.

  1. Initially, access the Edit option.
  2. There click on the Preferences option available.
  3. Then, click on the SQL Editor tab. Within this tab, uncheck Safe Updates checkbox and click OK.
  4. There you can see Query and Reconnect to Server.
  5. Then, login and finally logout

[Need any assistance with MySQL errors? – We’ll help you]

Conclusion

In conclusion, we fix this error either by using a where clause or by disabling ‘sql_safe_updates’. Today, we discussed the topic in detail and saw how our Support Engineers find a fix for error: code 1175.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:
  • Mysql error number 1114
  • Mysql error number 1062
  • Mysql error no 1067
  • Mysql error max user connections
  • Mysql error log xampp