10

In PostgreSQL we can define a column as SERIAL to auto increment it with insert query.

Can this auto increment happen by scoping to another column value ?

I will explain my question with below example.

In a multi tenant SaaS application, there could be a scenario where we may need to increment a column (say item_id column in items table) per user account.

Example:items table

item_id | account_id

100 | 1

101 | 1

102 | 1

100 | 2

sorry for the bad formatting of the table. I hope you got idea about the basic structure.

In the above example, as soon as a new item is created by a new account (say account 2), the item_id serial count should start from the beginning again i.e 100.

If user in account 1 deletes item_id 102 and creates a new item record, then item_id should set to 103 and so on.

I tried to find a solution but I could not get a pointer using Google search. So any help would be highly appreciated!

PS: I know this can be handled from backend code but I am more curious to know if database has a solution for this or not.

1
  • 2
    Did you find any appropriate solution? I have similar issue Commented Feb 13, 2022 at 15:48

1 Answer 1

3

You can't define SERIAL to be partitioned over other column. But you could use ROW_NUMBER() function. If you don't need that value materialized you could write something like:

CREATE VIEW v_item_table
AS
SELECT *, 
 ROW_NUMBER() OVER(PARTITION BY item_id ORDER BY some_timestamp_col) AS account_id
FROM item_table;
Sign up to request clarification or add additional context in comments.

Comments

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.