Ошибка field id doesn t have a default value

I am new to this SQL; I have seen similar question with much bigger programs, which I can’t understand at the moment. I am making a database for games of cards to use in my homepage.

I am using MySQL Workbench on Windows. The error I get is:

Error Code: 1364. Field ‘id’ doesn’t have a default value

CREATE TABLE card_games
(
nafnleiks varchar(50), 
leiklysing varchar(3000), 
prentadi varchar(1500), 
notkunarheimildir varchar(1000), 
upplysingar varchar(1000), 
ymislegt varchar(500), 
id int(11) PK
);

insert into card_games (nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values('Svartipétur',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum',
'Aðrar upplýsingar',
'ekkert hér sem stendur'
);

values('Handkurra',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun', 
'Aðrar upplýsingar',
'ekkert her sem stendur'
);

values('Veiðimaður',
'Leiklýsingu vantar',
'Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil. Reykjavík: Bókafélagið. Bls. 19-20.',
'vantar',
'vantar',
'vantar'
);

Brian Tompsett - 汤莱恩's user avatar

asked Sep 16, 2014 at 9:24

Tomas Albertsson's user avatar

2

As id is the primary key, you cannot have different rows with the same value. Try to change your table so that the id is auto incremented:

id int NOT NULL AUTO_INCREMENT

and then set the primary key as follows:

PRIMARY KEY (id)

All together:

CREATE TABLE card_games (
   id int(11) NOT NULL AUTO_INCREMENT,
   nafnleiks varchar(50),
   leiklysing varchar(3000), 
   prentadi varchar(1500), 
   notkunarheimildir varchar(1000),
   upplysingar varchar(1000),
   ymislegt varchar(500),
   PRIMARY KEY (id));

Otherwise, you can indicate the id in every insertion, taking care to set a different value every time:

insert into card_games (id, nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values(1, 'Svartipétur', 'Leiklýsingu vantar', 'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.', 'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum', 'Aðrar upplýsingar', 'ekkert hér sem stendur' );

TRiG's user avatar

TRiG

10.1k7 gold badges57 silver badges107 bronze badges

answered Sep 16, 2014 at 9:27

fedorqui's user avatar

fedorquifedorqui

272k103 gold badges543 silver badges595 bronze badges

There are 2 solutions mentioned below:

Solution 1

MySQL is most likely in STRICT SQL mode. Try to execute SQL query SET GLOBAL sql_mode='' or edit your my.cnf / my.ini to make sure you aren’t setting STRICT_ALL_TABLES and/or STRICT_TRANS_TABLES.

Solution 2

If Solution-1 is not working then try Solution-2 as given in below steps:

  1. Run MySQL Administrator tool as Administrator.
  2. Then go to Startup Variable.
  3. Then go to the Advance tab.
  4. find SQL Mode and remove the STRICT_ALL_TABLES and/or STRICT_TRANS_TABLES and then Click on Apply Changes.
  5. Restart MySQL Server.
  6. Done.

Note: I have tested these solutions in MySQL Server 5.7

Don't Panic's user avatar

Don’t Panic

41k10 gold badges59 silver badges80 bronze badges

answered Apr 29, 2016 at 10:45

Renish Aghera's user avatar

3

The id should set as auto-increment.

To modify an existing id column to auto-increment, just add this

ALTER TABLE card_games MODIFY id int NOT NULL AUTO_INCREMENT;

answered Mar 22, 2017 at 2:46

John Joe's user avatar

John JoeJohn Joe

12.3k16 gold badges69 silver badges133 bronze badges

2

I was getting error while ExecuteNonQuery() resolved with adding AutoIncrement to Primary Key of my table. In your case if you don’t want to add primary key then we must need to assign value to primary key.

ALTER TABLE `t1` 
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;

answered Apr 9, 2019 at 12:16

hardik patel's user avatar

0

Since mysql 5.6, there is a new default that makes sure you are explicitly inserting every field that doesn’t have a default value set in the table definition.

to disable and test this: see this answer here: mysql error 1364 Field doesn’t have a default values

I would recommend you test without it, then reenable it and make sure all your tables have default values for fields you are not explicitly passing in every INSERT query.

If a third party mysql viewer is giving this error, you are probably limited to the fix in that link.

Community's user avatar

answered Sep 16, 2015 at 6:48

radoo's user avatar

radooradoo

1682 silver badges7 bronze badges

This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.

There are a couple of fixes for this.

First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:

ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;

However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.

If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:

#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode=NO_ENGINE_SUBSTITUTION

Save the file and restart Mysql.

Source: https://www.euperia.com/development/mysql-fix-field-doesnt-default-value/1509

answered Dec 15, 2015 at 16:00

joseantgv's user avatar

joseantgvjoseantgv

1,9431 gold badge26 silver badges34 bronze badges

make sure that you do not have defined setter for the for your primary key in model class.

public class User{
@Id
@GeneratedValues
private int user_Id;
private String userName;

public int getUser_Id{
return user_Id;
}

public String getUserName{
return userName;
}

public void setUserName{
this.userName=userName;
}
}

answered Mar 12, 2015 at 9:59

Vivek Pal's user avatar

Vivek PalVivek Pal

1811 silver badge4 bronze badges

To detect run:

select @@sql_mode
-- It will give something like:
-- STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

To fix, run:

set global sql_mode = ''

answered Oct 22, 2020 at 18:17

Shadi Alnamrouti's user avatar

Shadi AlnamroutiShadi Alnamrouti

11.6k4 gold badges55 silver badges54 bronze badges

if you add the AUTO_INCREMENT clause to the primary key id field in the database table as shown below it will work.

CREATE TABLE user_role (
user_role_id bigint NOT NULL AUTO_INCREMENT,
user_id bigint NOT NULL,
role_id bigint NOT NULL,

answered Apr 5, 2021 at 0:49

user1419261's user avatar

user1419261user1419261

8198 silver badges5 bronze badges

Solution: Remove STRICT_TRANS_TABLES from sql_mode

To check your default setting,

mysql> set @@sql_mode = 
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)

mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode                                                     |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Run a sample query

mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value

Remove your STRICT_TRANS_TABLES by resetting it to null.

mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

Now, run the same test query.

mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)

Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731

answered Jun 30, 2016 at 12:16

biniam's user avatar

biniambiniam

8,0799 gold badges49 silver badges58 bronze badges

1

Disable FOREIGN_KEY_CHECKS and then

`SET FOREIGN_KEY_CHECKS = 0;

ALTER TABLE card_games MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;

SET FOREIGN_KEY_CHECKS = 1;`

answered May 20, 2021 at 17:10

Ahmad Alhaj-Karim's user avatar

For me the issue got fixed when I changed

<id name="personID" column="person_id">
    <generator class="native"/>
</id>

to

<id name="personID" column="person_id">
    <generator class="increment"/>
</id>

in my Person.hbm.xml.

after that I re-encountered that same error for an another field(mobno). I tried restarting my IDE, recreating the database with previous back issue got eventually fixed when I re-create my tables using (without ENGINE=InnoDB DEFAULT CHARSET=latin1; and removing underscores in the field name)

CREATE TABLE `tbl_customers` (
  `pid` bigint(20) NOT NULL,
  `title` varchar(4) NOT NULL,
  `dob` varchar(10) NOT NULL,
  `address` varchar(100) NOT NULL,
  `country` varchar(4) DEFAULT NULL,
  `hometp` int(12) NOT NULL,
  `worktp` int(12) NOT NULL,
  `mobno` varchar(12) NOT NULL,
  `btcfrom` varchar(8) NOT NULL,
  `btcto` varchar(8) NOT NULL,
  `mmname` varchar(20) NOT NULL
)

instead of

CREATE TABLE `tbl_person` (
  `person_id` bigint(20) NOT NULL,
  `person_nic` int(10) NOT NULL,
  `first_name` varchar(20) NOT NULL,
  `sur_name` varchar(20) NOT NULL,
  `person_email` varchar(20) NOT NULL,
  `person_password` varchar(512) NOT NULL,
  `mobno` varchar(10) NOT NULL DEFAULT '1',
  `role` varchar(10) NOT NULL,
  `verified` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I probably think this due to using ENGINE=InnoDB DEFAULT CHARSET=latin1; , because I once got the error org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'mob_no' in 'field list' even though it was my previous column name, which even do not exist in my current table. Even after backing up the database(with modified column name, using InnoDB engine) I still got that same error with old field name. This probably due to caching in that Engine.

answered Jun 24, 2017 at 16:15

user158's user avatar

user158user158

12.7k7 gold badges61 silver badges91 bronze badges

I landed this question in 2019. MY problem was updating table1 with table2 ignoring the variables with different name in both tables. I was getting the same error as mentioned in question: Error Code: 1364. Field ‘id’ doesn’t have a default value in mysql. Here is how solved it:

Table 1 Schema : id ( unique & auto increment)| name | profile | Age
Table 2 Schema: motherage| father| name| profile

This solved my error:
INSERT IGNORE INTO table2 (name,profile) SELECT name, profile FROM table1

answered Sep 7, 2019 at 20:12

Manish Srivastava's user avatar

As a developer it is highly recommended to use STRICT mode because it will allow you to see issues/errors/warnings that may come about instead of just working around it by turning off strict mode. It’s also better practice.

Strict mode is a great tool to see messy, sloppy code.

answered Dec 6, 2016 at 5:28

ex8's user avatar

ex8ex8

971 silver badge7 bronze badges

1

I had an issue on AWS with mariadb — This is how I solved the STRICT_TRANS_TABLES issue

SSH into server and chanege to the ect directory

[ec2-user]$ cd /etc

Make a back up of my.cnf

[ec2-user etc]$ sudo cp -a my.cnf{,.strict.bak}

I use nano to edit but there are others

[ec2-user etc]$ sudo nano my.cnf

Add this line in the the my.cnf file

#
#This removes STRICT_TRANS_TABLES
#
sql_mode=""

Then exit and save

OR if sql_mode is there something like this:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Change to

sql_mode=""

exit and save

then restart the database

[ec2-user etc]$ sudo systemctl restart mariadb

answered Nov 17, 2018 at 9:45

Andrew Wood's user avatar

It amazing for me, for solving Field ‘id’ doesn’t have a default value? I have tried all the possible ways what are given here like..

set sql_mode=""
set @@sql_mode = ''; etc

but unfortunately these didn’t work for me.
So after long investigation, I found that

@Entity
@Table(name="vendor_table")
public class Customer {
    @Id
    @Column(name="cid")
    private int cid;
.....
}

@Entity
@Table(name="vendor_table")
public class Vendor {
    @Id
    private int vid;
    @Column
    private String vname;
    .....
}

here you can see that both tables are having same name. It is very funny mistake, was done by me :)))). After correcting this,my problem was gone off.

