Reputation:
I have a question about primary keys in postgre or mysql.
So:
In mongodb the ids are not integers, they are some unique values like "507f191e810c19729de860ea". This helps when you want to synchronize records from multiple ids. They will never match (or the chances are little). So I can get a record from one database and insert it in my database without conflicts in the id primary key constraint.
So my question is there are similar functionality in Postgre SQL or MySQL databases.
I know I can generate the id with php/nodejs/python but I prefer to use something automatic and simple from the database itself.
I can make my procedure/function in the database but I avoid that - I want the database to handle this automatically (like mongodb does it).
Are there any downsides of this approach?
Upvotes: 1
Views: 1175
Reputation: 311228
In PostgreSQL, you can generate UUID.
First, you need to make sure you have the extension installed:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
and then use the uuid_generate_v4
function to generate a UUID
. If you don't want to have to remember to insert it every time, you can just define it as the default value of your primary key:
CREATE TABLE mytable (
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
-- other columns as needed...
);
Upvotes: 1
Reputation: 1353
You can use SERIAL as follows:
CREATE TABLE table_name(
id SERIAL
);
This is like a auto increment in SQL.
Upvotes: 0