Check for existence of a record

I have a table XX_TEMP. Let us say the columns are inventory_item, organization_id and description
The values are:
Inventory_item
Organization
Description
200
m1
Sample
200
m2
Not Sample
400
m4
check
700
m5
Test
I just want to check the existence of an item in the table, I have written two queries and would like to know which one is better in terms of performance:
Q1:
select count(1) from xx_temp where inventory_item=200 and rownum=1;
Q2:
select count(1) from dual where exists (select 1 from xx_temp where inventory_item=200);
Both Q1 and Q2 return the same result. In fact, I was surprised with the result from Q1 as I expected that the rownum would be evaluated after the where condition. I expected Q1 to return 2
I thought that the below query:
select count(1) from xx_temp where inventory_item=200;
and Q1 would return the same result as rownum would be evaluated at end. In effect, I've 2 questions:
1. Isn't rownum calculated at the end?
2. What is the best way in terms of performance to check for an existence of record?

Internally this is how it works:
select count(*) from xx_temp where inventory_item=200 and rownum=1;
  COUNT(*)
         1
1 row selected.
Execution Plan
   0       SELECT STATEMENT Optimizer Mode=ALL_ROWS (Cost=4 Card=1 Bytes=13)
   1    0    SORT AGGREGATE (Card=1 Bytes=13)
   2    1      COUNT STOPKEY
   3    2        TABLE ACCESS FULL XX_TEMP (Cost=4 Card=2 Bytes=26)
Statistics
          5  user calls
          0  physical read total multi block requests
          0  physical read total bytes
          0  cell physical IO interconnect bytes
          0  commit cleanout failures: block lost
          0  IMU commits
          0  IMU Flushes
          0  IMU contention
          0  IMU bind flushes
          0  IMU mbu flush
          1  rows processed
Plan
1 Every row in the table XX_TEMP  is read.
2 Processing was stopped when the specified number of rows from step 1 were processed.
3 The rows were sorted to support a group operation (MAX,MIN,AVERAGE, SUM, etc).
4 Rows were returned by the SELECT statement.
COUNT STOPKEY knows how many rows you want and will just keep calling its child function under it in the execution plan tree to get more and more rows, until the required amount of rows have been returned. Here it stopped at 1 iteration.
And to answer your second question : as to which is the fastest way to to check  for an existence of record :
Answer would be it depends on your requirement.  possible answers are :  Rowid --  fastest way to check for a row.   similar answers can be Index etc.. but all this is relative to what you work with.
Cheers,
Manik.

