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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Please **[EDIT]** your question and add some [sample data](http://plaintexttools.github.io/plain-text-table/) and the expected output based on that data. [**Formatted text**](http://stackoverflow.com/help/formatting) please, [**no screen shots**](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557). **[edit]** your question - do **not** post code or additional information in comments. –  Nov 28 '17 at 08:55
  • what makes you think, you need function for it?.. – Vao Tsun Nov 28 '17 at 08:58
  • i dont want to create new table . – Christos Antonopoulos Nov 28 '17 at 09: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. – Abelisto Nov 28 '17 at 10:16
  • I want get results of other table with batch queries not at once and return unique results – Christos Antonopoulos Nov 28 '17 at 10:24
  • to resolve the issue can i create temporary table ? – Christos Antonopoulos Nov 30 '17 at 08:34

1 Answers1

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 ...

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228