SELECT and ORDER with several indexes on a table

Hi,
I am looking for the best way to select rows from a table if they satisfy a condition depending on several indexes, or from a join.
I am currently doing it with unions, like that:
SELECT article_id, article_date, score(1) score
FROM articles
WHERE CONTAINS(article_body,'searchQuery',1) > 0
UNION
SELECT article_id, article_date, score(1) score
FROM articles
WHERE CONTAINS(article_title,'searchQuery',1) > 0
UNION
SELECT article_id, article_date, 100
FROM articles
WHERE article_id IN (SELECT article_id FROM article_keywords WHERE keyword = 'searchQuery')
ORDER BY score DESC, article_date DESC
But I was wondering whether it would be better performance-wise to do it with conditional expressions like
SELECT article_id, article_date, score(1) scoreBody, score(2) scoreTitle
FROM articles
WHERE
CONTAINS (article_body,'searchQuery',1) > 0
OR CONTAINS (article_title,'searchQuery',2) > 0
OR article_id IN (SELECT article_id FROM article_keywords WHERE keyword = 'searchQuery')
ORDER BY scoreHeadline DESC, scoreBody DESC, article_date DESC;
Also, if doing it with conditional expressions, I don't see how to avoir having to declare several "scores".
In a more general way, I don't see exactly how to consider the results coming from the join with the article_keywords table in terms of score (right now I'm giving them 100, so they're coming up first).
I am completely new to indexes, so my apologies if anything in this SQL is hurting just looking at it.
Thanks for reading, and for any help you can bring.

You can check out the explain plan for the two queries. I did a small test for employees table . The first query scans the table 3 times, while the second does only once.
hr@XE> EXPLAIN PLAN FOR
  2  SELECT * FROM employees
  3  WHERE last_name like 'Joh%'
  4  UNION
  5  SELECT * FROM employees
  6  WHERE last_name like 'Pet%'
  7  UNION
  8  SELECT * FROM employees
  9  WHERE last_name like 'King%';
Explained.
Elapsed: 00:00:03.06
hr@XE> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 1534505908
| Id  | Operation                     | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT              |             |     3 |   204 |     9  (78)| 00:00:01 |
|   1 |  SORT UNIQUE                  |             |     3 |   204 |     9  (78)| 00:00:01 |
|   2 |   UNION-ALL                   |             |       |       |            |          |
|   3 |    TABLE ACCESS BY INDEX ROWID| EMPLOYEES   |     1 |    68 |     2   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | EMP_NAME_IX |     1 |       |     1   (0)| 00:00:01 |
|   5 |    TABLE ACCESS BY INDEX ROWID| EMPLOYEES   |     1 |    68 |     2   (0)| 00:00:01 |
|*  6 |     INDEX RANGE SCAN          | EMP_NAME_IX |     1 |       |     1   (0)| 00:00:01 |
|   7 |    TABLE ACCESS BY INDEX ROWID| EMPLOYEES   |     1 |    68 |     2   (0)| 00:00:01 |
|*  8 |     INDEX RANGE SCAN          | EMP_NAME_IX |     1 |       |     1   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   4 - access("LAST_NAME" LIKE 'Joh%')
       filter("LAST_NAME" LIKE 'Joh%')
   6 - access("LAST_NAME" LIKE 'Pet%')
       filter("LAST_NAME" LIKE 'Pet%')
   8 - access("LAST_NAME" LIKE 'King%')
       filter("LAST_NAME" LIKE 'King%')
hr@XE> explain plan for
  2  select * from employees
  3  where last_name like 'Joh%' or last_name like 'Pet%' or last_name like 'King%';
Explained.
Elapsed: 00:00:00.01
hr@XE> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 1445457117
| Id  | Operation         | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |           |     3 |   204 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMPLOYEES |     3 |   204 |     3   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("LAST_NAME" LIKE 'Joh%' OR "LAST_NAME" LIKE 'Pet%' OR
              "LAST_NAME" LIKE 'King%')

