how to add prefix in id column with autoincrement in sql? - mysql

i have multiple user like admin and vendor etc. Now i want to add prefix in id field value while inserting data like if use is admin then value of id field is "A_1" or user is vendor then the value should be "V_1", while id field is autoincremented.Anyone has idea about this please comment.Thank you.

you can do it with sequence and trigger
here is a working example
create table tbl_usertypes(
usertypes_id varchar2(50),
name varchar2(50),
usertype varchar2(50),
CONSTRAINT pk_usertypes_id PRIMARY KEY(usertypes_id)
);
desc tbl_usertypes;
CREATE SEQUENCE sq_usertypes_id START WITH 1;
create or replace trigger add_random_id
BEFORE INSERT ON tbl_usertypes
FOR EACH ROW
BEGIN
IF :NEW.usertype = 'admin' THEN
SELECT 'A_' || sq_usertypes_id.NEXTVAL INTO :NEW.usertypes_id FROM dual;
ELSE
SELECT 'B_' || sq_usertypes_id.NEXTVAL INTO :NEW.usertypes_id FROM dual;
END IF;
END;
INSERT INTO tbl_usertypes values(null,'hoax', 'admin');
INSERT INTO tbl_usertypes values(null,'hoax', 'user');
select * from tbl_usertypes;
and the result

For auto incrementing an ID you can read something about auto increment on sql:
Some example of Identity used to auto increment an ID used as a Primary Key:
CREATE TABLE Test_AutoIncrement(
ID int AUTO_INCREMENT,
Name varchar(50) NULL,
Something varchar(100) NOT NULL,
PRIMARY KEY(ID));
In this case you didn't have to specify the ID filed during any INSERT statement, SQL will manage that.
For example we have some records of this tabel like:
ID | Name | Something |
1 "Simo" "Foo"
2 "Fred" "Bar"
Now, we simulate an Insert statement on our Test_AutoIncrement table:
INSERT INTO Test_AutoIncrement
VALUES(
NULL,
"FooBar()"
);
Now our Table will be as follow:
ID | Name | Something |
1 "Simo" "Foo"
2 "Fred" "Bar"
3 NULL "FooBar()"
Remarks:
In the above case we start with ID=1 and it will increment it by 1 on every new record.
You can specify ID=0 in the insert if you want to start counting from zero but NO_AUTO_VALUE_ON_ZERO must be disabled from MySQL.

Related

Auto increment with prefix showing wrong after adding 1000 records

I have fields in the table which are id, name, employee_id. The id column is the primary key with auto increment.In this table,
I need one column which called employee_id start from A5001, A5002, A5003...and soon.
I tried below code.
Table
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
employee_id VARCHAR(30) NOT NULL DEFAULT '0'
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.employee_id = CONCAT('A', LPAD(LAST_INSERT_ID(), 4, '500'));
END$$
DELIMITER ;
Then just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('ABC'),('ZXD'),('POI');
Finally, I got my output.
1|ABC | A5001
2|ZXD | A5002
3|POI | A5003
and so on
Now My issue is, I inserted 1000 rows in the table so my id is 1000 but there is some issue with my employee_id because after getting the A5999 it starts from A1000 which is totally wrong I need continuously like A6000, A6001, A6002.. and so on
I think there is some issue with my trigger.
Would you help me out in this?
You can use mathematical addition instead of string padding:
SET NEW.employee_id = CONCAT('V', 5000 + LAST_INSERT_ID());
Explanation:
I'm just adding 5000 to last insert ID. Think of it:
1st ID would be 5000 + 1 = 5001
999th ID would be 5000 + 999 = 5999
1000th ID would be 5000 + 1000 = 6000
It will never throw an ID shorter than 4 digits, so there is no need of LPAD.
Warning: You have to think what do you want after 4999th insert. It will cause an ID of 5 digits (5000 + 5000 = 10000). If you don't have a problem with 5 digits, leave it this way.

How to insert if not exists with selecting from same table?

I have my table schema in H2 db as follows:
create table if not exists Test ( id bigint not null,name varchar(255), primary key (id) );
alter table Test add constraint if not exists Test_NAME UNIQUE (name);
I want to insert a value for the name attribute as 'Default' if it does not exist in the table by selecting the latest id value from the table and increment it by one.
Example:
Do not insert if an entry for name = Default already exists.
ID | Name
1 | Default
Insert if an entry for name = Default does not exists.
ID | Name
1 | ABC
2 | XYZ
For the id column, find the max id and increment it by one. In this case, insert id=3 and name=Default.
My query is as follows:
INSERT INTO Test (id , name)
SELECT max(id) + 1, 'Default' from Test
WHERE NOT EXISTS (SELECT * FROM Test where name='Default');
However, it gives me an error saying:
NULL not allowed for column "ID"; SQL statement
as it applies the where condition on the inner select statement.
I also tried:
MERGE INTO Test KEY(name) VALUES (SELECT MAX(id) + 1 from Test, 'Default');
It gives an error because, merge tries to update with the new values.
If it finds 'Default', it will update the row with new id causing primary key violation.
Is there a better way to do this? How can I make the query work?
You are massively overcomplicating this. Define the id field as auto increment and place a unique index on the name field. The unique index prevents duplicate names to be inserted, while the auto increment increases the value of the id field by 1 (by default) if the insert is successful.
I updated id to auto increment and the following query work flawlessly
INSERT INTO Test (name) select * from (select 'Default') as tmp WHERE NOT EXISTS (SELECT name from Test where name='Default');
when you run your query first time, no record found in table so, it give error 'null' there, so if you add IFNULL() function there as below
INSERT INTO Test (id , name)
SELECT **IFNULL**(max(id),0) + 1, 'Default'
FROM Test
WHERE NOT EXISTS (SELECT * FROM Test where name='Default');

