473,461 Members | 1,400 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

insert with select as value

I need to insert a value = max(value)+1, where max is a select limited
by a 'where' clause. Like this:

INSERT INTO table (idthread, idsection,txt)
VALUES (
(SELECT max(idthread)+1 FROM table WHERE idsection = 'CZE'), 'CZE',
'sample text')
);

This works fine, except when the result of SELECT is empty - which is
true when the table is empty.

Is it possible to create a "SELECT max(idthread)+1 FROM table WHERE
idsection = 'CZE';" that will return value 1 instead of value None if
the SELECT has no results?

--
Milos Prudek
_________________
Most websites are
confused chintzy gaudy conflicting tacky unpleasant... unusable.
Learn how usable YOUR website is! http://www.spoxdesign.com

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #1
7 19274
You can use the COALESCE function, like this:

INSERT INTO table (idthread, idsection,txt)
VALUES (
COALESCE((SELECT max(idthread)+1 FROM table WHERE idsection =
'CZE'),1), 'CZE',
'sample text')
);

This function returns the first of its argument that is not null. If your
query returns no value, the second argument (in this case, the number
"1").
Marcelo Soares
Informática - Master Hotéis
ICQ Externo: 19398317
ICQ Interno: 1002
Linux user#: 288006
PGP Key: http://gravatai.ulbra.tche.br/~ringo...PubOficial.pgp
------------------------------------------------------------------
"Não há limite para a cultura, Watson. O campo de nossas experiências é
uma série de lições das quais a maior é sempre a última." Sherlock Holmes
(A.C.Doyle)
------------------------------------------------------------------
I need to insert a value = max(value)+1, where max is a select limited
by a 'where' clause. Like this:

INSERT INTO table (idthread, idsection,txt)
VALUES (
(SELECT max(idthread)+1 FROM table WHERE idsection = 'CZE'), 'CZE',
'sample text')
);

This works fine, except when the result of SELECT is empty - which is
true when the table is empty.

Is it possible to create a "SELECT max(idthread)+1 FROM table WHERE
idsection = 'CZE';" that will return value 1 instead of value None if
the SELECT has no results?

--
Milos Prudek
_________________
Most websites are
confused chintzy gaudy conflicting tacky unpleasant... unusable.
Learn how usable YOUR website is! http://www.spoxdesign.com

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org


---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #2
On Tue, Jun 22, 2004 at 16:22:33 +0200,
Milos Prudek <pr****@bvx.cz> wrote:
I need to insert a value = max(value)+1, where max is a select limited
by a 'where' clause. Like this:
If your purpose in doing this is just to generate unique keys, you should
be using sequences instead.

INSERT INTO table (idthread, idsection,txt)
VALUES (
(SELECT max(idthread)+1 FROM table WHERE idsection = 'CZE'), 'CZE',
'sample text')
);
Note that you probably want to lock the table before doing this or
two transactions running at the same time can generate the same
value for idthread.

This works fine, except when the result of SELECT is empty - which is
true when the table is empty.

Is it possible to create a "SELECT max(idthread)+1 FROM table WHERE
idsection = 'CZE';" that will return value 1 instead of value None if
the SELECT has no results?


You could either right your own max function, or you can use coallesce.
For example:
SELECT coallesce(max(idthread),0)+1 FROM table WHERE idsection = 'CZE';

If there is a compound index on idthread and idsection, then you are probably
better off using something like the following to take advantage of the index:
coallesce((SELECT idthread FROM table WHERE idsection = 'CZE' ORDER BY
idthread DESC, idsection DESC LIMT 1))+1
(You need to list idthread and idsection in the ORDER BY clause in the
same order they are listed in the index.)

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #3
> Is it possible to create a "SELECT max(idthread)+1 FROM table WHERE
idsection = 'CZE';" that will return value 1 instead of value None if
the SELECT has no results?


Never mind, I figured it myself. I found that there is COALESCE
function in Postgres (in Functions and Operators / Conditional
Expressions) and that it is exactly what is needed.

And Kuti Atilla send me the same answer in a private email.

Thanks!

--
Milos Prudek
_________________
Most websites are
confused chintzy gaudy conflicting tacky unpleasant... unusable.
Learn how usable YOUR website is! http://www.spoxdesign.com

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postgresql.org so that your
message can get through to the mailing list cleanly

Nov 23 '05 #4
Try rewriting the inner query as:

SELECT s.* FROM (
SELECT max(idthread)+1 as MX, 'CZE', 'sample text' FROM table WHERE
idsection = 'CZE'
union
SELECT 1 as MX, 'CZE', 'sample text'
) as s
ORDER BY s.MX desc
LIMIT 1

I think that should work, and always return a row.

John Sidney-Woollett

Milos Prudek wrote:
I need to insert a value = max(value)+1, where max is a select limited
by a 'where' clause. Like this:

INSERT INTO table (idthread, idsection,txt)
VALUES (
(SELECT max(idthread)+1 FROM table WHERE idsection = 'CZE'),
'CZE', 'sample text')
);

This works fine, except when the result of SELECT is empty - which is
true when the table is empty.