answered Nov 22, 2018 at 13:50

Brajesh's user avatar

BrajeshBrajesh

1,49513 silver badges18 bronze badges

If you are creating your schema using MySQL Workbench, you can check this checkbox.

enter image description here

If you can’t see the image, it’s the column titled AI, if you hover over it you’ll see it’s label Mark column as AUTO_INCREMENT.

answered May 12, 2022 at 13:16

Mahad Ahmed's user avatar

Mahad AhmedMahad Ahmed

1694 silver badges7 bronze badges

add a default value for your Id lets say in your table definition this will solve your problem.

answered May 29, 2019 at 17:53

Flavins's user avatar

FlavinsFlavins

1231 silver badge5 bronze badges

1

In this article, we will discuss why Error 1364 occurs and how to resolve it. 

Table of Contents

  • Introduction
  • Error code 1364 resolution with AUTO_INCREMENT
  • Error code 1364 resolution with DEFAULT value

Introduction

MySQL server throws the Error 1364 if the query or statement tries to insert a row without a value for a particular column defined as NOT NULL. We can say that the absence of a NOT NULL column value during insertion causes this error to be thrown by the MySQL server. 

Advertisements

Error 1364  indicates that the value of the particular field should be something other than NULL. One way to resolve the error forever is to make the column as DEFAULT NULL in table definition but if that does not meet your requirement, let us see some ways to fix this error in the below sections.

