Ошибка 1175 mysql

Приветствую Вас на сайте 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

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

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

As stated in previous posts, changing the default settings of the database server will result in undesired modification of existing data due to an incorrect query on the data in a published project. Therefore, to implement such commands as stated in previous posts, it is necessary to run them in a test environment on sample data and then execute them after testing them correctly.

My suggestion is to write a WHERE conditional statement that will loop through all the rows in all conditions if an update should work for all rows in a table. For example, if the table contains an ID value, the condition ID > 0 can be used to select all rows:

/**
 * For successful result, "id" column must be "Not Null (NN)" and defined in
 * INT data type. In addition, the "id" column in the table must have PK, UQ
 * and AI attributes.
 */
UPDATE schema_name.table_name
SET first_column_name = first_value, second_column_name = second_value, ...
WHERE id > 0;

If the table does not contain an id column, the update operation can be run on all rows by checking a column that cannot be null:

/**
 * "first_column_name" column must be "Not Null (NN)" for successful result.
 */
UPDATE schema_name.table_name
SET first_column_name = first_value, second_column_name = second_value, ...
WHERE table_name.first_column_name IS NOT NULL;

I am trying to run an update query where actual id looks like 1273106/2 using the following query but running into below error,can anyone help how to fix it?

UPDATE ids.id_submit_table SET picked_bit='1' 
        WHERE (id like '1273106')

Row looks like below

126 1273106/2   AL.BH.1.1.1 SU_CNSS_BT_FM_AL.BH.1.1.1 username  0   0

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 Queries and reconnect.   0.000 sec

asked Jun 16, 2015 at 20:58

4

This error appears because safe update mode requires key to update/delete with where clause, you can use

SET SQL_SAFE_UPDATES=0;

Before executing the query or if you want to avoid this situation in future please make sure update/delete by using key with where clause

answered May 20, 2018 at 16:47

Rahul Sharma's user avatar

try this for fix problem.

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

Go to Edit —> Preferences.

Click «SQL Editor» tab and uncheck «Safe Updates» (rejects UPDATEs and DELETEs with no restrictions) check box.

Query —> Reconnect to Server.

answered Nov 2, 2020 at 8:39

pankaj's user avatar

This is MySQL Workbench issue, not MySQL itself. You can try via any other MySQL client or you can toggle safe queries off in Workbench Preferences.

answered Jun 16, 2015 at 21:56

ptkoz's user avatar

ptkozptkoz

2,3481 gold badge20 silver badges28 bronze badges

click on edit and find Preferences.
find SQL editor click on it, go to the bottom, and uncheck
click on ok.

now goto server, find the startup and shut down, stop the server and start again

answered Nov 10, 2020 at 19:58

rushikesh veeramally's user avatar

This is a MySQL Workbench issue.

Instead of executing the query in workBench, connect to MySQL using the CLI client and run your Update/Delete query there.

The change will also be reflected in WorkBench.

Lucio Mollinedo's user avatar

answered Mar 4, 2022 at 19:03

Yl okeshWAR's user avatar

2

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).

Понравилась статья? Поделить с друзьями:
  • Ошибка 1174 форд транзит
  • Ошибка 11731 шкода етти
  • Ошибка 11731 фольксваген
  • Ошибка 11730 шкода йети
  • Ошибка 1172 форд транзит