473,811 Members | 3,151 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PL/PGSQL help for getting number of rows matched.


Hi,

We need to implement following logic efficiently.

SELECT * from some_table where .... [ Query 1 ]

IF rows_matched = 1 THEN

use the single row that matched.

ELSIF

loop thru the results of [Query 1]

END IF;
Currently i am doing select count(*) for getting rows_matched
in the top and repeating the same query in both branches of IF
to get the data of matching rows.

I have tried GET DIAGNOSTICS ROW_COUNT but for
"SELECTS" if returns 0 or 1 based on matching

I am sure there exists better methods. Kindly post a link
to better documentation of pl/pgsql or point out section in
the standard docs that discuss this issue.

Regds
Mallah.


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

Nov 12 '05 #1
4 9180
Hello,

it isn't problem. You can write

SELECT INTO ....
IF FOUND THEN
...
END IF

or

SELECT INTO ..
GET DIAGNOSTICS variable = ROW_COUNT;
IF variable > 0 THEN
...
END IF

You can see on
http://developer.postgresql.org/docs...QL-SELECT-INTO

Regards
Pavel
On Mon, 10 Nov 2003, Rajesh Kumar Mallah wrote:

Hi,

We need to implement following logic efficiently.

SELECT * from some_table where .... [ Query 1 ]

IF rows_matched = 1 THEN

use the single row that matched.

ELSIF

loop thru the results of [Query 1]

END IF;
Currently i am doing select count(*) for getting rows_matched
in the top and repeating the same query in both branches of IF
to get the data of matching rows.

I have tried GET DIAGNOSTICS ROW_COUNT but for
"SELECTS" if returns 0 or 1 based on matching

I am sure there exists better methods. Kindly post a link
to better documentation of pl/pgsql or point out section in
the standard docs that discuss this issue.

Regds
Mallah.


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

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

http://archives.postgresql.org

Nov 12 '05 #2

On Mon, 10 Nov 2003, Pavel Stehule wrote:
Hello,

it isn't problem. You can write

SELECT INTO ....
IF FOUND THEN
...
END IF

or

SELECT INTO ..
GET DIAGNOSTICS variable = ROW_COUNT;
IF variable > 0 THEN
...
END IF

You can see on
http://developer.postgresql.org/docs...QL-SELECT-INTO
Probably sectino 37.7.4 of the docs ( in
http://developer.postgresql.org/docs...tructures.html
) is a better source as shown lower.

On Mon, 10 Nov 2003, Rajesh Kumar Mallah wrote:

Hi,

We need to implement following logic efficiently.

SELECT * from some_table where .... [ Query 1 ]

IF rows_matched = 1 THEN

use the single row that matched.

ELSIF

loop thru the results of [Query 1]

END IF;
Currently i am doing select count(*) for getting rows_matched
in the top and repeating the same query in both branches of IF
to get the data of matching rows.

I have tried GET DIAGNOSTICS ROW_COUNT but for
"SELECTS" if returns 0 or 1 based on matching

I am sure there exists better methods. Kindly post a link
to better documentation of pl/pgsql or point out section in
the standard docs that discuss this issue.


DECLARE
tup RECORD;
BEGIN
FOR tup IN select * from mytable
LOOP
Do the required action
END LOOP;
END

Indeed, I'm not even sure how to loop through the results of the query using
the scheme you show above. What do you assign the results of the select to?
--
Nigel Andrews
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 12 '05 #3
On Monday 10 Nov 2003 5:38 pm, Pavel Stehule wrote:
Hello,

it isn't problem. You can write

SELECT INTO ....
IF FOUND THEN
...
END IF
I have *different* logic for match=1
and for match > 1 , so FOUND is not a
solution as manual says.
There is a special variable named FOUND of type boolean.
FOUND starts out false within each PL/pgSQL function.
It is set by each of the following types of statements:

Section 19.5.5
http://www.postgresql.org/docs/7.3/s...tatements.html

or

SELECT INTO ..
GET DIAGNOSTICS variable = ROW_COUNT;
IF variable > 0 THEN
...
END IF

