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.

dp7
  • 6,651
  • 1
  • 18
  • 37

1 Answers1

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;
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275