Suppose In my MySQL table there are no row inserted yet.
CREATE TABLE Users (
SerialNo INT(9) NOT NULL AUTO_INCREMENT,
UserID INT(9) NOT NULL,
PRIMARY KEY (SerialNo)
);
When I run the following MySQL statement:
INSERT INTO Users(UserID) SELECT MAX(UserID)+1 FROM Users;
The table looks like the following picture:
Image Link: https://s1.postimg.org/4r2xcc7ajj/z_Ii_A-_KUp_Tzio_-00_PBL0_KQ.png
Can anyone tell me why MAX(UserID)+1 setting 0 instead of 1?
0 is the default value used for an int field without a default
specified.
Inserting null values into not null fields usually results
in the field given the null value being assigned it's default value
instead.
Most aggregate functions only return null only if the
encounter no non-null values.
Since the table is empty, MAX returns null, and NULL + 1 is NULL.
You're inserting null into an integer field without a default value specified.
Edit: To insert 1 in such cases use IFNULL(MAX(UserId),0)+1
As mysql manual on max() says: max() returns null if there is no matching record. If there is no record at all in the table, then max(userid) returns null.
null + 1 will also be null. So, you query tries to insert null into your table.
Your mysql is configured with strict mode turned off, therefore when you try to insert a null value into a non-null field, mysql silently converts the null to the fields implicit default value. This happens to be 0 for an integer field.
If strict mode were turned on, then you would get an error message for trying to insert an illegal value into your table. This way, you only get a warning.
Btw, you should turn strict mode on.
How to make sure that MySQL does not find false positives when a alphabetic character is appended to a integer value?
Turns out that given this table:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `mytable`
ADD PRIMARY KEY (`id`);
And this query:
SELECT * FROM `mytable` WHERE `id`='2'
That works OK and shows a result where id=2. But i noticed that a string value of '2abc' in the query also returns the that row: a false positive. I'd rather have the query fail and signal that it could not find that id in mytable..
This could be circumvented by making sure the value is a valid integer before running the query, but i'd rather keep it string-compatible for future purposes.
This is well documented in the doc
https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html
Check for line
The reason for this is that there are many different strings that may
convert to the value 1, such as '1', ' 1', or '1a'.
So without explicit type cast it will convert the string to integer and in your case 2abc becomes 2 and 2=2 => true, this is called silent conversion
select '2ab'+0; => 2
but
select 'ab2'+0 => 0
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
CREATE TABLE 'test'.'sensor' (
'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
'time' TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
'value' VARCHAR( 10 ) NOT NULL
);
This is my code which I entered in phpMyAdmin. And when I pressed go I got the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''test'.'sensor' (
'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
'time' TIMES' at line 1
I have tried changing some statements but couldn't get the error.
MySQL uses backticks to escape identifiers, single and double quotes for strings.
In this case you should do:
CREATE TABLE `test`.`sensor` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`value` VARCHAR( 10 ) NOT NULL
);
It's worth noting that backticks are only strictly required when your name conflicts with a reserved keyword and even then many are only relevant in a specific context. Terms like ORDER or SELECT always need to be escaped, so using them for columns or table names is best avoided. Likewise, TIME is also a column type, so you may want to pick a different name.
Additionally the TIMESTAMP column type is quite limited, values can only exist in the range of 1970 to 2038, so using it is not recommended. The DATETIME type by comparison has a range of years 1000 to 9999, more than adequate for most needs. There's a few other quirks of TIMESTAMP worth keeping in mind, too, like automatic UTC conversion.
Check that which version of php and MySQL u are using i have face this problem but solved after research . this query is working on MySQL 5.5 or newer
and MariaDB 5.5 or newer
CREATE TABLE Ghee(
country_code char(1) NOT NULL default '',
description varchar(10) NOT NULL default '',
PRIMARY KEY (country_code)
)
I am not sure what is this error!
#1292 - Truncated incorrect DOUBLE value:
I don't have double value field or data!
I have wasted a whole hour trying to figure this out!
here is my query
INSERT INTO call_managment_system.contact_numbers
(account_id, contact_number, contact_extension, main_number, created_by)
SELECT
ac.account_id,
REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') AS Phone,
IFNULL(ta.ext, '') AS extention,
'1' AS MainNumber,
'2' AS created_by
FROM
cvsnumbers AS ta
INNER JOIN accounts AS ac ON ac.company_code = ta.company_code
WHERE
LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') ) = 10
here is my show create table for the table which the results are going into
CREATE TABLE `contact_numbers` (
`number_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`account_id` int(10) unsigned NOT NULL DEFAULT '0',
`person_id` int(11) NOT NULL DEFAULT '0',
`contact_number` char(15) NOT NULL,
`contact_extension` char(10) NOT NULL DEFAULT '',
`contact_type` enum('Primary','Direct','Cell','Fax','Home','Reception','Office','TollFree') NOT NULL DEFAULT 'Primary',
`contact_link` enum('Account','PDM','Other') NOT NULL DEFAULT 'Account',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 = inactive, 1=active',
`main_number` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 = main phone number',
`created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(11) NOT NULL,
`modified_on` datetime DEFAULT NULL,
`modified_by` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`number_id`),
KEY `account_id` (`account_id`),
KEY `person_id` (`person_id`)
) ENGINE=InnoDB AUTO_INCREMENT=534 DEFAULT CHARSET=utf8
This message means you're trying to compare a number and a string in a WHERE or ON clause. In your query, the only potential place where that could be occurring is ON ac.company_code = ta.company_code; either make sure they have similar declarations, or use an explicit CAST to convert the number to a string.
If you turn off strict mode, the error should turn into a warning.
I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and in between multiple fields during update, e.g.
update user
set token='lamblala',
accessverion='dummy' and
key='somekey'
where user = 'myself'
The problem in above query can be resolved by replacing and with comma(,)
I was facing the same issue. Trying to compare a varchar(100) column with numeric 1. Resulted in the 1292 error. Fixed by adding single quotes around 1 ('1').
Thanks for the explanation above
TL; DR
This might also be caused by applying OR to string columns / literals.
Full version
I got the same error message for a simple INSERT statement involving a view:
insert into t1 select * from v1
although all the source and target columns were of type VARCHAR. After some debugging, I found the root cause; the view contained this fragment:
string_col1 OR '_' OR string_col2 OR '_' OR string_col3
which presumably was the result of an automatic conversion of the following snippet from Oracle:
string_col1 || '_' || string_col2 || '_' || string_col3
(|| is string concatenation in Oracle). The solution was to use
concat(string_col1, '_', string_col2, '_', string_col3)
instead.
I've seen a couple cases where this error occurs:
1. using the not equals operator != in a where clause with a list of multiple or values
such as:
where columnName !=('A'||'B')
This can be resolved by using
where columnName not in ('A','B')
2. missing a comparison operator in an if() function:
select if(col1,col1,col2);
in order to select the value in col1 if it exists and otherwise show the value in col2...this throws the error; it can be resolved by using:
select if(col1!='',col1,col2);
When I received this error I believe it was a bug, however you should keep in mind that if you do a separate query with a SELECT statement and the same WHERE clause, then you can grab the primary ID's from that SELECT: SELECT CONCAT(primary_id, ',')) statement and insert them into the failed UPDATE query with conditions -> "WHERE [primary_id] IN ([list of comma-separated primary ID's from the SELECT statement)" which allows you to alleviate any issues being caused by the original (failed) query's WHERE clause.
For me, personally, when I was using quotes for the values in the "WHERE ____ IN ([values here])", only 10 of the 300 expected entries were being affected which, in my opinion, seems like a bug.
In my case it was a view (highly nested, view in view) insertion causing the error in mysql-5.6:
CREATE TABLE tablename AS
SELECT * FROM highly_nested_viewname
;
The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.
Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.
.where(`order.id IN (${orders})`);
If you have used CHECK CONSTRAINT on table for string field length
e.g: to check username length >= 8
use:
CHECK (CHAR_LENGTH(username)>=8)
instead of
CHECK (username>=8)
fix the check constraint if any have wrong datatype comparison
If you don't have double value field or data, maybe you should try to disable sql strict mode.
To do that you have to edit "my.ini" file located in MySQL installation folder, find "Set the SQL mode to strict" line and change the below line:
# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
to this, deleting "STRICT_TRANS_TABLES"
# Set the SQL mode to strict
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
After that, you have to restart MySQL service to enable this change.
To check the change, open the editor an execute this sql sentence:
SHOW VARIABLES LIKE 'sql_mode';
Very Important: Be careful of the file format after saving. Save it as "UTF8" and don't as "TFT8 with BOM" because the service will not restart.
This field type:
`id` int(10) NOT NULL auto_increment
...accepts does not accept value ('') on one server/database while another server/database accepts it.
Is there some kind of inconsistency somewhere in the setup? I tried different server versions - 5.1.52, 5.1.57, 5.5. How to make them consistent?
if your field is of autoincrement type then you should simply skip it.
for example
you need to insert a comment where id is 'autoincrement' field then:
$add="INSERT INTO comments (comment, author_id, article_id) VALUES
('".$comment."',".$authorID.",".$articleID." )";
$result=mysql_query($add)
...