Similar Messages

  • How to get  shipped orders, unshipped orders and orders with open deliverie

    Hi
    how to get  shipped orders, unshipped orders and orders with open deliveries
    can anybody answer this.
    points would be rewrded
    Thanks

    Hi,
    You can check in the VBUK table for the status of an order. If you do a Query on VBUK table to get all the orders whose delivery status is not 'C' or the total goods movement status is not 'C' you get to know the orders not yet shipped.
    Hope this helps. Reqard points if useful.
    David.

  • VA01: Creation of SD order with several material codes,with and without VAT

    hi guys,
    could someone tell me how to set up the system to not be able to create an SD orders with a mix of VAT condition?
    We don't want a sales order with an combination with and without VAT.
    Pls advise. Thanks.

    could someone tell me how to set up the system to not be able to create an SD orders with a mix of VAT condition?
    We don't want a sales order with an combination with and without VAT.
    H i
    1.The Vat ( Tax ) is applicable on basis of Customer and Mareial Tax classification.
    2. So as far as material is concerned , group all VAT applicable material in One Division
    Say in FMCG Company
    Divisions are Soaps , Skin Care , Shampoo etc
    Create Sub Divsions say for Eg Soaps-------Soaps 1( Taxable) & Soaps 2 .( Non Taxable ) and acordingly for other divisions
    And then Create Sales Areas accordingly.
    All this will need Reorganisation of your Sales Area
    Regards
    Rohit

  • Xsl:sort attribute value templates for select and order

    I've tried the xdk_java_9_0_1_0_0.tar.gz update today and for that the reported bugs are still there : one urgent (quite a stopper for us) is this one
    <xsl:template match="/resultlist">
    <xsl:variable name="sortorder">descending</xsl:variable>
    <xsl:variable name="sortfield">name</xsl:variable>
    <xsl:for-each select="result">
    <xsl:sort select="./{$sortfield}" order="{$sortorder}"/>
    <xsl:value-of select="./index"/>,<xsl:value-of select="./name"/>
    </xsl:for-each>
    </xsl:template>
    still it does not replace {$sortfield} and {$sortorder}.

    This is known bug 1798018 in the Oracle XSLT processor.
    The only workaround I can think of is to use <xsl:choose> to optionally use different <xsl:for-each> blocks, one with order="ascending" and one with order="descending" as literal values.

  • What happens to Existing index after table partition and created with local index

    Hi guys,
    desc part id  number, name  varchar2(100), salary  number
    In an existing table  PART  i am  adding 1 more column DATASEQ NUMBER. i am asked to partition the table part based on dataseq.now the table is created with this logic
    create table part( id  number, name  varchar2(100), salary  number, DATASEQ  number) partition by list(dataseq) (partition PART_INITIAL  values (1));
    Suggestionn required. since  the table is partitioned based on DATASEQ i am asked to add local index on dataseq. i have added local index to dataseq create index idx on part(dataseq) LOCAL; Now my question is  already there is existing index is for the column ID and salary.
    1)  IDX for  dataseq is created locally so that it will have partition on each partition on the main table. Please tell me what happens to the existing index on the column ID and salary.. will it again created in local?
    Please suggest
    S

    Hi,
    first of all, in reality "partition a table" means create a new table a migrate existing data there (although theoretically you can use dbms_redefinition to partition an existing table -- however, it's just doing the same thing behind the scenes). This means that you also get to decide what to do with the indexes -- which indexes will be local, which will be global (you can also re-evaluate some of existing indexes and decide that they're not really needed).
    Second of all, the choice of partitioning key looks odd. Partitioning is a data manageability technique more than anything else, so in order to benefit from it you need to find a good partitioning key. A recently added column named "data_seq" doesn't look like a good candidate. Can you provide more details about this column and why it was chosen as a partitioning key?
    I suspect that whoever suggested this partitioning scheme is making a huge mistake. A non-partitioned table is much better in all aspects (including manageability and performance) than wrongly partitioned one.
    Best regards,
    Nikolay

  • Policy-based Tunnel Selection and PBTS with Dynamic Tunnel Selection option

    Unfortunately I can't test this feature on GSR 12k platform.
    RP/0/0/CPU0:ios(config)#show config failed
    !! SEMANTIC ERRORS: This configuration was rejected by
    !! the system due to semantic errors. The individual
    !! errors with each failed configuration command can be
    !! found below.
    interface tunnel-te1
    policy-class 1
    !!% The requested operation is not supported: Feature not supported on this platform
    end
    What is the difference between Dynamic Tunnel Selection and ordinary PBTS? It would be nice to see some real-world example.

    PBTS with DTS is supported only on the Cisco XR 12000 Series Router... you should rather test it on 12K platform.

  • SQL Server 2014 Bug - with Clustered Index On Temp Table with Identity Column

    Hi,
    Here's a stored procedure.  (It could be shorter, but this will show the problem.)
              CREATE PROCEDURE dbo.SGTEST_TBD_20141030 AS
              IF OBJECT_ID('TempDB..#Temp') IS NOT NULL
                 DROP TABLE #Temp
              CREATE TABLE #Temp
               Col1        INT NULL
              ,Col2        INT IDENTITY NOT NULL
              ,Col3        INT NOT NULL
              CREATE CLUSTERED INDEX ix_cl ON #Temp(Col2)
              SET IDENTITY_INSERT #Temp ON;
              RAISERROR('Preparing to INSERT INTO #Temp...',0,1) WITH NOWAIT;
              INSERT INTO #Temp (Col1, Col2, Col3)
              SELECT 1,2,3
              RAISERROR('Insert Success!!!',0,1) WITH NOWAIT;
              SET IDENTITY_INSERT #Temp OFF;
    In SQL Server 2014, If I execute this (EXEC dbo.SGTEST_TBD_20141030)   It works.   If I execute it a second time - It fails hard with: 
            Msg 0, Level 11, State 0, Line 0
            A severe error occurred on the current command.  The results, if any, should be discarded.
            Msg 0, Level 20, State 0, Line 0
            A severe error occurred on the current command.  The results, if any, should be discarded.
    In SQL Server 2012, I can execute it over and over, with no problem.  I've discovered two work-a-rounds:   
    1) Add "WITH RECOMPILE" to the SP CREATE/ALTER statement, or 
    2) Declare the cluster index in the TABLE CREATE statement, e.g. ",UNIQUE CLUSTERED (COL2)" 
    This second option only works though, if the column is unique.    I've opted for the "WITH RECOMPILE" for now.  But, thought I should share.

    Hi,
    I did not get any error Message:
             CREATE TABLE #Temp
               Col1        INT NULL
              ,Col2        INT IDENTITY NOT NULL
              ,Col3        INT NOT NULL
              CREATE CLUSTERED INDEX ix_cl ON #Temp(Col2)
              SET IDENTITY_INSERT #Temp ON;
              RAISERROR('Preparing to INSERT INTO #Temp...',0,1) WITH NOWAIT;
              INSERT INTO #Temp (Col1, Col2, Col3)
              SELECT 1,2,3
              RAISERROR('Insert Success!!!',0,1) WITH NOWAIT;
              SET IDENTITY_INSERT #Temp OFF;
    SELECT * FROM #Temp
    OUTPUT:
    Col1 Col2
    Col3
    1 2 3
    1 2 3
    1 2 3
    Select @@version
    --Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64) 
    Oct 19 2012 13:38:57 
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
    Thanks Shiven:) If Answer is Helpful, Please Vote

  • ADF 11g can not select and copy data from cell of readonly table in IE

    hi,
    In ADF 11g, when render view object as readonly table with Single RowsSelection, using IE browser can not select and copy data from the cell, but it work in firefox.
    is it a bug?
    Edited by: kent2066 on 2009-5-18 上午8:46

    Hi Timo,
    Sorry forgot to mention versions.
    We are using 11.1.1.7 and IE 9.
    I tried in Google but could not get the solution.
    Kindly let me know solution for this.
    PavanKumar

  • Select and ... only one time in table - how?

    Hallo,
    in SRList from SRDemo "Select and View / Edit" comes only on top of the table.
    In my page it comes on top and bottom of the table. why is it so and how i can customize it?
    i don't see the point.

    There isn't much point when you only have 10 items in the table, but imagine the case where there are 100 or more rows in the table (possibly after the user has selected to view all rows). Then it would be conveniant to have the selection facet at the bottom of the table too, so that the user doesn't need to scroll all the way back up to the top.
    As for customisation, I don't think that you can change the behaviour in that way.

  • How to do lead select and double click on a row of table simultaniously ?

    Hello All,
    I am creating a freely programmed search help to search Material Number.
    i am displaying the values in normal table ( Not ALV ) on the search help popup.
    My requirement is
    when I select a row and click on OK button the Material number in that row is getting captured ( This is working fine for me)
    At the same time I also want to capture the value when user double cluck on the particular row.
    I am not able to do both on action methods simultaneously as I am getting syntactic error.
    i.e. When I create action method on the event "on_lead_select" and the event "On select"  and try to save Check & activate it throws error.
    Please find the screen shot below.
    Standard webdynpro component WDR_F4_ELEMENTARY was able to achieve this functionality some how, I have debugged it but didn't get the solution

    Hi,
    There is no double click provision. In the table you could change the cell editor of column to LinktoAction UI, then onclick of that you can set the selected value.  And in the component WDR_F4_ELEMENTARY its not a normal table UI but its a CTable UI, you can try creating a CTable and create an Action for onSelect.
    Regards,
    Kiran

  • Select and highlight a default row in a table

    Hi everybody.
    When using a table in WD, the first line is selected and highlighted by default.
    I'd like to reproduce the same behaviour but this time, the selected and highlighted row shouldn't be the first row but any other one that has to be defined previously.
    How could I do that??
    Thanks for any suggestions you may have.
    Regards,
    C.

    For example I have a node SFLIGHT which am using to display data in tabular format on my layout. I have attached a supply function POPULATE_DATA to my context node SFLIGHT to fetch & populate the node.
    METHOD populate_data .
      DATA: lt_sflight TYPE wd_this->elements_sflight.
      SELECT carrid
             connid
             fldate
             price FROM sflight INTO TABLE lt_sflight.
      node->bind_table( new_items = lt_sflight ).
    ENDMETHOD.
    And within my WDDOINIT method am programmatically setting the LeadSelection to the 3rd row as how shown below:
    METHOD wddoinit .
      DATA: wd_node TYPE REF TO if_wd_context_node.
      wd_node = wd_context->get_child_node( name = 'SFLIGHT' ).
      wd_node->set_lead_selection_index( '3' ).
    ENDMETHOD.
    Regards,
    Uday

  • Report of sales orders with several schedules lines

    Hi all,
    I try to develop a report for sales orders and delivery info. I need sales order quantity, delivery quantity and the quantity in the scheduled line. But I faced with the problem of several scheduled lines.
    I could not find the relation between delivery information and the scheduled lines of sales order.
    Any function module or other way to find out a delivery belongs to which cheduled line of the sales order ?
    Thanks,
    Utku

    Solved problem

  • Report of sales orders with several scheduled lines

    Hi all,
    I try to develop a report for sales orders and delivery info. I need sales order quantity, delivery quantity and the quantity in the scheduled line. But I faced with the problem of several scheduled lines.
    I could not find the relation between delivery information and the scheduled lines of sales order.
    Any function module or other way to find out a delivery belongs to which scheduled line of the sales order ?
    Thanks,
    Utku

    post this in ABAP forum for quicker response.
    Regards
    Raja

  • Select and update with lock exclusive

    Hello Everybody
    In our application we have a table autonum     to handle unique keys for all other tables.
    In Autonum we have a column "SUCHBEGRIFF" char(40) unique KEY and a column "WERT" fixed(10,0).
    Suchbegriff has values like Rechnungsnr,Auftragsnr,Bestellnr ...
    Example:
    Befor inserting a record into table rechnungen we do:
    Select wert from autonun where suchbegriff = "Rechnungsnr" with lock exclusive.
    l_rechnrneu = wert + 1 
    update autonum set wert = ?l_rechnrneu where suchbegriff = "Rechnungsnr"
    commit
    (then l_rechnrneu is used for an insert into rechnungen command)
    This technic works for all tables (250) in our application.
    We have about 400 concurrent users working with maxdb 7.6 via odbc 7.6
    No problems since 2 years!
    Now we start some backgroundjobs from an xp-workstation.
    We have scheduled 5 jobs, starting every 5 minutes, same time.(Same user,same odbc-connection)
    Each job inserts records into a table joblogs and therefore needs a unique JOBLOGNR from autonum.
    Now we run into problems 2 or 3 times a day?
    <Sometimes the backgound jobs are running (waiting?) without inserting a record into joblogs (deadlock?)
    And more worse:
    Sometimes the insert into joblogs failes with "duplicate key" ??
    We don't know where to begin? Maxdb Problem ? Workstation problem?
    Any help welcomed
    Best regards
    Albert

    > >Gosh - that's information overloading at it's best...
    > We call this needed information.
    > What does our SAP-System? We have 1 mandt,60 accounting areas and about 200 werks!
    > Of course SAP uses internal unique keys for all tables, but we configured different "number intervals" for each werks.
    With "information overloading" I was referring to the multiple meanings you encode in just one column (your "rechnungs-no").
    SAP tables do not have this.
    As you wrote, there is "MANDT", "BUKRS", "WERKS" ... and the primary key is defined over all relevant columns.
    There is no primary key column where all the different meanings are concatenated together.
    So there aren't any surrogate keys here (a.k.a. AUTOID) used here - (ok except the infamous DDLOG sequence...).
    > >What do you do, when the value of an invoice has to be changed? Update the primary key of the table?
    > Update rechnungen set amount = xyz,...... where rechnungnr = nnn
    > We never change rechnungsnr,if the invoice was wrong we produce a credit for it and then write a new invoice
    So, you could use a sequence here instead as well.
    > > We don't use rollback when fetching logids from autonum.
    > >So what do you do, when connection fails, the database crashes or the client application hits an error?
    > >You use rollback. There is no way to avoid it.
    > >Your application gets a "duplicate key" error - the database performs a rollback of your last action. What does your application do then? Commit?
    > Sorry, i meant that we do not do rollbacks over  2 or 3 inserts or updates in different tables.
    > SQL-Command,On error = messagebox,errorlog,quit
    You don't handle the fetching of the new number in the same transaction as the actual insert of your application data in the same transaction?
    > >What isolation level do you use?
    > We use DATABASE ISOLATION LEVEL 0
    Hmm... did you read the documentation on SQL Locks?
    [Internals Course - SQL Locks|http://maxdb.sap.com/training/internals_7.6/locking_EN_76.pdf] :
    "Isolation level 0 does not offer any protection against access anomalies."
    Basically it might have happened that the same number is read twice.
    Perhaps the application is not always requiring locks when reading data from this table?
    > After connecting to the database via odbc we do
    > =SQLSETPROP(verbindungsnr,"Transactions",2)
    > 2 = Transaction processing is handled manually through SQLCOMMIT( ) and SQLROLLBACK( ). Read/write.
    > =SQLSETPROP(verbindungsnr,"DisconnectRollback",.T.)
    >
    >
    > So normal select commands are fired without a following commit.
    > Insert and update commands are fired with a following commit command.
    > Selects from autonum are fired with "look exclusive"
    Please be more detailed here.
    What is the exact sequence of actions here?
    1. Fetch number from number table and update number table.
    2. COMMIT
    3. Insert new application data with the just fetched number.
    4. COMMIT
    or
    1. Fetch number from number table and update number table.
    2. Insert new application data with the just fetched number.
    3. COMMIT
    And what does your application do with its data when a rollback occurs?
    Is it guaranteed that all variables are reset?
    > Nevertheless you dislike our design, do you think it would be better (quicker,safer...) to use an internal databases procedure to get
    > the next speaking number for a given "suchbegriff" from our autonum table? (no translation of the sql-command every time)
    No, currently we don't know what is causing the problem, so we cannot tell whether such a change would help. In fact, right now it would make things more complicated because we would less understand, what's happening here.
    Concerning your design: it's not about "liking" or "not liking it".
    I just pointed out some problems that result from the design as it is.
    > select   wert into :neuerwert FROM "BWPROGI"."AUTONUM"  WHERE upper(suchbegriff)     = upper(:suchkey) WITH LOCK EXCLUSIVE;
    > update  "BWPROGI"."AUTONUM" set wert = wert + 1 WHERE upper(suchbegriff)     = upper(:suchkey) ;
    > SET neuerwert = neuerwert + 1;
    > end;
    1. The WHERE clause UPPER(suchbegriff) = UPPER(...) is the best way to disable the efficient use of any index structure. Better make sure that your data is in the right format in the table when you enter it and then look it up without the UPPER() conversion. 
    2. I wouldn't perform the increment two times.
    Get the current value into your variable, increment this variable, set the current value in the table to the variable.
    > A char(10) return value would be nice and i don't know wether this would be the quicker way.
    Why should it? You would have to convert it first - that's additional work.
    Anyhow, to move ahead with your duplicate keys problem, you may perform a vtrace with the "stop on error" option.
    As your error is a duplicate key on a primary key constraint you should set "stop on error" to the error code "200".
    The next time your application hits the error, the vtrace automatically stops and we could examine what happened before.
    See [MaxDB database trace|https://wiki.sdn.sap.com/wiki/x/2yg] for details on how to activate the trace.
    When the error occurs next time and you caught it in the vtrace we can take a look at it.
    regards,
    Lars

  • Confirmation of  production orders with several operations

    Hello,
    I am  using transaction CO11 in order to perform  confirmation of Production orders that has 3  operations...
    with this transaction, I have to enter 3 times the transaction for each  operation...
    could you please tell me a transaction where I can make the confirmation  for all operations in one step ? ( a kind of screen where I can access all operations and manage  the hours and quantities before saving.)
    thanks and regards

    Dear,
    How many such orders would you come across everyday for the confirmation to happen?
    Does the operation sequence remain the same across all the orders?
    Then,i would like to suggest a method,Im not sure how it can be adopted to your scenario
    Try this!!
    We can  group all the production orders on daily basis or in shift basis in a EXCEL spreadsheet.
    Through a BDC,we can migrate the information on a daily basis to SAP.
    Regards,
    Joseph Charles vaikathussery

Maybe you are looking for

  • All of my apps are gone, and I'm having trouble with iCloud

    Let me preface this by saying that Apple made me change my password a few days ago, before I downloaded the new IoS software. So I synced my music, videos and apps to my PC this afternoon before downloading the new software. I downloaded the software

  • Overflow during the arithmetical operation (type P) in program

    Hi all, I have a report. This report is giving dump in production server. The report is running in Quality and development without this dump. Actaully I have added a variable and that of try rseg-wrbtr. And I am not clearing this variable.. So is thi

  • How can i count line wich begins with NCOUNT word

    I want to make a loop to count first a number of lines in file after that to count number of block data wich begins with NCOUNT word

  • Control file name of exported data/pdf

    I have LiveCycle forms that internal auditors use to record their audit results. These forms will be used by by many different people and submitted to Quality by a Submit-By-E-mail button. Is there a way to control the file name of the exported data.

  • After effects help & adobe air

    i'm in the after effects cs5 application (creative suite production premium) on a power mac 10.5.8 and when i go to the help pull down and click on after effects help, i get the following error message: don't even know what abobe air is. i'm assuming