We will be creating a sample table employee_details for illustration of the concept.

Frequently Asked:

  • MySQL select first row in each group
  • MySQL add primary key multiple columns
  • How to rename a column in MySQL
  • Every derived table must have its own alias[Solved]
#create the table employee_details
 CREATE TABLE employee_details(
  emp_id int ,
  emp_enroll_no varchar(255) NOT NULL,
  emp_firstName varchar(255) DEFAULT NULL,
  emp_lastName varchar(255) DEFAULT NULL,
  primary key(emp_id)
);

Here, the column emp_id and emp_enroll_no both cannot be NULL.

DESC employee_details;

Output:-

image_1

Error code 1364 resolution with AUTO_INCREMENT

In this section, we will recreate error 1364 and will fix it using the AUTO_INCREMENT keyword. AUTO_INCREMENT in MySQL assigns a numeric value to a column starting from 1 (when another starting number not specified) and then increments the value by 1 for consecutive inserts.

Let us try to insert a row without specifying any value for column emp_id.

INSERT INTO employee_details (emp_enroll_no,emp_firstName,emp_lastName) VALUES("1-N","Henry","Smith");

Action Output:-

image_2

Since we did not specify any value for emp_id in the insert statement, the output in image_2 shows that the error 1364 is thrown with the message response: Error Code: 1364. Field ’emp_id’ doesn’t have a default value.