Even this does not solve my problem.
See my actual code and the output.

-- *************** ** CODE *************** ****
CREATE OR REPLACE FUNCTION general.copy_ac counts() returns integer AS
'
DECLARE
users_c CURSOR FOR SELECT userid FROM general.user_ac counts where userid=46 ;
userid_v int;
i int;
matched int;
rec RECORD;
BEGIN
OPEN users_c;

i := 1;
LOOP
FETCH users_c INTO userid_v;
EXIT WHEN NOT FOUND ;

SELECT INTO rec profile_id from general.profile _master where userid=userid_v ;
GET DIAGNOSTICS matched = ROW_COUNT;
RAISE INFO ''matched = % '' , matched;

SELECT INTO matched count(*) from general.profile _master where userid=userid_v ;
RAISE INFO ''matched = % '' , matched;

EXIT;

END LOOP;
CLOSE users_c;
RETURN 1;
END
' LANGUAGE 'plpgsql';

-- ------ CODE ENDS
RESULTS BELOW:

tradein_clients =# SELECT copy_accounts() ;
INFO: matched = 1
INFO: matched = 3

Note that matched was 3 but in first place it did not come.

+---------------+
| copy_accounts |
+---------------+
| 1 |
+---------------+
(1 row)

Time: 386.76 ms
tradein_clients =#
Regds
Mallah.

You can see on
http://developer.postgresql.org/docs...nts.html#PLPGS
QL-SELECT-INTO

Regards
Pavel

On Mon, 10 Nov 2003, Rajesh Kumar Mallah wrote:
Hi,

We need to implement following logic efficiently.

SELECT * from some_table where .... [ Query 1 ]

IF rows_matched = 1 THEN

use the single row that matched.

ELSIF

loop thru the results of [Query 1]

END IF;
Currently i am doing select count(*) for getting rows_matched
in the top and repeating the same query in both branches of IF
to get the data of matching rows.

I have tried GET DIAGNOSTICS ROW_COUNT but for
"SELECTS" if returns 0 or 1 based on matching

I am sure there exists better methods. Kindly post a link
to better documentation of pl/pgsql or point out section in
the standard docs that discuss this issue.

Regds
Mallah.


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

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 12 '05 #4
On Monday 10 Nov 2003 6:05 pm, Nigel J. Andrews wrote:
DECLARE
tup RECORD;
BEGIN
FOR tup IN select * from mytable
LOOP
Do the required action
END LOOP;
END
Indeed, I'm not even sure how to loop through the results of the query
using the scheme you show above. What do you assign the results of the
select to?

My working code which i think can be improved is below
note that i treat match=1 and match>1 differently.

I hope it will answer both of your question.

Thanks everyone for the responses though :)

Pl/Pgsql itself seems to be the most mature of all PL
hence we have decided to shift our business logic from
perl layer to DataBase for obvious gains.

-- Actual Code-------

CREATE OR REPLACE FUNCTION general.copy_ac counts() returns integer AS

'

DECLARE

users_c CURSOR FOR SELECT userid FROM general.user_ac counts ;
userid_v int;
i int;
matched int;
rec RECORD;

BEGIN

OPEN users_c;

i := 1;

LOOP
FETCH users_c INTO userid_v;
EXIT WHEN NOT FOUND ;
SELECT INTO matched count(*) from general.profile _master where userid=userid_v ;
IF matched = 1 THEN
SELECT INTO rec email,title1 , fname1 , mname1 , lname1 , desg1 , mobile from general.profile _master where userid=userid_v ;

ELSIF matched > 1 THEN

-- multiple profiles then get the profile that
-- has highest score.

SELECT INTO rec email,title1 , fname1 , mname1 , lname1 , desg1 , mobile,source
from general.profile _master join
general.temp_so urce_priority using(source) where userid=userid_v
order by profile_score(e mail,title1 , fname1 , mname1 , lname1 , desg1 , mobile) desc limit 1;

END IF;

