How to order by Levenshtein distance? I want to order a table according to a char field using Levenshtein distance or similar because some entries may contain underscores or grammar errors.

It is a table with all the books I plan to read and it contains repeated entries I need list all the entries ordered by the field name, It should take the previous row and find the closest text. 

This is a failed attempt I made:

SELECT name, 
levenshtein(substring(name from 1 for 200), lag(name) OVER (PARTITION BY name)) 
FROM books WHERE name &lt;&gt; '';


Thanks
You didn't tell us what the "failed attempt" means. But something like this should work:

with ldist as (
   select name, 
          levenshtein(substring(name,1,200), lag(name) OVER (order by name))  as distance
   FROM books 
   WHERE name &lt;&gt; ''
) 
select * 
from ldist
order by distance;


you don't want partition by name because that essentially puts every name into a single group and thus there is no "previous" row to. 

As you you want the "previous" row based on the ordering of the name column, you need an order by name in the window definition.