Observe the below ALTER query for the solution. Any insert happening after executing the below statement will assign a value to emp_id starting with 1 and incremented by 1 in successive inserts. 

ALTER TABLE employee_details MODIFY emp_id int NOT NULL AUTO_INCREMENT;

Action Output:-

image_3

Let us again try to execute the insert statement.

INSERT INTO employee_details (emp_enroll_no,emp_firstName,emp_lastName) VALUES("1-N","Henry","Smith");

Action Output:-

image_4

Insert is successful this time.

SELECT * FROM employee_details;

Output:-

image_5

Error code 1364 resolution with DEFAULT value

This section will recreate error 1364 and fix it by assigning a DEFAULT value to the column.

Let us try to insert a row without specifying any value for column emp_enroll_no.

 INSERT INTO employee_details (emp_id, emp_firstName, emp_lastName) VALUES(2, "Richa", "Johnson");

Action Output:-

image_6

Since we did not specify any value for emp_enroll_no in the insert statement, the output in image_6 shows that the error 1364 is thrown with the message response: Error Code: 1364. Field ’emp_enroll_no’ doesn’t have a default value.

Observe the below ALTER query for the solution. Here, we will give a default value to the column emp_enroll_no such that if any insert happens without any value for emp_enroll_no, a default value “N-N” will be inserted.

ALTER TABLE employee_details MODIFY emp_enroll_no varchar(255) NOT NULL DEFAULT "N-N";

Action Output:-

image_7

Let us again try to execute the same insert statement.

INSERT INTO employee_details (emp_id, emp_firstName, emp_lastName) VALUES(2, "Richa", "Johnson");

Action Output:-

image_8

Insert is successful this time.

SELECT * FROM employee_details;

Output:-

image_9

The output in image_9 shows that a default value of “N-N” was inserted in second row.

READ MORE:

  • MySQL: Error 1264 Out of range value for a column [Solved]

We hope this article helped you understand and resolve Error 1364 in MySQL. Good Luck!!!

Если у вас возникает ошибка mysql:

«Field xxx doesn’t have a default value»

