0

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?

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to do it without creating an additional table?
Sure, you'll just have to generate it in the application layer and insert it into the file... The filename itself would be a good one to insert. Of course, you'll be inserting a good chunk of additional data. What you're describing is a great case for basic database normalization.
1

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

Comments

0

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.

1 Comment

I don't want it to increment on each insert. I want all the rows from the same file to have the same id so that I can later retrieve all the entries from a particular file with something like SELECT * FROM example WHERE uid = 5 (if 5 is the unique id).
0

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

1 Comment

Umm.. not really. I also want to be able to print the unique id generated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.