Specific field parameter when creating a table MySQL - mysql

I'm using MySQL Workbench.
I would like to create a table named courseInfo and I want to put a column named moduleCode in it, but I want it to always be similar in format: CFSM H0000 where the four zeros are a number that increases starting with 0000.
For example:
CFSM H0001
CFSM H0002
[..]

You cannot auto-increment character type columns in MySQL, as auto-increment is only possible on integer type columns. One (alphanumeric) auto-incrementing moduleCode column would therefore not be possible. However, you could try splitting up the moduleCode into two columns, for example like so:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
KEY (`id`)
) AUTO_INCREMENT = 0;
Where prefix could for example be "CFSM H" and id could be 0001
Then, upon executing SELECT statements, you could merge the prefix column with the id column into a moduleCode column with CONCAT, e.g.:
SELECT CONCAT(`prefix`, `id`) as `moduleCode` FROM `courseInfo`;
An alternative approach (from MySQL version 5.7 and up) seems to be the use of a generated column, for example:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10) AS (CONCAT(`prefix`, `id`)),
KEY (`id`)
) AUTO_INCREMENT = 0;
However, the above example of a generated column would not work, because moduleCode is dependent on an auto-increment column, and the auto-increment is not executed yet at the time the generated column is computed. See also: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. It would throw an ER_GENERATED_COLUMN_REF_AUTO_INC error.
You could therefore use the first solution, or try to add moduleCode as a column and use an AFTER INSERT trigger to update its value:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10),
KEY (`id`),
UNIQUE KEY `unique_index` (`prefix`,`id`)
) AUTO_INCREMENT = 0;
DELIMITER //
CREATE TRIGGER `addModuleCode` AFTER INSERT ON `courseInfo`
FOR EACH ROW
BEGIN
UPDATE `courseInfo` SET `moduleCode` = CONCAT(NEW.`prefix`, NEW.`id`) WHERE `prefix` = NEW.`prefix` AND `id` = NEW.`id`;
END;//
DELIMITER ;

Related

SQL AUTO_INCREMENT starting at number

am on a MySQL database and am using MySQL workbench.
here's my table DDL
CREATE TABLE `contract_validator` (
`id` bigint(20) NOT NULL,
`created` datetime(6) NOT NULL,
`user_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I want to make an id column in a table auto_increment, i did so using
SET FOREIGN_KEY_CHECKS = 0;
ALTER TABLE validator MODIFY id bigint AUTO_INCREMENT;
SET FOREIGN_KEY_CHECKS = 1;
I have two issues, i want to set the auto_increment to max(id) + 1
i have tried:
SELECT #validator_id := max(id) + 1 FROM validator;
ALTER TABLE validator AUTO_INCREMENT = #validator_id ;
but i get syntax error,
the second issue is that when i try to insert a line i get an error
Error Code: 1364. Field 'id' doesn't have a default value
I don't know what I did wrong,
thank you for your help.
Normally, you don't have to take care of AUTO_inCREMENT value.
When you update id column to make it auto increment, MySQL will automatically set AUTO_INCREMENT value to the MAX + 1 value, event if there are gaps in in column numerotation.
SQL for setting auto increment on id field:
ALTER TABLE `test` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT, add PRIMARY KEY (`id`);

How to use more than 1 auto-increment column in MySQL

I want to create a table name Users where I should have have columns User, cookieID, sessionID, Geo and then I want to first three columns to have some random unique value assigned automatically. I tried to make all three columns AUTO_INCREMENT with User column PRIMARY and 'cookieIDandsessionIDcolumnUNIQUE`. The SQL code is:
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL AUTO_INCREMENT ,
`cookieID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL ,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
But, it did not work because only one column can be declared as AUTO_INCREMENT which must be PRIMARY.
What is the another approach to do this?
Since the auto-increment cannot be applied to multiple to rows and there no option for sequence in MySQL. You can use triggers for the unique update of the row with datetime.
Change to table creation to be of single auto-increment row.
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL,
`cookieID` INT(20) NULL DEFAULT NULL,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
Create a trigger on the same table as below. You can set the unique values under the SET for as many column as you want.
CREATE DEFINER=`root`#`localhost` TRIGGER `users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW BEGIN
SET
NEW.cookieID = (SELECT curdate()+curtime());
END
Now when you insert into the table as below.
insert into `users`(`User`) values("test");
You table looks like this.
User cookieID sessionID Geo
test 20315169 0 NULL
If the value which are auto incrementing, you wanna keep both values the same. Then copy the value of one column to another during insertion time of new value.

Hash of two columns in mysql

I have a MYSQL table, with 5 columns in it:
id bigint
name varchar
description varchar
slug
Can I get MySQL to automatically generate the value of slug as a 256 Bit Hash of name+description?
I am now using PHP to generate an SHA256 value of the slug prior to saving it.
Edit:
By automatic, I mean see if it's possible to change the default value of the slug field, to be a computed field that's the sha256 of name+description.
I already know how to create it as part of an insert operation.
MySQL 5.7 supports generated columns so you can define an expression, and it will be updated automatically for every row you insert or update.
CREATE TABLE IF NOT EXISTS MyTable (
id int NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
description varchar(50) NOT NULL,
slug varchar(64) AS (SHA2(CONCAT(name, description), 256)) STORED NOT NULL,
PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;
If you use an earlier version of MySQL, you could do this with TRIGGERs:
CREATE TRIGGER MySlugIns BEFORE INSERT ON MyTable
FOR EACH ROW SET slug = SHA2(CONCAT(name, description));
CREATE TRIGGER MySlugUpd BEFORE UPDATE ON MyTable
FOR EACH ROW SET slug = SHA2(CONCAT(name, description), 256);
Beware that concat returns NULL if any one column in the input is NULL. So, to hash in a null-safe way, use concat_ws. For example:
select md5(concat_ws('', col_1, .. , col_n));
Use MySQL's CONCAT() to combine the two values and SHA2() to generate a 256 bit hash.
CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`description` varchar(50) NOT NULL,
`slug` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `mytable` (`name`,`description`,`slug`)
VALUES ('Fred','A Person',SHA2(CONCAT(`name`,`description`),256));
SELECT * FROM `mytable`
OUTPUT:
COLUMN VALUE
id 1
name Fred
description A Person
slug ea76b5b09b0e004781b569f88fc8434fe25ae3ad17807904cfb975a3be71bd89
Try it on SQLfiddle.

Inserting data into newly created column MySQL

I have been successful in adding a new column to my table in MySQL. However I can't seem to add any data to it. I have tried using an UPDATE but I get an error. I am including the original code for the table, and the ALTER that added the column and the attempted update.
CREATE TABLE `Teams` (
`Team_id` INTEGER unsigned NULL AUTO_INCREMENT DEFAULT NULL,
`team name` VARCHAR(50) NULL DEFAULT NULL,
`league` CHAR(2) NULL DEFAULT NULL,
`div` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`Team_id`)
);
the filling (abbreviated)
INSERT INTO `Teams` (`team name`,`league`,`div`) VALUES
('Free Agent','',''),
('Blue Jays','AL','East'),
('Yankees','AL','East'),
('Orioles','AL','East'),
...and so on
The ALTER:
ALTER TABLE Teams
ADD City VARCHAR(20);
The UPDATE:
UPDATE Teams
SET City='NONE' where (team name='Free Agent');
You should escape identifiers if they contain spaces:
UPDATE `Teams`
SET `City`='NONE' where (`team name`='Free Agent');

alter table statment to insert duplicate into another table

I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.