im using mysql to make a table
CREATE TABLE school.student(
Std_id INT NOT NULL AUTO_INCREMENT,
Std_name CHAR(40) NOT NULL,
Std_Birth DATE,
Std_Group CHAR(2) check(Std_Group in ('G1', 'G2','G3','G4'))
);
and im trying to make the auto incrment start from 1000 and incrment by 2 (1000,1002,1004,1006.....) while using CREATE
You may try this solution.
CREATE TABLE school.student(
Std_id INT NOT NULL AUTO_INCREMENT,
Std_name CHAR(40) NOT NULL,
Std_Birth DATE,
Std_Group CHAR(2) check(Std_Group in ('G1', 'G2','G3','G4'))
) AUTO_INCREMENT = 1000;
set ##auto_increment_increment=2;
while, you set the value of ##auto_increment_increment it will
effect all over the database. Because, It's Global variable for
MySQL.
For setting starting value from 1000 you may need to set
AUTO_INCREMENT at the end of the Create Table syntax.
You can do it as follows :
INSERT INTO _students
(Std_id, Std_name, Std_Birth, Std_Group)
select case when count(Std_id) >= 1 then max(Std_id) + 2 else 1000 end as Std_id, 'test', '2022-10-10', 'G1'
from _students;
select case when count(Std_id) >= 1 then max(Std_id) + 2 else 1000 end : this will check if there are any records in your table, if not it will insert first with id 1000
Create table #autoincre
(
Std_id int not null Primary key identity (1000,2),
Std_name char(40) Not null,
Std_Birth date,
Std_Group char(2) check(Std_group in ('G1','G2','G3','G4'))
)
Drop table #autoincre
insert into #autoincre values('Ajay','2022-07-10','G1')
select * from #autoincre
You can start the auto_increment for a given table at 1000 with a table option:
CREATE TABLE school.student(
...
) AUTO_INCREMENT=1000;
Note that the next id generated will be one greater than the table option is set to, so it will generate value 1001. If you want it to include the value 1000, set the table option AUTO_INCREMENT=999.
Your other requirement is more difficult.
https://dev.mysql.com/doc/refman/8.0/en/replication-options-source.html#sysvar_auto_increment_increment says:
It is not possible to restrict the effects of these two variables to a single table; these variables control the behavior of all AUTO_INCREMENT columns in all tables on the MySQL server.
In other words, if you set auto_increment_increment=2, this will apply to all tables with an auto-increment column. It is not a per-table option.
You could set auto_increment_increment=2 as a session variable only before inserting into the student table, then set it back to the default before inserting to another table. That sounds like it will be error-prone, because you could forget to change the session variable.
Related
Based on my question above, I have a MySQL table called qrc_creation. This table consists of columns like id (auto increment), creation_code, and creation_name. For example, if I want to insert a new creation_name, the ID will auto 1. But, I also want the creation_code to become qrc_00000001, where 1 comes from ID.
Thus, can I know what is the query to do this? Thank you in advance!
You have two options. If you want, the column to autopopulate during insert, you can use MySQL generated columns while defining table schema. However, you cannot use Auto Increment column with this method.
CREATE TABLE `table_1` (
`id` INT(10) ZEROFILL NOT NULL,
`creation_name` VARCHAR(45) NOT NULL,
`creation_code` VARCHAR(55) GENERATED ALWAYS AS (CONCAT(`name`, '_', `id`)),
PRIMARY KEY (`id`));
If you don't want that dedicated column in your table, you can easily get calculated field on your SQL query by using a simple concat function.
SELECT
`id`, `creation_name`, CONCAT(`name`, '_', `id`) AS `creation_code`
FROM
table_1;
Hope it helps.
first of all you need to show your code so that stackoverflow community respond. But still i got your problem and given below is the solution-
CREATE TABLE qrc_creation
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
creation_code AS 'qrc' + RIGHT('0000000' + CAST(ID AS VARCHAR(7)), 7) PERSISTED,
creation_name varchar(255),
);
Select * from qrc_creation;
INSERT INTO qrc_creation(creation_name)
VALUES ('Monsen');
Select * from qrc_creation;
Hope you like my answer.
I want to create a column with default value as null and when any operation is performed it should change to 0. How do i do this in mysql database?
Here example how to add colum in existing table with default value
ALTER TABLE `test1` ADD `no` INT NULL DEFAULT NULL ;
When you call function then you have to write following query
UPDATE test1 SET `no` = '0' WHERE `test1`.`id` =your_id;
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
test_id INT,
cost FLOAT(5,2) DEFAULT NULL,
);
each time when you do some operation on that you need to update it as #Sadikhasan
or write a trigger that will update it to zero automatically.
if the operation you want to perform is read then write trigger on ON SELECT
if the operation you want to perform is update then write trigger on ON UPDATE
like wise for others.
My company has different type of invoices.
Example:
H00001/2013
.
.
.
H99999/2013
and
T00001/2013
.
.
.
T99999/2013
The problem is, the numbering is increasing for new year.
How can I make auto increment value reset for each new year?
This is my current code:
CREATE TABLE `invoices` (
`invoicenumber` mediumint unsigned NOT NULL auto_increment,
`invoicetype` enum('A','B') NOT NULL,
`date` date NOT NULL,
`client` varchar(100) NOT NULL,
PRIMARY KEY (invoicetype,invoicenumber)
) COMMENT='' ENGINE='MyISAM';
Hey if you are using any client application for database like MysqlWorkBench or MYSQL Query Browser
then you can do below steps to set AutoIncrement no -
Right click on Table and go to Alter Table
Select Options tab
Under that you can find Auto Increment label there you can reset the number.
You can reset auto increment value by using the ALTER TABLE statement. The syntax of the ALTER TABLE statement to reset auto increment value is as follows:
ALTER TABLE table_name AUTO_INCREMENT = VALUE;
EDITED:
If you don't want to run this query every year then you have other two option to do such thing as I am aware of this two.
Create cron job/windows scheduled job
As you are using MySql then there is Event Scheduler (Keep in mind this is added in MySql 5.1.6 not in previous versions of MySql)
In your DB table, you can reset the counter with the following code:
ALTER TABLE tablename AUTO_INCREMENT = 1
Perhaps you already found a solution and the answer I'm giving may not be useful, since it's been seven months. Returning to the topic, I noticed that you have a composed primary key with two columns (invoicetype,invoicenumber). So there can be no duplicates of pairs invoicetype,invoicenumber . If you reset the auto_increment every year there might be possible to have duplicate pairs like 'A',1 for two rows, one invoice from year 2013 and the other from year 2014. So you can eliminate that primary key to prevent the violation of the primary key constraint. You can instead define a primary key (any decent table has one) with an auto_incremented column to make every row unique. Then you can define an auto incrementation mechanism for the invoicenumber column (I will shall return to this issue). First I would define the invoice table like this:
CREATE TABLE `invoices` (
`id` int unsigned NOT NULL auto_increment,
`invoicenumber` mediumint unsigned NOT NULL,
`invoicetype` enum('A','B') NOT NULL,
`invoicedate` date NOT NULL, -- not recomended to use reserved words for column names like date
`client` varchar(100) NOT NULL,
PRIMARY KEY (id)
) COMMENT='' ENGINE='MyISAM';
Then I would define another table list_id :
CREATE TABLE `list_id` (
`id` int unsigned NOT NULL auto_increment,
`id_inc` int unsigned NOT NULL, -- number of invoice
`the_year` date NOT NULL, -- year corresponding to the number of invoice
PRIMARY KEY (id)
) COMMENT='' ENGINE='MyISAM';
The above table can be used to set the value of invoicenumber for the current row inserted in invoice table (1 if it is the first invoice of the year of invoicedate, the maximum value of id_inc (coresponding to the year of invoicedate) plus one, otherwise). The rows are completed using a trigger of type before insert for the invoice table. So, before I insert a new invoice, I have to determine the value of invoicenumber. It will be 1, if there are no records in table list_id with column the_year having the value equal to the year of the new invoice. In this case I can insert in table list_id a new record with the values (1,2014) (id_inc,year). It will be the maximum value of id_inc plus 1, if there are record(s) in table list_id with column the_year having the value equal to the year of the new invoice. In this case I can insert in table list_id a new record with the values (7,2014) (id_inc,year). The trigger looks like this:
CREATE TRIGGER `increment_or_reset_new_year`
BEFORE INSERT ON `invoices`
FOR EACH ROW
thisTrigger : begin
declare new_id_year int(11);
declare nr_invoices_year int(11);
declare new_invoice_begin int(11);
declare current_year_row int(11);
set current_year_row = year(new.invoice_date);
set nr_invoices_year = get_nr_invoices_year(current_year_row);
if(get_nr_invoices_year(current_year_row) < 1) then
set new.invoicenumber = 1;
insert into list_id(id_inc,the_year) values (1,current_year_row);
leave thisTrigger;
end if;
if(get_nr_invoices_year(current_year_row) >= 1) then
set new.invoicenumber = get_max_id(year(new.invoice_date)) + 1;
set new_id_year = get_max_id(year(new.invoice_date)) + 1;
insert into list_id(id_inc,the_year) values(new_id_year,year(new.invoice_date));
end if;
end;
There are 2 functions in the trigger. The first one determines the number of rows from the list_id table having the_year equal with the current invoice year (given as parameter):
create function get_nr_invoices_year(invoice_year int) returns int
begin
declare nr_invoices_year int(11);
select count(*) into nr_invoices_year from lista_id where the_year = invoice_year;
return nr_invoices_year;
end;
The second one determines the maximum value of id_inc from table list_id which has the coresponding value of the_year equal with the year of current invoice (given as parameter):
create function get_max_id(year_invoice int) returns int
begin
declare max_id_year int(11);
select max(id_inc) into max_id_year from invoices.lista_id where the_year =year_invoice;
return max_id_year;
end;
So I can have one trigger, two functions and one table which controls the incrementation of invoicenumber.
Hope this helps! It worked for me!
Scenario:
I have a table which references two foreign keys, and for each unique combination of these foreign keys, has its own auto_increment column. I need to implement a Composite Key that will help identify the row as unique using combination of these three (one foreign keys and one auto_increment column, and one other column with non-unique values)
Table:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no)
);
Of course, there has to be something wrong with my query, because of which the error thrown is:
ERROR 1075: Incorrect table definition; there can be only one auto
column and it must be defined as a key
What I am trying to achieve:
I have an Application Table (with app_id as its primary key), each Application has a set of Issues to be resolved, and each Application has multiple number of tests (so the test_id col)
The sr_no col should increment for unique app_id and test_id.
i.e. The data in table should look like:
The database engine is InnoDB.
I want to achieve this with as much simplicity as possible (i.e. avoid triggers/procedures if possible - which was suggested for similar cases on other Questions).
You can't have MySQL do this for you automatically for InnoDB tables - you would need to use a trigger or procedure, or user another DB engine such as MyISAM. Auto incrementing can only be done for a single primary key.
Something like the following should work
DELIMITER $$
CREATE TRIGGER xxx BEFORE INSERT ON issue_log
FOR EACH ROW BEGIN
SET NEW.sr_no = (
SELECT IFNULL(MAX(sr_no), 0) + 1
FROM issue_log
WHERE app_id = NEW.app_id
AND test_id = NEW.test_id
);
END $$
DELIMITER ;
You can do this with myISAM and BDB engines. InnoDB does not support this. Quote from MySQL 5.0 Reference Manual.
For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
I don't fully understand your increment requirement on the test_id column, but if you want an ~autoincrement sequence that restarts on every unique combination of (app_id, test_id), you can do an INSERT ... SELECT FROM the same table, like so:
mysql> INSERT INTO `issue_log` (`sr_no`, `app_id`, `test_id`, `issue_name`) SELECT
IFNULL(MAX(`sr_no`), 0) + 1 /* next sequence number */,
3 /* desired app_id */,
1 /* desired test_id */,
'Name of new row'
FROM `issue_log` /* specify the table name as well */
WHERE `app_id` = 3 AND `test_id` = 1 /* same values as in inserted columns */
This assumes a table definition with no declared AUTO_INCREMENT column. You're essentially emulating autoincrement behavior with the IFNULL(MAX()) + 1 clause, but the manual emulation works on arbitrary columns, unlike the built-in autoincrement.
Note that the INSERT ... SELECT being a single query ensures atomicity of the operation. InnoDB will gap-lock the appropriate index, and many concurrent processes can execute this kind of query while still producing non-conflicting sequences.
You can use a unique composite key for sr_no,app_id & test_id. You cannot use incremental in sr_no as this is not unique.
CREATE TABLE IF NOT EXISTS `issue_log` (
`sr_no` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`issue_name` varchar(255) NOT NULL,
UNIQUE KEY `app_id` (`app_id`,`test_id`,`sr_no`)
) ENGINE=InnoDB ;
I have commented out unique constraint violation in sql fiddle to demonstrate (remove # in line 22 of schema and rebuild schema )
This is what I wanted
id tenant
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
My current table definition is
CREATE TABLE `test_trigger` (
`id` BIGINT NOT NULL,
`tenant` varchar(255) NOT NULL,
PRIMARY KEY (`id`,`tenant`)
);
I created one table for storing the current id for each tenant.
CREATE TABLE `get_val` (
`tenant` varchar(255) NOT NULL,
`next_val` int NOT NULL,
PRIMARY KEY (`tenant`,`next_val`)
) ENGINE=InnoDB ;
Then I created this trigger which solve my problem
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE INSERT
ON test_trigger
FOR EACH ROW
BEGIN
UPDATE get_val SET next_val = next_val + 1 WHERE tenant = new.tenant;
set new.id = (select next_val from get_val where tenant=new.tenant);
END$$
DELIMITER ;
This approach will be thread safe also because any insertion for the same tenant will happen sequentially because of the update query in the trigger and for different tenants insertions will happen parallelly.
Just add key(sr_no) on auto-increment column:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no),
key (`sr_no`)
);
Why don't you try to change the position of declare fields as primary key, since when you use "auto_increment" it has to be referenced as the first. Like in the following example
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (sr_no,app_id, test_id)
);
How can I set a minimum length for my primary key ID which is auto incremented. Now the auto increment starts at 1 and goes up from there. However I would like the id to be at least 5 characters long. So it would start at 10001, 10002, 10003 etc
If you have the table, but not the column run the following code with the appropriate modifications:
ALTER TABLE MyTableName
ADD MyTableNameId INT NOT NULL AUTO_INCREMENT,
ADD INDEX (MyTableNameId);
If you have already created the column, you can do this:
ALTER TABLE MyTableName AUTO_INCREMENT = 10001;
Beginning with MySQL 5.0.3, InnoDB supports the AUTO_INCREMENT = N table option in CREATE TABLE and ALTER TABLE statements.
You can't define a length, but you can specify what value it starts with.
At declaration time:
CREATE TABLE test
(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
whatever VARCHAR(10),
...
) AUTO_INCREMENT = 100000;
Or, after declaring / at run time:
ALTER TABLE test AUTO_INCREMENT=200000;