Table of Contents
1. sql_mode is used to solve the following types of problems
2. Description of the default value of the sql_mode parameter in MySQL5.7 (the following is the MySQL 5.7.27 version)
Home Database Mysql Tutorial How to set SQL_MODE in MySQL 5.7

How to set SQL_MODE in MySQL 5.7

Jun 03, 2023 pm 03:22 PM
mysql sql_mode

sql_mode is a variable that is easily overlooked. The default value in 5.5 is null. Under this setting, some illegal operations can be allowed, such as allowing the insertion of some illegal data.

This value setting has been strengthened in 5.6, and 5.7 has paid more attention to security specifications. This value defaults to strict mode

1. sql_mode is used to solve the following types of problems

By setting sql mode, data verification with different stringency levels can be completed to effectively ensure data readiness.

By setting the sql mode to relaxed mode, we ensure that most sql conforms to the standard sql syntax. In this way, when the application is migrated between different databases, there is no need to make major modifications to the business sql, and it can be easily Conveniently migrate to the target database.

2. Description of the default value of the sql_mode parameter in MySQL5.7 (the following is the MySQL 5.7.27 version)

  • ONLY_FULL_GROUP_BY

For SQL that uses GROUP BY for query, fields that do not appear in GROUP BY are not allowed to appear in the SELECT part. That is, the fields in the SELECT query must appear in GROUP BY or use aggregate functions or be Has unique properties.

create table test(name varchar(10),value int);
insert into test values ('a',1),('a',20),('b',23),('c',15),('c',30);
#默认情况是可能会写出无意义或错误的聚合语句:
SET sql_mode='';
select * from test group by name;
select value,sum(value) from test group by name;
# 使用该模式后,写法必须标准
SET sql_mode='ONLY_FULL_GROUP_BY';
select name,sum(value) from test group by name;
-- 错误写法则报错
select value,sum(value) from test group by name;
# 报错终止
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.test.value' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Copy after login
  • STRICT_TRANS_TABLES

This option only works for transactional storage engines and is invalid for non-transactional storage engines. , its function is to enable strict SQL mode. In strict sql mode, if a field value that does not meet the requirements is inserted or updated in an INSERT or UPDATE statement, an error will be reported directly and the operation will be interrupted

create table test(value int(1));
SET sql_mode=''; #默认只要第一个值
 
insert into test(value) values('a'),(1); #不报错
insert into test(value) values(2),('a'); #不报错
select * from test;
+------------+
| value      |
+------------+
|          0 |
|          1 |
|          2 |
|          0 |
+------------+
#后面删除表不再说明!
drop table test; 
create table test(value int(1));
 
SET sql_mode='STRICT_TRANS_TABLES'; #每个值都判断
 
insert into test(value) values('a'),(1);
#报错,第一行'a'错误。
ERROR 1366 (HY000): Incorrect integer value: 'a' for column 'value' at row 1
Copy after login
  • NO_ZERO_IN_DATE

The time field value inserted in MySQL does not allow the date and month to be zero

create table test(value date);
SET sql_mode='';
insert into test(value) values('2020-00-00'); #结果为 '2020-00-00'
 
SET sql_mode='NO_ZERO_IN_DATE';
insert into test(value) values('2021-00-00'); #不符合,转为 '0000-00-00'
Copy after login
  • NO_ZERO_DATE

The time field value inserted in MySQL is not allowed to insert the ‘0000-00-00’ date

create table test(value date);
 
SET sql_mode='';
insert into test(value) values('0000-00-00'); #无警告 warning
 
SET sql_mode='STRICT_TRANS_TABLES';
insert into test(value) values('0000-00-00'); #无警告 warning
 
SET sql_mode='NO_ZERO_DATE';
insert into test(value) values('0000-00-00'); #有警告 warning
 
SET sql_mode='NO_ZERO_DATE,STRICT_TRANS_TABLES'
insert into test(value) values('0000-00-00');
# 报错终止
ERROR 1292 (22007): Incorrect date value: '0000-00-00' for column 'value' at row 1
Copy after login
  • ##ERROR_FOR_DIVISION_BY_ZERO

In an INSERT or UPDATE statement, if the data is divided by 0, a warning (in non-strict sql mode) or an error (in strict sql mode) will appear.

  • When this option is turned off, the number is divided by 0, resulting in NULL and no warning is generated

  • When this option is turned on and is in non-strict In sql mode, if the number is divided by 0, NULL will be obtained but a warning will be generated

  • When this option is turned on and in strict sql mode, the number is divided by 0, an error will be generated and the operation will be interrupted

  • create table test(value int);
     
    SET sql_mode='';  
    select 10/0;  #无警告 warning
    insert into test(value) values(10/0);   #无警告 warning
     
    SET sql_mode='STRICT_TRANS_TABLES'; 
    select 10/0;   #无警告 warning
    insert into test(value) values(10/0);  #无警告 warning
     
    SET sql_mode='ERROR_FOR_DIVISION_BY_ZERO'; 
    select 10/0;  #有警告 warning
    insert into test(value) values(10/0);  #有警告 warning
     
    SET sql_mode='ERROR_FOR_DIVISION_BY_ZERO,STRICT_TRANS_TABLES';
    select 10/0; #有警告 warning
    insert into test(value) values(10/0); 
    #报错:ERROR 1365 (22012): Division by 0
    Copy after login
  • ##NO_AUTO_CREATE_USER

    ##Prohibit GRANT from creating users with empty passwords
  • SET sql_mode='';
    grant all on test.* to test01@'localhost';  #不报错(无需要设置密码)
    SET sql_mode='NO_AUTO_CREATE_USER';
    # 报错
    ERROR 1133 (42000): Can't find any matching row in the user table
    
    #正确 写法,需要设置密码
    grant all on test.* to test01@'localhost' identified by 'test01...';
    Copy after login

    NO_ENGINE_SUBSTITUTION
  • #When using CREATE TABLE or ALTER TABLE syntax to execute the storage engine, if the set storage engine is disabled or not Compiling will produce an error.
  • # 查看当前支持的存储引擎
    show engines;
    
    set sql_mode='';
    create table test(id int) ENGINE="test";
    Query OK, 0 rows affected, 2 warnings (0.03 sec)
    
    select table_name,engine from information_schema.tables where table_schema='test' and table_name='test'; # 转为默认存储引擎
    +------------+--------+
    | table_name | engine |
    +------------+--------+
    | test       | InnoDB |
    +------------+--------+
    SET sql_mode='NO_ENGINE_SUBSTITUTION';
    create table test(id int) ENGINE=test;
    # 报错
    ERROR 1286 (42000): Unknown storage engine 'test'
    Copy after login
3. sql_mode setting and modification

Method 1: This is a modifiable global variable

> show variables like '%sql_mode%';
> set @@sql_mode="NO_ENGINE_SUBSTITUTION"
> set session sql_mode='STRICT_TRANS_TABLES';
Copy after login

Method 2: By modifying the configuration file (requires restart to take effect)

# vim /etc/my.cnf
[mysqld]
......
sql_mode="NO_ENGINE_SUBSTITUTION"
......
Copy after login

The above is the detailed content of How to set SQL_MODE in MySQL 5.7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles