0

I've tried disabling similarity column output on SELECT SIMILARITY but still cannot.

Below query will generate a column similarity:

SELECT SIMILARITY(title, 'Nation'), title
FROM gallery
WHERE title % 'Nation'
ORDER BY similarity DESC LIMIT 5;

Below query does not output similarity column but I am unable to sort:

SELECT title FROM gallery WHERE title % 'Nation';
Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked May 18, 2015 at 17:25
3
  • 1
    Like this:? SELECT title FROM gallery WHERE title % 'Nation' ORDER BY SIMILARITY(title, 'Nation') DESC LIMIT 5; Commented May 18, 2015 at 17:31
  • That works but it not following set_limit. When set set_limit value is 0.3, it will get from 0.2. I'm not sure if this is caused by Postgres bug. Thank you for pointing it out. Commented May 18, 2015 at 19:35
  • There must be an additional misunderstanding here. You won't get results with a similarity of 0.2 after running SELECT set_limit(0.3) in the same session. ypercube's query should work. You are aware that the setting only persists for the duration of the current session? Compare: stackoverflow.com/questions/27034559/… Commented May 18, 2015 at 20:01

1 Answer 1

4

Generally, you can always wrap a query as subquery if you don't want to output all rows:

SELECT title FROM (SELECT ...) sub;

But you can also use expressions in ORDER BY, not just input or output columns. So there is no need for this (like @ypercube already commented).

For the case at hand, it must be mentioned that you are using the additional module pg_trgm. What you are trying to do can be simplified to:

SELECT title
FROM gallery
WHERE title % 'Nation'
ORDER BY title <-> 'Nation'
LIMIT 5;

I replaced SIMILARITY(title, 'Nation') DESC with the simpler, equivalent title <-> 'Nation', since the <-> operator (per documentation):

Returns the "distance" between the arguments, that is one minus the similarity() value.

Either version works, but the latter is shorter and index support is bound to the operator, not the function. And you should have a GiST index on title.

Details:

Also relevant:

answered May 18, 2015 at 19:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.