Produce a range of numbers with select from the gaps of ID column

(1)
Suppose I have a table t which has rows like this:
A B
2 4
6 7
I would like to use select to produce rows with numbers ranging between A column and B column inclusive
for each row, like this:
select ... from t ...
2
3
4
6
7
(2)
Suppose I have ID column which has gaps, I would like to get lowest <N> available numbers between the gaps.
I did research, and I can find the range of the gaps, but I cannot have the numbers listed individually, that is why
I ask question (1). But is there a direct way to get the list instead of going through ranges and the list.
For example, I have ID column which has
2
5
6
7
9
2000000
I would like to get a select query that produces
select ...
3
4
8
10
11
I have a way to get a list from 2 to 2000000 and then minus what we have to get all the
gap numbers, but that is not efficient and could runs out of memory.
PS: Before I post to this group, I did research already on "connect by", with recursive queries.

First of all, I would like to thank jeneesh and Frank for helpful and correct reply. However, due to the a bug of this forum,
when I mark jeneesh's reply as correct, I cannot mark Frank's reply as correct anymore. Therefore I would like to formally
state here that I have tested both solutions and they are both correct. jeneesh and Frank use different approach, connect by
and less join ( <=, I do not know what is the proper name for it ).
Secondly I would like to report my small findings: use connect by, you control the level from 1 to the max number, so you
do not need to use order by, and the performance is better (0.37 seconds version 0.92 seconds). And also it performs better
if I use an intermediate view to limit the result sets. One line of code is worth one thousand words, now I am posting two
versions of the code and highlighted the points I mentioned here.
I am sorry that either I do not know how to format the code or I do not have the capability when posting on this forum.
The code listing does not look good, but I hope you get the idea. I have "plain text" and I am not if I can use fixed width font
and preserve space. After I used the spelling checker, it becomes double spaced and I have to manually delete the blank lines.
/* I learned about { code } after the post and edited the original post */
Thanks again to both jeneesh and Frank.
"connect by" version:
SQL> VARIABLE  new_id_cnt NUMBER
SQL> EXEC        :new_id_cnt := 10;
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00
SQL> WITH my_table AS
  2  (
  3     SELECT num
  4     FROM   prs_elm
  5     WHERE  1=1
  6  )
  7  ,       my_num   AS
  8  (
  9  SELECT num, ct
10  FROM   (
11                    SELECT num AS num, LEAD(num) OVER (ORDER BY num) - num - 1 AS ct
12                    FROM   ( SELECT 0 AS num
13                             FROM   DUAL
14                             UNION ALL
15                             SELECT num
16                             FROM   my_table
17                             UNION ALL
18                             SELECT ( MAX(num) + :new_id_cnt + 1 ) AS num
19                             FROM   my_table
20                    )
21          )
22  WHERE      ct >= 1
23  AND         ROWNUM <= :new_id_cnt
24  )
25  SELECT     num + level AS available_id
26  FROM       my_num
27  WHERE      ROWNUM  <= :new_id_cnt
28  CONNECT BY level <= ct
29  AND        prior num = num
30  AND        prior sys_guid() is not null
31  ;
AVAILABLE_ID
        3219
        3261
        3264
        3269
        3270
        3275
        3281
        3288
        3289
        3290
10 rows selected.
Elapsed: 00:00:00.37"Less join" version:
SQL> VARIABLE  new_id_cnt NUMBER
SQL> EXEC        :new_id_cnt := 10;
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00
SQL> WITH my_table AS
  2  (
  3     SELECT num
  4     FROM   prs_elm
  5     WHERE  1=1
  6  )
  7  ,       my_num   AS
  8  (
  9                    SELECT num AS num, LEAD(num) OVER (ORDER BY num) - num - 1 AS ct
10                    FROM   ( SELECT 0 AS num
11                             FROM   DUAL
12                             UNION ALL
13                             SELECT num
14                             FROM   my_table
15                             UNION ALL
16                             SELECT ( MAX(num) + :new_id_cnt + 1 ) AS num
17                             FROM   my_table
18                    )
19  )
20  ,       my_cnt    AS
21  (
22          SELECT  LEVEL AS ct
23          FROM    DUAL
24          CONNECT BY    LEVEL <= :new_id_cnt
25  )
26  SELECT     available_id
27  FROM
28  (
29          SELECT    n.num + c.ct AS available_id
30          FROM      my_num n
31          JOIN      my_cnt c  ON c.ct <= n.ct
32          WHERE     n.ct >= 1
33          ORDER BY  available_id
34  )
35  WHERE      ROWNUM  <= :new_id_cnt
36  ;
AVAILABLE_ID
        3219
        3261
        3264
        3269
        3270
        3275
        3281
        3288
        3289
        3290
