sql - pg: left join on table puts nil records first -
here project table:
column | type | modifiers | storage | stats target | description ------------+-----------------------------+-------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('projects_id_seq'::regclass) | plain | | name | character varying(255) | | extended | | repo_id | integer | | plain | | created_at | timestamp without time zone | | plain | | updated_at | timestamp without time zone | | plain | | user_id | integer | | plain | | data_path | character varying(255) | | extended | | private | boolean | default false | plain | | uniqueurl | character varying(255) | | extended | | urlbase | character varying(255) | | extended | | ancestry | character varying(255) | | extended | | deleted_at | timestamp without time zone | | plain | | indexes: "projects_pkey" primary key, btree (id) "index_projects_on_name_and_user_id" unique, btree (name, user_id) "index_projects_on_ancestry" btree (ancestry) "index_projects_on_deleted_at" btree (deleted_at) has oids: no
and here rating_cache table:
column | type | modifiers | storage | stats target | description ----------------+-----------------------------+------------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('rating_caches_id_seq'::regclass) | plain | | cacheable_id | integer | | plain | | cacheable_type | character varying(255) | | extended | | avg | double precision | not null | plain | | qty | integer | not null | plain | | dimension | character varying(255) | | extended | | created_at | timestamp without time zone | | plain | | updated_at | timestamp without time zone | | plain | | indexes: "rating_caches_pkey" primary key, btree (id) "index_rating_caches_on_cacheable_id_and_cacheable_type" btree (cacheable_id, cacheable_type) has oids: no
i doing left outer join on 2 tables with:
select "projects".* "projects" left outer join rating_caches on rating_caches.cacheable_id = projects.id "projects"."deleted_at" null order rating_caches.avg desc
this orders projects correctly (highest avg come first) projects no matching record in rating_caches table come before highest avg. ex: projects:
id name 1 2 b 3 c
rating_caches:
id cacheable_id avg 1 3 3.0 2 2 2.5
result of query looks like:
id name 1 3 c 2 b
shouldn't project id = 1 come last?
just use nulls last
:
order rating_caches.avg desc nulls last
as note, documentation specifies:
the
nulls first
,nulls last
options can used determine whether nulls appear before or after non-null values in sort ordering. default, null values sort if larger non-null value; is,nulls first
defaultdesc
order, ,nulls last
otherwise.
Comments
Post a Comment