Query a table and exit when first record found

I want to query a table and just want to know if any rows matching my query criteria exist in the table. I just want to find one row, irrespective of order and stop the query right there. How do I do that?

The most efficient way would be either to use rownum = 1 as part of the condition in your second query, but, as written, both will return multiple rows. Your first will need to have an additional predicate and rownum = 1 in addition to the exists.
Assuming that the predicate can use an index, then the most efficient approach would be either:
SELECT 1 FROM table
WHERE <conditions> and
      rownum = 1or possibly:
SELECT 1 FROM dual
WHERE EXISTS (SELECT 1 FROM table
              WHERE <conditions>)Both will do a range scan on the applicable index, stopping when the find the first matching entry. To my mind, the first is clearer in intent.
To illustrate the error in your first query, consider:
SQL> SELECT * FROM t;
        ID DESCR
         1 One
         2 Two
         3 Three
         4 Four
         5 Five
         1 One
         2 Two
         3 Three
         4 Four
         5 Five
SQL> SELECT * FROM t
  2  WHERE id = 1 and
  3        rownum = 1;
        ID DESCR
         1 One
SQL> SELECT * FROM t
  2  WHERE EXISTS (SELECT 1 FROM t
  3                WHERE id = 1);
        ID DESCR
         1 One
         2 Two
         3 Three
         4 Four
         5 Five
         1 One
         2 Two
         3 Three
         4 Four
         5 FiveJohn
Edited by: John Spencer on Oct 2, 2009 12:06 PM
Added queries from t

