This one has been stumping me for a while, not sure there is a fix after the research I've already done.
Problem:
I have an Oracle 12C DB table with the following DDL:
CREATE TABLE TEST_TABLE
(
ID NUMBER(10, 0) NOT NULL
, STRINGCOL VARCHAR2(50)
, CONSTRAINT TEST_TABLE_PK PRIMARY KEY
(
ID
)
ENABLE
);
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (1, null);
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (2, 'ZZZZ');
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (3, '1111');
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (4, 'zzzz');
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (5, '9999');
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (6, 'aaaa');
INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (7, 'AAAA');
I want to sort this column in either ASC or DESC and have values in this order:
Expected Outcome:
ASC | DESC |
---|
(null) | zzzz |
1111 | aaaa |
9999 | ZZZZ |
aaaa | AAAA |
zzzz | 9999 |
AAAA | 1111 |
ZZZZ | (null) |
EF Core 2.2 LINQ expression (Descending sort):
var results = dbContext.TestTables.OrderByDescending(x => x.StringCol).ToList();
SQL Statement constructed:
SELECT "x"."ID", "x"."STRINGCOL"
FROM "TEST_TABLE" "x"
ORDER BY "x"."STRINGCOL" DESC;
Query Results:
STRINGCOL |
---|
(null) |
zzzz |
aaaa |
ZZZZ |
AAAA |
9999 |
1111 |
The SQL query I want to achieve is the following:
SELECT "x"."ID", "x"."STRINGCOL"
FROM "TEST_TABLE" "x"
ORDER BY "x"."STRINGCOL" DESC NULLS LAST
FETCH NEXT 20 ROWS ONLY;
Query Results:
STRINGCOL |
---|
zzzz |
aaaa |
ZZZZ |
AAAA |
9999 |
1111 |
(null) |
I've tried a number of LINQ expressions, and have come up empty on getting the generated SQL query to properly allow this type of sorting. Seems like many others would want this same thing, am I missing something here?
EF Core 2.2 LINQ expression (Descending sort):
var results = dbContext.TestTables.OrderByDescending(x => !string.IsNullOrEmpty(x.StringCol)).ThenByDescending(x => x.StringCol).ToList();
Generated Query:
SELECT "x"."ID", "x"."STRINGCOL"
FROM "TEST_TABLE" "x"
ORDER BY CASE
WHEN "x"."STRINGCOL" IS NOT NULL AND ("x"."STRINGCOL" <> N'')
THEN 1 ELSE 0
END DESC, "x"."STRINGCOL" DESC;
Query Results:
STRINGCOL |
---|
(null) |
zzzz |
aaaa |
ZZZZ |
AAAA |
9999 |
1111 |