MySQL inserting same value - mysql

I stumbled upon weird behavior in MySQL.
Lets say that I have only one record in table
| id | oib |
|----|-----|
| 1 | 5 |
Field oib is unique.
INSERT INTO `test` (`id`, `oib`) VALUES (NULL, '6')
I get following exception
Duplicate entry '5' for key 'oib_UNIQUE'
And this keeps going on no matter what value I try to save.
Anyone have idea what could cause this. I've never seen it.
UPDATE:
Here is CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS `user` (
`id` int(25) NOT NULL AUTO_INCREMENT,
`email` varchar(45) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`dob` int(25) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`zip` int(6) DEFAULT NULL,
`oib` int(11) DEFAULT NULL,
`position` tinyint(4) DEFAULT NULL,
`role` varchar(45) DEFAULT NULL,
`status` tinyint(4) DEFAULT NULL,
`note` mediumtext,
PRIMARY KEY (`id`),
UNIQUE KEY `email_UNIQUE` (`email`),
UNIQUE KEY `oib_UNIQUE` (`oib`)
)

You cannot insert null value in id primary key

Are you sure your table have one record for oib = '5' ?
You cannot insert null into primary key.

Related

Slow query with NULL IS NULL OR condition syntax using Mysql 5.7

I'm getting some strange timing values from Mysql running a "simple" query.
This is the DDL of the table:
CREATE TABLE `frame` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`createdBy` varchar(255) DEFAULT NULL,
`createdDate` datetime(6) NOT NULL,
`lastModifiedBy` varchar(255) DEFAULT NULL,
`lastModifiedDate` datetime(6) DEFAULT NULL,
`sid` varchar(36) NOT NULL,
`version` bigint(20) NOT NULL,
`brand` varchar(255) DEFAULT NULL,
`category` varchar(255) DEFAULT NULL,
`colorCode` varchar(255) DEFAULT NULL,
`colorDescription` varchar(255) DEFAULT NULL,
`description` longtext,
`imageUrl` varchar(255) DEFAULT NULL,
`lastPurchase` datetime(6) DEFAULT NULL,
`lastPurchasePrice` decimal(19,2) DEFAULT NULL,
`lastSell` datetime(6) DEFAULT NULL,
`lastSellPrice` decimal(19,2) DEFAULT NULL,
`line` varchar(255) DEFAULT NULL,
`manufacturer` varchar(255) DEFAULT NULL,
`manufacturerCode` varchar(255) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`preset` bit(1) NOT NULL DEFAULT b'0',
`purchasePrice` decimal(19,2) DEFAULT NULL,
`salesPrice` decimal(19,2) DEFAULT NULL,
`sku` varchar(255) NOT NULL,
`stock` bit(1) NOT NULL DEFAULT b'1',
`thumbUrl` varchar(255) DEFAULT NULL,
`upc` varchar(255) DEFAULT NULL,
`arm` int(11) DEFAULT NULL,
`bridge` int(11) DEFAULT NULL,
`caliber` int(11) DEFAULT NULL,
`gender` varchar(255) DEFAULT NULL,
`lensColor` varchar(255) DEFAULT NULL,
`material` varchar(255) DEFAULT NULL,
`model` varchar(255) NOT NULL,
`sphere` decimal(10,2) DEFAULT NULL,
`type` varchar(255) NOT NULL,
`taxRate_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_k7s4esovkoacsc264bcjrre13` (`sid`),
UNIQUE KEY `UK_ajh6mr6a6qg6mgy8t9nevdym1` (`sku`),
UNIQUE KEY `UK_boqikmg9o89j8q0o5ujkj33b3` (`upc`),
KEY `idx_manufacturer` (`manufacturer`),
KEY `idx_brand` (`brand`),
KEY `idx_line` (`line`),
KEY `idx_colorcode` (`colorCode`),
KEY `idx_preset` (`preset`),
KEY `idx_manufacturer_model_color_caliber` (`manufacturer`,`model`,`colorCode`,`caliber`),
KEY `FK1nau29fd70s1nq905dgs6ft85` (`taxRate_id`),
CONSTRAINT `FK1nau29fd70s1nq905dgs6ft85` FOREIGN KEY (`taxRate_id`) REFERENCES `taxrate` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=392179 DEFAULT CHARSET=utf8;
The query is created programatically from my application. The "strange" syntax (NULL IS NULL OR condition) is very convenient to me in order to make more compact my code and removing the need to create a different query based on the numbers of parameters.
For who understand how Hibernate HQL and JPA works, this is the query:
This query is generated when the user is not setting any filter, so all parameters in my condition are null and this is how the query comes out.
SELECT SQL_NO_CACHE COUNT(frame0_.`id`) AS col_0_0_ FROM `Frame` frame0_
WHERE (NULL IS NULL OR NULL LIKE CONCAT('%', NULL, '%') OR frame0_.`manufacturer` LIKE CONCAT('%', NULL, '%') OR frame0_.`manufacturerCode`=NULL OR frame0_.`sku`=NULL OR frame0_.`upc`=NULL OR frame0_.`line` LIKE CONCAT('%', NULL, '%') OR frame0_.`model` LIKE CONCAT('%', NULL, '%')) AND (NULL IS NULL OR frame0_.`manufacturer`=NULL) AND (NULL IS NULL OR frame0_.`line`=NULL) AND (NULL IS NULL OR frame0_.`caliber`=NULL) AND (NULL IS NULL OR frame0_.`type`=NULL) AND (NULL IS NULL OR frame0_.`material`=NULL) AND (NULL IS NULL OR frame0_.`model`=NULL) AND (NULL IS NULL OR frame0_.`colorCode`=NULL)
The query takes about 0.105s on a table of 137548 rows.
The EXPLAIN of the previous query returns:
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE frame0_ \N ALL \ N \N \N \N 137548 100.00 \N
The previous query is identical to this one:
SELECT SQL_NO_CACHE COUNT(frame0_.`id`) AS col_0_0_ FROM `Frame` frame0_
This query takes just 0.05s for the same result in the same table.
Why for Mysql they are different and the first is taking so much time? Is there a way to improve performance of the first query keeping the syntax "NULL IS NULL or condition"?
I think Ryan has right, so the many or statement made the query so bad.
You should programatically build queries for better performance. So if the user not select by a possible filter, than you shouldn't include to the query!
(HQL)
if(!StringUtils.isEmpty(manufacturer)) {
query.and(m.manufacturer.eq(manufacturer))
}

MySQL use separate indices for JOIN and GROUP BY

I am trying to execute following query
SELECT
a.sessionID AS `sessionID`,
firstSeen, birthday, gender,
isAnonymous, LanguageCode
FROM transactions AS trx
INNER JOIN actions AS a ON a.sessionID = trx.SessionID
WHERE a.ActionType = 'PURCHASE'
GROUP BY trx.TransactionNumber
Explain provides the following output
1 SIMPLE trx ALL TransactionNumber,SessionID NULL NULL NULL 225036 Using temporary; Using filesort
1 SIMPLE a ref sessionID sessionID 98 infinitiExport.trx.SessionID 1 Using index
The problem is that I am trying to use one field for join and different field for GROUP BY.
How can I tell MySQL to use different indices for same table?
CREATE TABLE `transactions` (
`SessionID` varchar(32) NOT NULL DEFAULT '',
`date` datetime DEFAULT NULL,
`TransactionNumber` varchar(32) NOT NULL DEFAULT '',
`CustomerECommerceTrackID` int(11) DEFAULT NULL,
`SKU` varchar(45) DEFAULT NULL,
`AmountPaid` double DEFAULT NULL,
`Currency` varchar(10) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`Name` tinytext NOT NULL,
`Category` varchar(45) NOT NULL DEFAULT '',
`customerInfoXML` text,
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `TransactionNumber` (`TransactionNumber`),
KEY `SessionID` (`SessionID`)
) ENGINE=InnoDB AUTO_INCREMENT=212007 DEFAULT CHARSET=utf8;
CREATE TABLE `actions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`sessionActionDate` datetime DEFAULT NULL,
`actionURL` varchar(255) DEFAULT NULL,
`sessionID` varchar(32) NOT NULL DEFAULT '',
`ActionType` varchar(64) DEFAULT NULL,
`CustomerID` int(11) DEFAULT NULL,
`IPAddressID` int(11) DEFAULT NULL,
`CustomerDeviceID` int(11) DEFAULT NULL,
`customerInfoXML` text,
PRIMARY KEY (`id`),
KEY `ActionType` (`ActionType`),
KEY `CustomerDeviceID` (`CustomerDeviceID`),
KEY `sessionID` (`sessionID`)
) ENGINE=InnoDB AUTO_INCREMENT=15042833 DEFAULT CHARSET=utf8;
Thanks
EDIT 1: My indexes were broken, I had to add (SessionID, TransactionNumber) index to transactions table, however now, when I try to include trx.customerInfoXML table mysql stops using index
EDIT 2 Another answer does not really solved my problem because it's not standard sql syntax and generally not a good idea to force indices.
For ORM users such syntax is a unattainable luxury.
EDIT 3 I updated my indices and it solved the problem, see EDIT 1

Long time to exec a simple query in mysql

I am with a performance problem in my MySQL database, and do not know if it's the server configuration issue or disk space, or simply not riding the query correctly.
a simple query that summarizes the total number of rows in a table by a distinct field, it takes more than 3 minutes. The status is "Sending data" for a long time.
the query is as follows:
SELECT COUNT (DISTINCT (ca.nm_slug)) the qtd_total
FROM consulta_atual ca
WHERE ca.cd_categoria_site = 436
below the description of the table (has a 4 million records)
CREATE TABLE IF NOT EXISTS `consulta_atual` (
`cd_categoria` int(11) NOT NULL DEFAULT '0',
`cd_categoria_site` int(11) DEFAULT NULL,
`ds_categoria` varchar(100) NOT NULL,
`ds_subcategoria` varchar(200) NOT NULL,
`cd_produto_price` bigint(11) NOT NULL,
`cd_seq` bigint(20) NOT NULL DEFAULT '0',
`tp_fornecedor` int(11) NOT NULL DEFAULT '0',
`name` varchar(300) NOT NULL,
`nm_slug` varchar(200) DEFAULT NULL,
`fornecedor` int(11) NOT NULL,
`url_img_fornecedor` varchar(200) NOT NULL,
`url_raiz_fornecedor` varchar(200) NOT NULL,
`url_imagem` varchar(500) NOT NULL,
`url_produto` varchar(500) NOT NULL,
`vlr_produto` varchar(49) NOT NULL DEFAULT '',
`pnt_produto` varchar(53) NOT NULL DEFAULT '',
`vlr_produto_original` float(10,2) NOT NULL,
`menor_valor` float DEFAULT NULL,
`maior_valor` float DEFAULT NULL,
`qtd_lojas` int(11) DEFAULT NULL,
PRIMARY KEY (`cd_produto_price`,`fornecedor`),
KEY `nm_slug_2` (`nm_slug`),
KEY `ds_categoria` (`ds_categoria`),
KEY `vlr_produto_original` (`vlr_produto_original`),
KEY `cd_categoria_site` (`cd_categoria_site`),
KEY `fornecedor` (`fornecedor`),
KEY `tp_fornecedor` (`tp_fornecedor`),
FULLTEXT KEY `name` (`name`),
FULLTEXT KEY `ds_categoria_2` (`ds_categoria`),
FULLTEXT KEY `ds_categoria_3` (`ds_categoria`,`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
How can I improve execution performance of this simple query?

