1

I need to add unique constraint to the urls column:

CREATE OR REPLACE FUNCTION myFunction() RETURNS TABLE(urls TEXT) LANGUAGE plpgsql AS $$ DECLARE --my code BEGIN END; 

How to make urls column unique?

6
  • Please Edit your question and add some sample data and the expected output based on that data. Formatted text please, no screen shots. edit your question - do not post code or additional information in comments. Commented Nov 28, 2017 at 8:55
  • what makes you think, you need function for it?.. Commented Nov 28, 2017 at 8:58
  • i dont want to create new table . Commented Nov 28, 2017 at 9:06
  • You can not apply any constraints to the function's result directly (except of natural constraints of the type returned). Make sure that the values are unique inside the function's body. Commented Nov 28, 2017 at 10:16
  • I want get results of other table with batch queries not at once and return unique results Commented Nov 28, 2017 at 10:24

1 Answer 1

1

I want get results of other table with batch queries not at once and return unique results

It's not possible to add a UNIQUE constraint to the return type of a function like you can do it in a table definition.

You could use UNION (not UNION ALL) to get unique URLs like this:

CREATE OR REPLACE FUNCTION myfunction() RETURNS TABLE(url TEXT) AS -- singular term "url" makes more sense $func$ BEGIN RETURN QUERY SELECT url FROM ... UNION SELECT url FROM ... -- more? ; END $func$ LANGUAGE plpgsql; 

This is an SQL feature and you wouldn't need PL/pgSQL for the single UNION query. Nor even a function. A plain (sub-)query or a VIEW are alternatives.

Related:

Or you just return everything from the function:

... RETURN QUERY SELECT url FROM ...; RETURN QUERY SELECT url FROM ...; -- more ? ... 

and de-duplicate the result in the call like:

SELECT DISTINCT url FROM myfunction(); 

To resolve the issue can I create temporary table?

You can. But be aware ...

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.