473,855 Members | 2,141 Online
Bytes | Software Development & Data Engineering Community
+ 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 19317
You can use the COALESCE function, like this:

INSERT INTO table (idthread, idsection,txt)
VALUES (
COALESCE((SELEC T 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.c z> 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(i dthread),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((SELE CT 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*******@postg resql.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 YourEmailAddres sHere" to ma*******@postg resql.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(i dthread),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((SELE CT 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.c z> 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 YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 23 '05 #7
On Wed, Jun 23, 2004 at 13:42:12 +0200,
Milos Prudek <pr****@bvx.c z> 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
1475
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 AUTO_INCREMENT) Thanks again //Lars Rasmussen
8
5695
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 DUPLICATE KEY UPDATE field2 = 1 Is it possible to use both INSERT... SELECT... with ON DUPLICATE KEY? I cant get it to work.
2
2735
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, CustomerNumber of the two tables. Help, Example Appreciated. Thanks Frank
1
483
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 from a parameter @orderid ( the field is called orderid) Can someone tell me how this can be acheived?? At present I run the slect statment and then I add the parameter, by
0
2103
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
17614
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 checkform(this);"> <table width="452" border="1" align="right" cellpadding="4" cellspacing="3" bordercolor="#003093" id="table"> <tr> <td width="210" class="labelfield">Record Code:</td> <td width="211" nowrap class="field">
6
7717
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 which reads and drops the same temporary table. My users are not able to create dbo tables (eg dbo.tblTest), but are permitted to create tables under their own user (eg MyUser.tblTest). I have found that I can achieve my aim by using code like...
3
2677
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 of xml data type. i was successful in inserting the static value inside my table.by following code:--- UPDATE docs
0
2101
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 inserting a NULL value. Oddly sometimes it works but I don't know why. Can anyone suggest anything else I can try? Perhaps this is the wrong group I'm posting to - it was just the one that came up with other errors giving the same message, but none of...
1
2158
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 CPresensiFingerprint Dim presensiFinger As New CPresensiFingerprint Dim SQLSelectdbRAS As String Dim rsFinger As Recordset Dim dateNow_ As Date dateNow_ = um_TgldanJamSkrg()
0
10692
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10767
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10375
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9526
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7927
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7084
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5952
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4168
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3194
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.