это означает, что при вставке или обновлении данных у поля нет значения по умолчанию. Для решения проблемы нужно:

найти данный запрос и исправить его, добавить необходимое поле;
в свойствах таблицы указать значение по умолчанию;
Еще одним способом решения является выключение режима mysql: «Strict Mode», т.е. мы выключаем режим строгого соответствия стандарту MySql.

Выключить его можно в конфиге my.ini:
прописав вместо:

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

следующий код:

# Set the SQL mode to strict
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Или выполнив следующий запрос:

SET @@GLOBAL.sql_mode= ''
SET @@SESSION.sql_mode= ''

After creating a table and while trying to insert data into the table you would have got Error code 1364. Which would be the following error response-

Error Code: 1364. Field ‘id’ doesn’t have a default value

This error usually comes in MySQL when you have not created the table properly. Check the below correct SQL syntax for creating a table:

There should be some default value for the id. Here while creating the table we have made the id as ‘AUTO_INCREMENT’. So while inserting a record by default it will have some value assigned for id.

How to resolve this error?

If have not created the table properly and this error persists? No problem, you can resolve by altering the table. Use the below syntax to resolve the error –

Переношу сайт, но возникает ошибка!

Query Error 1364: Field ‘id’ doesn’t have a default value
Query: INSERT INTO wa_log
(`app_id`, `contact_id`, `datetime`, `action`, `subject_contact_id`, `params`) VALUES (‘webasyst’, 0, ‘2020-10-28 15:38:57’, ‘login_failed’, NULL, ‘{/n /»source/»: /»backend/»,/n /»login/»: /»adm-artem/»,/n /»ip/»: /»188.187.168.209/»/n}’) code 1364

## wa-system/database/waModel.class.php(266) #0 wa-system/database/waModel.class.php(321): waModel->run('INSERT  INTO wa...') #1 wa-system/database/waModel.class.php(598): waModel->exec('INSERT  INTO wa...') #2 wa-system/webasyst/lib/models/waLog.model.php(50): waModel->insert(Array) #3 wa-system/controller/waController.class.php(84): waLogModel->add('login_failed', '{/n    "source":...', NULL, NULL) #4 wa-system/login/actions/login/waBaseLogin.action.php(422): waController->logAction('login_failed', Array) #5 wa-system/login/actions/login/waBaseLogin.action.php(67): waBaseLoginAction->tryAuth() #6 wa-system/webasyst/lib/actions/login/webasystLogin.action.php(26): waBaseLoginAction->execute() #7 wa-system/login/actions/waLoginModule.controller.php(73): webasystLoginAction->execute() #8 wa-system/controller/waViewController.class.php(86): waLoginModuleController->display() #9 wa-system/webasyst/lib/actions/login/webasystLogin.controller.php(25): waViewController->executeAction(Object(webasystLoginAction)) #10 wa-system/controller/waController.class.php(21): webasystLoginController->execute() #11 wa-system/controller/waViewController.class.php(46): waController->run(NULL) #12 wa-system/controller/waFrontController.class.php(263): waViewController->run(NULL) #13 wa-system/controller/waFrontController.class.php(190): waFrontController->runController(Object(webasystLoginController), NULL) #14 wa-system/waSystem.class.php(706): waFrontController->execute(NULL, 'login', NULL, true) #15 wa-system/waSystem.class.php(613): waSystem->dispatchBackend('webasyst/') #16 index.php(7): waSystem->dispatch() #17 {main}

GET

array()

POST

array(  'login' => 'adm-artem',  'password' => 'zoom2020',  'remember' => '0',  'wa_auth_login' => '1',  '_csrf' => '[hidden]',  'wa_json_mode' => '1',  'need_redirects' => '1', )

Помогите исправить! 

Понравилась статья? Поделить с друзьями:
  • Ошибка fl studio asio error
  • Ошибка ffr 3300 ман тга
  • Ошибка fl studio access violation at address
  • Ошибка ffr 03284 00 на ман тга
  • Ошибка fixing d stage 1