Received: from localhost (maia-5.hub.org [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 2F6B79FB6EA for ; Wed, 7 Mar 2007 07:55:28 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-new, port 10024) with ESMTP id 00629-03 for ; Wed, 7 Mar 2007 07:55:15 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from eppesuigoccas.homedns.org (host245-172-dynamic.0-87-r.retail.telecomitalia.it [87.0.172.245]) by postgresql.org (Postfix) with ESMTP id D4CA89FB725 for ; Wed, 7 Mar 2007 07:55:19 -0400 (AST) Received: from 89-96-243-184.ip14.fastwebnet.it ([89.96.243.184] helo=scarafaggio) by eppesuigoccas.homedns.org with esmtpsa (TLS-1.0:RSA_AES_256_CBC_SHA1:32) (Exim 4.63) (envelope-from ) id 1HOug3-0007pu-7o for pgsql-jdbc@postgresql.org; Wed, 07 Mar 2007 12:51:27 +0100 Received: from giuseppe by scarafaggio with local (Exim 4.63) (envelope-from ) id 1HOunY-00047n-KI for pgsql-jdbc@postgresql.org; Wed, 07 Mar 2007 12:59:12 +0100 Subject: Transaction atomicity From: Giuseppe Sacco To: pgsql-jdbc@postgresql.org Content-Type: text/plain Content-Transfer-Encoding: 7bit Date: Wed, 07 Mar 2007 12:59:12 +0100 Message-Id: <1173268752.20645.29.camel@scarafaggio> Mime-Version: 1.0 X-Mailer: Evolution 2.6.3 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=3.13 tagged_above=0 required=5 tests=AWL, BAYES_50, FORGED_RCVD_HELO, RCVD_IN_NJABL_DUL, RCVD_IN_SORBS_DUL X-Spam-Level: *** X-Archive-Number: 200703/66 X-Sequence-Number: 16780 Hi all, I have a question about a simple code that should automatically insert a record in a table. The primary key for this record is automatically generated during the INSERT statement, as the max value plus one. The (simplified, since the real number of fields is 5) code is: final String query = "INTO table (docId,seqNr) " + "VALUES (?, (SELECT 1 + coalesce (max(seqNr), 0) "+ "FROM table " + "WHERE seqNr BETWEEN 0 AND (9223372036854775807-1) ))"; Connection conn=daof.getConnection(); try { conn.setAutoCommit(true); PrepararedStatemen st = conn.prepareStatement(query); st.setString(1,'myDocId'); st.executeUpdate(); conn.close(); } catch (SQLException e) { try { conn.close(); } catch (SQLException ee) {} throw e; } I then create Runtime.getRuntime().availableProcessors() threads that create a DataSource and start executing that code in parallel. What happens is that I get many DUPLICATE KEY errors. I thought that in AutoCommit all insert are supposed to be serialized, so they should create a seqNr different since MAX(seqNr) is different at each call. Is my reasoning correct? Or is it a different problem, maybe with jdbc or postgresql? Thanks, Giuseppe