Insert into Table by getting NextVal of Sequence in PostgreSQL

I have a table called SEQ_TABLE which has two columns, SEQ_NAME and ID
SEQ_NAME | ID
----------------------
SEQ_TABLE_10 | 1
SEQ_TABLE_20 | 5
Where ID is the Max of COLUMN_1 of TABLE_10 and TABLE_20
Now, I have to Insert new records into TABLE_10 by obtaining nextvalue of sequence from SEQ_TABLE.
I have written PostgreSQL query as follows:
INSERT INTO TABLE_10 (COLUMN_1, COLUMN_2, COLUMN_3) VALUES ((SELECT nextval(SEQ_TABLE)), 'Bangalore' ,NULL);
When I execute above Query, It is giving below error:
********** Error **********
ERROR: column "SEQ_TABLE_10" does not exist
SQL state: 42703
Character: 99
But, following Query works fine in MySQL Database:
INSERT INTO TABLE_TABLE(COLUMN_1, COLUMN_2, COLUMN_3) VALUES ((SELECT nextval('TABLE_172_SEQ','true')), 'Bangalore' ,NULL);
What is the Exact Postgres Query to achieve it in PostgreSQL DB?
You want to create a sequence, not a table(SEQ_TABLE)
Kindly refer this link
https://www.postgresql.org/docs/8.1/static/sql-createsequence.html
Eg.
CREATE SEQUENCE serial START 101;
SELECT nextval('serial');
create table MyTable(col1 int,col2 varchar(20));
INSERT INTO MyTable VALUES (nextval('serial'), 'nothing');
In current PostgreSQL versions you would use identity columns:
CREATE TABLE table_10 (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
other text NOT NULL
);
That will implicitly generate a sequence. You are not allowed to insert numbers into into id, but you have to
INSERT INTO table_10 (other) VALUES ('new');
or
INSERT INTO table_10 (id, other) VALUES (DEFAULT, 'new');
and id is automatically filled with the next value from the sequence.
On older PostgreSQL versions, you would use serial or bigserial:
CREATE TABLE table_10 (id serial PRIMARY KEY, other text NOT NULL);
Then id is of type integer, a sequence table_10_id_seq is created and a nextval call is added to the DEFAULT clause of the id column.
You can examine this with \d in psql:
\d table_10
Table "laurenz.table_10"
Column | Type | Modifiers
--------+---------+-------------------------------------------------------
id | integer | not null default nextval('table_10_id_seq'::regclass)
other | text | not null
Indexes:
"table_10_pkey" PRIMARY KEY, btree (id)
Moreover, the sequence belongs to the table and will be dropped automatically when the table is dropped.
You insert rows omitting the id column like this:
INSERT INTO table_10 (other) VALUES ('something');
Then the DEFAULT values will be used.
If you want to do the same thing “on foot”, for example to use a different name or different starting values for the sequence, that would work like this:
CREATE TABLE table_10 (id integer PRIMARY KEY, other text NOT NULL);
CREATE SEQUENCE table_10_id_seq OWNED BY table_10.id;
ALTER TABLE table_10 ALTER id SET DEFAULT nextval('table_10_id_seq');

How to set username using id in mysql

I have a database table in mysql
create table userstable
(
id int not null auto_increment,
name varchar(80) not null,
username varchar(80) not null,
primary key(id)
);
How to add new row in mysql database, so that username will be 'name'+('id'*100)
Example :
ID name username
1 A A100
2 B B200
3 C C300
4 user user400
You need trigger for that process. Create the following trigger
CREATE TRIGGER username_change
BEFORE INSERT ON userstable
FOR EACH ROW
BEGIN
SET NEW.username = CONCAT(NEW.name,(NEW.id*100));
END
OR
INSERT INTO userstable (id,name, username) VALUES (2, 'B', CONCAT(name,(id*100)));
Try this.
You'll need to write a trigger or update the field after insertion. A similar question provides more insight:
Can you access the auto increment value in MySQL within one statement?
As #ArunKrish correctly pointed out, you may use TRIGGER to update the data as part of the insert. Another option is to use view:
CREATE VIEW v1 AS
SELECT id,name,CONCAT(name,id*100) AS username FROM userstable;
You may also use the query as-is, without view:
SELECT id,name,CONCAT(name,id*100) AS username FROM userstable;

Mysql table with more than one Auto-Incremented column

I have a table with the following structure:
id | number | text
----------------------
1 | 1 | test
in which, id is my primary key with auto increment value. I want to make number as auto increment value too. Is it possible to have more than one auto increment column in one table?
It is not possible.There can be only one auto-increment column and it must be defined as a key in MySQL.
But You can do it by using trigger for detail go this link CREATE TRIGGER
create trigger nameTrigger before insert on tables
for each row
begin
DECLARE newNumber unsigned default 0;
SELECT Max(number)+1 INTO newNumber FROM myTable WHERE id = new.id;
UPDATE myTable SET number = newNumber WHERE id = new.id;
end