unique
unique

Reputation: 1

Generating unique ID in postgres

Is there a way to generate an unique id in postgres? Suppose I have a two files:

file 1:
a, b, c
d, e, f

file2:
h, i, j
a, f, h

and I want to insert them into the same table (which should be possible because they have the same number of elements with same data type) but still be able to obtain them separately later. Can I get postgresql to generate an unique id for me?

Upvotes: 0

Views: 1483

Answers (4)

user533832
user533832

Reputation:

Yes, there is a way to generate an unique id in postgres. It sound like all you need is a sequence

For example:

create sequence file_id;


then use nextval('file_id') each time you load a file. Once you have used nextval('file_id'), you can use currval('file_id') to return the value without incrementing the sequence

Upvotes: 1

anon
anon

Reputation:

You sure can! You can create a loaded_files table and store the name of the file you're loading. Retrieve the id from loaded_files and use that to insert the data into your file_items table.

What you're asking for is a solution that is usually solved during data loading with either application code or else multiple SQL statements.

Upvotes: 1

Brian Showalter
Brian Showalter

Reputation: 4349

Would the solution at How to generate uuid with PostgreSQL 8.4.4 on Ubuntu 10.04? work for you?

Upvotes: 0

John Ledbetter
John Ledbetter

Reputation: 14213

Yes, assuming you want the unique Id to be the primary key:

CREATE TABLE my_table (id SERIAL PRIMARY KEY,
                       your_other_fields... );

The SERIAL specifier automatically does the following for you:

CREATE SEQUENCE my_seq START 1;
CREATE TABLE my_table (id integer PRIMARY KEY DEFAULT nextval('my_seq'));

Which will start your rows off with id = 1 and incrementing on each insert.

Upvotes: 0

Related Questions