Problem with Declaration ORDER BY

1

I have the following concern:

When making this query

SELECT * FROM la_tabla ORDER BY padre

row 4 should be located below row 1, however I am getting this result, what is the error here?

    
asked by Alex Hunter 18.12.2017 в 19:51
source

3 answers

2

What happens is that the null values can not be drawn by the ORDER BY.

I suggest you try to give it a value for when they are null, like this:

SELECT * FROM la_tabla ORDER BY padre WHEN padre is null THEN "" ELSE padre END, padre

The "WHEN" will evaluate that if it is null it puts an "empty" string that can be drawn.

    
answered by 18.12.2017 / 20:06
source
1

OP comment:

  

The logic is that each new record will "inherit" the parent id from above, so when the select all is done, it should be positioned below its parent.

The simplest solution to this problem depends on how many parent-child levels you allow. If there can only be one level, so there can never be "grandparents", then you can make the order this way:

SELECT * 
  FROM la_tabla 
 ORDER BY case when padre is null then id else padre end, -- agrupa hijos con padres
          padre is not null,                              -- hijos después de padres
          id                                              -- hijos en orden de ID

... where with the expression CASE the children are sorted using the ID of the parent so that they are grouped together.

But if it is possible to have several parent-child levels, then it is necessary to use a recursive query. This would be an example (inspired by this answer ):

with recursive cte as (
  select id, contenido, padre, array[id] as path
    from la_tabla
   where padre is null
   union all
  select t.id, t.contenido, t.padre, c.path || t.id as path
    from cte c
    join la_tabla t
      on t.padre = c.id
)
select id, contenido, padre
 from cte
 order by path
    
answered by 18.12.2017 в 21:09
0

I imagine that you mean to order from highest to lowest, being the 1 the "largest" to have one unlike the others that are null. You could try using DESC

Like this:

SELECT * 
FROM la_tabla 
ORDER BY padre DESC

I hope it serves you!

    
answered by 18.12.2017 в 20:02