10 rows selected.
Elapsed: 00:00:00.92PS: In Frank's code, there is a typo, <= should read as <.
Edited by: PuraVidaOTN on 04-feb-2013 22:49
What: To use tags to format the code.
Edited by: PuraVidaOTN on 04-feb-2013 22:56                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Performance problem with select from _DIFF view

    Hi,
    we have a versioned table with more then one million records. We use the DBMS_WM.SetDiffVersions procedure and select from DIFF view to get data differences between two workspaces. The problem is that the select from the DIFF view is very slow. I takes more than 15 minutes. Has anybody an idea why it consumes so much time? Is there any way how to improve it?
    Thanks and regards
    Ondrej

    Hi,
    This can be due to any number of things, but is typically caused by an inefficient optimizer plan. Make sure that statistics on the _LT table have been recently analyzed.
    Also the following information would be useful:
    1. What is the relationship of the workspaces that you are trying to compare (parent/child, children of the same parent, etc) ?
    2. How many and of what type dml are being performed in the workspaces ?
    3. What version of Workspace Manager are you using and what is the version of the database ?
    4. What is the time needed to select from the _DIFF view based on the primary key ?
    Regards,
    Ben

  • MacBook Pro won't stay asleep with external monitor attached.  When sleep is selected from the Apple menu the computer will go to sleep only to continually wake up...go back to sleep...wake up...etc. every few seconds.

    MacBook Pro won't stay asleep with external monitor attached.  When sleep is selected from the Apple menu the computer will go to sleep only to continually wake up...go back to sleep...wake up...etc. every few seconds.  This only happens when using the external monitor. Does anyone have any suggestions?

    Mine does that too. The worst thing is when it goes to sleep, then wakes up and keeps running while the lid is closed and it is wrapped up in a case. I am afraid when the hot weather comes it is going to burn up. I am hoping Apple fixes it in the software or they may have a melted MBP to replace.
    Then when I open the lid it is crashed running at fill tilt, pumping out heat to beat the band. I am forced to hold the button down and reboot.
    I wiped my hard disk and reinstalled my OS, but it didn't help. I reversed my OS to 10.5.0 and it solved the DVI problem but still won't sleep. This post will probably be deleted by Apple, they did it a few days ago. I just don't know what to do, and I consider myself a real Apple expert. Just hoping you realize you are not the only one.

  • I just connected my Mac Mini running OS 10.6.8 to a IG 32' monitor. What resolution should I select from the menu?

    I just connected my wife's Mac Mini running OS 10.6.8 to an IG 32' monitor. What resolution should I select from the menu in order to provide maximum screen appearance? My wife has AMD and a visual acuity of 20/400 with central scotonata.

    In System Preferences:Displays you have an option to show
    Displays Prefs in the title bar above the screen - where she can
    iteratively adjust to her liking. Higher screen resolutions, ironically,
    result in smaller characters so adjust to suit. Below, Displays is
    4th from L.
    All best, Tom

  • How do i create a drop down menu for selecting from the drop down arrow

    how can i create a drop down menu so that when i click on the arrow in the cell i can select from the menu that appears

    katiesandell wrote:
    how can i create a drop down menu so that when i click on the arrow in the cell i can select from the menu that appears
    Hi Katie,
    Welcome to Apple Discussions and the Numbers '09 forum.
    Numbers vocabulary for this feature is a "Pop-up Menu". It's available as a Cell Format, and is set and edited in the Cell Format Inspector.
    See "Using a Checkbox, Slider, Stepper, or Pop-Up Menu in Table Cells" starting on page 96 of the Numbers '09 User Guide.
    This guide, and the equally useful iWork Formulas and Functions User Guide are available for download through the Help menu in Numbers.
    Regards,
    Barry

  • Views - SELECT from VIEW and SELECT from the query inside view definition returning different results

    Hi,
    I am facing this weird issue. Any help would be appriciated.
    I have view with the following definition:
    CREATE VIEW [marketing].[OpenedMails]
    AS
    SELECT
    ID_EmailAddress, 
    ID_Date_Opened, 
    ID_Contact, 
    ID_MailSendJobs,
    COUNT(ID_OpenedMails) AS OpenCount,
    CASE
    WHEN ROW_NUMBER() OVER (PARTITION BY CAST(ID_EmailAddress AS VARCHAR(10)) + ' ' + CAST(ID_MailSendJobs AS VARCHAR(10)) ORDER BY ID_Date_Opened) = 1 THEN 1 
    ELSE 0 
    END
    AS UniqueOpenCount
    FROM            
    dbo.Fact_OpenedMails
    where ID_Contact = 382340
    GROUP BY ID_EmailAddress, ID_Date_Opened, ID_Contact, ID_MailSendJobs;
    order by ID_MailSendJobs 
    When I run the the select statement in the view definition I get combination of both 1 and 0 for the 'UniqueOpenCount' column.
    But when I run the select from the view itself using the following query:
    SELECT [ID_EmailAddress]
          ,[ID_Date_Opened]
          ,[ID_Contact]
          ,[ID_MailSendJobs]
          ,[OpenCount]
          ,[UniqueOpenCount]
      FROM [marketing].[OpenedMails]
    I get equal amount of rows but only 0 values for the 'UniqueOpenCount' column which seems to be very weird to me. Why is this happening ? Can anyone help regarding how to solve this ??
    Result from the select inside view definition:
    Result from the select query directly from the view:
    Thanks in advance.
    Vivek Kamath

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You failed. Temporal
    data should use ISO-8601 formats – you failed again. Code should be in Standard SQL AS much AS possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    Things like “ID_Date_Opened” are wrong. The affixes “id” and “date” are called attribute properties in ISO-11179 and data modeling. Since a date is a unit of measurement on a temporal scale, it cannot be an identifier by definition. My guess is this would be
    “open_date” if it were done right. And the only display format in ANSI/ISO Standard SQL is ISO-8601 (yyyy-mm-dd)
    An email address of -1?? Email addresses are VARCHAR(256), not numeric. There is no reason to cast them AS string!
    Your vague “mail_send_jobs” is plural, but columns hold scalars and cannot be plural by definition. The partition cause can hold a list of columns: 
    WHEN ROW_NUMBER() 
         OVER (PARTITION BY email_address, mail_send_job 
                   ORDER BY open_date)
         = 1 
    THEN 1 ELSE 0 END 
    This still makes no sense, but the syntax is better. You do not understand how ROW_NUMBER() works. 
    Would you like to try again with proper Netiquette? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Table - populate one table with data from the list of another table

    Hello All,
    I am a newbie in Swing and am a book and few tutorials old.
    I am trying to achieve the following:
    (1) I populate Table1 (a JTable) with a list of data - each row consists of several columns. And I have a Table2 (also JTable) that is in the beginning empty.
    Both the tables (Table1 and Table2) are showed in the window.
    (2) Lets say, there's a button (JButton) in between the two tables.
    Now if I Select a row from Table1 and press the button, this row will be sent/copied to Table2.
    And this way I can choose different rows and pass the data to Table2.
    I have manages to make Table1 and put data in it ... but for the rest, I don't know where and how to begin.
    Would appreciate some ideas and tips.
    Thank you.

    Since you are using a button to start the copy process you don't need to worry about a ListSelectionListener or a MouseListener. You need to create a button with an ActionListener that does the following:
    a) Create an Array based on the size of the number of columns in the table
    b) get the index of the selected row
    c) populate the Array with data from the TableModel by using the table.getModel().getValueAt(...) method for each
    d) Now you can add the row of data to the other JTable by updating its model.
    DefaultTableModel model2 = (DefaultTableModel)table2.getMode();
    model.addRow( theArray );

  • ProjectUID selected from the reporting database from Project Server OnPublished event is taking some delay

    Hi all,
    I'm invoking a stored procedure from the reporting database from the project server onPublished event.  I'm having some issues in getting the details of that particular project from the published event handler.  This i noticed that there is some
    delay is taking place in moving the data(project uid )  from the published to the reporting database .
    My stored procedure select statement is as follows:
    SELECT ProjectUID, ProjectName FROM MSP_EpmProject_UserView
     WHERE ProjectUID=value
    This stored procedure is invoked from the onPublished event of the project server event handler where that particular projectuid is passed in that stored procedure.I have noticed that some delay is taking palce to move  the data into the reporting database. 
    My stored procedure got invoked from the onPublished event of the project server event handler before the delay is complete.  So the row selected from the stored procedure is alwys zero (0).  Is there any other method to wait for repoting database
    to get refreshed. Please help me .

    Hi sabithad,
    The issue you are facing is because of the conflict of permissions, event handlers always works through administrative user credentials whereas the project is open in edit mode by the logged-in user. And you are tyring to update custom field at the back
    end with Administrative credentials, while project queue is in process by logged-in users credentials. Its not gonna work this way :) 
    The best option is to use Javascript on your PDP using CEWP, you can either build your complete logic in JavaScript and place that code on your PDP. OR you can use the combination of JavaScript and PSI and create a webpart to be placed on PDP.
    below blog link willgive you directions to go ahead with, but for sure the solution to your query is
    JavaScript :)
    http://epmxperts.wordpress.com/2012/05/21/generate-unique-id-for-project-using-a-webpart/
    hope this helps.
    Khurram Jamshed - MBA, PMP, MCTS, MCITP (
    Blog, Twitter, Linkedin )
    If you found this post helpful, please “Vote as Helpful”. If it answered your question, please “Mark as Answer”.

  • On my Iphone, i'm not able to purchase with itunes from the game clash of clans! I did it the first time, it worked, but now it wont work and says : contact support.

    i'm not able to purchase with itunes from the game clash of clans! I did it the first time, it worked, but now it wont work and says : contact support.

    What they mean is iTunes Customer Service Contact - http://www.apple.com/support/itunes/contact.html

  • Alerts with variables from the messages payload without BPM?

    Hi, experts:
    Is it possible to define a alert category with variables from the messages payload(for example:order_id ) without BPM?
    Regards
    Yu Ming

    Refer to
    http://searchsap.techtarget.com/tip/0,289483,sid21_gci1240902,00.html
    initially this also talk about BPM but you can check whether you can use the container variable in you case.
    How to define the container variable in ALRTCATDEF is mention in above link.
    **Points if answers find useful.
    Gaurav Jain

  • ARQ: Manager Id manual selection from the list???

    Hi,
    I had discussed in my other thread here that, in some of the cases, a user may not have manager id for some reason either in HR or AD. For such users, the option is to select manager id manually from the list by pressing F4.
    The problem is that, as soon as a manager id is searched, this will display "all" the users available in GRC system: requester, manager, role owner, other dialog users and even background users!
    This causes the requester to select incorrect manager id and exposes all the irrelevant users from GRC system.
    May I know how I can control this? Or do we have any other way to handle this?
    As I know, there are following options:
    1. Maintain users' details properly either in AD or SAP HR systems
    2.In case of non-availability of manager id, route request to appropriate team/person who can take proper decision (which I have done currently)
    Does any also suggest/endorse an idea to modify the default search ability of ARQ?
    I would appreciate if we can have ideas/suggestions on this.
    Would be waiting for kind responses.
    Regards,
    Faisal

    Dear Alessandro,
    Thanks for your reply.
    Regarding :
    I understand your concern regarding correct/wrong mangers. But in case that manager information is wrong in LDAP/HR from which source should GRC get the correct managers?
    I would share on thing and that is, for contractors (for example) some how manager details are not maintained in LDAP (as in SAP HR only permanent employees' HR data is maintained).
    I could not get the first 3 lines of next paragraph and I think this is not the issue
    Basically you can say who ever is a manager can also be a manager from someone else. But it is possible that someone who is not yet a manager can be a new manager and has to be defined as manager in ARQ.
    The issue that, for some type of employees (contractors), manager details are not maintained neither in LDAP nor in SAP HR system. Therefore, in such cases, manager field is empty. But let me tell you there are managers for even contractors, but not maintained in LDAP due to the maintenance responsibility and gathering this information from different department is assumed to be a big and painful task.
    But these managers (for contractors) are definitely available in GRC system as approvers. Therefore, for users (contractors) whose manager is not maintained, manually it is to be selected from the search option. If we start searching for a "suitable" manager, then it displays all the users available in GRC system (because they are created in SU01).
    Also, we might face similar problem at the time of forwarding a request! Actually, a manager should only see the list of other managers, not all users!
    Similarly, a role owner will intend to forward his responsibility to another role owner only!
    Therefore, we should only see the relevant users from the search, but not all!
    Please share your valuable inputs.
    Regards,
    Faisal

  • How to burn a video produced in iMovie in iDVD: with gratitude for the advice received I used the "professional quality" setting in iDVD for a video which in iMovie is 1h 20min long.  however this also failled. where did I go wrong, please?

    how to burn a video produced in iMovie in iDVD: with gratitude for the advice received I used the "professional quality" setting in iDVD for a video which in iMovie is 1h 20min long.  however this also failled. where did I go wrong, please?
    the message sked me to alter the quality of the DVD as the content was too large for the quality sellected.
    PLEASE HELP again,
    THANK YOU VERY MUCH
    MIchael

    Check the Advanced ➙ Project Information menu option to make sure the playing time of the entire project, movie plus menu is below the 120 minute limit.
    OT

  • When i give end location from my location which is selected from the options available, also i receive the message that the directions could not found- pl. help

    when i give end location from my location which is selected from the options available, also i receive the message that the directions could not found- pl. help

    # Yes, if you go to accounts.firefox.org, sign out, you will now be signed out.
    # Sign back in, and you will be asked to save the password you entered.
    # This will save the password and autocomplete if you have this option turned on.
    I am not exactly sure why the menu did not detect the password change or if it was stored incorrectly after you changed it? But after storing the correct password you can manage any duplicate passwords in the password manager.[[Password manager - Remember, delete and change saved passwords in Firefox]]

  • How do you edit photos with photoshop from the new  Photos app?  The edit in external editor menu item seems to be gone.

    How do you edit photos with photoshop from the new  Photos app?  The edit in external editor menu item seems to be gone.

    Tell Apple what additional features you want in Photos via both http://www.apple.com/feedback/macosx.html and http://www.apple.com/feedback/iphoto.html  since they don't have a feedback page for Photos as yet.

  • Export the data with Alias from the alternative table using ODI

    Hi!
    How to export the data from Essbase with Alias from the alternative table using ODI?
    Thanks.

    Are you on 10.1.3.6.x? Then: http://john-goodwin.blogspot.com/2008/09/odi-series-part-2-agent.html
    Are you on 11g? Then: http://john-goodwin.blogspot.com/2010/12/managing-odi-11g-standalone-agents.html
    I will say with only a mild amount of shame and a large amount of gratitude that I installed both releases' agents through John's blog posts.
    Regards,
    Cameron Lackpour
    Edited by: CL on Jun 4, 2012 5:48 PM
    Whoops, had the same link in there twice.

Maybe you are looking for

  • Can I manage 2 instagram accounts on one iPad device

    How do I create 2 instagram accounts on 1 iPad mini? I created 2 iTunes accounts but cannot activate the 2nd account I created.

  • No longer under warranty, how does pricing work?

    Seen as it's impossible to contact Apple directly regarding technical issues regarding MacBook, I'll have to ask here. Firstly, I know the issues with my MacBook are hardware related I've spent relentless hours trying to fix them with thousands of di

  • Small issue in dialog program

    Hello all, i have a requirement in dialog programming. I have to modify a record a record which exist in zatble. For each record , i have a header info, item details. for header iam ok , i can use modify. for item details i have like itemno    materi

  • How to make a trasnparent background in Motion

    I am just making a Lower Third and I want to be able to bring it into FCP and place it on top of my existing timeline. I dont want to export FCP to Motion because I already chroma keyed my "stuff" in FCP. How do I make a transparent background for Mo

  • What should I get X6 or N97 ?

    Please help guys I am really confused btw I don't care about the QWERTY I really don't need it.