1

In my database I have a table "Datapoint" with the two columns "Id" (integer) and "Description" (character varying). Table "Datapoint"

I then have a table "Logging" with the three columns "Id" (integer), "Dt" (timestamp without timezone) and "Value" (double precision).Table "Logging"

I also have the following function:

CREATE OR REPLACE FUNCTION count_estimate(query text)
  RETURNS integer AS
$BODY$ DECLARE rec   record;ROWS  INTEGER;BEGIN FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP ROWS := SUBSTRING(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)');EXIT WHEN ROWS IS NOT NULL;END LOOP;RETURN ROWS;END $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

This function returns the estimated count of entries that are found by a SELECT-Query, e.g. SELECT count_estimate('SELECT * FROM "Logging" WHERE "Id" = 3') would return 2.

I would now like to combine a SELECT-query on the table "Datapoint" with the return value of my function, so that my result looks like this:

ID  |   Description |   EstimatedCount
1   |   Datapoint 1 |   3
2   |   Datapoint 2 |   4
3   |   Datapoint 3 |   2
4   |   Datapoint 4 |   1    

My SELECT-query should look something like this:

SELECT
 "Datapoint"."Id",
 "Datapoint"."Description",

(SELECT count_estimate ('SELECT * FROM "Logging" WHERE "Logging"."Id" = "Datapoint"."Id"')) AS "EstimatedCount"

 FROM
 "Datapoint"

So my problem is to write a functioning SELECT-query for my purposes.

2 Answers 2

0

What about:

SELECT
 "Datapoint"."Id",
 "Datapoint"."Description",

count_estimate ('SELECT * FROM "Logging" WHERE "Logging"."Id" = "Datapoint"."Id"') AS "EstimatedCount"

 FROM
 "Datapoint"
Sign up to request clarification or add additional context in comments.

3 Comments

... but that's just a literal copy of the query that doesn't work, no?
see Laurenz's fix below, but the difference here is that you don't need to put it in a subselect.
Ah, I didn't see that.
0

You almost got it right, except that you need to supply the value of "Datapoint"."Id":

SELECT
   "Datapoint"."Id",
   "Datapoint"."Description",
   count_estimate(
      'SELECT * FROM "Logging" WHERE "Logging"."Id" = ' || "Datapoint"."Id"
   ) AS "EstimatedCount"
FROM "Datapoint";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.