How to set varchar primary key field in Mysql
Table structure of Users table
CREATE TABLE `users` (
`id` varchar(36) NOT NULL DEFAULT 'InitiallyEmpty',
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Want to fill id an automatically filled. You need to create trigger
Trigger structure for automatically update
DROP trigger if exists before_insert_users;
delimiter $$
CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
SET new.id = uuid();
END $$
delimiter ;
Now create insert query
insert into users (first_name,last_name,email,password) values ('Sudhir','Pandey','psudhir20@gmail.com','123465');
Table structure of Users table
CREATE TABLE `users` (
`id` varchar(36) NOT NULL DEFAULT 'InitiallyEmpty',
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Want to fill id an automatically filled. You need to create trigger
Trigger structure for automatically update
DROP trigger if exists before_insert_users;
delimiter $$
CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
SET new.id = uuid();
END $$
delimiter ;
Now create insert query
insert into users (first_name,last_name,email,password) values ('Sudhir','Pandey','psudhir20@gmail.com','123465');

This article provides a practical example of using a VARCHAR field as a primary key in MySQL and automatically generating UUIDs with a BEFORE INSERT trigger. This approach can be useful when applications require unique identifiers instead of traditional auto-incrementing integer IDs. Understanding database design and key generation is important when building reliable, scalable applications.
ReplyDeleteDevelopers working with Python applications can benefit from learning how to map database tables to Python models and manage database operations efficiently. The SQLAlchemy Course is relevant for understanding ORM concepts and integrating Python applications with relational databases.
Beyond individual database operations, understanding data modeling, data pipelines, and database integration is valuable for building robust data-driven systems. The Data Engineering Course is another relevant learning resource for developers interested in strengthening their data engineering skills.
ReplyDelete