Similar Messages

  • Checking for existence of a record in csv file

    Hey all, I have two csv files residing on the server that I will be processing using the UTL_FILE package. One of these files (File A) has only one column and the other one (File B) has over ten. The data in file A is the same as the one in column 2 of File B. File A is mainly there for a lookup purpose whereas File B is the one that has all the data that will be processed. The following example should describe better:
    File A[b]
    Number
    "TR_56575"
    "TY_76756"
    etc
    File B
    Column1, Number, Column3, Column4
    "Mine","TR_56575","uhsht","76744"
    "Yours","TY_76756","nghdjd","45645"
    What I have to do is check whether a Number in File B exists anywhere in File A. If it does then I just skip that record and move on to the next. So basically, I wanted to find out if there is any way to compare the two columns on the server side. I know there is a dbms_lob.fileexists function to check the existence of a file on a server, just wanted to see if there is an extension to that or something that checks the existence of a string in file. Any feedback would be appreciated. Thanks.

    Yeah I thought about that. It would be the ideal way to go, however in this case, I already have a Pl/Sql procedure that grabs File B and just processes it from the server. It works fine and everything but now that this extra logic and file is added where I have to check the existence of a corresponding record in File A, I'm just looking for something to add in my code to just make the comparison on the fly and the rest would be the same.

  • I had downloaded Mountain OX and installed it on my macbook air.  The notes app is now not working.  I get the following message erminating app due to uncaught exception 'MFSQLiteException', reason: 'checking for existence of object' abort() called termin

    i had downloaded Mountain OX and installed it on my macbook air.  The notes app is now not working.  I get the following message
    "Terminating app due to uncaught exception 'MFSQLiteException', reason: 'checking for existence of object'
    abort() called
    terminate called throwing an exception"
    Can someone help me with solving the problem.

    i had downloaded Mountain OX and installed it on my macbook air.  The notes app is now not working.  I get the following message
    "Terminating app due to uncaught exception 'MFSQLiteException', reason: 'checking for existence of object'
    abort() called
    terminate called throwing an exception"
    Can someone help me with solving the problem.

  • Check for existence of a node?

    What is the best way to check for the existence of a node (before attempting to delete it or perform other operation on it)? Maybe assign it an "id" then search for that id?

    If the node is in a Container you can use lookup(id: String): Node function.
    Documentation
    Or directly call it from the scene:
    Documentation
    Enjoy!

  • Existence of a record

    Hi,
    I am a starter to Oracle. I wanted to find the existence of a record in a table and then depending on the existence I have to add records to other tables.
    I mean depending on the existence I have like 3 cases to handle. Is it possible to store(temp variable) the result of the query to find existence and use the value of the temp variable to run other cases. If so can anyone show a small query.
    Thanks in advance.
    VR.

    Are you working with PL/SQL?
    you can check for existence in PL/SQL with something like
    select count(*) into local_variable
    from table
    where ...
    if you are in straight SQL you would need to use a not exists clause.
    i.e.
    insert into table
    select a, b, c
    from dual
    where not exists ( query that would return you row here..)

  • BI Loading for Infoobject : Number of records

    Hi Experts,
    When i am loading the data from DS 0wbs_elemt_attr to Infoobject 0wbs_elemt, in rsa3 there are 102117 number of records. but when i run the infopackge i see the number of records are 102035. I would like to know if there are any checkpoints to check as to where should I check for less number of records that are coming up.
    Kindly advise.
    thanks & regards,
    M.S

    Hi experts,
    I deleted everything and reloaded. It is now reflecting 1020117 number of records(dont know how).
    Thankyou guys for your help. Assigned points.
    thanks & regards,
    M.S
    Edited by: M.S on May 7, 2010 12:14 PM

  • Need script to check for duplicate file names when copying a folder

    Hello,
    I am a new applescript user trying to write what I believe should be a simple script. I was planning on using the "add-new item alert" script as a template.
    Basically I have people copying folders of photos into a library folder, but I don't want the Finder to copy the photo if it already exists in the library. The images in the library are organized into subfolders.
    I need a script that will check all the file names in the new folder against all the file names in the library, and NOT add the new one if it already exists.
    If anyone can help it would be greatly appreciated,
    Thanks,
    C

    I have a script that "kind of" works. The only problem I've seen is that it gets confused when filenames contain characters that are fine in Macland but not good in Unixland. Forward slashes are a good example of this.
    In this case I have a folder in my home named "copytest" Inside copytest are two folders:
    Source (containing the images to be added)
    Dest (My existing library of images)
    It also assumes that the folder of images to be added contains no sub-folders. Hope this helps.
    tell application "Finder"
    set theSource to folder "source" of folder "copytest" of home
    set imagesToBeCopied to name of every file of theSource
    end tell
    repeat with theFile in imagesToBeCopied
    try
    if (do shell script "find -r ~/copytest/dest -name " & quoted form of (theFile as string)) is not equal to "" then
    --The file exists. Don't copy it
    else
    --the file doesn't already exist. Copy it.
    end if
    on error
    return "Failed while trying to check for existence of a file"
    end try
    end repeat

  • Check table existence method

    I have the following Java method that is suppose to determine whether a given table exists or not:
    public boolean tableExists(String table) {
    String defstmt = "select TABLE_NAME from ALL_TABLES where (TABLE_NAME = '" + table + "')";
    System.err.println("tableExists: stmt = " + defstmt);
    tc.executeSEL(defstmt);
    ResultSet rs = tc.getRS();
    String tname = new String();
    try {
    while (rs.next()) {
    rs.getString(tname);
    System.err.println("tableExists.try: tname = " + tname);
    rs.close();
    return true;
    catch (SQLException ex) {
    System.err.println("tableExists.catch: tname not found");
    try {
    rs.close();
    catch (SQLException ex1) {
    return false;
    Since this one didn't appear to work reliabily a friend suggested the following:
    public boolean tableExists(String table) {
    boolean exists = false;
    String defstmt = "select TABLE_NAME from ALL_TABLES where (TABLE_NAME = '" + table + "')";
    System.err.println("tableExists: stmt = " + defstmt);
    if (tc.executeSEL(defstmt)) {
    ResultSet rs = tc.getRS();
    try {
    exists = rs.first();
    // This returns false if the rs is empty
    // This should be sufficient if the query will return zero rows or one row.
    // If there's a possibility that the query could return more than one row
    // (for example if multiple schema data is in there and a table name
    // might be duplicated), then this section will need to be more picky.
    System.err.println("tableExists.try: tname found");
    catch (SQLException ex) {
    System.err.println("tableExists.catch: tname not found");
    try {
    rs.close();
    catch (SQLException ex1) {
    return exists;
    Bottom line; neither method seems to be able to determine whether the table exists. Someone out there got any suggestions?
    Thanks in advance
    RCulp

    The method "tc.executeSEL" is in a class "TableConnector" which I use to hold connection data and execute SQL statements. A new instance of the "TableConnector" class is created for each table prior to the check for existence. The method itself is boolean, returning true or false if the SQL runs successfully:
    public boolean executeSEL(String inpstmt) {
    rs = null;
    try {
    Connection conn = ConnectionData.getConnectionData().openConnection();
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(inpstmt);
    return true;
    //debugdumpRS(rs);
    catch (SQLException ex) {
    System.err.println("SEL Statement = " + inpstmt);
    System.err.println("Error code = " + ex.getErrorCode());
    System.err.println("Error message = " + ex.getMessage());
    System.err.println("SQL state = " + ex.getSQLState());
    return false;
    /*FINALLY CAN NOT BE USED HERE; ERASES THE RESULT SET
    finally {
    if (stmt != null) {
    try {
    stmt.close();
    catch (SQLException ex) {
    System.err.println("Error code = " + ex.getErrorCode());
    System.err.println("Error message = " + ex.getMessage());
    The TableConnector class also has a get method for the ResultSet:
    public ResultSet getRS() {
    return rs;
    I'll try your suggestion and post the result.
    Thanks
    RCulp

  • Check for duplicate record in SQL database before doing INSERT

    Hey guys,
           This is part powershell app doing a SQL insert. BUt my question really relates to the SQL insert. I need to do a check of the database PRIOR to doing the insert to check for duplicate records and if it exists then that record needs
    to be overwritten. I'm not sure how to accomplish this task. My back end is a SQL 2000 Server. I'm piping the data into my insert statement from a powershell FileSystemWatcher app. In my scenario here if the file dumped into a directory starts with I it gets
    written to a SQL database otherwise it gets written to an Access Table. I know silly, but thats the environment im in. haha.
    Any help is appreciated.
    Thanks in Advance
    Rich T.
    #### DEFINE WATCH FOLDERS AND DEFAULT FILE EXTENSION TO WATCH FOR ####
                $cofa_folder = '\\cpsfs001\Data_pvs\TestCofA'
                $bulk_folder = '\\cpsfs001\PVS\Subsidiary\Nolwood\McWood\POD'
                $filter = '*.tif'
                $cofa = New-Object IO.FileSystemWatcher $cofa_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
                $bulk = New-Object IO.FileSystemWatcher $bulk_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
    #### CERTIFICATE OF ANALYSIS AND PACKAGE SHIPPER PROCESSING ####
                Register-ObjectEvent $cofa Created -SourceIdentifier COFA/PACKAGE -Action {
           $name = $Event.SourceEventArgs.Name
           $changeType = $Event.SourceEventArgs.ChangeType
           $timeStamp = $Event.TimeGenerated
    #### CERTIFICATE OF ANALYSIS PROCESS BEGINS ####
                $test=$name.StartsWith("I")
         if ($test -eq $true) {
                $pos = $name.IndexOf(".")
           $left=$name.substring(0,$pos)
           $pos = $left.IndexOf("L")
           $tempItem=$left.substring(0,$pos)
           $lot = $left.Substring($pos + 1)
           $item=$tempItem.Substring(1)
                Write-Host "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"  -fore green
                Out-File -FilePath c:\OutputLogs\CofA.csv -Append -InputObject "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"
                start-sleep -s 5
                $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=PVSNTDB33; Initial Catalog=adagecopy_daily; Integrated Security=TRUE")
                $conn.Open()
                $insert_stmt = "INSERT INTO in_cofa_pvs (in_item_key, in_lot_key, imgfileName, in_cofa_crtdt) VALUES ('$item','$lot','$name','$timestamp')"
                $cmd = $conn.CreateCommand()
                $cmd.CommandText = $insert_stmt
                $cmd.ExecuteNonQuery()
                $conn.Close()
    #### PACKAGE SHIPPER PROCESS BEGINS ####
              elseif ($test -eq $false) {
                $pos = $name.IndexOf(".")
           $left=$name.substring(0,$pos)
           $pos = $left.IndexOf("O")
           $tempItem=$left.substring(0,$pos)
           $order = $left.Substring($pos + 1)
           $shipid=$tempItem.Substring(1)
                Write-Host "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"  -fore green
                Out-File -FilePath c:\OutputLogs\PackageShipper.csv -Append -InputObject "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"
    Rich Thompson

    Hi
    Since SQL Server 2000 has been out of support, I recommend you to upgrade the SQL Server 2000 to a higher version, such as SQL Server 2005 or SQL Server 2008.
    According to your description, you can try the following methods to check duplicate record in SQL Server.
    1. You can use
    RAISERROR to check the duplicate record, if exists then RAISERROR unless insert accordingly, code block is given below:
    IF EXISTS (SELECT 1 FROM TableName AS t
    WHERE t.Column1 = @ Column1
    AND t.Column2 = @ Column2)
    BEGIN
    RAISERROR(‘Duplicate records’,18,1)
    END
    ELSE
    BEGIN
    INSERT INTO TableName (Column1, Column2, Column3)
    SELECT @ Column1, @ Column2, @ Column3
    END
    2. Also you can create UNIQUE INDEX or UNIQUE CONSTRAINT on the column of a table, when you try to INSERT a value that conflicts with the INDEX/CONSTRAINT, an exception will be thrown. 
    Add the unique index:
    CREATE UNIQUE INDEX Unique_Index_name ON TableName(ColumnName)
    Add the unique constraint:
    ALTER TABLE TableName
    ADD CONSTRAINT Unique_Contraint_Name
    UNIQUE (ColumnName)
    Thanks
    Lydia Zhang

  • How can I check for the existence of an XML file in Illustrator Javascript??

    I'm writing a Javascript to run at startup. I want to check for the existence of XML files and process them, if they are available. How can I check for their existence?

    Your first line just sets a variable to a string value… getFiles() is a method of Folder… so
    var InputXMLDir = Folder( "D:/Brackets/Create_Bracket_Graphics/Input/XML-n-Templates/" );
    Not a PC user so I can't remember if the colon is OK…? As you appear to know the file name why bother with a folder get files anyhow you could just check if the file exists then do some thing…
    alert( File( "D:/Brackets/Create_Bracket_Graphics/Input/XML-n-Templates/brackets_men_web.xml" ).exists );

  • Checking for the existence of a Frame

    Hello,
    I am currently designing an application which consists of 8 JFrames (all in different classes), During the application, one JFrame provides information to a user and when they select the appropriate fields another JFrame opens an the active one closes. However the problem i am having is that i need to be able to write an if statement saying
    if (this particular frame exists already){
    destroy it;
    }else{
    whatever........};
    But i dont know how to check for the existence of a frame currently running, or how to destroy it..
    im currently using dispose(); to destroy frames but the dispose method only works when your in the class thats creating the frame, it wont let me write something like class1.dispose() (where class1 is the frame object created in the constructor of class1.java); in class2.
    I have searched throught the forum and havent found anything that can help me, i would really appreciate anyones input.
    Thanks in advance,
    Dev

    Hey its ok i've decided to restructure the program, but if anyone does know how to do this please still reply to the message, as i would still like to know

  • DB installs fails with [INS-30060] Check for group existence failed

    Hi folks
    as user jjayet I'm running on OEL 5.6 64 bits the following command to install DB 11gR2 :
    $ /mntmats/SOAVM0504/AUTO_WORK/dbzip_shiphome/database/Disk1/runInstaller -ignoreSysPrereqs -invPtrLoc /ade/jjayet_dte9672/oracle/work/DATABASE1/oraInst.loc -force -silent -waitforcompletion -responseFile /ade/jjayet_dte9672/oracle/work/DATABASE1/db.rsp
    Starting Oracle Universal Installer...
    Checking Temp space: must be greater than 120 MB. Actual 15258 MB Passed
    Checking swap space: must be greater than 150 MB. Actual 16454 MB Passed
    Preparing to launch Oracle Universal Installer from /tmp/OraInstall2012-04-05_06-07-54AM. Please wait ...[FATAL] [INS-30060] Check for group existence failed.
    CAUSE: Unexpected error occurred while trying to check for group existence.
    $ id
    uid=511053(jjayet) gid=8500(dba) groups=8500(dba),59031(oinstall)
    the problems seems relater to accessing /tmp
    as the local disk is not enough to use the default /tmp (the DB install will fail with full disk error as the local disk space is very low )
    I've created a partition from new disk to /tmp which I have then mounted (default is nfs3) :
    # mount /dev/xvdc1 /tmp
    # mount
    /dev/xvdc1 on /tmp type ext2 (rw)
    the result of DB install into /tmp is :
    # cd /tmp
    # ls -altr
    drwxr-xr-x 32 root root 4096 Apr 5 06:07 ..
    drwxr-xr-x 2 jjayet dba 4096 Apr 5 06:36 CVU_11.2.0.2.0_jjayet
    drwxrwxrwx 7 root root 4096 Apr 5 06:36 .
    if I umount /tmp but use the local /tmp
    re-running the DB installer as user jjayet it does not raise the error above
    and now local /tmp contains :
    # cd /tmp
    # ls -altr
    drwxr-xr-x 32 root root 4096 Apr 5 06:07 ..
    drwxr-x--- 10 jjayet dba 4096 Apr 5 06:25 OraInstall2012-04-05_06-25-28AM
    drwxr-xr-x 3 jjayet dba 4096 Apr 5 06:25 CVU_11.2.0.2.0_jjayet
    drwxrwxrwt 5 root root 4096 Apr 5 06:25 .
    do you know how to use tmp over nfs with user jjayet so that the DB can install properly ?
    it seems that the files created as user jjayet into mounted /tmp are not identified properly
    thks in advance
    jean

    thks for the pointer
    I found the post you mention but it does not help
    it does not explain the root cause of the problem but just propose a workaround to pass an option to installer which will popi\up an interactive messgae at install time
    as installation is done automatically through ADE / DTE I cannot use this workaround
    any expert in oracle DB install can help ?
    thks
    Jean

  • I am on a MAC Application. It has  been rejected by following reason.  This app does not check for the existence of a purchase receipt, which can prevent In-App Purchases from being correctly processed. We recommend implementing receipt validation to reso

    I am on a MAC Application.
    It has  been rejected by following reason.
    This app does not check for the existence of a purchase receipt, which can prevent In-App Purchases from being correctly processed.
    We recommend implementing receipt validation to resolve this issue.
    At a minimum, the app will need to check for the existence of an App Store receipt and exit at launch with a status of 173 if it does not exist.
    Any help ?
    Thanks in Advance.

    I am on a MAC Application.
    It has  been rejected by following reason.
    This app does not check for the existence of a purchase receipt, which can prevent In-App Purchases from being correctly processed.
    We recommend implementing receipt validation to resolve this issue.
    At a minimum, the app will need to check for the existence of an App Store receipt and exit at launch with a status of 173 if it does not exist.
    Any help ?
    Thanks in Advance.

  • BAPI for Existence check of Delivery Address

    Hello Everyone,
    Can anyone suggest me of a BAPI or Remote Enabled FM that does an Existence check for Delivery address "AD_ADDRNUM" while creating a Purchase Order? I would appreciate your help.
    Regards,
    Gopal.

    I couldnt find any BAPI or FM for you but you can write your own RFC. Tables: ADRC, ADRP , ADRT may help you. Check them with your address number

  • Checking for the existence of a file.

    I have a GUI to enter test info. A file is created based on the entered test number. I want to check for the existence of a file, and then notify the operator while not allowing the program to save it.

    This vi checks the presence of the input file.
    If file is not found, it will be created.
    regards
    ian.f
    Ian F
    Since LabVIEW 5.1... 7.1.1... 2009, 2010
    依恩与LabVIEW
    LVVILIB.blogspot.com
    Attachments:
    File_check_existance_openorcreate_2003.vi ‏72 KB

Maybe you are looking for

  • Getting an iMac G5 ready to sell

    I have a G5 pc that I am selling. Thanks to archived threads, I have backed up, used disk utliity to erase with 0's, installed the original disks (Tiger) and installed 10.5.4 (disk is part of the sale). I would like to get the computer to start up fr

  • IOS5/Itunes 5 sync issues - music greyed out, not syncing across

    Hello, I am having issues syncing music from iTunes to my iphone and ipad. I use autofill, but have had the same issue when using the sync all music option. All the files are listed in the music tab under the device, but half are greyed out and unpla

  • Capturing HI8 tapes: Date/Time

    Hi all, I recently started to capture my HI8 tape collections from an old HI8 Video Cam via Fire Wire into Premiere Pro CC 2014. The data/time when the footage was taken is visible for around 3 to 5 seconds in the Camcorder display at the beginning o

  • Multiple Network Device Groups when importing to ISE using template

    I have a question about importing a group of network devices into ISE using the template provided. The template only has a single column for Network Device Groups - is there a way to import devices and include more than one NDG? For instance, the NDG

  • Toplink, EJB, JPA, and GlassFish

    Hi, I need call a stored procedure from a SessionBean using de toplink: I need obtain a toplink Session object to call de stored procedure, ¿How can I obtain this from the EntityManager object?