TSQL verify sort order / UNION ALL

CREATE PROCEDURE Test
AS
BEGIN
SELECT * FROM (
SELECT 1 AS a,'test1' as b, 'query1' as c
UNION ALL
SELECT 2 AS a,'test22' as b, 'query22' as c
UNION ALL
SELECT 2 AS a,'test2' as b, 'query2' as c
UNION ALL
SELECT 3 AS a,'test3' as b, 'query3' as c
UNION ALL
SELECT 4 AS a,'test4' as b, 'query4' as c
) As sample
FOR XML RAW
END
Can we guarantee that the stored procedure returns results in given order?
Normally it says when we insert these select query to temporary table we can't guarantee its inserting order. So we have to use order by clause. But most of time it gives same order. Can we enforce to give it some different order? Is this related with clustered
and non clustered indices.
In second case can we enforce inserting order by adding Identity column?
Explain more on behind logic as well. I'm checking whether I need to add ORDER BY in old Stored Procedures or not.

Can we guarantee that the stored procedure returns results in given order?  
No. The only way to get a guaranteed order is to use an ORDER BY clause.
Normally it says when we insert these select query to temporary table we can't guarantee its inserting order. So we have to use order by clause. But most of time it gives same order. Can we enforce to give it some different order? Is this related with
clustered and non clustered indices.  
The only way to get a guaranteed order is to use an ORDER BY clause. Anything else is happenstance.
In second case can we enforce inserting order by adding Identity column?   Explain more on behind logic as well. I'm checking whether I need to add ORDER BY in old Stored Procedures or not.
Again: the only way to get a guaranteed order is to use an ORDER BY clause.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Sort Order of All Unplayed Episodes

    The sort order of all unplayed episodes is from Newest to Oldest, which is backwards for me.
    Why would I listen to the Newest episode first? It completely breaks any chronology of the podcasts!
    I found that you can change this for individual podcasts if you find the details by clicking on the podcast title to open its preferences, but the big list does not have the option.
    Please, give me the option to ORDER THE UNPLAYED EPISODES OLDEST AT TOP TO NEWEST AT BOTTOM!
    Thanks, in advance.

    Tom Peterson wrote:
    This did the trick for me, Harry. Thanks!
    I was surprised to see you can/must set this on a podcast-by-podcast basis, but it is hard to argue with having finer control. Oldest to newest seems like a slightly more logical default, but that may just be personal preference.
    Not to split off in a new direction, but if I then subscribe to a podcast in Podcasts app that I already subscribe to in iTunes, is it recommended I turn off syncing between iTunes and my iPhone for that podcast? Or will this question basically go away when iOS 6.0 is released?
    Do the Podcasts app and the Music/iPod app share podcast files? Or will they be duplicated on my iPhone?
    Tom
    The podcasts will duplicate themselves on your device. I turned off podcast syncing on my devices. But the weird thing is that when I sync, podcasts then copy themselves to my iTunes library. Either sync or don't, but don't copy to both.

  • 2.1 sort order on 'all projects'

    I really like the 'all projects' view, it looks like iPhoto 'events' view, which was sorted, as it should be, in alphabetical order. I love Aperture, however I've been waiting for an alphabetical sort to the 'all projects' view so that I can get rid of (or rather stop using) iPhoto. They seem to have added sort with what seems to only have two options, by date, which is horrible if, like me you have downloaded pictures or old digital photos that contain wonky incorrect information from the wild west days of digital photography.
    Any ideas on how to get things to display in 'all projects' like they do in iPhoto 'events'??
    BTW, my projects are all titled in the way they should display. events that I want by date are titled as such, other pictures are grouped in projects such as 'Shorty' (my dog).

    Sorry Grom, no, there is no UI for the kind of sort you are seeking.

  • How to set default sort order for all folders/albums/etc

    This is driving me nuts, having to change the sort order from manual to file name every time I change projects or folders (and I have a lot of both). Is there a way to set the default to just sort by file name ascending? Or sort by timestamp (that's date + time, not just date)?

    Chuckcars wrote:
    I am in process of doing some rearrangement to make Projects as the main box (the file drawer) with headings like: iPhone, Assignments, Events, Landscape, People, Travel. Then, a specific folder under the project. Then, an Album under the Folder.
    This should be started as a new thread -- do so if you have any questions.
    Strongly recommend using Projects as intended (see comments by Frank and DLSCreative in current thread ^1^ and long comment by me in another thread ^2^ ). In your case that would mean Folders with the headings you've selected, the (most likely) Projects, then Albums (and perhaps more Folders).
    ^1^ http://discussions.apple.com/thread.jspa?threadID=2716711&tstart=0
    ^2^ http://discussions.apple.com/thread.jspa?threadID=2654297&tstart=0

  • Update all views sort order in a list using powershell

    I have a column "Employee Name" in my Lists/Library of my sitecollection ,
    I need to update Sort order of all views of that  lists and library to be sort alphabetically by "Employee Name" .
    I have already some filters applied on these views.I dont want these to get effected.I want to change only the sort order to be based on "Employee Name" column.
    Any pointers on how to achieve this by Powershell will be helpful

    Hi,
    The following PowerShell script for your reference:
    $webURL = "http://siteurl";
    $listName = "ListName";
    $web = Get-SPWeb $webURL;
    $list = $web.Lists[$listName];
    $views= $list.Views;
    for ($i = 0; $i -lt $views.Count; $i++)
    $view=$views[$i];
    $view.Query = '<OrderBy><FieldRef Name="Employee_x0020_Name"/></OrderBy>';
    $view.Update();
    $list.Update();
    Best Regards
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • ITunes U Sort Order Issue

    I purchase a lot of audio courses from a company called the Teaching Company. I buy and download them as MP3's and they've worked great on all my iPods (I have a nano, a classic, and a touch 64GB). I previously kept all of the course lectures in my Audiobook section to keep them separate from my music and podcasts and other media. This was fine until I decided to purchase an Audible account and began to build up a large library of audiobooks as well. When I got my brand new 64GB iPod Touch and the new iTunes, I saw that iTunes U was now a separate entity within my library. So, for organizational purposes and to allow me to better fine-tuning of my sync preferences (I much more media than could ever fit on any of my iPods at one time), I moved all my educational and lecture media out of my Audiobooks area and into iTunes U by editing the tags through "get info".
    This has worked just fine except for one mysterious problem.
    When I view any of these audio courses (each course is an album) in iTunes, they display fine in normal sort order by track number. But when I go to listen to them on my iPod, the sort order is all jumbled up and all the tracks are out of order. So I cannot listen to the classes from one lecture to another, at the end of each lecture I must exit back to the album and FIND the next lecture. They appear to be sorted in no obvious order (not alphabetical, not by name, not by track number). Again, they are set to sort by track number in iTunes and they display (and play) perfectly straight through in iTunes. But on my iPod, the sort order is completely messed up.
    So, what's going on? Why? And how can I fix it??

    Vague789 wrote:
    Set your track numbers correctly (by right clicking, clinking 'Get Info' and clicking on the info tab), and make sure you also set the totals (e.g. 12 of 18 - the "of 18" is what I mean by the totals). This sorted it out on my iPod.
    This worked for me for my Teaching Company files. They were all jumbled previously because they took the track numbers from the default import from the internet. Once I changed it, no problem.
    It would be better if Apple allowed just a dragging, or if there was a quick tool, but at least this works.
    I had previously been using "Join Together" for stuff like this. I think I like this method better, though. I can still keep the individual lecture files on a playlist, but not have to worry about all the separate titles in a general listing.

  • Genre sort in Browser, auto sync, sort order

    I just updated to 3.1.1 and iTunes 9.0. Now Genre is missing in the browser. How can I get it back? Also none of my playlist sync in auto. I have to manually manage it. I rarely use it for music, just for listening to stories and podcasts, so it's important to have them in the correct order for listening, i.e. chapters. Now the playlist doesn't show up on the itouch sorted correctly.
    1. Doesn't have Genre in Browser. 2. Doesn't auto sync. 3. Sort order is messed up between iTunes and iTouch. 4. Is it caused by 3.1.1 or iTunes 9.0? Does anyone know how to fix these issues? I don't have an old download of iTunes 8 to uninstall 9 and reinstall 8. iTouch 3.1.1 can't be uninstalled. Shadow

    shadow1953 wrote:
    1. Doesn't have Genre in Browser.
    iTunes 9 changed the browser to a column on the left side (by default), but you can go back to how it was on top, see the View/Column Browser menu. You can have multiple filters (Artist, Album, Composer, etc.) either as a column on the left, or across the top.
    shadow1953 wrote:
    2. Doesn't auto sync.
    You have to be doing something wrong since auto-sync does work. Make sure your iPod is in auto-sync mode -- if you change the sync mode, make sure you click the "Apply" button -- if you don't, it won't change. If you're not syncing your entire library, then make sure that you've selected the playlists you want loaded onto the Touch.
    shadow1953 wrote:
    3. Sort order is messed up between iTunes and iTouch.
    Are you referring to the sort order within a playlist, or the sort order of all your playlist names? I know that the playlist name sorting has changed (again) such that punctuaion comes first, then letters, then numbers. If you're referring to the sort order of the items within a playlist, then it may be a bug -- there are reports of problems with the sorting of podcasts within playlists, so maybe the same is true for books?
    shadow1953 wrote:
    4. Is it caused by 3.1.1 or iTunes 9.0? Does anyone know how to fix these issues?
    Not sure, could be either.
    shadow1953 wrote:
    I don't have an old download of iTunes 8 to uninstall 9 and reinstall 8. iTouch 3.1.1 can't be uninstalled.
    You can get down-rev versions of iTunes at sites like filehippo (there are others). Keep in mind though that your "iTunes Library.itl" file was changed with iTunes 9 and is not backward-compatible. You'll have to look for the old .itl file in your "Previous iTunes Libraries" folder (check the date of these .itl files). If you fid the .itl file from iTunes 8, just replace the current one and then uninstall iTunes as well as "Apple Mobile Device Services" and Quicktime, then install iTunes 8.
    You can go back to a prior OS version on your Touch if you have the native file (you would if you previously did a firmware update, it stays on your computer). If you updated to 3.0 then you can go back to it by holding the SHIFT key as you click the Restore button (use the OPT key on a Mac) and then select the 3.0 version. You can't go back to 2.x in this manner, but there is a different way to go back to 2.x if you ever want to (won't go into that here).

  • Using order by with the UNION ALL operator

    Hi,
    I have 2 queries and i'm using UNION ALL to join both of them.
    And i want to sort the final result based on a column.
    When i try to do that, its not allowing me to use the ORDER BY clause.
    Any suggestions??
    Example
    select * from xxx where job='Manager'
    order by ename
    union all
    select * from yyy where job='Engineer'
    order by ename
    Thanks in advance
    --Kumar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    SQL> select * from test_emp where deptno = 10 order by ename
      2  union all
      3  select * from test_emp where deptno = 20 order by ename;
    union all
    ERROR at line 2:
    ORA-00933: SQL command not properly ended
    SQL> select * from test_emp where deptno = 10 --order by ename
      2  union all
      3  select * from test_emp where deptno = 20 order by ename;
    select * from test_emp where deptno = 20 order by ename
    ERROR at line 3:
    ORA-00904: "ENAME": invalid identifier
    SQL> select * from test_emp where deptno = 10 --order by ename
      2  union all
      3  select * from test_emp where deptno = 20 --order by ename;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7698 BLAKE      MANAGER         7839 01-MAY-81       3141          1         10
          7782 CLARK      MANAGER         7839 09-JUN-81       2700                    10
          7839 KING       PRESIDENT            17-NOV-81       5512                    10
          7934 MILLER     CLERK           7782 23-JAN-82       1433                    10
          7369 SMITH      CLERK           7902 10-OCT-06        882        123         20
          7566 JONES      MANAGER         7839 10-OCT-06       3279        123         20
          7788 SCOTT      ANALYST         7566 11-OCT-06       3307        123         20
          7876 ADAMS      CLERK           7788 10-OCT-06       1212        123         20
          7902 FORD       ANALYST         7566 10-OCT-06       3307        123         20
    9 rows selected.
    SQL> select * from
      2  (select * from test_emp where deptno = 10 union all
      3  select * from test_emp where deptno = 20)
      4  order by ename;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7876 ADAMS      CLERK           7788 10-OCT-06       1212        123         20
          7698 BLAKE      MANAGER         7839 01-MAY-81       3141          1         10
          7782 CLARK      MANAGER         7839 09-JUN-81       2700                    10
          7902 FORD       ANALYST         7566 10-OCT-06       3307        123         20
          7566 JONES      MANAGER         7839 10-OCT-06       3279        123         20
          7839 KING       PRESIDENT            17-NOV-81       5512                    10
          7934 MILLER     CLERK           7782 23-JAN-82       1433                    10
          7788 SCOTT      ANALYST         7566 11-OCT-06       3307        123         20
          7369 SMITH      CLERK           7902 10-OCT-06        882        123         20
    9 rows selected.
    SQL>

  • Union All slow with order by

    I have 2 queries that I do an "union all" and then an order by after the "union all" This seems to be extremely slow. But when I run the queries individually, they are really fast. Could some help me out with this please.
    SELECT *
      FROM (SELECT a.*, ROWNUM rnum
              FROM (SELECT   COLS......
        FROM (((SELECT  from tables with joins)
               UNION ALL
               (SELECT from tables and view with joins))
                order by colname)
          ) a
             WHERE ROWNUM <= 500)
    WHERE rnum >= 1
    PLAN_TABLE_OUTPUT
    Plan hash value: 3988534528
    | Id  | Operation                                      | Name                          | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                               |                               |   500 |  1600K|       |  3634M  (1)|999:59:59 |       |       |
    |*  1 |  VIEW                                          |                               |   500 |  1600K|       |  3634M  (1)|999:59:59 |       |       |
    |*  2 |   COUNT STOPKEY                                |                               |       |       |       |            |          |       |       |
    |   3 |    VIEW                                        |                               |  4277K|    13G|       |  3634M  (1)|999:59:59 |       |       |
    |*  4 |     SORT ORDER BY STOPKEY                      |                               |  4277K|   311M|  1095M|  3634M  (1)|999:59:59 |       |       |
    |   5 |      UNION-ALL                                 |                               |       |       |       |            |          |       |       |
    PLAN_TABLE_OUTPUT
    |*  6 |       FILTER                                   |                               |       |       |       |            |          |       |       |
    |*  7 |        HASH JOIN                               |                               |   212K|    15M|       |   153K  (1)| 00:03:37 |       |       |
    |*  8 |         HASH JOIN RIGHT OUTER                  |                               |   507 | 22308 |       |     6  (17)| 00:00:01 |       |       |
    |   9 |          TABLE ACCESS FULL                     | DIR                           |   143 |  3861 |       |     2   (0)| 00:00:01 |       |       |
    |  10 |          TABLE ACCESS FULL                     | USER                          |   507 |  8619 |       |     3   (0)| 00:00:01 |       |       |
    |  11 |         PARTITION RANGE ITERATOR               |                               |   212K|  6645K|       |   153K  (1)| 00:03:37 |   KEY |   KEY |
    |  12 |          TABLE ACCESS BY LOCAL INDEX ROWID     | FL                                |   212K|  6645K|       |   153K  (1)| 00:03:37 |   KEY |   KEY |
    |* 13 |           INDEX RANGE SCAN                     | I_FL_ID                      |   382K|       |       | 38943   (2)| 00:00:56 |   KEY |   KEY |
    |* 14 |            COUNT STOPKEY                       |                               |       |       |       |            |          |       |       |
    |* 15 |             FILTER                             |                               |       |       |       |            |          |       |       |
    |  16 |              PARTITION RANGE ITERATOR          |                               |     1 |    22 |       |   856   (1)| 00:00:02 |   KEY |   KEY |
    PLAN_TABLE_OUTPUT
    |* 17 |               TABLE ACCESS BY LOCAL INDEX ROWID| PAY                           |     1 |    22 |       |   856   (1)| 00:00:02 |   KEY |   KEY |
    |* 18 |                INDEX RANGE SCAN                | I_PAY_FLID                       |     1 |       |       |   855   (1)| 00:00:02 |   KEY |   KEY |
    |* 19 |       FILTER                                   |                               |       |       |       |            |          |       |       |
    |* 20 |        HASH JOIN RIGHT OUTER                   |                               | 25019 |  3029K|       |   138K  (1)| 00:03:17 |       |       |
    |  21 |         TABLE ACCESS FULL                      | DIR                            |   143 |  3861 |       |     2   (0)| 00:00:01 |       |       |
    |* 22 |         HASH JOIN                              |                               | 25019 |  2369K|       |   138K  (1)| 00:03:17 |       |       |
    |  23 |          TABLE ACCESS FULL                     | USER                          |   507 |  8619 |       |     3   (0)| 00:00:01 |       |       |
    |* 24 |          HASH JOIN                             |                               | 25019 |  1954K|       |   138K  (1)| 00:03:17 |       |       |
    |  25 |           INDEX FULL SCAN                      | PK_HO                         |   278 |  1112 |       |     1   (0)| 00:00:01 |       |       |
    |* 26 |           HASH JOIN                            |                               | 25019 |  1856K|       |   138K  (1)| 00:03:17 |       |       |
    |  27 |            INDEX FULL SCAN                     | PK_HO                         |   278 |  1112 |       |     1   (0)| 00:00:01 |       |       |
    PLAN_TABLE_OUTPUT
    |  28 |            NESTED LOOPS                        |                               | 25019 |  1759K|       |   138K  (1)| 00:03:17 |       |       |
    |  29 |             PARTITION RANGE ITERATOR           |                               | 25018 |   830K|       | 63575   (1)| 00:01:30 |   KEY |   KEY |
    |* 30 |              TABLE ACCESS BY LOCAL INDEX ROWID | PAY                           | 25018 |   830K|       | 63575   (1)| 00:01:30 |   KEY |   KEY |
    |* 31 |               INDEX RANGE SCAN                 | I_PAY_TIME_ID                  |  1493K|       |       |  9052   (2)| 00:00:13 |   KEY |   KEY |
    |* 32 |             TABLE ACCESS BY GLOBAL INDEX ROWID | FL                            |     1 |    38 |       |     3   (0)| 00:00:01 | ROWID | ROWID |
    |* 33 |              INDEX UNIQUE SCAN                 | PK_FL                         |     1 |       |       |     2   (0)| 00:00:01 |       |       |
      SELECT *
      FROM (SELECT a.*, ROWNUM rnum
              FROM ( SELECT  from tables with joins order by colname) a
             WHERE ROWNUM <= 500)
    WHERE rnum >= 1
    PLAN_TABLE_OUTPUT
    Plan hash value: 3503998222
    | Id  | Operation                                     | Name                    | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                              |                         |   500 |  1228K|   222K  (1)| 00:05:15 |       |       |
    |*  1 |  VIEW                                         |                         |   500 |  1228K|   222K  (1)| 00:05:15 |       |       |
    |*  2 |   COUNT STOPKEY                               |                         |       |       |            |          |       |       |
    |   3 |    VIEW                                       |                         |   520 |  1271K|   222K  (1)| 00:05:15 |       |       |
    |*  4 |     FILTER                                    |                         |       |       |            |          |       |       |
    |   5 |      NESTED LOOPS OUTER                       |                         |    26 |  1976 |    54   (0)| 00:00:01 |       |       |
    PLAN_TABLE_OUTPUT
    |   6 |       NESTED LOOPS                            |                         |    26 |  1274 |    48   (0)| 00:00:01 |       |       |
    |   7 |        PARTITION RANGE ITERATOR               |                         |   212K|  6645K|    22   (0)| 00:00:01 |   KEY |   KEY |
    |   8 |         TABLE ACCESS BY LOCAL INDEX ROWID     | FL                      |   212K|  6645K|    22   (0)| 00:00:01 |   KEY |   KEY |
    |*  9 |          INDEX RANGE SCAN                     | I_FL_START_ID              |    47 |       |     8   (0)| 00:00:01 |   KEY |   KEY |
    |* 10 |           COUNT STOPKEY                       |                         |       |       |            |          |       |       |
    |* 11 |            FILTER                             |                         |       |       |            |          |       |       |
    |  12 |             PARTITION RANGE ITERATOR          |                         |     1 |    22 |   856   (1)| 00:00:02 |   KEY |   KEY |
    |* 13 |              TABLE ACCESS BY LOCAL INDEX ROWID| PAY                   |     1 |    22 |   856   (1)| 00:00:02 |   KEY |   KEY |
    |* 14 |               INDEX RANGE SCAN                | I_PAY_ID               |     1 |       |   855   (1)| 00:00:02 |   KEY |   KEY |
    |  15 |        TABLE ACCESS BY INDEX ROWID            | USER                     |     1 |    17 |     1   (0)| 00:00:01 |       |       |
    |* 16 |         INDEX UNIQUE SCAN                     | PK_USER                  |     1 |       |     0   (0)| 00:00:01 |       |       |
    PLAN_TABLE_OUTPUT
    |  17 |       TABLE ACCESS BY INDEX ROWID             | DIR                    |     1 |    27 |     1   (0)| 00:00:01 |       |       |
    |* 18 |        INDEX UNIQUE SCAN                      | PK_DIR                 |     1 |       |     0   (0)| 00:00:01 |       |       |
       SELECT *
      FROM (SELECT a.*, ROWNUM rnum
              FROM ( SELECT from tables and view with joins order by colname) a
             WHERE ROWNUM <= 500)
    WHERE rnum >= 1
    PLAN_TABLE_OUTPUT
    Plan hash value: 1786470271
    | Id  | Operation                                   | Name                          | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                            |                               |   500 |  1600K|  1696   (1)| 00:00:03 |       |       |
    |*  1 |  VIEW                                       |                               |   500 |  1600K|  1696   (1)| 00:00:03 |       |       |
    |*  2 |   COUNT STOPKEY                             |                               |       |       |            |          |       |       |
    |   3 |    VIEW                                     |                               |   501 |  1596K|  1696   (1)| 00:00:03 |       |       |
    |*  4 |     FILTER                                  |                               |       |       |            |          |       |       |
    |   5 |      NESTED LOOPS                           |                               |   501 | 60120 |  1696   (1)| 00:00:03 |       |       |
    PLAN_TABLE_OUTPUT
    |   6 |       NESTED LOOPS                          |                               |   501 | 58116 |  1696   (1)| 00:00:03 |       |       |
    |   7 |        NESTED LOOPS OUTER                   |                               |   501 | 56112 |  1695   (1)| 00:00:03 |       |       |
    |   8 |         NESTED LOOPS                        |                               |   501 | 42585 |  1689   (1)| 00:00:03 |       |       |
    |   9 |          NESTED LOOPS                       |                               |   501 | 34068 |  1550   (1)| 00:00:03 |       |       |
    |  10 |           PARTITION RANGE ITERATOR          |                               |   829K|    23M|    42   (0)| 00:00:01 |   KEY |   KEY |
    |  11 |            TABLE ACCESS BY LOCAL INDEX ROWID| PAY                        |   829K|    23M|    42   (0)| 00:00:01 |   KEY |   KEY |
    |* 12 |             INDEX RANGE SCAN                | I_PAY_TIME_ID               |   902 |       |     9   (0)| 00:00:01 |   KEY |   KEY |
    |* 13 |           TABLE ACCESS BY GLOBAL INDEX ROWID| FL                               |     1 |    38 |     3   (0)| 00:00:01 | ROWID | ROWID |
    |* 14 |            INDEX UNIQUE SCAN                | PK_FL                            |     1 |       |     2   (0)| 00:00:01 |       |       |
    |  15 |          TABLE ACCESS BY INDEX ROWID        | USER                              |     1 |    17 |     1   (0)| 00:00:01 |       |       |
    |* 16 |           INDEX UNIQUE SCAN                 | PK_USER                           |     1 |       |     0   (0)| 00:00:01 |       |       |
    PLAN_TABLE_OUTPUT
    |  17 |         TABLE ACCESS BY INDEX ROWID         | DIR                          |     1 |    27 |     1   (0)| 00:00:01 |       |       |
    |* 18 |          INDEX UNIQUE SCAN                  | PK_DIR                          |     1 |       |     0   (0)| 00:00:01 |       |       |
    |* 19 |        INDEX UNIQUE SCAN                    | PK_HO                         |     1 |     4 |     0   (0)| 00:00:01 |       |       |
    |* 20 |       INDEX UNIQUE SCAN                     | PK_HO                         |     1 |     4 |     0   (0)| 00:00:01 |       |       |
    ---------------------------------------------------------------------------------------------------------------------------------------------

    Can you limit the number of rows coming out of each part of the UNION ALL before limiting the number of rows you're trying to return? So that you end up with something like
    SELECT *
      FROM (<<Get first 500 rows from first query>>
           UNION ALL
           <<Get first 500 rows from second query>>)
    WHERE rownum <= 500It appears from the query plan that your problem is that Oracle is sorting the entire result of the UNION ALL before finding the first 500 rows. That's obviously rather time consuming since the two queries return 10's of GB of data. Individually, the two queries are fast because you're limiting each of them to 500 rows, so Oracle can do a quick index scan (presumably on the sort column) that would find those rows.
    And depending on what's behind the queries, I'd look to see whether you can put some additional filter conditions in place to look for data with dates in the past day or two in order to at least limit the worst case if Oracle does have to sort everything.
    Justin

  • Is the order in which a UNION ALL query returns rows guaranteed?

    Guys
    I'm doing a kind of query where I want to return matching rows in a priority order and take the first one. THink of it as getting the most specific error message for a particular context.
    SELECT * FROM (
    SELECT msg FROM errormessages WHERE device = 'x'
    UNION ALL
    SELECT msg FROM errormessages WHERE client = 'y'
    UNION ALL
    SELECT msg FROM (SELECT msg from errormessages WHERE class LIKE 'generic_' ORDER BY class)
    UNION ALL
    SELECT 'missing error message' FROM dual
    WHERE ROWNUM =1
    If UNION ALL is guaranteed to return rows in this order, great. If not, would it be better to have:
    SELECT * FROM ( SELECT * FROM(
    SELECT 1 as ord, msg FROM errormessages WHERE device = 'x'
    UNION ALL
    SELECT 2, msg FROM errormessages WHERE client = 'y'
    UNION ALL
    SELECT 4+SUBSTR(class, 7, 1), msg FROM errormessages WHERE class LIKE 'generic_'
    UNION ALL
    SELECT 9999, 'missing error message' FROM dual
    ) ORDER BY ord )
    WHERE ROWNUM =1Or, another option:
    SELECT msg FROM(
    SELECT
      CASE
        WHEN device = 'x' THEN 1
        WHEN client = 'y' THEN 2
        WHEN class LIKE 'generic_' THEN 4+SUBSTR(class, 7, 1)
      END as ord, msg
    FROM (
      SELECT * FROM errormessages WHERE device = 'x' OR  client = 'y' OR class LIKE 'generic_'
      UNION ALL
      SELECT 999, 'missing error' FROM dual
    ) ORDER BY ord
    )WHERE ROWNUM =1As you can see there is a complication in the generic; devices may advertise that they accept 1,2,3 or 4 lines of info, so I want to use the advertised capabiltiy to pick the most relevant message from the generic set if no specifics exist for the device or the client
    Which was would you go?
    Cheers
    Edited by: charred on Feb 11, 2009 4:56 AM - code tags

    charred wrote:
    So tell me guys, do I go for:
    4 queries unioned together
    or
    1 query with 4 ORs in the where clause and a case when to determine priority?It will depend on your conditions, but if you look at your explain plans you should get an idea for which is the better one; typically I would expect this to be the OR method...
    SQL> select * from emp where deptno = 20
      2  union all
      3  select * from emp where job = 'CLERK'
      4  union all
      5  select * from emp where sal > 2500;
    Execution Plan
    Plan hash value: 3153085224
    | Id  | Operation                    | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |          |    14 |   546 |     8  (75)| 00:00:01 |
    |   1 |  UNION-ALL                   |          |       |       |            |          |
    |   2 |   TABLE ACCESS BY INDEX ROWID| EMP      |     5 |   195 |     2   (0)| 00:00:01 |
    |*  3 |    INDEX RANGE SCAN          | DEPT_IDX |     5 |       |     1   (0)| 00:00:01 |
    |*  4 |   TABLE ACCESS FULL          | EMP      |     4 |   156 |     3   (0)| 00:00:01 |
    |*  5 |   TABLE ACCESS FULL          | EMP      |     5 |   195 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - access("DEPTNO"=20)
       4 - filter("JOB"='CLERK')
       5 - filter("SAL">2500)
    Statistics
              1  recursive calls
              0  db block gets
             18  consistent gets
              1  physical reads
              0  redo size
           1328  bytes sent via SQL*Net to client
            396  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> select * from emp
      2  where deptno = 20 or job = 'CLERK' or sal > 2500;
    Execution Plan
    Plan hash value: 3956160932
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |    10 |   390 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP  |    10 |   390 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("DEPTNO"=20 OR "SAL">2500 OR "JOB"='CLERK')
    Statistics
              1  recursive calls
              0  db block gets
              8  consistent gets
              0  physical reads
              0  redo size
           1146  bytes sent via SQL*Net to client
            396  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              9  rows processed
    SQL>

  • HT4236 Hello, does anyone have any advice on how to sort photos in an albumn on an Iphone by date of photo? I've ordered them all in my Pictures but then when I sync them across through Itunes, they all end up in a jumble on my phone. Thanks!

    Hello, does anyone have any advice on how to sort photos in an albumn on an Iphone by date of photo? I've ordered them all in my Pictures but then when I sync them across through Itunes, they all end up in a jumble on my phone. Thanks!

    When viewing an album on the iPhone you can tap "Photos" at the bottom and that will show all photos by date. Unfortunately though it is all photos, not just the album you are currently viewing.
    What I have done is the following. On the computer I have a main folder (e.g. iPhone photos) and then make sub-folders within that. Placing photos that will be synched to the iPhone into various subfolders gives quite a bit of organizational capablility. In iTunes when you select the main folder to sync, the sub-folders will show on the iPhone as separate albums. Beyond that, in one case where I really wanted a specific sort within an album I renamed the photos on the computer (something like A-picxxx, B-picxxx) so they sorted on the computer alphabetically in the order I want on the phone. That sort order was maintained after the sync.
    Note that each time you sync using iTunes, the non-Camera Roll pictures on the phone will be set to match the current iTunes settings/photos -- so you can experiment.

  • All Photos Album Incorrect Sort Order

    When I view the album "All Photos" from iCloud.com my photos are sorted by date with the newest ones at the bottom. When I view "All Photos" within iOS or the OS X app, the sorting order isn't correct. Any ideas?
    Thanks!

    I think this is an embarrassing thought-fail on Apple's part.
    After removing good ways of sharing photos from one library to another, people end up having to get older pictures, or pictures loaded into a laptop while traveling, back onto our main Photos libraries though copying (edited) files over the network and re-add them. This create systematic discrepancies in date added and date taken.
    When "All Photos" Panoramas", "Videos" and otherwise handy views can only be viewed by date added they add to the feeling of having to keep your photos in an exposed disorder.
    If you think of a photo, do you think about when/where you took it or when/to what library you added the photo?
    People think of the first, and machines (and now apparently Apple) intuitively think of the second..
    But maybe I'm too harsh, and I have missed something. Can anybody see a good reason for focusing on date added rather than date taken?

  • How to change sort order when viewing all tracks by an artist?

    When I choose:
    Music --> Artists --> <any artist> --> All
    The tracks are organized in the order they apear in an alphabetized list of that artist's albums.
    For example:
    Joe Blow - CD 1
    Track 1
    Track 2
    Track 3
    Joe Blow - CD 2
    Track 1
    Track 2
    Track 3
    In the "All Songs By Artist" list, the songs appear as:
    Track 1
    Track 2
    Track 3
    Track 1
    Track 2
    Track 3
    How can I cange the sort order, so that they are sorted alphabetically, like this?
    Track 1
    Track 1
    Track 2
    Track 2
    Track 3
    Track 3
    Thanks,
    - Robert
    iPod nano

    I'm pretty sure you can't do that.

  • All Projects view - Sort Order

    Is there a way of changing the sort order of the All Projects view - either to name order, or custom rather than the way it seems at the moment - time of project creation from oldest to newest?
    Jason

    I am also looking for a way to do this. When you have 300 projects, it's annoying to always have to scroll down to the bottom every time you click into projects view. I wonder if there is a hidden preference or something like that. Can anybody help?

  • Using order by in Union ALL

    hi Following is my query and am unable to accomplish my order by statement in Union All . please help me in this.
    <code>
    SELECT b.audit_trail_id,
    TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    (u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
    b.col_name "Field",
    b.new_value "New Value",b.previous_value "Old Value",
    a.lot_id,
    b.comment_text "Comments"
    FROM clem_audit_trail b,lot a, users u
    WHERE a.lot_id = b.lot_id(+)
    AND u.user_id(+) = b.last_update_user_id
    AND a.lot_id in (select lot_id from request_lot where request_id = 51914)
    AND col_name IN
    ('Interim Release Date',
    'Final Disposition Date',
    'On Time Disposition',
    'Intended Use',
    'REJECTS_YN',
    '# of QARs',
    '# of Quality Events',
    '# of LIRs',
    '# of Change Controls',
    '# of Batch Records',
    '# of GMP Batch Records',
    'EXPLANATION',
    'QA Notes',
    'GDMS_LINK')
    AND UPPER (table_name) IN('LOT') order by b.last_update_date
    UNION ALL
    SELECT b.audit_trail_id,
    TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    (u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
    b.col_name "Field",
    b.new_value "New Value",b.previous_value "Old Value",
    r.request_id,
    b.comment_text "Comments"
    FROM clem b,request r, users u
    WHERE r.request_id = b.request_id(+)
    AND u.user_id(+) = b.last_update_user_id
    AND r.request_id = 51914
    AND UPPER (table_name) IN ('REQUEST') AND
    b.col_name IN ('Partial Release',
    'All QP Docs in GDMS',
    'Number of Batch Records',
    'Request',
    'QP Issues',
    'Snag Comments',
    'Responsible Group',
    'Reason Late',
    'Study Impact',
    'Other Details',
    'Request Status',
    'QP Link to GDMS'
    ) order by b.last_update_date
    </code>
    If i execute individually it works fine, if i use union all it throughs error for me.
    Any suggestion...

    Hi,
    In a set operation (such as UNION) table aliases (such as b.) only have meaning within the branch in which they are defined. The ORDER BY clause is not part of any 1 branch, so a table alias can't be used there.
    In most cases, you can use a column name (or alias) from the first branch, like this:
    SELECT    b.audit_trail_id,
              TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    order by  "Revision Date"
    ;and you can always order by column number, like this:
    SELECT    b.audit_trail_id,
              TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    order by  2
    ;In this case, however, there's an extra problem. You're transforming the DATE to a string in the SELECT clause. The string is all that's available in the ORDER BY clause, and the string '19-NOV-2012' comes after the string '01-JAN-2015', because the character '1' comes after '0'. Perhaps the simplest solution is to have your front end, and not the query, format the dates. In SQL*Plus, you can do this:
    ALTER SESSION  SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
    SELECT    b.audit_trail_id,
              b.last_update_date    AS "Revision Date",
    order by  2
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

Maybe you are looking for

  • Period = Year

    Hi, I have a dashboard prompt where users are picking a financial period in the format MON-YY, but where APR-09 to MAR-10 = financial year 2010. The behaviour I want on the page is that the user picks the PERIOD in the dashboard prompt, but certain r

  • I am having trouble with comcast e mail using safari

    I am having trouble with xfinity e mail using browser, SAFARI

  • Quark eps files crash PhotoShop CS2

    I have an intermittent problem I have not had with previous versions of PS. When I open a Quark eps (rasterize) it will only open if there are no other PS files open. Otherwise, PS will crash or I will get a "not enough memory" message. Same file wil

  • Transferring IPod Librabry to new Computer & Hard Drive Failure

    My main computer had a hard drive failure and after I got a new hard drive I can't find a way to transfer the music library from my IPod to the new computer. I can't de-authorize the old computer beacuse the hard drive is dead. Does anyone know how t

  • Reinstall Adobe using Vista Windowa

    I lost access to Flashplayer. When I tried to reinstall it says close programs Internet Explorer and Waol? Please advise how to reinstall. Thank you