sql - Order by with a condition -


i have 2 tables, products , category. each product related specific category, , has expiry_date may null value.

i want query productsordered soonest expiry_date first. null-expiry_date products ordered last category specific name, food.

updated (sample data below):

product table:

enter image description here

category table:

enter image description here

results:

enter image description here

this isn't ordering, want exclude rows null dates include others based on category name; , order what's left:

select p.prod_id, p.name, p.expiry_date, c.cat_id product p join category c on c.cat_id = p.cat_id (c.name = 'food' or p.expiry_date not null) order p.expiry_date desc nulls last; 

the where clause excludes products null expiry dates, unless in category called 'food'. order-by straightforward, though want in descending date order need specify nulls last those... er... last.

demo sample data in ctes:

with product (prod_id, name, expiry_date, cat_id) (   select 1, 'name1', date '2018-01-10', 1 dual   union select 2, 'name2', date '2018-01-11', 2 dual   union select 3, 'name3', date '2018-01-12', 3 dual   union select 4, 'name4', null, 1 dual   union select 5, 'name5', null, 2 dual   union select 6, 'name6', date '2018-01-13', 2 dual   union select 7, 'name7', date '2018-01-14', 2 dual   union select 8, 'name8', null, 3 dual ), category (cat_id, name) (   select 1, 'food' dual   union select 2, 'food1' dual   union select 3, 'food2' dual ) select p.prod_id, p.name, p.expiry_date, c.cat_id product p join category c on c.cat_id = p.cat_id (c.name = 'food' or p.expiry_date not null) order p.expiry_date desc nulls last;     prod_id name  expiry_dat     cat_id ---------- ----- ---------- ----------          7 name7 2018-01-14          2          6 name6 2018-01-13          2          3 name3 2018-01-12          3          2 name2 2018-01-11          2          1 name1 2018-01-10          1          4 name4                     1 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -