Function results in SELECT and WHERE

Is there a way to avoid calling a function twice in order to have its results appear in the SELECT clause and used in the WHERE clause?
This SELECT statement will not work (as promised by documents):
select name, getLocation(name) as location
where location is not null
The only way to avoid it that I can see is to wrap this into another select with the additional criteria:
select * from ( select name, getLocation(name) as location )
where location is not null
Any alternatives?
Thanks.
--Peter

The nested select statements are much quicker than even doing a count(*) in the select and using the function call in the where clause. It appears that a function call in the where clause is expensive. The function involves selects from the same table and others, and joins but no updates, deletes, etc.
select count(*) from ... where location(...) is null
takes > 6 min. !
select count(*) from (select location(...) ) where location is null takes < 10 sec. !

Similar Messages

  • Avoid repeating same logic in 'select' and 'where' clauses?

    I'll preface by saying I'm self-taught and have only been fiddling with SQL for a couple of months, so forgive me if this is a dumb question. I have a query written to pull out customers who are configured to have their products stored at the wrong warehouse, according to the first 3 digits of the zip code. Here is an extremely simplified version of a query I'm trying to run:
    select custno, custbuy_zip_cd, custbuy_prim_ship_loc_cd as Warehouse,
    case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
    when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
    end as StdWhse
    from customers
    where case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
    when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
    end <> custbuy_prim_ship_loc_cd
    or (case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
    when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
    end is not null and custbuy_prim_ship_loc_cd is null)
    Now, the query works, but it seems overly convoluted and feels like there must be a way to make it simpler and faster. I'm using the same 'case when' 3 times. Originally, I had thought I could use the aliases from the 'select' clause in the 'where' clause, which would simplify things:
    select custno, custbuy_prim_ship_loc_cd as Warehouse,
    case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
    when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
    end as StdWhse
    from customers
    where StdWhse <> custbuy_prim_ship_loc_cd
    or (StdWhse is not null and custbuy_prim_ship_loc_cd is null)
    I then found out that that caused 'invalid identifier' errors. My first attempt at a solution was to use a subquery in the 'from' clause, but that ran the 'case when' on every single customer instead of the small subset, so it wound up taking much longer even though it looked neater. Any tips on how to clean up that first query to make it run faster?
    this is Oracle 11i, I believe. As a side note, I don't have write access to the database.

    Thanks for all the tips so far - still going through them. You all respond fast! Sorry about using double angle brackets for != and not using code tags, I'll make sure to format my posts properly going forward. I think the double angle brackets messed up the appearance of my original queries a little. Here's how I probably should have pasted my first query in my first post:
    select custno, custbuy_zip_cd, custbuy_prim_ship_loc_cd as Warehouse,
        case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
            when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
        end as StdWhse
    from customers
    where case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
            when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
        end != custbuy_prim_ship_loc_cd
        or (case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
            when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
        end is not null and custbuy_prim_ship_loc_cd is null)The almost unanimous opinion seems to be that I should use a subquery in one way or another, but the problem remains that the only significant logic to narrow down the results is the logic that matches the 'case when' results (which are what the warehouse number should be, based on the zip code) to the current warehouse number. Therefore, it seems like any subquery is going to return my entire list of 600k customers, and take a much longer time than my original (messy) query. At least it has in the test runs I created based on
    Satyaki's and Peter's examples. The query based on my original example takes about 2.5 minutes, and the subquery examples take about 5+ even though they look cleaner.
    to clarify what the query is trying to accomplish, I want it to pull any records where the warehouse number does not equal the correct warehouse number based on zip code (or if the warehouse number is null when it shouldn't be).
    I'll try to create some sample data and sample results. Customers table:
    custno   custbuy_zip_cd  custbuy_prim_ship_loc_cd
    1        59024           20
    2        59024           33desired results:
    custno   custbuy_zip_cd   warehouse   StdWhse
    1        59024            20          33If I could create a table to hold the standard warehouses to join on, the whole thing would be much easier. The full version of the query really has hundreds of zip code prefixes and 5 different warehouses and each account has 4 alternate warehouses as well. However, I'm stuck with read only access so everything has to go right in the query. It wouldn't be the end of the world to just stick with my original query since it's not like it takes hours, and I'll only be running it weekly. I just wanted to make sure there wasn't some other solution that wasn't just cleaner but was also faster.

  • Select and where clause

    Hi
    I want to write a select statement and in where condition
    1.I want to retrieve the fields which contains a string 'ABAP'
    2.I want to retreive the fields which is equal to space.
    eg;
    SELECT FLD1 FLD2 FLD3 FROM TABLE1 WHERE
       WHERE
       fld1 contains string 'ABAP'
    and fld2 is equal to space.

    Hi
    Yes you can, but you should use the language in the selection on MAKT:
    SELECT MARA~MATNR
    MAKT~MAKTX
    MCH1~CHARG
    MCH1~VFDAT INTO CORRESPONDING FIELDS OF TABLE GT_MATERIALS
    FROM MARA
    INNER JOIN MAKT
    ON MARAMATNR = MAKTMATNR
    INNER JOIN MCH1
    ON MAKTMATNR = MCH1MATNR
    INNER JOIN MVKE
    ON MVKEMATNR = MAKTMATNR
    WHERE MARA~MTART = 'ZDRU'
    AND MARA~LVORM = SPACE
    <b>  AND MAKT~MAKTG LIKE '%DISCONTINUE%'
      AND MAKT~SPRAS  = SY-LANGU "or EN</b>
    AND MVKE~VKORG = 'PUSA'
    AND MVKE~VTWEG = 'SPART'
    AND MVKE~MVGR4 = 92
    AND MCH1~CHARG IN S_CHARG.
    Max

  • Inserting Comments into Universe SELECT and WHERE clauses

    I am converting an application from Crystal Reports to Business Objects.  In conjunction with that, I am (manually) converting our Business View to a Universe.  In Crystal we frequently documented our formulas using the Crystal Syntax "//...".  Out of habit, I tried using the same syntax in the Universe... that didn't work.  And poring through the Universe Designer's Guide and reviewing these forums didn't turn up anything either.  Anyone else know how to do this?  If it matters, we're reporting against an Oracle database.

    Hi Scott,
    if we are talking about plain SQL from ORACLE it's one of the inline comment characters (as /.../ )
    documented in the Oracle manual.
    see:
    select 1 from dual  /* my test */
    union /*  additional comments here
    and here
    and here
    -- and here
    select 2 from dual
    BO may cover information in it's database specific documentation
    bye
    yukonkid

  • DB buffer cache vs. SQL query & PL/SQL function result cache

    Hi all,
    Started preparing for OCA cert. just myself using McGraw Hill's exam guide. Have a question about memory structures.
    Actually, DB buffer cache is used to copy e.g. SELECT queries result data blocks, that can be reused by another session (server process).
    There is also additional otion - SQL query & PL/SQL function result cache (from 11g), where also stored the results of such queries.
    Do they do the same thing or nevertheless there is some difference, different purpose?
    thanks in advance...

    There is also additional otion - SQL query & PL/SQL function result cache (from 11g), where also stored the results of such queries.Result cache located in shared pool.So it is one component of shared pool.When server process execute query(and if you configured result cache) then result will store in shared pool.Then next execution time run time mechanism will detect and consider using result cache without executing this query(if data was not changed this is happen detection time)
    Do they do the same thing or nevertheless there is some difference, different purpose?.Buffer cache and result cache are different things and purpose also,but result cache introduced to improve response time of query in 11g(but such mechanism also implemented in 10g subquery execution,in complex query).In buffer cache holds data blocks but not such results.
    Edited by: Chinar on Nov 4, 2011 4:40 AM
    (Removing lots of "But" word from sentences :-) )

  • Photoshop Elements select tool, when targeting layer or multiple layers the layer properties box pops up.  Having to very carefully and repeatedly select and highlight layers to move, or merge when using Move Tool.  Win 8, Adobe 12, Intuos 4 w/ updated dr

    This issue has been going on for several weeks.
    The Move Tool is not functioning properly when selecting and TARGETING a layer or multiple layers, as the Layer Properties box pops up requiring me to close it and try again.
    How to reset or is there an update and fix for this issue.
    Using Win 8, Elements 12, and Intuos 4 Pen and Tablet.

    To reset the tool I suggest click on it once and then look for something like this in the bottom half of your window:
    In the above picture I have marked one section in red box.  You need to click on it to get the option to either reset the only tool you have clicked or to reset all the tools in the editor window.  Of course you have to be in Expert Mode to get this to work.
    Good luck.

  • Oracle stored functions and where clauses

    Hello everybody,
    I need to call an Oracle stored function and at the same time do a select on
    the result of the query, it works well except when I use a where clause. I
    am connecting to Oracle 8.1.7 through OLEDB using the Oracle provider for
    OLEDB distributed with this Oracle version.
    Here is the query I am doing:
    select * from {call MC.SEC.QryTermbases(?, ?) where ID = ?}
    If I remove the where clause it works well but I need to use the where. I
    know that I could pass the parameter to the procedure instead of doing that
    in the select but there are places where I can not do that since the SQL
    query is generated dynamically. The code above is just a demo.
    Thanks very much for your help,
    Jose.

    Thanks for answering, it is actually possible to do a select on the return of a function, I have tested it with other than "select *" and it has worked well. What has not worked for me is using a "where" clause. That is "select" without "where" has worked but not with the "where".
    I also suspect that it does not work but similar queries work well in MSSQL 2000 and Interbase 6.0 so I thought may be there was a way to do that with Oracle. That is in MSSQL I can treat the result of a function as a normal table and I can do the same thing with a stored procedure that returns a recordset in Interbase.
    Thanks again for answering,
    Jose.

  • What is the defference between select single * from and select * from Where

    What is the defference between select single * from and select * from Where
    which is prefferable and best one.

    Hai,
    *Difference Between Select Single and Select * from table UpTo One Rows:*
    According to SAP Performance course the SELECT UP TO 1 ROWS is faster than SELECT SINGLE because you are not using all the primary key fields.
    select single is a construct designed to read database records with primary key. In the absence of the primary key, it might end up doing a sequential search, whereas the select up to 1 rows may assume that there is no primary key supplied and will try to find most suitable index.
    The best way to find out is through sql trace or runtime analysis.
    Use "select up to 1 rows" only if you are sure that all the records returned will have the same value for the field(s) you are interested in. If not, you will be reading only the first record which matches the criteria, but may be the second or the third record has the value you are looking for.
    The System test result showed that the variant Single * takes less time than Up to 1 rows as there is an additional level for COUNT STOP KEY for SELECT ENDSELECT UP TO 1 ROWS.
    The 'SELECT SINGLE' statement selects the first row in the database that it finds that fulfils the 'WHERE' clause If this results in multiple records then only the first one will be returned and therefore may not be unique.
    Mainly:  to read data from
    The 'SELECT .... UP TO 1 ROWS' statement is subtly different. The database selects all of the relevant records that are defined by the WHERE clause, applies any aggregate, ordering or grouping functions to them and then returns the first record of the result set.

  • How to put variable selection and the query result the same screen

    Dear all,
       how can I put the variable selection and the query result in the same screen? Please advise. Thanks.
    Jin Ming

    Not sure if you are saying you want the prompts on the same page as the results... however in 7.0 with BEx Analyzer, you can insert a text object from the design toolbar and assign it to the variable.... this way, lets say you run query for period 6, then the text object will display "6" on the same area where the query results are.

  • Select statement returns different results from 9i and 10g

    Hi all,
    Would appreciate if someone could help to solve this puzzle here:
    I have the exact the statements running on Oracle 9i and 10g, why do they return different results?
    Select unique(GroupDesc) , GroupSeq from Module where ModuleId in (Select ModuleId from User_Access where UserId='admin') and Status='A'
    In Oracle 9i:
    Both columns returned as follows...
    GroupDesc | GroupSeq
    In Oracle 10g:
    Only one column returned, the column with unique keyword was missing...
    GroupSeq
    Could anyone enlighten me?

    yes, the table structure... actually the CREATE TABLE statement...
    with some sample data (INSERT INTO)
    and the actual queries (both of them - copy-paste them from each separate environment)
    you can use tags around the statements this will format it to a fixed font - making it easier to read
    Edited by: Alex Nuijten on Feb 20, 2009 10:05 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • TS3297 Error when I use search function in itunes store and select an artist

    When I use search function in itunes store and select an artist I get this message. Microsoft visual C++ run time library. Prog C:\progfiles\itunes\itunes.exe  R6025 - Pure virtual function call .  It then shuts down itunes and cannot provide a solution.
    Have tried reinstalling itunes but it did not help.  Any other ideas?

    I have yet to find a solution, but as a work around, do not click or select any of the suggested results while you are typing in your search. Type in your search, and press enter.

  • My iPhone is in a mode where no buttons work. Seems like a debugging mode. How do I restore functionality?  Power off and on does not change it.

    Somehow I pressed a combination of buttons on my iPhone and now it is in a mode where pressing buttons only shows the button is selected and a voice prompt speaks the button. I've tried to shut down and turn back on... nothing changes. When I try to enter passcode it only speaks the code, it does not enter the code in to the spaces, so I cannot login. The phone is totally unusable in this mode. What did I do to enable this function, and how do I turn it off?

    Try pressing the HOME button 3 times quickly. In this mode you need to double-tap anywhere that you would otherwise just tap. Once you get there go to Settings/General/Accessibility and turn off voiceover.
    See: Use Accessibility features in iOS - Apple Support. You can also connect the phone to iTunes  and manage your Accessibility features from there.

  • The InitCVIRTE function is not listed in the NIDAQ function reference online help? Why? and where can I find a description of this function?

    the InitCVIRTE function is not listed in the NIDAQ function reference online help? Why? and what does she do?and where can I find a description of this function? Can i use this function with visualc++ 6.0?

    The InitCVIRTE function is in the CVI run time engine (cvirte.dll)..not part of NI-DAQ.
    Applications written or using CVI may call this function..
    How are you running into this ?
    From the CVI help...
    This function performs initialization of the CVI Run-Time Engine. It is needed only in executables or DLLs that are linked using an external compiler. Otherwise, it is harmless.
    It should be called in your main, WinMain, or DllMain, function. The parameter values you should pass depend on which of these three functions you are calling InitCVIRTE from. The following examples show how to use InitCVIRTE in each case.
    If you are using main, your code should be as follows.
    int main (int argc, char *argv[])
    if (InitCVIRTE (0, argv, 0) == 0)
    return -1; /* out of memory */
    /* your other code */
    return 0;
    If you are using WinMain, your code should be as follows.
    int __stdcall WinMain (HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpszCmdLine,
    int nCmdShow)
    if (InitCVIRTE (hInstance, 0, 0) == 0)
    return -1; /* out of memory */
    /* your other code */
    return 0;
    If you are creating a DLL, you must call InitCVIRTE and CloseCVIRTE in your DllMain function, as in the following.
    int __stdcall DllMain (void *hinstDLL, int fdwReason,
    void *lpvReserved)
    if (fdwReason == DLL_PROCESS_ATTACH)
    if (InitCVIRTE (hinstDLL, 0, 0) == 0)
    return 0; /* out of memory */
    /* your other ATTACH code */
    else if (fdwReason == DLL_PROCESS_DETACH)
    /* your other DETACH code */
    CloseCVIRTE ();
    return 1;
    NOTE: The prototype for InitCVIRTE is in cvirte.h, not
    utility.h.
    NOTE: In CVI 4.0.1, this function was expanded from one to
    three parameters. Executables and DLLs that were
    created using the one-parameter version of the function
    will continue to work properly.
    /*-------------------- Prototype ---------------------*/
    int InitCVIRTE (void *HInstance, char *Argv[], void *Reserved);
    Nandan Dharwadker
    Staff Software Engineer
    Measurement Studio Hardware Team

  • Absolute dynamic select query with dynamic join and where

    Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
    I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
    Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
        SELECT (FIELDS) INTO TABLE IT_TABLES
          FROM ( (ME->TABLE1)  inner join ( me->table2 )
          on ( on_condition ) )
          WHERE (me->where_fields).
    Ags.

    It worked for me in a following way:
    select * into corresponding fields of table <result_table>
            from (join_string)
            where (l_where).
    Where the contents of join_string were dynamically build using concatenation. So it will be something like
    concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
    <...>
    add here matching/reference colums, something like
    concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
    concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
    concatenate join_string temp1 '=' temp2 into join_string separated by space.
    <...>
    concatenate join_string ')' into join_string separated by space.
    And then use similar approach for l_where variable.

  • How to get result of Select from stored function.

    I need to get result of select from a stored function.
    In the end of my stored function I makes final select (four columns).
    How it can be retrived from function?

    Hi,
    A function can only return one value, but it sounds like you want to return 4 values.
    The one value that you return can be a record, with many columns, such as a ROWTYPE, or a TYPE that you define.
    You can return an XMLTYPE that has whatever elements you want.
    You can write a procedure that has several OUT parameters. (You can have OUT parameters in a function, but a lot of people find that confusing.)
    In very special circumstance, you might consider returning a string that is a delimited list of values, such as '7639,SMITH,,17-DEC-1980'.
    Someoneelse has a good point.
    We could give a better answer if you ask a specific question, like:
    "I have this table ...
    I want a function such that, if I call it with these parameters ... I get ...
    but if I call it like this ... then I get ..."

Maybe you are looking for