why Mysql is giving me error 1280 "Wrong Index"

Can anyone explain why Mysql is giving me error 1280 ("wrong index for 'fk_chart_aid_aid' ") error whend I try to create the "CHART OF ACCOUNTS" table. I'm completly confused here. How can I fix this so I can create the table? The "ACCOUNT" table already exists in the database and has data in it.
Thanks for the help.
MYSQL Server version: 5.1.54
CHART OF ACCOUNTS:
DROP TABLE IF EXISTS `rst`.`acctg_chart_of_accounts` ;
CREATE TABLE IF NOT EXISTS `rst`.`acctg_chart_of_accounts` (
`acctg_chart_of_accounts_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`account_id` INT UNSIGNED NOT NULL ,
`account_nbr` VARCHAR(45) NULL ,
`description` VARCHAR(45) NULL ,
`account_type` INT UNSIGNED NULL ,
`commissionable` TINYINT UNSIGNED NULL ,
`hidden` TINYINT UNSIGNED NULL ,
`deduct_balance_from_owner_check` TINYINT UNSIGNED NULL ,
PRIMARY KEY (`acctg_chart_of_accounts_id`) ,
CONSTRAINT `fk_chart_aid_aid`
FOREIGN KEY (`account_id` )
REFERENCES `rst`.`account` (`account_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE INDEX `fk_chart_aid_aid` ON `rst`.`acctg_chart_of_accounts` (`account_id` ASC) ;
ACCOUNTS TABLE THAT IS BEING REFERENCED:
CREATE TABLE IF NOT EXISTS `account` (
`account_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`account_status_id` int(10) unsigned NOT NULL,
`company_name` varchar(155) DEFAULT NULL,
`address1` varchar(155) DEFAULT NULL,
`address2` varchar(155) DEFAULT NULL,
`city` varchar(155) DEFAULT NULL,
`state` varchar(155) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
`work_phone` varchar(45) DEFAULT NULL,
`mobile_phone` varchar(45) DEFAULT NULL,
`time_zone` varchar(45) DEFAULT NULL,
`subdomain` varchar(155) DEFAULT NULL,
`cname_URL` varchar(255) DEFAULT NULL,
`promotion_code` varchar(45) DEFAULT NULL,
`can_we_contact_you` tinyint(4) DEFAULT NULL COMMENT '0=false, 1=true',
`units_managed_nbr` varchar(10) DEFAULT NULL,
`a_hear_about_us_list_id` tinyint(3) unsigned DEFAULT NULL COMMENT 'populated from dropdown list.',
`receive_special_offers` tinyint(4) DEFAULT NULL,
`receive_announcements` tinyint(4) DEFAULT NULL,
`receive_newsletter` tinyint(4) DEFAULT NULL,
`create_ts` timestamp NULL DEFAULT NULL,
`expires` timestamp NULL DEFAULT NULL,
`storage_capacity` varchar(255) DEFAULT NULL COMMENT '1073741824 = 1GB',
`logo` varchar(455) DEFAULT NULL,
`max_active_connections` int(11) DEFAULT '3',
`_product_id` int(11) DEFAULT NULL,
`report_footer` varchar(455) DEFAULT NULL,
`welcome_dialog` tinyint(4) DEFAULT '1',
`ARB_subscription_id` int(11) DEFAULT NULL,
`trashbin` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`account_id`),
KEY `fk_account_account_status_id` (`account_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=58 ;
Are you getting the error after the CREATE TABLE statement, or after the subsequent CREATE INDEX?
Looks like you are attempting to name both a FOREIGN KEY constraint and an INDEX fk_chart_aid_aid. Try choosing a different name for either one of them.
Also, in the accounts table, account_id is INT(10). Try also to change the column definition in acctg_chart_of_accounts to:
`account_id` INT(10) UNSIGNED NOT NULL ,
Though, I think that mysql defaults type INT to INT(10) anyway...
I met the same issue; tried manually rename the index to a different name but don't like the idea of 'manually' and neither I don't really understand why we need to generate the index separately. so I decide to generate it within the create statement by unchecking the option of 'generate separate index statement' in 'forwarding engineer', and this fix the issue.

Unexpected behaviour of the query

This particular query is supposed to enter the user into the database.
This query does not always insert the values of the firstname and the lastname fields along with others. firstname and lastname are empty for a few insertions and for the others its working as expected.
INSERT INTO `users` (mobile, passwordHash, firstname, lastname, ent_id, email )
VALUES ('913800341127', '678a1491514b7f1006d605e9161946b1', 'nat', 'sam', '108', NULL)
ON DUPLICATE KEY UPDATE `firstname` = VALUES(firstname),`lastname` = VALUES(lastname)
Related Info:
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`tag` varchar(5) NOT NULL default 'ind',
`username` varchar(50) default NULL,
`firstname` varchar(100) default NULL,
`lastname` varchar(100) default NULL,
`passwordhash` varchar(255) NOT NULL,
`secretq` varchar(255) default NULL,
`secreta` varchar(100) default NULL,
`email` varchar(50) default NULL,
`mobile` varchar(13) default NULL,
`last_login` datetime default NULL,
`ent_id` bigint(20) NOT NULL default '1',
`is_inactive` tinyint(1) NOT NULL COMMENT 'Whether the user is active or not',
PRIMARY KEY (`id`),
UNIQUE KEY `mobile_2` (`mobile`,`ent_id`),
UNIQUE KEY `email_2` (`email`,`ent_id`),
KEY `username` (`username`),
KEY `ent_id` (`ent_id`,`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
syntax error it should be :
ON DUPLICATE KEY UPDATE firstname = 'nat',lastname = 'sam'