Can CURRENT_TIMESTAMP be used as a PRIMARY KEY?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
4
down vote

favorite












Can CURRENT_TIMESTAMP be used as a PRIMARY KEY?



Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP?







share|improve this question

















  • 2




    I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
    – Victor Di Leo
    20 hours ago











  • Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
    – Akina
    17 hours ago






  • 1




    n°32 of falsehoods programmers believe about time
    – Neyt
    8 hours ago
















up vote
4
down vote

favorite












Can CURRENT_TIMESTAMP be used as a PRIMARY KEY?



Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP?







share|improve this question

















  • 2




    I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
    – Victor Di Leo
    20 hours ago











  • Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
    – Akina
    17 hours ago






  • 1




    n°32 of falsehoods programmers believe about time
    – Neyt
    8 hours ago












up vote
4
down vote

favorite









up vote
4
down vote

favorite











Can CURRENT_TIMESTAMP be used as a PRIMARY KEY?



Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP?







share|improve this question













Can CURRENT_TIMESTAMP be used as a PRIMARY KEY?



Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP?









share|improve this question












share|improve this question




share|improve this question








edited 20 hours ago









Erwin Brandstetter

83.8k8148253




83.8k8148253









asked 23 hours ago









John Puskin

243




243







  • 2




    I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
    – Victor Di Leo
    20 hours ago











  • Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
    – Akina
    17 hours ago






  • 1




    n°32 of falsehoods programmers believe about time
    – Neyt
    8 hours ago












  • 2




    I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
    – Victor Di Leo
    20 hours ago











  • Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
    – Akina
    17 hours ago






  • 1




    n°32 of falsehoods programmers believe about time
    – Neyt
    8 hours ago







2




2




I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
– Victor Di Leo
20 hours ago





I heard of an app that was coded using timestamp as a PK, back in the 1990's. Ten years later PCs became faster and timestamps were duplicated. This caused very serious problems, as the app's functionality was highly critical. Also, PK uniqueness was not properly enforced throughout the app.
– Victor Di Leo
20 hours ago













Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
– Akina
17 hours ago




Is there a possibility that two or more different INSERTs, get the same CURRENT_TIMESTAMP? It's enough one query inserted 2 records for collision. So the answer for a subject question is "NO".
– Akina
17 hours ago




1




1




n°32 of falsehoods programmers believe about time
– Neyt
8 hours ago




n°32 of falsehoods programmers believe about time
– Neyt
8 hours ago










3 Answers
3






active

oldest

votes

















up vote
11
down vote













As per the documentation, the precision of the CURRENT_TIMESTAMP is microseconds. Thus, the probability of a collision is low, but possible.



Now imagine a bug which happens very rarely, and causes database errors. How hard is to debug it? It is a far worser bug than one which is at least deterministic.



The more broad context: you probably want to avoid these little nuances with the sequences, which is particularly annoying if you are accustomed to MySQL.



Furthermore, if you are using transactions (most web frameworks, particularly the Java ones, do!), then the timestamps will be the same inside a transaction! A demonstration:



postgres=# begin;
BEGIN
postgres=# select current_timestamp;
current_timestamp
-------------------------------
2018-08-06 02:41:42.472163+02
(1 Zeile)

postgres=# select current_timestamp;
current_timestamp
-------------------------------
2018-08-06 02:41:42.472163+02
(1 Zeile)


See you? Two selects, exactly the same result. I don't type so fast. ;-)



--



If you want easily IDs, avoiding the usage of the sequences, then generate some hash value from the real identifiers of the records. For example, if your database has humans, and you know that their birthdate, mother's maiden name and real name uniquely identifies them, then use an



md5(mother_name || '-' || given_name || '-' birthday);


as id. Beside that, you can use a CreationDate column, after what you index the table, but it is not a key (which is the id).





P.s. In general, it is a very good practice to make your DB so deterministic, as it is possible. I.e. the same operation should create exactly the same change in the DB. Any timestamp-based ID fails this important feature. What if you want to debug or simulate anything? You replay an operation and the same object will be created with a different id... it is really not hard to follow, and it spares a lot of work hours.



