0

It sounds retarded but can it be possible?

I have EMPLOYEE_ID and DEPARTMENT_ID i have to sort it according to the DEPARTMENT_ID without using ORDER BY.

It should not present anywhere in the query i.e in USING clause or in SUB-QUERY or in SELECT statement or in anywhere.

Is it possible?

Thank you.

Narasimha Maiya
  • 1,009
  • 4
  • 12
  • 35
  • 5
    No. `ORDER BY` is the *one* place where you can specify *what* ordering guarantees you want the system to provide. The system is free to return results in any order that is convenient, *provided* it complies with the `ORDER BY` clause. – Damien_The_Unbeliever Jan 20 '16 at 08:52
  • 1
    Yes, it is possible. but you must be a very good with logic, there is bubble sort, divide and sort etc. logic available – Ubiquitous Developers Jan 20 '16 at 08:52
  • 1
    If you want a specific order, do `ORDER BY`. (Even if you get the wanted order without it, it may change later, due to changed optimization etc.) – jarlh Jan 20 '16 at 08:53
  • 4
    This is impossible. The ***only*** way to sort results is to use an `order by` (really: that's the **only** way) –  Jan 20 '16 at 08:58
  • Not unless you're [Chuck Norris.](http://www.chucknorrisfacts.com/all-chuck-norris-facts) – Zohar Peled Jan 20 '16 at 09:02
  • 1
    I dunno what are you trying to do but you could try with group by (sort by groups and in this case it'd DEPARTMEND_ID. – Jessica Jan 20 '16 at 11:03
  • I was not trying to do anything. I was just curious. @Jessica,@Madhivanan – Narasimha Maiya Jan 20 '16 at 12:04
  • @Jessica That should be the answer (for some RDBMS). + [Does “group by” automatically guarantee “order by”?](http://stackoverflow.com/questions/28149876/does-group-by-automatically-guarantee-order-by) – Y.B. Jan 22 '16 at 11:30

4 Answers4

2

There are a few approaches that can work depending on particular RDBMS and none of them is to be used in production environment, but just for fun:

  1. Use XML output and apply server-side XSLT transformation (through CLR for instance) with <xsl:sort>.
  2. Use stored procedure to produce sorted list in one text return value.
  3. Write own SQL proxy client replacing -- HIDDEN MESSAGE with ORDER BY. (I admit, this is not exactly SQL solution).
  4. Create an Indexed (Materialized) View on the table sorted by DEPARTMENT_ID that would be solely used by this query. Not guaranteed to work every single time.
  5. Create temporary table with all possible IDs in incremental order, left join source table on DEPARTMENT_ID and use hints to prevent optimizer from reordering joins. Not guaranteed to work every single time.

Upd 6. When there are fewer rows to sort then the RDBMS supported CTE recursion depth:

With Example (EMPLOYEE_ID, DEPARTMENT_ID) As (
        Select 4, 2 Union All
        Select 5, 2 Union All
        Select 6, 3 Union All
        Select 7, 3 Union All
        Select 2, 1 Union All
        Select 3, 1 Union All
        Select 1, 1
    ),
    Stringified (ID) AS (
        Select
            RIGHT('0000000000' + CAST(DEPARTMENT_ID AS NVARCHAR(10)), 10) +
            RIGHT('0000000000' + CAST(EMPLOYEE_ID AS NVARCHAR(10)), 10)
        From Example
    ),
    Sorted (PREV_EMPLOYEE_ID, PREV_DEPARTMENT_ID,
            NEXT_EMPLOYEE_ID, NEXT_DEPARTMENT_ID) As (
        Select
            CAST(Right(ex1.ID, 10) AS INT),
            CAST(Left(ex1.ID, 10) AS INT),
            CAST(Right(Min(ex2.ID),10) AS INT),
            CAST(Left(Min(ex2.ID),10) AS INT)
        From Stringified ex1
        Inner Join Stringified ex2 On ex1.ID < ex2.ID
        Group By ex1.ID
    ),
    RecursiveCTE (EMPLOYEE_ID, DEPARTMENT_ID) AS (
        Select
            CAST(Right(Min(ID),10) AS INT),
            CAST(Left(Min(ID),10) AS INT)
        From Stringified
        Union All
        Select NEXT_EMPLOYEE_ID, NEXT_DEPARTMENT_ID
        From Sorted
        Inner Join RecursiveCTE
             ON RecursiveCTE.EMPLOYEE_ID = Sorted.PREV_EMPLOYEE_ID
            AND RecursiveCTE.DEPARTMENT_ID = Sorted.PREV_DEPARTMENT_ID
    )
Select *
From RecursiveCTE

Upd 7. Many RDBMS engines would sort result when applying GROUP BY, UNION, EXCEPT, INTERSECT or just DISTINCT especially if they are single-threaded or forced not to use parallelism with a hint. Not guaranteed to work every single time.

Y.B.
  • 3,526
  • 14
  • 24
1

That could be possible if you would create a index on your table where first(or only) key is DEPARTMENT_ID and you would force your query engine to use this index. This should be a plain SELECT statement as well.

But even then, it won't guarantee correct sort order.

Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
  • 1
    Even if you force a particular index to be used, it's still not guaranteed. E.g. In some circumstances, SQL Server will piggy-back one query's data access off of the back of another, already running query. So, it *could* pick up on an index scan already in progress, use that for some results, and then do a partial scan of the start of that index to complete its full scan. It's crazy what SQL systems *can* do because of the freedom that the language is designed to allow. – Damien_The_Unbeliever Jan 20 '16 at 08:55
  • @Damien_The_Unbeliever. Postgres, Oracle and DB2 will also re-use running (table) scans in the same way. –  Jan 20 '16 at 08:59
  • @Damien_The_Unbeliever I agree. I just told that it *could* be theoretically possible, that's it. Other than that, `ORDER BY` is only correct way to do this. – Evaldas Buinauskas Jan 20 '16 at 09:17
  • How would you "force your query engine" to use this index? Even if you did, the data might be already in cache and the index could be untouched. – cliffordheath Jan 20 '16 at 10:18
  • @cliffordheath That's possible in SQL Server. [Please read this link](http://blog.sqlauthority.com/2009/02/07/sql-server-introduction-to-force-index-query-hints-index-hint/) – Evaldas Buinauskas Jan 20 '16 at 10:25
  • A query "hint" does not force the optimiser to use that index. It's a *hint*. If the data is already cached, it might use *no* index. – cliffordheath Jan 21 '16 at 02:42
0

May be this link would help you

sort results without use of order by clause

This is what the link says

You cannot, at least not reliably.

Some SQL implementations may well return rows in the order of their primary keys or clustered indexes, but SQL itself is a relational algebra that returns arbitrarily ordered sets unless specifically told otherwise.

There's a good chance that the order in which rows are returned may well depend on the insertion and deletion activity since the table was created.

Community
  • 1
  • 1
Krishna P S
  • 340
  • 2
  • 9
  • 1
    Should have been a comment, not an answer. – jarlh Jan 20 '16 at 08:57
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/10959609) – David Pilkington Jan 20 '16 at 09:14
  • @DavidPilkington Edited the answer now. Thanks! – Krishna P S Jan 20 '16 at 09:28
-1

You could make your query without ORDER BY, put every row into a multidimensional array and after that sorting your array. It can be done in several languages.

In PHP it would be something like this:

$result = [];
// In $result you put every row from your SELECT

$aSortField = [];

    foreach ($result as $key => $row)   
        {
        $aSortField [$key] = $row['theNameOfYourSortColumn'];
        }

    array_multisort($aLocal, SORT_ASC, $result);    // This makes the "order by" job