Snowflake: create a default field value that auto increments for each primary key, resets per primary key












0















I would like to create a table to house the following type of data



+--------+-----+----------+
| pk | ctr | name |
+--------+-----+----------+
| fish | 1 | herring |
| mammal | 1 | dog |
| mammal | 2 | cat |
| mammal | 3 | whale |
| bird | 1 | penguin |
| bird | 2 | ostrich |
+--------+----_+----------+


PK is the primary key string (100) not null
ctr is a field I want to auto increment by 1 for each pk row



I have tried the following



create or replace  table schema.animals (
pk string(100) not null primary key,
ctr integer not null default ( select NVL(max(ctr),0) + 1 from schema.animals )
name string (1000) not null);


This produced the following error




SQL compilation error: error line 6 at position 52 aggregate functions
are not allowed as part of the specification of a default value
clause.




So i would have used the auto increment /identity property like so



AUTOINCREMENT | IDENTITY [ ( start_num , step_num ) | START num INCREMENT num ]


but it doesnt seem to be able to support the resetting per unique pk



looking for any suggestions on how to solve this, thanks for any help in advance










share|improve this question



























    0















    I would like to create a table to house the following type of data



    +--------+-----+----------+
    | pk | ctr | name |
    +--------+-----+----------+
    | fish | 1 | herring |
    | mammal | 1 | dog |
    | mammal | 2 | cat |
    | mammal | 3 | whale |
    | bird | 1 | penguin |
    | bird | 2 | ostrich |
    +--------+----_+----------+


    PK is the primary key string (100) not null
    ctr is a field I want to auto increment by 1 for each pk row



    I have tried the following



    create or replace  table schema.animals (
    pk string(100) not null primary key,
    ctr integer not null default ( select NVL(max(ctr),0) + 1 from schema.animals )
    name string (1000) not null);


    This produced the following error




    SQL compilation error: error line 6 at position 52 aggregate functions
    are not allowed as part of the specification of a default value
    clause.




    So i would have used the auto increment /identity property like so



    AUTOINCREMENT | IDENTITY [ ( start_num , step_num ) | START num INCREMENT num ]


    but it doesnt seem to be able to support the resetting per unique pk



    looking for any suggestions on how to solve this, thanks for any help in advance










    share|improve this question

























      0












      0








      0








      I would like to create a table to house the following type of data



      +--------+-----+----------+
      | pk | ctr | name |
      +--------+-----+----------+
      | fish | 1 | herring |
      | mammal | 1 | dog |
      | mammal | 2 | cat |
      | mammal | 3 | whale |
      | bird | 1 | penguin |
      | bird | 2 | ostrich |
      +--------+----_+----------+


      PK is the primary key string (100) not null
      ctr is a field I want to auto increment by 1 for each pk row



      I have tried the following



      create or replace  table schema.animals (
      pk string(100) not null primary key,
      ctr integer not null default ( select NVL(max(ctr),0) + 1 from schema.animals )
      name string (1000) not null);


      This produced the following error




      SQL compilation error: error line 6 at position 52 aggregate functions
      are not allowed as part of the specification of a default value
      clause.




      So i would have used the auto increment /identity property like so



      AUTOINCREMENT | IDENTITY [ ( start_num , step_num ) | START num INCREMENT num ]


      but it doesnt seem to be able to support the resetting per unique pk



      looking for any suggestions on how to solve this, thanks for any help in advance










      share|improve this question














      I would like to create a table to house the following type of data



      +--------+-----+----------+
      | pk | ctr | name |
      +--------+-----+----------+
      | fish | 1 | herring |
      | mammal | 1 | dog |
      | mammal | 2 | cat |
      | mammal | 3 | whale |
      | bird | 1 | penguin |
      | bird | 2 | ostrich |
      +--------+----_+----------+


      PK is the primary key string (100) not null
      ctr is a field I want to auto increment by 1 for each pk row



      I have tried the following



      create or replace  table schema.animals (
      pk string(100) not null primary key,
      ctr integer not null default ( select NVL(max(ctr),0) + 1 from schema.animals )
      name string (1000) not null);


      This produced the following error




      SQL compilation error: error line 6 at position 52 aggregate functions
      are not allowed as part of the specification of a default value
      clause.




      So i would have used the auto increment /identity property like so



      AUTOINCREMENT | IDENTITY [ ( start_num , step_num ) | START num INCREMENT num ]


      but it doesnt seem to be able to support the resetting per unique pk



      looking for any suggestions on how to solve this, thanks for any help in advance







      sql database-design snowflake-datawarehouse






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 15:31









      Jay RizziJay Rizzi

      2,70642652




      2,70642652
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example



          CREATE TABLE dbo.animals ( 
          pk nvarchar(100) NOT NULL,
          ctr integer NOT NULL,
          name nvarchar(1000) NOT NULL,
          CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
          )
          GO

          CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
          AS
          BEGIN
          SET NOCOUNT ON;
          INSERT INTO animals (pk, ctr, name)
          SELECT
          i.pk,
          (ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
          i.name
          FROM inserted i
          LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
          ON i.pk = a.pk;
          END
          GO

          INSERT INTO dbo.animals (pk, name) VALUES
          ('fish' , 'herring'),
          ('mammal' , 'dog'),
          ('mammal' , 'cat'),
          ('mammal' , 'whale'),
          ('bird' , 'pengui'),
          ('bird' , 'ostrich');

          SELECT * FROM dbo.animals;


          Result



          pk      ctr   name
          ------- ----- ---------
          bird 1 ostrich
          bird 2 pengui
          fish 1 herring
          mammal 1 cat
          mammal 2 dog
          mammal 3 whale


          Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.






          share|improve this answer
























          • snowflake doesnt support triggers which makes things more difficult

            – Jay Rizzi
            Nov 20 '18 at 16:23











          • @JayRizzi ah ok, it's DBMS-specific, I misunderstood

            – serge
            Nov 20 '18 at 16:31



















          0














          I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:



          create or replace table schema.animals (
          animal_id int identity primary key,
          name string(100) not null primary key,
          );

          create view schema.v_animals as
          select a.*, row_number() over (partition by name order by animal_id) as ctr
          from schema.animals a;


          That is, calculate ctr when you need to use it, rather than storing it in the table.






          share|improve this answer
























          • pk is the primary key, its unfortunately a string, following a design doc given to me

            – Jay Rizzi
            Nov 20 '18 at 16:22











          • @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

            – Gordon Linoff
            Nov 20 '18 at 18:40











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396361%2fsnowflake-create-a-default-field-value-that-auto-increments-for-each-primary-ke%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example



          CREATE TABLE dbo.animals ( 
          pk nvarchar(100) NOT NULL,
          ctr integer NOT NULL,
          name nvarchar(1000) NOT NULL,
          CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
          )
          GO

          CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
          AS
          BEGIN
          SET NOCOUNT ON;
          INSERT INTO animals (pk, ctr, name)
          SELECT
          i.pk,
          (ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
          i.name
          FROM inserted i
          LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
          ON i.pk = a.pk;
          END
          GO

          INSERT INTO dbo.animals (pk, name) VALUES
          ('fish' , 'herring'),
          ('mammal' , 'dog'),
          ('mammal' , 'cat'),
          ('mammal' , 'whale'),
          ('bird' , 'pengui'),
          ('bird' , 'ostrich');

          SELECT * FROM dbo.animals;


          Result



          pk      ctr   name
          ------- ----- ---------
          bird 1 ostrich
          bird 2 pengui
          fish 1 herring
          mammal 1 cat
          mammal 2 dog
          mammal 3 whale


          Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.






          share|improve this answer
























          • snowflake doesnt support triggers which makes things more difficult

            – Jay Rizzi
            Nov 20 '18 at 16:23











          • @JayRizzi ah ok, it's DBMS-specific, I misunderstood

            – serge
            Nov 20 '18 at 16:31
















          0














          You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example



          CREATE TABLE dbo.animals ( 
          pk nvarchar(100) NOT NULL,
          ctr integer NOT NULL,
          name nvarchar(1000) NOT NULL,
          CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
          )
          GO

          CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
          AS
          BEGIN
          SET NOCOUNT ON;
          INSERT INTO animals (pk, ctr, name)
          SELECT
          i.pk,
          (ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
          i.name
          FROM inserted i
          LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
          ON i.pk = a.pk;
          END
          GO

          INSERT INTO dbo.animals (pk, name) VALUES
          ('fish' , 'herring'),
          ('mammal' , 'dog'),
          ('mammal' , 'cat'),
          ('mammal' , 'whale'),
          ('bird' , 'pengui'),
          ('bird' , 'ostrich');

          SELECT * FROM dbo.animals;


          Result



          pk      ctr   name
          ------- ----- ---------
          bird 1 ostrich
          bird 2 pengui
          fish 1 herring
          mammal 1 cat
          mammal 2 dog
          mammal 3 whale


          Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.






          share|improve this answer
























          • snowflake doesnt support triggers which makes things more difficult

            – Jay Rizzi
            Nov 20 '18 at 16:23











          • @JayRizzi ah ok, it's DBMS-specific, I misunderstood

            – serge
            Nov 20 '18 at 16:31














          0












          0








          0







          You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example



          CREATE TABLE dbo.animals ( 
          pk nvarchar(100) NOT NULL,
          ctr integer NOT NULL,
          name nvarchar(1000) NOT NULL,
          CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
          )
          GO

          CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
          AS
          BEGIN
          SET NOCOUNT ON;
          INSERT INTO animals (pk, ctr, name)
          SELECT
          i.pk,
          (ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
          i.name
          FROM inserted i
          LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
          ON i.pk = a.pk;
          END
          GO

          INSERT INTO dbo.animals (pk, name) VALUES
          ('fish' , 'herring'),
          ('mammal' , 'dog'),
          ('mammal' , 'cat'),
          ('mammal' , 'whale'),
          ('bird' , 'pengui'),
          ('bird' , 'ostrich');

          SELECT * FROM dbo.animals;


          Result



          pk      ctr   name
          ------- ----- ---------
          bird 1 ostrich
          bird 2 pengui
          fish 1 herring
          mammal 1 cat
          mammal 2 dog
          mammal 3 whale


          Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.






          share|improve this answer













          You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example



          CREATE TABLE dbo.animals ( 
          pk nvarchar(100) NOT NULL,
          ctr integer NOT NULL,
          name nvarchar(1000) NOT NULL,
          CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
          )
          GO

          CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
          AS
          BEGIN
          SET NOCOUNT ON;
          INSERT INTO animals (pk, ctr, name)
          SELECT
          i.pk,
          (ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
          i.name
          FROM inserted i
          LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
          ON i.pk = a.pk;
          END
          GO

          INSERT INTO dbo.animals (pk, name) VALUES
          ('fish' , 'herring'),
          ('mammal' , 'dog'),
          ('mammal' , 'cat'),
          ('mammal' , 'whale'),
          ('bird' , 'pengui'),
          ('bird' , 'ostrich');

          SELECT * FROM dbo.animals;


          Result



          pk      ctr   name
          ------- ----- ---------
          bird 1 ostrich
          bird 2 pengui
          fish 1 herring
          mammal 1 cat
          mammal 2 dog
          mammal 3 whale


          Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 16:13









          sergeserge

          61047




          61047













          • snowflake doesnt support triggers which makes things more difficult

            – Jay Rizzi
            Nov 20 '18 at 16:23











          • @JayRizzi ah ok, it's DBMS-specific, I misunderstood

            – serge
            Nov 20 '18 at 16:31



















          • snowflake doesnt support triggers which makes things more difficult

            – Jay Rizzi
            Nov 20 '18 at 16:23











          • @JayRizzi ah ok, it's DBMS-specific, I misunderstood

            – serge
            Nov 20 '18 at 16:31

















          snowflake doesnt support triggers which makes things more difficult

          – Jay Rizzi
          Nov 20 '18 at 16:23





          snowflake doesnt support triggers which makes things more difficult

          – Jay Rizzi
          Nov 20 '18 at 16:23













          @JayRizzi ah ok, it's DBMS-specific, I misunderstood

          – serge
          Nov 20 '18 at 16:31





          @JayRizzi ah ok, it's DBMS-specific, I misunderstood

          – serge
          Nov 20 '18 at 16:31













          0














          I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:



          create or replace table schema.animals (
          animal_id int identity primary key,
          name string(100) not null primary key,
          );

          create view schema.v_animals as
          select a.*, row_number() over (partition by name order by animal_id) as ctr
          from schema.animals a;


          That is, calculate ctr when you need to use it, rather than storing it in the table.






          share|improve this answer
























          • pk is the primary key, its unfortunately a string, following a design doc given to me

            – Jay Rizzi
            Nov 20 '18 at 16:22











          • @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

            – Gordon Linoff
            Nov 20 '18 at 18:40
















          0














          I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:



          create or replace table schema.animals (
          animal_id int identity primary key,
          name string(100) not null primary key,
          );

          create view schema.v_animals as
          select a.*, row_number() over (partition by name order by animal_id) as ctr
          from schema.animals a;


          That is, calculate ctr when you need to use it, rather than storing it in the table.






          share|improve this answer
























          • pk is the primary key, its unfortunately a string, following a design doc given to me

            – Jay Rizzi
            Nov 20 '18 at 16:22











          • @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

            – Gordon Linoff
            Nov 20 '18 at 18:40














          0












          0








          0







          I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:



          create or replace table schema.animals (
          animal_id int identity primary key,
          name string(100) not null primary key,
          );

          create view schema.v_animals as
          select a.*, row_number() over (partition by name order by animal_id) as ctr
          from schema.animals a;


          That is, calculate ctr when you need to use it, rather than storing it in the table.






          share|improve this answer













          I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:



          create or replace table schema.animals (
          animal_id int identity primary key,
          name string(100) not null primary key,
          );

          create view schema.v_animals as
          select a.*, row_number() over (partition by name order by animal_id) as ctr
          from schema.animals a;


          That is, calculate ctr when you need to use it, rather than storing it in the table.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 16:15









          Gordon LinoffGordon Linoff

          767k35300402




          767k35300402













          • pk is the primary key, its unfortunately a string, following a design doc given to me

            – Jay Rizzi
            Nov 20 '18 at 16:22











          • @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

            – Gordon Linoff
            Nov 20 '18 at 18:40



















          • pk is the primary key, its unfortunately a string, following a design doc given to me

            – Jay Rizzi
            Nov 20 '18 at 16:22











          • @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

            – Gordon Linoff
            Nov 20 '18 at 18:40

















          pk is the primary key, its unfortunately a string, following a design doc given to me

          – Jay Rizzi
          Nov 20 '18 at 16:22





          pk is the primary key, its unfortunately a string, following a design doc given to me

          – Jay Rizzi
          Nov 20 '18 at 16:22













          @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

          – Gordon Linoff
          Nov 20 '18 at 18:40





          @JayRizzi . . . pk s a component of a compound primary key. Hence, "it" is not the primary key.

          – Gordon Linoff
          Nov 20 '18 at 18:40


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396361%2fsnowflake-create-a-default-field-value-that-auto-increments-for-each-primary-ke%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          'app-layout' is not a known element: how to share Component with different Modules

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          WPF add header to Image with URL pettitions [duplicate]