Similar Messages

  • Send email when first record updated problem

    Hi guys i have problem
    this code send email based on timer every 5 minutes
    it working ok but my problem i need to determine first rcord updated not inserted
    and send email this is starting work
    this is my code
    ---timer1_Tick---
    Sales.SalesClass SalesClass1 = new Sales.SalesClass();
    DataTable dt = SalesClass1.ShowSalesData("Data Source=192.168.1.5;Initial Catalog=Altawi-last06-01-2015;User ID=admin;Password=123");
    dataGridView1.DataSource = dt;
    dataGridView1.Refresh();
    namespace Sales
    class SalesClass
    public DataTable ShowSalesData(string ConnectionString)
    SqlConnection con = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "showsales1";
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    return dt;
    SELECT     ROW_NUMBER() OVER (ORDER BY dbo.[Jeddah-Live$Sales Header].No_) AS [م], dbo.[Jeddah-Live$Sales Line].[Document No_] AS 'رقم الطلب',
    dbo.[Jeddah-Live$Sales Header].[Bill-to Name] AS 'العميل', dbo.[Jeddah-Live$Sales Line].Area AS 'نوع الصبه', dbo.[Jeddah-Live$Sales Line].Description AS 'البيان',
    dbo.[Jeddah-Live$Sales Header].[Pump No_] AS 'المضخه', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].Quantity, 0, 1) AS int) AS 'المطلوب',
    CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Quantity Shipped], 0, 1) AS int) AS 'المصبوب', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Outstanding Quantity], 0,
    1) AS int) AS 'المتبقى '
    FROM         dbo.[Jeddah-Live$Sales Header] INNER JOIN
                          dbo.[Jeddah-Live$Sales Line] ON dbo.[Jeddah-Live$Sales Header].No_ = dbo.[Jeddah-Live$Sales Line].[Document No_] AND
                          dbo.[Jeddah-Live$Sales Header].[Sell-to Customer No_] = dbo.[Jeddah-Live$Sales Line].[Sell-to Customer No_]
    The code above not have any problem and working
    When first record updated send email
    Example to show
    orderno   quantity  shipped quantity
    12            20               0
    13            30               0
    14            25               0
    15           22                0
    suppose order no 14 shipped quantity updated be 10 (meaning 0 be 10
    then send email with starting work
    after this any updated to any record not send
    no problem i dont need any send email code but how to get record updated first

    Hi guys i have problem
    this code send email based on timer every 5 minutes
    it working ok but my problem i need to determine first rcord updated not inserted
    and send email this is starting work
    this is my code
    ---timer1_Tick---
    Sales.SalesClass SalesClass1 = new Sales.SalesClass();
    DataTable dt = SalesClass1.ShowSalesData("Data Source=192.168.1.5;Initial Catalog=Altawi-last06-01-2015;User ID=admin;Password=123");
    dataGridView1.DataSource = dt;
    dataGridView1.Refresh();
    namespace Sales
    class SalesClass
    public DataTable ShowSalesData(string ConnectionString)
    SqlConnection con = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "showsales1";
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    return dt;
    SELECT     ROW_NUMBER() OVER (ORDER BY dbo.[Jeddah-Live$Sales Header].No_) AS [?], dbo.[Jeddah-Live$Sales Line].[Document No_] AS '??? ?????',
    dbo.[Jeddah-Live$Sales Header].[Bill-to Name] AS '??????', dbo.[Jeddah-Live$Sales Line].Area AS '??? ?????', dbo.[Jeddah-Live$Sales Line].Description AS '??????',
    dbo.[Jeddah-Live$Sales Header].[Pump No_] AS '??????', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].Quantity, 0, 1) AS int) AS '???????',
    CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Quantity Shipped], 0, 1) AS int) AS '???????', CAST(ROUND(dbo.[Jeddah-Live$Sales Line].[Outstanding Quantity], 0,
    1) AS int) AS '??????? '
    FROM         dbo.[Jeddah-Live$Sales Header] INNER JOIN
                          dbo.[Jeddah-Live$Sales Line] ON dbo.[Jeddah-Live$Sales Header].No_ = dbo.[Jeddah-Live$Sales Line].[Document No_] AND
                          dbo.[Jeddah-Live$Sales Header].[Sell-to Customer No_] = dbo.[Jeddah-Live$Sales Line].[Sell-to Customer No_]
    The code above not have any problem and working
    When first record updated send email
    Example to show
    orderno   quantity  shipped quantity
    12            20               0
    13            30               0
    14            25               0
    15           22                0
    suppose order no 14 shipped quantity updated be 10 (meaning 0 be 10
    then send email with starting work
    after this any updated to any record not send
    no problem i dont need any send email code but how to get record updated first

  • Query for a value result when no rows found

    Kindly help me out when I use following query it return no record but I want 0 against this query how plz let me know
    select b.accode,decode(sum(b.debit),null,0,sum(b.debit)) op_dr,
    decode(sum(b.credit),null,0,sum(b.credit)) op_cr,
    c.actitle
    from v_mast a, v_det b, chart c
    where a.v_type=b.v_type
    and a.vouchno=b.vouchno
    and b.accode=c.accode
    and a.VOID='F'
    and a.posted_by is not null
    and a.v_date between '01-JAN-06' and '31-JAN-06'
    and b.accode in (select accode from account where open='T')
    and b.accode in (select accode from chart)
    and a.v_type in ('RN','PV','CV','RV','JV')
    and b.accode = '3050571'
    group by b.accode,c.actitle
    order by b.accode
    Result is : No rows found but is there any possibilities that it will give me following result
    Accode op_dr op_cr
    3050571 0 0

    Why not respond to the earlier threads ?
    Query
    and
    0 when no records found
    Regards,
    Rob.
    Message was edited by:
    Rob van Wijk
    PS: Of course you could do a
    <your query> union all select 3050571,0,0,null from dual
    It answers the question, but I doubt that this is what you want.

  • Query Dictionary tables and V$ views in EM

    Hello;
    I want to query dba_ tables and v$ views from Enterprise manager (10g).
    I hv tried that in the Tables -> SYS schema ; But these tables are not shown there. Im unable to query from the EM.
    Able to query from the sql plus , Where i have logged as SYS
    select status from v$instance;
    From where can i access these tables; (in EM)
    v$instance
    v$database
    dba_tablespaces
    Edited by: Zerandib on Dec 8, 2009 8:39 AM

    Zerandib wrote:
    From where can i access these tables; (in EM)
    v$instance
    v$database
    dba_tablespaces
    Those are not tables, they are views. Try looking under Adminstration|Schema|Views with schema as SYS. Keep in mind many of the V$ names, such as V$INSTANCE, are public synonyms for V_$ views. For example V$INSTANCE is a public synonym for V_$INSTANCE.

  • HT1414 when i facetime somebody they cant hear me, and also when i record a video the sound is muffled. there isnt a problem when making a phone call. any solutions?

    when i facetime someone they cant hear me, and also when i record a video there is no sound, however when i make a phone call there is no problem. any solutions?

    When I try to make a call it will go through and I can hear the other person but they cannot hear me, is there a setting that disables the speaker when using the headphones to try to make a call, also speakerphone automatically goes on when I start a call which I do not like, any suggestions how to fix this?
    I also have this problem...........

  • How to query a table and result together with autonumber

    Hi all
    How to query a table and the result return autonumber for each row together with the table values.
    I have tried rowid but it provide me with characters.
    Tj

    What is your exact requirement?
    If you want the number of rows selected, you can use rownum.
    select rownum, a.* from <table> a;
    Cheers
    Deepak

  • WD ABAP: Reset Table To Show the First Record.

    Hi WebDynpro ABAP Experts,
    Settings of tables allow me to display set of 10 records at a time. If i want to select , say 18th record I use paginator to select & use it. i navigate to next view , do some processing here. When I come back to the previous view, i see that table is still showing the 18th Records.  How can i make this TABLE to show the first 10 records again & we want to achieve this without going back to DB.
    or  in other words we want to call the "FIRST ROW" functionality of Paginator that JUMPS to display the first Ten Row.

    Hi Prash,
    If you used supply function for filling the data to the table means you can use the Invalidate method.
    Before leaving the first view you can call the invalidate method. The invalidate method again calls the supply function and your node as well as table getting refreshed.
    Code for Invalidation :
    node_node1 = wd_context->get_child_node( name = 'NODE1' ).
    elem_node1 = node_node1->get_element( ).
    node_node1->invalidate( ).
    Thanks.

  • Query a table according to SYSTIMESTAMP  for records within an interval

    Hello ,
    I am trying to query a table based on the systimestamp and taking two timestamp as intervals.Following is the query:
    select * FROM MY_TBL where to_char(SYSTIMESTAMP,'YYYY-MM-DD HH24:MI:SS')
    BETWEEN (to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'))
    AND (to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'));
    I am not getting any results.(no rows selected)
    So i tried:
    SELECT * FROM MY_TBL AS OF TIMESTAMP
    to_date(to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')
    - to_date(to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS');
    ERROR at line 3:
    ORA-00932: inconsistent datatypes: expected TIMESTAMP got DATE JULIAN
    Since TIMESTAMP is in a different format.I may be getting this error.How do i cast TIMESTAMP in the above query to map to the intervals.
    Please let me know how to approach this issue.
    Thanks in Advance,
    Santosh

    Thanks for the quick and prompt replies....
    To provide a quick background.I am providing a daily report to my customer which is based on column (DATE type) in the table.But the records were inconsistent.Hence it was agreed that we get the report based on systime stamp.
    Range is : between day-before-yesterday midnight(START_TIME) and yesterday midnight(END_TIME).A perl script runs the report at midnight 2 AM as cron .So i figure the interval can be :
    (SYSTIMESTAMP - INTERVAL '40' hour) - It is 12 AM day before-yesterday-night if run at 2 AM - Interval 1
    --------------------------------------------------------BETWEEN----------------------------------------------------------------------------
    (SYSTIMESTAMP - INTERVAL '16' hour) - It is 12 AM day yesterday-night if run at 2 AM - Interval 2
    SQL> select to_timestamp(to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')START_TIME from dual;
    START_TIME
    08-JUN-09 06.43.59.000000000 PM
    SQL> select to_timestamp(to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS') END_TIME from dual
    2 ;
    END_TIME
    09-JUN-09 06.44.46.000000000 PM
    How do i get the records for these two intervals.
    Thankyou..
    -Santosh

  • Linking multiple tables and Trying to insert records into Detail

    Hello,
    I have been struggling with this one for years...
    Work Order, Employee Labor, and Materials.  I then create a group headers using the Location field from the Work Order table.  I then create another Group, suppress the group name, and insert several fields from the Work Order table (work order number, wo description, status and completion date into Group 2 section.  Multiple rows of info are displayed.  I then enter some Employee Labor fields from the Labor table into the Details section (employee name, labor hours, pay rate, etc.).  I get several lines of employee labor transaction information grouped below each row of work order info from the Group 2 section.  So far, so good.
    Now I attempt to bring a field into the Details section from the 3rd table (Materials).  The moment I introduce the record, the rows of employee labor are duplicated over and over.  In fact, there are multiple duplicate labor transaction rows (over and over).
    What am I doing wrong???  I've tried every combination of Linking Order that I can think of...  I need help.
    Please reply.
    ps.  Let me know if I need to attach a screen shot.
    Thank you
    Robert

    hi Robert,
    this is a common issue when you add several details tables to a report. once you add the fields, then the sql generated will include those parent tables and you get a multiplier of records.
    my recommendation to you would be to use a subreport for the materials table instead.
    go to the Insert menu, choose Subreport and create a new subreport using the Wizard then add your current connection but this time only add the materials table. in the Linking tab, choose your Work order and then add the subreport to the Work order group header. now in the subreport add some fields from your materials table onto the subreport canvas.
    what this is essentially doing is a subquery to the database and returning all associated materials records based on a filter for the work order.
    the main report should not include any materials records and you can also remove this table from the database expert for the main report.
    i hope this helps,
    jamie

  • How to get orphan records in Wf_notifications table and how to purge records in WF notifications out table

    Hi Team,
    1) I need Query to get the orphan records in the wf_notification tables to purge them.
    2) Same way I need to purge unwanted records in WF NOTIFICATION OUT table.Can you please let me know the process to get unwanted records in
    WF NOTIFICATION OUT table and the process to purge them.
    Thanks in Advance!
    Thanks,
    Rakeesh

    Hi Rakeesh,
    Please review notes:
    11i-12 Workflow Analyzer script for E-Business Suite Workflow Monitoring and Maintenance [Video] (Doc ID 1369938.1)
    bde_wf_data.sql - Query Workflow Runtime Data That Is Eligible For Purging (Doc ID 165316.1)
    What Tables Does the Workflow Purge Obsolete Data Program (FNDWFPR) Touch? (Doc ID 559996.1)
    Workflow Purge Data Collection Script (Doc ID 750497.1)
    FAQ on Purging Oracle Workflow Data (Doc ID 277124.1)
    Thanks &
    Best Regards,

  • How to Query from table and insert into another table.

    Hi
    I am using the following query in VO and all the columns are attached to EO ( table name emp_temp)
    select a.npw_number, a.person_id,b.assignment_id,a.title,a.last_name,a.first_name,a.date_of_birth,a.sex,
    b.organization_name,b.organization_id,b.job_id,b.job_name,b.position_id,b.position_name,b.supervisor_id,
    b.supervisor_name,b.location_id,b.effective_start_date,b.effective_end_date
    from per_all_people_f a,per_assignments_v b
    where a.person_id=b.person_id
    and a.npw_number=:1
    I can query the data in screen. I need into insert the data into the emp_temp.
    I don't know how to do this . Please help me.
    Thanks
    Subra

    You can create a VO based on EO on emp_temp table.....
    And u have attached a Different VO on the page... Right...
    Now what u can do is....once u click on apply....
    u can set the each attributes of EO based VO explicitly via code, from the values of second VO.... and then commit.....
    Perhaps this might help...

  • Opening a form and displaying the first record

    Any ideas on what the easiest solution would be to show the first record on a form when the form is opened? I've tried some of the ideas discussed in the FAQ section, but without success!!
    Thanks........GD

    Greg,
    Sorry, but there is no other solutions other than those described in the FAQ. I know that it is not very "user-friendly", but should work.
    Also if you search the forum's archive there were some concrete examples posted.
    Thanks,
    Dmitry

  • Calendar and Adressbook error: Duplicate records found for GUID

    Hi all,
    i have a Mountaion Lion Server running on a mac mini and everything was working well.
    This morning one user of mine is unable to connect to his calendar and adressbook.... i found this error in the log files:
    2013-06-30 15:19:50+0200 [-] [caldav-1]  [-] [twistedcaldav.directory.appleopendirectory.OpenDirectoryService#error] Duplicate records found for GUID ****USER_GUID****:
    2013-06-30 15:19:50+0200 [-] [caldav-1]  [-] [twistedcaldav.directory.appleopendirectory.OpenDirectoryService#error] Duplicate: ***USER_Shortname***
    Apperetnly there is a duplicate match in the database. how can i fix this issue?
    In Server App this user is only listed once.
    Mail and other services for this user are working correctly.
    Thanks for any advice!

    Hi Samuel,
    You may try:
    select code,count(code)
    from [dbo\].[@XTSD_XA_CMD\]
    group by code having count(code) > 1
    What is the result?
    Thanks,
    Gordon

  • SELECT query & Database Table Difference in number of records

    Hi All,
    In program it’s selecting 3 records based on selection parameters whereas when i execute SE16 with same selection criteria gives 4 records.
    Please suggest when we will face these kind of issue
    Thanks,
    Spandana

    SELECT objnr wlges
    FROM bpge
    INTO TABLE t_bpge
    FOR ALL ENTRIES IN t_prps
    WHERE lednr  EQ c_0002
    AND      objnr  EQ t_prps-objnr
    AND      wrttp  EQ c_41.
    Here t_prps-objnr has the following values
    PR00473170
    PR00397060
    PR00397061
    PR00397062
    PR00397063
    PR00397064
    PR00397065
    For this selection criteria there are 4 records in BPGE table where as the program is fetching only 3

  • Pivot table and link to account record logs user out of OnDemand

    All,
    I have created a simple accounts report using a pivot table. I would like the user to be able to drill down on the detail account record. I followed the instructions in Doc ID 454434.1 that describes how to do this without using an action link.
    From the example, I created the following URL and inserted it in the account name column under data format using custom text format. The account id is also included, but hidden in the report layout.
    http://"@[html]"<a target=_top href=https://secure.crmondemand.com/OnDemand/user/AccountDetail?OMTHD=AccountDetailNav&OMTGT=AccountDetailForm&AccountDetailForm.Id="@">"@"</a>
    The link is available in the finished report, but when I run the report from shared custom analyses and click on the link it logs me out of the application and returns me to the sign in page.
    Any suggestions are greatly appreciated.
    Thanks in advance,
    Dan

    Here's an attempt to post the entire url again:
    "http://"@[html]"<a target=_top href=https://secure.crmondemand.com/OnDemand/user/AccountDetail?OMTHD=AccountDetailNav&OMTGT=AccountDetailForm&AccountDetailForm.Id="@">"@"</a>"

Maybe you are looking for

  • Trial Balance with specific transaction code

    Hi all, I want to print the trial balance showing balances of all the GL after considering only choosen (specific) transaction code. Please help.. Thanks Sanjeev

  • Best way to set up to new iPad?

    My iPad should arrive next week, and I am excited to get it set up. I am curious as to the best way to do so... Between my wife and I, we share a MacBook and an iMac, each with our own user accounts on each computer. We share an iTunes library and an

  • How to INSTALL SAMPLES on 10.4.6 HD when system is 10.4.8 RED " ! "

    I get a red explamation point ! ! ! ! only in RED when I go to choose a HD to install. Read here it happens when a HD may have an old OS on it. Is there a way to fix this? I want to install SOFTWARE SAMPLES (Drums) onto a different drive but the syst

  • Trying to wireless internet on my computer with an AC595U...how do I do it?

    I am confused. Dont know the wording Im looking for either. I have a wireless USB thing from Verizon it is a AC595U and it came with a disc. I know I need to purchase a plan from verizon. But how do I go about setting this up.. Any help would be grea

  • Hard driver failing

    Hi everyone I have the problem for 1 TB HDD hard driver failing. Imac 21.5 - inch, late 2012 Processor 2.7 GHz intel Core i5 Memory 8 GB 1600 MHz DDR3 Software OS X 10.8.5 Version 10.8.5 Imac worked not probably. When I reinstall by using Disk Utilit