Is it possible to create a "SELECT max(idthread)+1 FROM table WHERE
idsection = 'CZE';" that will return value 1 instead of value None if
the SELECT has no results?


---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to ma*******@postgresql.org)

Nov 23 '05 #5
> If your purpose in doing this is just to generate unique keys, you should
be using sequences instead.
I would need 150 separate sequences, because each idsection needs its
own, independent sequence of idthread.
Note that you probably want to lock the table before doing this or
two transactions running at the same time can generate the same
value for idthread.
That's a surprise. I could have made two separate queries (a select and
then insert) in my programming language (Python), but I wanted to make
it in one query PRECISELY because I thought that would prevent the race
condition that you describe. Are you quite sure?
For example:
SELECT coallesce(max(idthread),0)+1 FROM table WHERE idsection = 'CZE';
Someone already sent me this by private email, and it works fine.
If there is a compound index on idthread and idsection, then you are probably
better off using something like the following to take advantage of the index:
coallesce((SELECT idthread FROM table WHERE idsection = 'CZE' ORDER BY
idthread DESC, idsection DESC LIMT 1))+1


That's interesting and valuable, thank you very much.
--
Milos Prudek
_________________
Most websites are
confused chintzy gaudy conflicting tacky unpleasant... unusable.
Learn how usable YOUR website is! http://www.spoxdesign.com

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #6
In article <40**************@bvx.cz>,
Milos Prudek <pr****@bvx.cz> writes:
If your purpose in doing this is just to generate unique keys, you should
be using sequences instead.
I would need 150 separate sequences, because each idsection needs its
own, independent sequence of idthread.


What you really seem to need is a counter for each idsection.
Depending on how often you need to access the counter value, it might
be worthwile to not store the count at all and instead use a single sequence.
You can compute the counter value at SELECT time by something like

SELECT idsection,
( SELECT count (*)
FROM tbl t
WHERE idsection = tbl.idsection
AND id <= tbl.id
) AS idthread
FROM tbl

where "id" is the single sequence.
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to ma*******@postgresql.org)

Nov 23 '05 #7
On Wed, Jun 23, 2004 at 13:42:12 +0200,
Milos Prudek <pr****@bvx.cz> wrote:
If your purpose in doing this is just to generate unique keys, you should
be using sequences instead.


I would need 150 separate sequences, because each idsection needs its
own, independent sequence of idthread.


Not if you just want to generate unique keys. In that case you can use one
sequence for each idsection. If you need more than uniqueness then you
don't want to use sequences.
Note that you probably want to lock the table before doing this or
two transactions running at the same time can generate the same
value for idthread.


That's a surprise. I could have made two separate queries (a select and
then insert) in my programming language (Python), but I wanted to make
it in one query PRECISELY because I thought that would prevent the race
condition that you describe. Are you quite sure?


Yes. If two transactions are proceeding at the same time they can both
see the same highest value and hence pick the same next value. You need
to do some sort of locking to prevent this. Lock table is the simplest.
You could also use select for update, but I believe this may result
in occassional deadlocks, so you will need to be able to retry queries
when that happens.

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Lars Rasmussen | last post by:
I tried that, but i dont work either. I need to insert a way that mysql doese'nt complain when i copy some records that have the same id (or that it just gives it an id according to the...
8
by: Nick | last post by:
Im trying to insert a bunch of rows into a table. If the row already exists id like to update the row 'counter'. For example... INSERT INTO table1 SELECT field1, field2 FROM table2 ON...
2
by: Frank Py | last post by:
I need a query that looks at one table and appends another if new customer data is added. I think I need an Insert, Select statement using the NOT IN clause. I need to compare Division,...
1
by: m3ckon | last post by:
Hi there I have a stored procedure which uses an INSERT ... SELECT statement to transfer records from one table to another. However, I also need to insert an extra field to the table which is...
0
by: Donius | last post by:
Hello team. I'm running mysql 4.0.20-standard and i'm trying to do a query like this: INSERT IGNORE INTO `DonorPledges` ( nDonor_id, nPledgeYear, nTotalPaid, nTotalPledge ) SELECT
1
by: hellyna | last post by:
How to insert radiobutton value into the mysql? This is addrecordfrom.php <form name="addsummonrecord" method="post" action="addrecordprocess.php" id="signup" onSubmit="return...
6
by: Peter Nurse | last post by:
For reasons that are not relevant (though I explain them below *), I want, for all my users whatever privelige level, an SP which creates and inserts into a temporary table and then another SP...
3
by: Mukesh | last post by:
sir, i am developing a database, which will store the users profile both personal and professional which includes the address, telephone, gender and etc. in my main table i have created a column...
0
by: diane | last post by:
Just trying to upsize using VFP 9 with SQL 2005 using VFP remote views. One in particular keeps coming up and saying Cannot insert the value NULL into column, when I really don't think I am...
1
by: Octo Siburian | last post by:
I have been collecting data from ms.access database into a class object '_Get and put in data from database Fingerprint(RAS) into CPresensiFingerprint Public Function GetdbFingerprint() As...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.