IF matched >= 1 THEN
i := i + 1;
UPDATE general.user_ac counts set
email= rec.email,
title= rec.title1 ,
fname= rec.fname1 ,
mname= rec.mname1 ,
lname= rec.lname1 ,
desg = rec.desg1 ,
mobile= rec.mobile where userid = userid_v;
END IF;

IF i % 100 = 0 THEN
RAISE INFO '' copied % accounts '' , i;
END IF;
END LOOP;

CLOSE users_c;
RAISE INFO '' Successfully finished with % accounts '' , i;

RETURN 1;

END

' LANGUAGE 'plpgsql';
---------------------------(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 12 '05 #5

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

Similar topics

3
24103
by: Xizor | last post by:
Ok, what I want to do is find out the number of rows in a table. The most obvious solution is to do something like the following: $sql = "SELECT blah FROM blah WHERE 1"; $result = mysql_query($sql, $db); $num = mysql_num_rows($result); If you have a large table, to me that seems like it would be a system hog if all you want is the number of rows but not the data. I'm not sure if using mysql_unbuffered_query() would solve this, would...
0
7202
by: t_pet422 | last post by:
Hi, I've been scouring the net and reading the PostgreSQL docs for a while now trying to learn how to create a recursive function in PL/pgSQL that will return a whole subtree given a starting node. I wanted to share my summary results here. Maybe this will help someone and save them from doing a bunch of research (like I had to do :). For the record, this is the first thing I've ever written in PL/pgSQL, although I do have significant...
1
2257
by: Diogo Biazus | last post by:
From time to time I'm getting this error message: WARNING: Error occurred while executing PL/pgSQL function atualizabusca WARNING: line 25 at for over select rows ERROR: unknown cmdtype 136748160 in exec_stmt It's a 7.3.3 running on a FreeBSD 4.8 When I recreate the function it works well for some time, but after using the database for some hours this error shows up again. Very strange, does anyone has a clue?
1
1453
by: Jenny Zhang | last post by:
I have stored procedure written in pl/pgsql which takes about 13 seconds to finish. I was able to identify that the slowness is caused by one update SQL: UPDATE shopping_cart SET sc_sub_total=sc_subtotal, sc_date=now() WHERE sc_id=sc_id; If I comment this sql out, the stored procedure returns within 1 second. What puzzles me is that if I execute the same update SQL in psql
7
5271
by: Jim Crate | last post by:
I have a couple queries in a PL/PGSQL function which execute very slowly (around one minute each) which execute in .5 second when not executed from within the function. Is there any way to determine why this is happening? I couldn't figure out how to run EXPLAIN ANALYZE from within the function. The queries aren't very complicated. Here is an example query and plan. About 240K rows in x_rbl_ips, 7.5M rows in filter_ips. explain...
34
5075
by: Karam Chand | last post by:
Hello I have been working with Access and MySQL for pretty long time. Very simple and able to perform their jobs. I dont need to start a flame anymore :) I have to work with PGSQL for my companies current project. I have been able to setup postgresql in my rh box and
2
4666
by: Tim Vadnais | last post by:
Hi, My boss wants to add a special type of logging to some of our tables on update/delete/insert. I need to log who, when, table_name, field name, original value and new value for each record, but only logging modified fields, and he wants me to do this using postgres pgSQL triggers. The changes would be inserted into a second table. We are given 10 automatically created variables. Some of which I know I can use: NEW, OLD, TG_WHEN,...
11
2563
by: UDBDBA | last post by:
Hi: This is a merge questions which has been posted and answered... in my case need more clairification when target table (tableB) matched multiple rows to be updated based on the ON condition for a single row from source table (tableA). There is a one to many relationship from source to target table (because of the ON condition). We also know upfront that thsi merge will result in all update and no inserts. The source table is tableA...
7
21617
by: harijay | last post by:
Hi I am a few months new into python. I have used regexps before in perl and java but am a little confused with this problem. I want to parse a number of strings and extract only those that contain a 4 digit number anywhere inside a string However the regexp p = re.compile(r'\d{4}')
0
9734
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10652
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10395
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
10408
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
10137
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...
1
7673
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
5561
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3874
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3026
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.