Questions tagged [set-returning-functions]

Functions possibly returning more than one row. Typical examples are series generating functions or unnest(). A.k.a. "table-functions".

Filter by
Sorted by
Tagged with
22
votes
1answer
2k views

Does SQL Server cache the result of a multi-statement table-valued function?

A multi-statement table-valued function returns its result in a table variable. Are these results ever reused, or is the function always fully evaluated every time it is called?
18
votes
1answer
805 views

Multi-statement TVF vs Inline TVF Performance

Comparing some of the answers on the Palindrome question(10k+ users only, since I've deleted the answer), I'm getting confusing results. I proposed a multi-statement, schema-bound TVF which I thought ...
11
votes
1answer
16k views

Error: set_valued function called in context that cannot accept a set. What is it about?

I use Postgresql 9.1, with ubuntu 12.04. Inspired by Craig's answer to my question Concatenation of setof type or setof record I thought I would go well with using return query, setof record, and a ...
8
votes
1answer
322 views

Why does a Set Returning Function (SRF) run slower in a FROM clause?

This is a database-internals question. I'm using PostgreSQL 9.5, I'm wondering why Set Returning Functions (SRFs), also known as Table Valued Functions (TVFs) run slower when in a FROM clause, for ...
8
votes
2answers
8k views

Array integer[]: how to get all distinct values in a table and count them?

I'm not so good with SQL (PostgreSQL). Here is what I want to do: I have a table, fields: id SERIAL inet INET ports integer[] id | inet | ports ----+------------+------------ 2 | 1.2.2.1 ...
8
votes
1answer
2k views

Understanding Set Returning Function (SRF) in the SELECT List

Why is there a difference in behavior between using a Set Returning Function (SRF) in the SELECT list vs using SRF in the FROM clause? For example, for a simple SRF returning 2 rows: CREATE OR ...
7
votes
2answers
15k views

Unnest multiple arrays into rows

I have been shown a great way to bulkinsert with this example: WITH p AS ( INSERT INTO parent_table (column_1) SELECT $1 RETURNING id) INSERT INTO child_table (parent_table_id, ...
7
votes
1answer
824 views

How to name table-variable function unique constraint?

I am renaming some unique constraints to match our database objects naming convention. Strangely, there are several multi-line table valued function which returned table has unique constraints as ...
6
votes
5answers
4k views

UNION ALL or other ways to return first row of result-set

I am writing a table valued function to geocode an address based on its Suburb, State and Postcode. I try to geocode the address using different methods, in order of decreasing accuracy: Exact match ...
6
votes
2answers
9k views

How to recompile all stored procedures and table valued functions in SQL Server database?

In a SQL Server database sp_recompile can be run on a stored procedure to update the execution plan. I would like to run this on all stored procedures in a database. Also, I would like to run its ...
6
votes
1answer
3k views

Function that returns table with an additional column

I want to write a PostgreSQL function that returns a table, plus an additional column. Is there a way to do this without manually specifying RETURNS TABLE (col1 type, col2 type, ...)? For example, ...
5
votes
1answer
12k views

Call function where argument is a (sub)select statement

My function takes an int4 as argument and returns a table: SELECT * FROM test_function(545421); -- works fine SELECT * FROM test_function(SELECT customerid FROM tableX ...
5
votes
2answers
671 views

T-SQL Daylight Saving lookup table - poorly performing table-valued function

I've created a "Daylight Savings" lookup calendar table for the GMT region. The function I'm using to query the table to return the local datetime from a UTC datetime is performing poorly. Any help ...
4
votes
2answers
8k views

Filling in missing dates in record set from generate_series()

Consider: with days as (select day::date from generate_series(date '2013-01-01', date '2013-01-01' + 365, interval '1 day' day) day ) select 'Inspections'::text as data_label, count(i.reporting_id) ...
4
votes
1answer
167 views

Slow left join lateral in subquery

I have three tables: units (apartment units), leases, and line_items (a better name would have been recurring rents). A unit has many leases and lease has many line items (associated with each rent ...
4
votes
1answer
87 views

Is it safe to use set-returning sql functions instead of security-barrier views?

Since 9.2, it's been possible to use the security_barrier attribute to guard against maliciously-chosen functions and operators accessing data 'hidden' behind filters in views (full info in the ...
3
votes
1answer
2k views

Should I add set nocount for functions?

I've been reading about the benefits for all triggers and procedures having "set nocount on" implemented unless you make use of DONE_IN_PROC. I have a scalar-valued function that is called from an ...
3
votes
2answers
3k views

Cross-product between table column and input values

I seem to be unable to write an SQL query, which computes the cross-product between a table column and a set of given input values. Something along the lines of: WITH {1,2} as Input Select * From ...
3
votes
2answers
1k views

jsonb_array_elements() in the select seems to turn a left join into an inner join

PostgreSQL 9.6. create table jon.vins (vin citext primary key); insert into jon.vins values ('3GNAXUEV1KL221776'), ('3GNAXHEV2KS548975'); CREATE TABLE jon.describe_vehicle ( vin citext primary key,...
3
votes
2answers
951 views

How to (optimally) get random sample of (a.id, b.id) pairs from two tables (a, b)?

Let's assume I have to very simple tables CREATE TABLE a(id integer PRIMARY KEY, t timestamp default now(), sensor_readings real[]); CREATE TABLE b(id integer PRIMARY KEY, t ...
3
votes
1answer
3k views

returning set of records in stored procedure

I would like to return a set of records from a pl/pgsql. Is there a way to do that without using the "for" construct and cursors? For instance when I compared these two stored procedures: create or ...
3
votes
2answers
1k views

Split up interval into year slices

Being a novice Postgres user, I have a table ad in my PostgreSQL 9.5 (x64) database with 87 rows. In addition to other columns, it has two columns 'start' and 'end' having date-time duration range ...
3
votes
1answer
2k views

How to use RETURNS TABLE with an existing table in PostgreSQL?

From the PostgreSQL documentation here: There is another way to declare a function as returning a set, which is to use the syntax RETURNS TABLE(columns). ... This notation is specified in recent ...
3
votes
1answer
406 views

Need for recursive lookup, stuck in query design

In PostgreSQL 9.4, here is my table: with r(pk, userid,partneruserid) as (values (1,1,2), (2,1,3), (3,1,6), (4,2,5), (5,2,6), (6,3,1), (7,4,1), (8,5,3), (9,6,2), (10,6,3) ) select * from r; In a ...
3
votes
1answer
30 views

Fill missing dates within groups

I have the following table with values for different stations from 2014-01-01 to 2014-01-04. The data has some date gaps that I want to fill leaving the value as NULL, and assigning the missing date ...
3
votes
0answers
803 views

Does PostgreSQL support `unnest` as a column?

Does PostgreSQL document and support this behavior of the SRF unnest() as a computer/virtual column, SELECT unnest(array_agg(id)) AS id FROM foo GROUP BY CUBE (a,b,c,d) HAVING count(*) > 1 If ...
2
votes
1answer
146 views

Efficiency of Scalar UDF vs TVF

I am trying to optimize the rollup code for my company and ran into a very peculiar issue. I converted many Scalar functions to be TVFs and they all seem to run more quickly than the original, which ...
2
votes
1answer
369 views

aggregating json fields

I have a table that holds JSON data. In a query with a GROUP BY clause, I'd like to get an array of all of the JSON field names in the result set. I tried a query like this: SELECT array_agg(...
2
votes
1answer
785 views

How do you declare a set-returning-function to only be allowed in the FROM clause?

I was just reading this answer by Erwin Brandstetter. Informative as usual, it makes note that (multi-parameter) unnest is only allowed in the FROM clause. I had never tried it in the SELECT clause so ...
2
votes
1answer
774 views

Incorrect statistics are used on index seek

I have a table-valued function and ordinary table and need to perform INNER JOIN on them. Because, the engine thinks that the function is returning always one row, I try to store the results in ...
2
votes
2answers
8k views

Function execute query, manipulates result and then return the same result

I need a function that does something like this pseudocode: function get_data() RETURN SET OF something... as BEGIN myResultSet = select id, some_other_column from ...... limit 20000; update ...
2
votes
2answers
212 views

Generate a sequence of timestamps but skip given periods

I have a table things_to_do in PostgreSQL. For example: thing_id --------- 1 2 3 4 5 6 And I want to add a timestamp to every row: SELECT thing_id, '2016-02-10 19:57:00'::timestamp ...
2
votes
1answer
49 views

Query involving TVF very slow on SQL Server 2008

I have a query that runs in under 1 second on SQL Server 2014. A similar query takes over 12 minutes when run against a table on a linked server running SQL Server 2008. I don't know if it's because ...
2
votes
1answer
164 views

Audit use of CLR Table-valued function

I have written some CLR table-valued functions that invoke a web service and I would like to audit their use. Does anyone know of any way this can be achieved in the CLR code itself? I would be nice ...
2
votes
1answer
4k views

Selecting only overlapping elements from array of ranges

The table I need to search contains an array of numrange values illustrated by: CREATE TABLE data ( sensor varchar(25), ranges numrange[] ); INSERT INTO data VALUES ('sensor0','{"[872985609.0,...
2
votes
1answer
106 views

Grouping data by year based on two timestamp columns

My data table has the following columns: id INTEGER, name TEXT, created TIMESTAMP, deleted TIMESTAMP I want to product a report of the count of each name (which can appear several times in the table)...
2
votes
1answer
4k views

Concatenation of setof type or setof record

I use Postgresql 9.1 with Ubuntu 12.04. In a plpgsql function I try to concatenate setof type returned from another function. the type pair_id_value in question is created with create type ...
2
votes
1answer
184 views

'Ungroup' data based on column

I'm using SQL Server 2012 and I have a table A that has the Id and PseudoId columns and a bunch of others I am not interested in. What I am interested in, is the PseudoId especially. This PseudoId has ...
2
votes
1answer
244 views

How does cast work with Set Returning Functions (SRF) like generate_series?

I got to wondering about how we would best use generate_series if we only want a series of dates. As a note, generate_series returns setof timestamp or setof timestamp with time zone (same as argument ...
2
votes
1answer
741 views

RETURN NEXT in Postgres Function

I'm currently writing a plpgsql function that will select from a table and produce a substantial amount of data. I was originally going to return an array, but I found a resource that explains the "...
1
vote
2answers
147 views

Why would adding a column to a view corrupted a table-valued function?

I have a TVP myTVP implemented as select val.* from vw_MyView val. The other day, I modified vw_MyView, replacing: select Foo,Bar from DB with select Foo, Bash, Bar from DB. This had a strange side ...
1
vote
1answer
59 views

Multi-statement Table Valued Function causing massive PAGELATCH_EX waits

We are getting insane PAGELATCH_EX waits because of a Multi-Statement TVF. I've found that the temp table created by the function is on tempdb file #1 and doesn’t ever change (always '#A465FC0D'). It ...
1
vote
1answer
89 views

PostgreSQL - Return type and EXECUTE QUERY

My function returns a setof composite type, however the RETURN EXECUTE seems to return some other unknown type: create type core.search_result as ( user_id uuid, country core.country, ethnicity ...
1
vote
2answers
82 views

How to fan out rows with a specified range of values?

I have a table which essentially contains 3 columns: ID, FIRST, LAST. They're all integers. I'm wondering if there's a way to use generate_series() to get a query result where for each row in the ...
1
vote
1answer
990 views

Getting generate_series(date, date) does not exist

When I run commands like this, SELECT * FROM generate_series('YESTERDAY'::date, 'TODAY'::date); SELECT * FROM generate_series('YESTERDAY'::timestamp without time zone, 'TODAY'::timestamp without time ...
1
vote
2answers
2k views

Postgres - Return default value if regex match fails

I'd like to attempt a regex match, and return null if it fails. The following query attempts to find the first number in a string. The result ignores the entry with text 'blah'. I'd prefer it to ...
1
vote
1answer
126 views

Table Valued UDF vs Stored Proc for passing values to a SELECT statement

I work with an application that, in many places, uses stored procedures to return data to the application, kind of like a view, but these procedures take in parameters (which isn't possible in a SQL ...
1
vote
2answers
673 views

SQL Server: Pass table name into table valued function as a parameter

All of my tables have those two columns: [Id] [uniqueidentifier] NOT NULL [Revision] [bigint] IDENTITY(1, 1) NOT NULL Every other time I write a query, I want to eliminate some of the rows. The ...
1
vote
1answer
29 views

Error in function creating query

There is an error in the following function creating query: CREATE FUNCTION `_increase_num` () RETURNS int(11) RETURNS INT READS SQL DATA DETERMINISTIC BEGIN RETURN IF(@counter, @counter:=@...
1
vote
1answer
2k views

jsonb_each_text(jsonb) returns jsonb, not text

According to docs , jsonb_each_text(jsonb) returns setof key text, value text but if you pg_typeof(value) on result it shows jsonb, Eg: SELECT *, pg_typeof(key) AS type_key, pg_typeof(value) AS ...