P.s.2 Anybody checking your code in the future, won't have the best opinion seeing timestamp-generated ids, on the reasons above.








share|improve this answer























  • Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
    – Kevin
    16 hours ago






  • 2




    I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
    – Balazs Gunics
    7 hours ago










  • @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
    – peterh
    5 hours ago










  • @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
    – peterh
    4 hours ago

















up vote
8
down vote













Not really because it’s possible for CURRENT_TIMESTAMP to provide two identical values for two subsequent INSERTs (or a single INSERT with multiple rows).



Use a time-based UUID instead: uuid_generate_v1mc().






share|improve this answer




























    up vote
    5
    down vote













    Strictly speaking: No. Because CURRENT_TIMESTAMP is a function and only one or more table columns can form a PRIMARY KEY constraint.



    If you mean to create a PRIMARY KEY constraint on a column with the default value CURRENT_TIMESTAMP, then the answer is: Yes, you can. Nothing keeps you from doing it, like nothing keeps you from shooting apples from your son's head. The question still wouldn't make sense while you don't define the purpose of it. What kind of data are column and table supposed to hold? What rules are you trying to implement?



    Typically, the idea is bound to run into duplicate key errors since CURRENT_TIMESTAMP is a STABLE function returning the same value for the same transaction (the start time of the transaction). Multiple INSERTs in the same transaction are bound to collide - like other answers already illustrated. The manual:




    Since these functions return the start time of the current
    transaction, their values do not change during the transaction. This
    is considered a feature: the intent is to allow a single transaction
    to have a consistent notion of the “current” time, so that multiple
    modifications within the same transaction bear the same time stamp.




    Postgres timestamps are implemented as 8-byte integers representing up to 6 fractional digits (microsecond resolution).



    If you are building a table that is supposed to hold no more than one row per microsecond and that condition is not going to change (something named sensor_reading_per_microsecond), then it might make sense. Duplicate rows are supposed to raise a duplicate key violation error. That's an exotic exception, though. And the data type timestamptz (not timestamp) would probably be preferable. See:



    • Ignoring time zones altogether in Rails and PostgreSQL

    I would still rather use a surrogate serial primary key instead. And add a UNIQUE constraint on the timestamp column. Fewer possible complications, not relying on implementation details of the RDBMS.






    share|improve this answer























      Your Answer







      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "182"
      ;
      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',
      convertImagesToLinks: false,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );








       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f214110%2fcan-current-timestamp-be-used-as-a-primary-key%23new-answer', 'question_page');

      );

      Post as a guest






























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      11
      down vote













      As per the documentation, the precision of the CURRENT_TIMESTAMP is microseconds. Thus, the probability of a collision is low, but possible.



      Now imagine a bug which happens very rarely, and causes database errors. How hard is to debug it? It is a far worser bug than one which is at least deterministic.



      The more broad context: you probably want to avoid these little nuances with the sequences, which is particularly annoying if you are accustomed to MySQL.



      Furthermore, if you are using transactions (most web frameworks, particularly the Java ones, do!), then the timestamps will be the same inside a transaction! A demonstration:



      postgres=# begin;
      BEGIN
      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)

      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)


      See you? Two selects, exactly the same result. I don't type so fast. ;-)



      --



      If you want easily IDs, avoiding the usage of the sequences, then generate some hash value from the real identifiers of the records. For example, if your database has humans, and you know that their birthdate, mother's maiden name and real name uniquely identifies them, then use an



      md5(mother_name || '-' || given_name || '-' birthday);


      as id. Beside that, you can use a CreationDate column, after what you index the table, but it is not a key (which is the id).





      P.s. In general, it is a very good practice to make your DB so deterministic, as it is possible. I.e. the same operation should create exactly the same change in the DB. Any timestamp-based ID fails this important feature. What if you want to debug or simulate anything? You replay an operation and the same object will be created with a different id... it is really not hard to follow, and it spares a lot of work hours.



      P.s.2 Anybody checking your code in the future, won't have the best opinion seeing timestamp-generated ids, on the reasons above.








      share|improve this answer























      • Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
        – Kevin
        16 hours ago






      • 2




        I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
        – Balazs Gunics
        7 hours ago










      • @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
        – peterh
        5 hours ago










      • @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
        – peterh
        4 hours ago














      up vote
      11
      down vote













      As per the documentation, the precision of the CURRENT_TIMESTAMP is microseconds. Thus, the probability of a collision is low, but possible.



      Now imagine a bug which happens very rarely, and causes database errors. How hard is to debug it? It is a far worser bug than one which is at least deterministic.



      The more broad context: you probably want to avoid these little nuances with the sequences, which is particularly annoying if you are accustomed to MySQL.



      Furthermore, if you are using transactions (most web frameworks, particularly the Java ones, do!), then the timestamps will be the same inside a transaction! A demonstration:



      postgres=# begin;
      BEGIN
      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)

      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)


      See you? Two selects, exactly the same result. I don't type so fast. ;-)



      --



      If you want easily IDs, avoiding the usage of the sequences, then generate some hash value from the real identifiers of the records. For example, if your database has humans, and you know that their birthdate, mother's maiden name and real name uniquely identifies them, then use an



      md5(mother_name || '-' || given_name || '-' birthday);


      as id. Beside that, you can use a CreationDate column, after what you index the table, but it is not a key (which is the id).





      P.s. In general, it is a very good practice to make your DB so deterministic, as it is possible. I.e. the same operation should create exactly the same change in the DB. Any timestamp-based ID fails this important feature. What if you want to debug or simulate anything? You replay an operation and the same object will be created with a different id... it is really not hard to follow, and it spares a lot of work hours.



      P.s.2 Anybody checking your code in the future, won't have the best opinion seeing timestamp-generated ids, on the reasons above.








      share|improve this answer























      • Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
        – Kevin
        16 hours ago






      • 2




        I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
        – Balazs Gunics
        7 hours ago










      • @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
        – peterh
        5 hours ago










      • @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
        – peterh
        4 hours ago












      up vote
      11
      down vote










      up vote
      11
      down vote









      As per the documentation, the precision of the CURRENT_TIMESTAMP is microseconds. Thus, the probability of a collision is low, but possible.



      Now imagine a bug which happens very rarely, and causes database errors. How hard is to debug it? It is a far worser bug than one which is at least deterministic.



      The more broad context: you probably want to avoid these little nuances with the sequences, which is particularly annoying if you are accustomed to MySQL.



      Furthermore, if you are using transactions (most web frameworks, particularly the Java ones, do!), then the timestamps will be the same inside a transaction! A demonstration:



      postgres=# begin;
      BEGIN
      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)

      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)


      See you? Two selects, exactly the same result. I don't type so fast. ;-)



      --



      If you want easily IDs, avoiding the usage of the sequences, then generate some hash value from the real identifiers of the records. For example, if your database has humans, and you know that their birthdate, mother's maiden name and real name uniquely identifies them, then use an



      md5(mother_name || '-' || given_name || '-' birthday);


      as id. Beside that, you can use a CreationDate column, after what you index the table, but it is not a key (which is the id).





      P.s. In general, it is a very good practice to make your DB so deterministic, as it is possible. I.e. the same operation should create exactly the same change in the DB. Any timestamp-based ID fails this important feature. What if you want to debug or simulate anything? You replay an operation and the same object will be created with a different id... it is really not hard to follow, and it spares a lot of work hours.



      P.s.2 Anybody checking your code in the future, won't have the best opinion seeing timestamp-generated ids, on the reasons above.








      share|improve this answer















      As per the documentation, the precision of the CURRENT_TIMESTAMP is microseconds. Thus, the probability of a collision is low, but possible.



      Now imagine a bug which happens very rarely, and causes database errors. How hard is to debug it? It is a far worser bug than one which is at least deterministic.



      The more broad context: you probably want to avoid these little nuances with the sequences, which is particularly annoying if you are accustomed to MySQL.



      Furthermore, if you are using transactions (most web frameworks, particularly the Java ones, do!), then the timestamps will be the same inside a transaction! A demonstration:



      postgres=# begin;
      BEGIN
      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)

      postgres=# select current_timestamp;
      current_timestamp
      -------------------------------
      2018-08-06 02:41:42.472163+02
      (1 Zeile)


      See you? Two selects, exactly the same result. I don't type so fast. ;-)



      --



      If you want easily IDs, avoiding the usage of the sequences, then generate some hash value from the real identifiers of the records. For example, if your database has humans, and you know that their birthdate, mother's maiden name and real name uniquely identifies them, then use an



      md5(mother_name || '-' || given_name || '-' birthday);


      as id. Beside that, you can use a CreationDate column, after what you index the table, but it is not a key (which is the id).





      P.s. In general, it is a very good practice to make your DB so deterministic, as it is possible. I.e. the same operation should create exactly the same change in the DB. Any timestamp-based ID fails this important feature. What if you want to debug or simulate anything? You replay an operation and the same object will be created with a different id... it is really not hard to follow, and it spares a lot of work hours.



      P.s.2 Anybody checking your code in the future, won't have the best opinion seeing timestamp-generated ids, on the reasons above.









      share|improve this answer















      share|improve this answer



      share|improve this answer








      edited 14 hours ago


























      answered 21 hours ago









      peterh

      73911028




      73911028











      • Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
        – Kevin
        16 hours ago






      • 2




        I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
        – Balazs Gunics
        7 hours ago










      • @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
        – peterh
        5 hours ago










      • @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
        – peterh
        4 hours ago
















      • Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
        – Kevin
        16 hours ago






      • 2




        I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
        – Balazs Gunics
        7 hours ago










      • @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
        – peterh
        5 hours ago










      • @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
        – peterh
        4 hours ago















      Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
      – Kevin
      16 hours ago




      Even if you are not using transactions, you are in fact using transactions (because Postgres doesn't have a no-transactions mode, it just has autocommit). So if you do an INSERT of multiple rows, they all get the same current_timestamp. And then you have triggers...
      – Kevin
      16 hours ago




      2




      2




      I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
      – Balazs Gunics
      7 hours ago




      I have heard about an app that broke because of the 2 guys had the same name and born on the same day and their mother names were identical. Ouch. If it CAN happen it WILL happen, sooner or later.
      – Balazs Gunics
      7 hours ago












      @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
      – peterh
      5 hours ago




      @BalazsGunics Helló :-) It was just an example. For example, in real scenarios, I think id as email address or the chosen user name (which can be registered only if it doesn't exist yet) is enough. Government tends to use some personal identification number, like 1 870728 0651. The important thing is, binding an id to a timestamp or to a random value is imho a bad practice, because it makes the DB lesser deterministic.
      – peterh
      5 hours ago












      @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
      – peterh
      4 hours ago




      @BalazsGunics Beside that, two people with the same mother_name + given_name + birthday, it would cause still a deterministic error. Primary key collision due to that two transactions having inserts happened in in the same microsecond, it still a non-deterministic, and very hardly reproducable problem.
      – peterh
      4 hours ago












      up vote
      8
      down vote













      Not really because it’s possible for CURRENT_TIMESTAMP to provide two identical values for two subsequent INSERTs (or a single INSERT with multiple rows).



      Use a time-based UUID instead: uuid_generate_v1mc().






      share|improve this answer

























        up vote
        8
        down vote













        Not really because it’s possible for CURRENT_TIMESTAMP to provide two identical values for two subsequent INSERTs (or a single INSERT with multiple rows).



        Use a time-based UUID instead: uuid_generate_v1mc().






        share|improve this answer























          up vote
          8
          down vote










          up vote
          8
          down vote









          Not really because it’s possible for CURRENT_TIMESTAMP to provide two identical values for two subsequent INSERTs (or a single INSERT with multiple rows).



          Use a time-based UUID instead: uuid_generate_v1mc().






          share|improve this answer













          Not really because it’s possible for CURRENT_TIMESTAMP to provide two identical values for two subsequent INSERTs (or a single INSERT with multiple rows).



          Use a time-based UUID instead: uuid_generate_v1mc().







          share|improve this answer













          share|improve this answer



          share|improve this answer











          answered 20 hours ago









          Linas

          2363




          2363




















              up vote
              5
              down vote













              Strictly speaking: No. Because CURRENT_TIMESTAMP is a function and only one or more table columns can form a PRIMARY KEY constraint.



              If you mean to create a PRIMARY KEY constraint on a column with the default value CURRENT_TIMESTAMP, then the answer is: Yes, you can. Nothing keeps you from doing it, like nothing keeps you from shooting apples from your son's head. The question still wouldn't make sense while you don't define the purpose of it. What kind of data are column and table supposed to hold? What rules are you trying to implement?



              Typically, the idea is bound to run into duplicate key errors since CURRENT_TIMESTAMP is a STABLE function returning the same value for the same transaction (the start time of the transaction). Multiple INSERTs in the same transaction are bound to collide - like other answers already illustrated. The manual:




              Since these functions return the start time of the current
              transaction, their values do not change during the transaction. This
              is considered a feature: the intent is to allow a single transaction
              to have a consistent notion of the “current” time, so that multiple
              modifications within the same transaction bear the same time stamp.




              Postgres timestamps are implemented as 8-byte integers representing up to 6 fractional digits (microsecond resolution).



              If you are building a table that is supposed to hold no more than one row per microsecond and that condition is not going to change (something named sensor_reading_per_microsecond), then it might make sense. Duplicate rows are supposed to raise a duplicate key violation error. That's an exotic exception, though. And the data type timestamptz (not timestamp) would probably be preferable. See:



              • Ignoring time zones altogether in Rails and PostgreSQL

              I would still rather use a surrogate serial primary key instead. And add a UNIQUE constraint on the timestamp column. Fewer possible complications, not relying on implementation details of the RDBMS.






              share|improve this answer



























                up vote
                5
                down vote













                Strictly speaking: No. Because CURRENT_TIMESTAMP is a function and only one or more table columns can form a PRIMARY KEY constraint.



                If you mean to create a PRIMARY KEY constraint on a column with the default value CURRENT_TIMESTAMP, then the answer is: Yes, you can. Nothing keeps you from doing it, like nothing keeps you from shooting apples from your son's head. The question still wouldn't make sense while you don't define the purpose of it. What kind of data are column and table supposed to hold? What rules are you trying to implement?



                Typically, the idea is bound to run into duplicate key errors since CURRENT_TIMESTAMP is a STABLE function returning the same value for the same transaction (the start time of the transaction). Multiple INSERTs in the same transaction are bound to collide - like other answers already illustrated. The manual:




                Since these functions return the start time of the current
                transaction, their values do not change during the transaction. This
                is considered a feature: the intent is to allow a single transaction
                to have a consistent notion of the “current” time, so that multiple
                modifications within the same transaction bear the same time stamp.




                Postgres timestamps are implemented as 8-byte integers representing up to 6 fractional digits (microsecond resolution).



                If you are building a table that is supposed to hold no more than one row per microsecond and that condition is not going to change (something named sensor_reading_per_microsecond), then it might make sense. Duplicate rows are supposed to raise a duplicate key violation error. That's an exotic exception, though. And the data type timestamptz (not timestamp) would probably be preferable. See:



                • Ignoring time zones altogether in Rails and PostgreSQL

                I would still rather use a surrogate serial primary key instead. And add a UNIQUE constraint on the timestamp column. Fewer possible complications, not relying on implementation details of the RDBMS.






                share|improve this answer

























                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  Strictly speaking: No. Because CURRENT_TIMESTAMP is a function and only one or more table columns can form a PRIMARY KEY constraint.



                  If you mean to create a PRIMARY KEY constraint on a column with the default value CURRENT_TIMESTAMP, then the answer is: Yes, you can. Nothing keeps you from doing it, like nothing keeps you from shooting apples from your son's head. The question still wouldn't make sense while you don't define the purpose of it. What kind of data are column and table supposed to hold? What rules are you trying to implement?



                  Typically, the idea is bound to run into duplicate key errors since CURRENT_TIMESTAMP is a STABLE function returning the same value for the same transaction (the start time of the transaction). Multiple INSERTs in the same transaction are bound to collide - like other answers already illustrated. The manual:




                  Since these functions return the start time of the current
                  transaction, their values do not change during the transaction. This
                  is considered a feature: the intent is to allow a single transaction
                  to have a consistent notion of the “current” time, so that multiple
                  modifications within the same transaction bear the same time stamp.




                  Postgres timestamps are implemented as 8-byte integers representing up to 6 fractional digits (microsecond resolution).



                  If you are building a table that is supposed to hold no more than one row per microsecond and that condition is not going to change (something named sensor_reading_per_microsecond), then it might make sense. Duplicate rows are supposed to raise a duplicate key violation error. That's an exotic exception, though. And the data type timestamptz (not timestamp) would probably be preferable. See:



                  • Ignoring time zones altogether in Rails and PostgreSQL

                  I would still rather use a surrogate serial primary key instead. And add a UNIQUE constraint on the timestamp column. Fewer possible complications, not relying on implementation details of the RDBMS.






                  share|improve this answer















                  Strictly speaking: No. Because CURRENT_TIMESTAMP is a function and only one or more table columns can form a PRIMARY KEY constraint.



                  If you mean to create a PRIMARY KEY constraint on a column with the default value CURRENT_TIMESTAMP, then the answer is: Yes, you can. Nothing keeps you from doing it, like nothing keeps you from shooting apples from your son's head. The question still wouldn't make sense while you don't define the purpose of it. What kind of data are column and table supposed to hold? What rules are you trying to implement?



                  Typically, the idea is bound to run into duplicate key errors since CURRENT_TIMESTAMP is a STABLE function returning the same value for the same transaction (the start time of the transaction). Multiple INSERTs in the same transaction are bound to collide - like other answers already illustrated. The manual:




                  Since these functions return the start time of the current
                  transaction, their values do not change during the transaction. This
                  is considered a feature: the intent is to allow a single transaction
                  to have a consistent notion of the “current” time, so that multiple
                  modifications within the same transaction bear the same time stamp.




                  Postgres timestamps are implemented as 8-byte integers representing up to 6 fractional digits (microsecond resolution).



                  If you are building a table that is supposed to hold no more than one row per microsecond and that condition is not going to change (something named sensor_reading_per_microsecond), then it might make sense. Duplicate rows are supposed to raise a duplicate key violation error. That's an exotic exception, though. And the data type timestamptz (not timestamp) would probably be preferable. See:



                  • Ignoring time zones altogether in Rails and PostgreSQL

                  I would still rather use a surrogate serial primary key instead. And add a UNIQUE constraint on the timestamp column. Fewer possible complications, not relying on implementation details of the RDBMS.







                  share|improve this answer















                  share|improve this answer



                  share|improve this answer








                  edited 19 hours ago


























                  answered 20 hours ago









                  Erwin Brandstetter

                  83.8k8148253




                  83.8k8148253






















                       

                      draft saved


                      draft discarded


























                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f214110%2fcan-current-timestamp-be-used-as-a-primary-key%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Popular posts from this blog

                      Peggy Mitchell

                      Palaiologos

                      The Forum (Inglewood, California)