How to auto increment in phpmydamin with custom number and character string - mysql

How can I set my custom value in auto increment column when insert query fire in phpMyAdmin
I want like when I insert a data in MySQL at that time the auto increment column value add with like something ABC001 and next record will be ABC002
It there any way to setup this functionality
This is my table structure
I want new code for every insert query for red mark field

Yes, you can use a TRIGGER like this:
CREATE DEFINER=`root`#`localhost` TRIGGER `setDrinkk` BEFORE INSERT ON `yourTable`
FOR EACH ROW BEGIN
SET NEW.DrinkCode = CONCAT('ABC-', LPAD(NEW.db_id,4,'0'));
END

You'll have to add 2 more fields to the table..One field(eg:drink_text)containing the text 'ABC' and other field (Eg:drink_no) with autoincrement.
Set default value of drink_text as ABC.
Set autoincrement primary key for drink_no
ALTER TABLE tablename AUTO_INCREMENT=101;
Now in insert query you have to concatenate both the fields to drink_code
//your insert query
INSERT INTO tablename( user_id,club_id) VALUES ('xyz','abc');
//drink_code with custom string
UPDATE tablename SET drink_code = concat( drink_text, drink_no ) ;

Related

How to make unique incrementing counter in MySQL

How to assign unique auto incrementing values to a certain column? Kind of like AUTO_INCREMENT does but it should be NULL at the time of insertion and assigned at some later point.
I have a table that gets regular data inserts and a few workers that process that data and set processed_at datetime field when they're done. Now I want incrementally select new processed rows since the last call. If I naively use where processed_at > #last_update_time I'm afraid there might be a situation where some records are processed at the same second and I miss some rows.
update: Can I just do
begin;
select #max := max(foo) from table1;
update table1 set foo = #max + 1 where id = 'bar' limit 1;
commit;
if foo column is indexed?
You can use a trigger to implement that.
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
CREATE TRIGGER pk AFTER UPDATE ON your_table_name
BEGIN
UPDATE my_increment
SET value = value + 1
WHERE table_name = 'your_table_name';
UPDATE your_table_name
SET ID2 = (
SELECT value
FROM my_increment
WHERE table_name = 'your_table_name')
WHERE ROWID = new.ROWID;
END;
But bear in mind that this trigger will work on every execution of the Update query.
You can also do it manually:
Create the table to store increment value:
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
Then when you want to update the table, get the last value from this table and insert value+1 to your column needed to be incremented.

Two autoincrements columns or autoincrement and same value in other column

I need two columns in table that would have same value on insert. Is there any way to do it from database side?
So you want to let one column use the auto_increment feature, but make another column in the same table also have the same value?
I can't think of a reason you would need this feature. Perhaps you could explain what you're trying to accomplish, and I can suggest a different solution?
A trigger won't work for this. It's a chicken-and-egg problem:
You can't change any column's value in an AFTER trigger.
But the auto-increment value isn't set yet when a BEFORE trigger executes.
It also won't work to use a MySQL 5.7 GENERATED column:
CREATE TABLE MyTable (
id INT AUTO_INCREMENT PRIMARY KEY,
why_would_you_want_this INT GENERATED ALWAYS AS (id)
);
ERROR 3109 (HY000): Generated column 'why_would_you_want_this'
cannot refer to auto-increment column.
You can't do it in a single SQL statement. You have to INSERT the row, and then immediately do an UPDATE to set your second column to the same value.
CREATE TABLE MyTable (
id INT AUTO_INCREMENT PRIMARY KEY,
why_would_you_want_this INT
);
INSERT INTO MyTable () VALUES ();
UPDATE MyTable SET why_would_you_want_this = LAST_INSERT_ID()
WHERE id = LAST_INSERT_ID();
You could alternatively generate the ID value using some other mechanism besides AUTO_INCREMENT (for example a Memcached incrementing key). Then you could insert the new value in both columns:
INSERT INTO MyTable (id, why_would_you_want_this) VALUES ($gen_id, $gen_id);
Define a before or after insert trigger and assign the value of the 2nd field in the trigger.
If the 1st field is an auto increment column, then you need to use an after insert trigger. If your application assigns value to the 1st field, then you can use a before insert trigger.
However, I would no necessarily duplicate the value on insert. You can leave the 2nd field as null on insert, which would mean that its value is the same as the 1st field's. The only drawback of this approach is that it may be more difficult to create joins on the 2nd field.
You can do this in one query by using the primary key (assumed to be id) and setting your column (assumed to be columnName):
"INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1"
This will not work if you have deleted the most recent primary key row however. To get past this, you can insert into the id as well:
"INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1, `id`= (SELECT MAX(x.id) FROM tableName x)+1"
However, this solution has the downside (or upside depending on the case) of reusing primary key values that have already been deleted.
suggested way:
To use the actual auto_increment value, you can do this:
"INSERT INTO tableName SET `columnName` = (SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'table_name')"
Sources that helped me solve this: Prashant Pimpale's answer

how to create a trigger in concatenating a auto_increment value column and a column that has a default value

DELIMITER $$
CREATE DEFINER=`root`#`localhost` TRIGGER `grade_one_BINS`
BEFORE INSERT ON `grade_one` FOR EACH ROW
set new.student_no = concat(new.letter, ' - ',new.num)
there is a problem in concatenating the num column that has auto increment value since the trigger is for before insert cause it will show a 0 value since the auto increment is still 0 until you insert some values...can you help me???
I suggest you don't store data again in another column that you already have in the num and letter columns.
You can generate the student_no column on-the-fly in your selects like this
select *,
concat(letter, ' - ', num) as student_no
from your_table

Computed field value based on other column while insertion

I have a table where I have an ID column(primary key auto increment) and one more column for name.
I want to fill name column's value automatically while insertion based on generated ID column value in format
<IDColumnValue>_School
I am aware of the two ways to do this
using trigger
inserting the row first and then update its column value based on the inserted row id column value
But actually I want to make this field Non Nullable but to use the second option I will have to make it nullable.
Is there any direct way to do this while inserting row so that I can have the field non nullable?
As I said in the comment, you can use a temporary value for the name column. You can use a request like :
INSERT INTO `table` VALUES('', 'name') /*let's assume name is the real name you want to insert*/
I'm not sure then how to use a trigger, but you may want to write something like this :
delimiter #
CREATE TRIGGER update_name_after_insert INSERT ON `table`
for each row
begin
update `table` set name = CONCAT_WS("_", id, name)
end#
It work for firebird but I think it must work in MySQL because MySQL have new/old operators. Bellow trigger for table XYZ with fields B and C (not null).
CREATE OR ALTER trigger xyz_bi0 for xyz
active before insert position 0
AS
begin
new.c=new.b||' some text';--this construction must work in MySQL
end

Trigger to insert percentage value in a table based on the values of two different fields

I have a table 'attendance' having 3 fields 'class_total','class_attended' and 'attendance_percent'.
I want to insert/update the value of 'attendance_percent' whenever values are inserted/updated in the fields 'class_total' and 'class_attended' by (class_attended/class_total)*100.
For this I am using the trigger:
CREATE TRIGGER percent_update
BEFORE INSERT ON attendance
FOR EACH ROW
SET NEW.attendance_percent =(attendance.class_attended/attendance.class_total)*100 ;
But its not working.
Use a NEW clause instead of table name -
...
SET NEW.attendance_percent = (NEW.class_attended/NEW.class_total)
...