Customer Count Query

Hello All
I need help in writing a Optimized query .
Scenario :
We have several customers across multiple vendors .We want to get Customercount by vendor for a year 
In this scenario we wanted to claculate 
Customer Count for Vendor 
Example 
2014  Kroger(Vendor) has 100 customers
2014  Target(Vendor) has 50 customers
I wanted to see out of those 100 customers for Kroger who were not customer of kroger in 2012 and 2013 but customer of target
Similarly  out of those 50 customers for Target who were not customer of target in 2012 and 2013 but customer of
kroger
In 2012 same customer might have bought with different vendor.We are calculating new to vendor 
C1  2012   Kroger 100
C1  2012   Walmart 100
C2  2012   target 100
C2  2012   Kroger 100
C1  2014   target 100
C2  2014   Kroger 100
C2  2014   target 100
C2  2014   walmart 100
In this case C1 is customer count for target   as he did not buy with target but with other vendors
and c2 canot be counted towarsd kroger or walmart becauase be bought with both of them but can be counterd towarrds walmart as he did not buy with walmart
I am trying to write a query to get 2012 and 2013 data for all vendors and then join with 2014 data set
but the thing is i am getting wrong count 
Please let me know

this?
SELECT Vendor,
YEAR(DATEADD(yy,DATEDIFF(yy,0,Datefield),0)) AS Yr,
COUNT(CustomerID) AS CustomerCount,
COUNT(CASE WHEN Cnt = 0 THEN CustomerID ELSE NULL END) AS FirstTimeCustomerCount
FROM Table t
OUTER APPLY (SELECT COUNT(*) AS Cnt
FROM Table
WHERE CustomerID = t.CustomerID
AND DATEDIFF(yy,0,Datefield) < DATEDIFF(yy,0,t.Datefield)
AND Vendor = t.Vendor)
GROUP BY Vendor,DATEDIFF(yy,0,Datefield)
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page

Similar Messages

  • Count the number of customer in query designer

    Dear Friends,
    I am trying to create a query where we have two key figures.
    ( Division )      (Total Customer)        (Total Customer who purchase)
    10                      10                                 5
    20                       20                              15
    This means i need two figures one is total number of customer against
    each division irrespect of sales either they purchase somthing or not means read from
    master data.
    and second figure i need total number of customer who purchase
    from us by eash division.
    second KF is achived by creating a  New Formula and put 1 in detail view and
    in aggregation tab i select total option and in ref. char. i choose division.
    now i am getting right number of customer who purchased from us.
    for KF one  i dont know how can we read from master data for customer count.
    i know there is a option for characterstics in advance properties choose from
    transaction data or from master data but i am unable to build logic for counting using
    these advance features.
    any help higly appricated.
    Regards,
    Malik
    Edited by: Malik Naeem on Jan 20, 2009 9:01 AM

    HI,
    Maintain the Total Customer as an attribute..
    Then this characteristic has the values from master data..
    THen Convert this characteristic into key figure using Formula Variable with Replacement path.
    Using Formula varaible with replacemant path,  we can convert a characteristic into key fure..
    I Hope u can achieve the result now...
    Hope this helps u..
    Best Regards.
    VVenkat..

  • How can I use the Rownum/Customized SQL query in a Mapping?

    Hi,
    * I need to use a Rownum for populating one of the target field? How to create a mapping with Rownum?
    * How can I use an Dual table in OWB mapping?
    * Can I write Customized SQL query in OWB? How can I achieve this in a Mapping?
    Thanks in Advance
    Kishan

    Hi Niels,
    As I'm sure you know, the conundrum is that Reports doesn't know how many total pages there will be in the report until it is all done formatting, which is too late for your needs. So, one classical solution to this problem is to run the report twice, storing the total number of pages in the database using a format trigger, and throwing away the output from the first run when you don't know the total number of pages.
    Alternatively, you could define a report layout so that the number of pages in the output is completely predictable based upon, say, the number of rows in the main query. E.g., set a limit of one, two, ... rows per page, and then you'll know how many pages there will be simply because you can count the rows in a separate query.
    Hope this helps...
    regards,
    Stewart

  • Incorrectly read attributes with custom SQL query

    Hi folks,
    I'm trying to read in a random sampling of records from a table, so I tried:
    ReadAllQuery q = new ReadAllQuery();
    q.setReferenceClass(Foo.class);
    q.addPartialAttribute("bar");
    q.setSQLString("select * from Foo sample(10)");
    q.useCursoredStream(100,100, new ValueReadQuery("select count(*) from Foo sample(10)"));
    This all worked fine, the Foos were retrieved, but after the first dozen or so, all the "bar" attributes were null, which they should not be. This only occurs when using a custom SQL string. I tried bringing back all the objects (i.e., without using setSQLString) and examining them and all the "bar"s were present. But when I use setSQLString the attributes don't get read correctly.
    Can anyone tell me what I'm doing wrong? Is there a better way to do it?
    Thanks,
    Bryn

    Okay, here's the actual code:
    ReadAllQuery q = new ReadAllQuery();
    q.setReferenceClass(ActivityCenter.class);
    boolean useCustom = true;
    if (useCustom) {
    q.setSQLString("SELECT SetupDt, TerminationDt, ReinstateDt, IID, upDt, ID, " +
    "Stat, SubType, Acct FROM ACtr");
    q.useCursoredStream(100,100, new ValueReadQuery("select count(IID) from actr"));
    } else {
    q.useCursoredStream(100,100);
    session.logMessages();
    activityCenters = (CursoredStream) session.executeQuery(q);
    ActivityCenter ac = (ActivityCenter) activityCenters.read();
    if (ac.getAccount() == null) {
    System.err.println(ac.getID() + ": Oops!");
    } else {
    System.err.println(ac.getID() + ": Has account!");
    System.exit(0);
    So, everything about this program is the same - how the mapping is done, how things get initialized, everything. The only difference is whether I use a custom SQL query or not. Here's what it looks like when I run it both ways:
    First, custom:
    DatabaseSession(2433702)--Connection(393272)--SELECT SetupDt, TerminationDt, ReinstateDt, IID, upDt, ID, Stat, SubType, Acct FROM ACtr
    1.1: Oops!
    Now, without the custom SQL:
    DatabaseSession(393272)--Connection(7896086)--SELECT SetupDt, TerminationDt, ReinstateDt, IID, upDt, ID, Stat, SubType, Acct FROM ACtr
    DatabaseSession(393272)--Connection(7896086)--SELECT
    //bunch of fields from the Acct attribute...
    FROM Acct WHERE (IID= 'ffbe5c47f3ea762cfd50fbe9e6d6de6')
    1.1: Has account!
    Notice that the first query on Actr is identical in both cases. Also note there are no null Actr.acct fields in the database:
    SQL> select * from actr where actr.acct is null;
    no rows selected
    SQL>
    This is on Oracle 9i, with the thin jdbc driver.
    Also, I was curious that you asked if I was using partial attributes - when I try to add a partial attribute when using the custom SQL string, I get exceptions like this one:
    java.lang.ClassCastException: oracle.toplink.internal.queryframework.CallQueryMechanism
    at oracle.toplink.queryframework.ObjectLevelReadQuery.initializeDefaultBuilder(Unknown Source)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.getExpressionBuilder(Unknown Source)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.addPartialAttribute(Unknown Source)
    at jenkon.magellan.util.MLMulator.getActivityCenters(MLMulator.java:782)
    at jenkon.magellan.util.MLMulator.run(MLMulator.java:897)
    at jenkon.magellan.util.MLMulator.main(MLMulator.java:943)
    Thanks,
    Bryn

  • Customer Count

    Hi all,
    I want to come up with a query listing the NUMBER OF CUSTOMERS PER DAY.
    Anyone with a better query than the one below which according to my analysis is
    returning a higher number than usual?
    SELECT DISTINCT 'Customers:', COUNT(T0.DocEntry) as [Customer Count] FROM INV1 T0 WHERE  T0.DocDate='%0'
    Reagards,
    Henry

    Hi Peter,
    Thanks for your prompt response. Sure, it should be OINV.
    SELECT count(T0.DocNum) FROM [dbo].[OINV]  T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry WHERE T0.DocDate =[%0] and  T1.WhsCode =[%1]
    the query above is precisely what i was talking about. I have linked the two tables in order to
    be able to select customers per every warehouse separate. But it gives me overblown figures.
    The query below works fine but it does not have a Warehouse Selection Option because we don't
    have WhsCode or WhsName field in OINV.
    SELECT count(T0.DocNum) FROM [dbo].[OINV]  T0 WHERE T0.DocDate =[%0]
    Please advise on how best to modify the first query to functon properly. Thanks
    Regards,
    Henry

  • Can we implement the custom sql query in CR for joining the two tables

    Hi All,
    Is there anyway to implement the custom sql query in CR for joining the two tables?
    My requirement here is I need to write sql logics for joining the two tables...
    Thanks,
    Gana

    In the Database Expert, expand the Create New Connection folder and browse the subfolders to locate your data source.
    Log on to your data source if necessary.
    Under your data source, double-click the Add Command node.
    In the Add Command to Report dialog box, enter an appropriate query/command for the data source you have opened.
    For example:
    SELECT
        Customer.`Customer ID`,
        Customer.`Customer Name`,
        Customer.`Last Year's Sales`,
        Customer.`Region`,
        Customer.`Country`,
        Orders.`Order Amount`,
        Orders.`Customer ID`,
        Orders.`Order Date`
    FROM
        Customer Customer INNER JOIN Orders Orders ON
            Customer.`Customer ID` = Orders.`Customer ID`
    WHERE
        (Customer.`Country` = 'USA' OR
        Customer.`Country` = 'Canada') AND
        Customer.`Last Year's Sales` < 10000.
    ORDER BY
        Customer.`Country` ASC,
        Customer.`Region` ASC
    Note: The use of double or single quotes (and other SQL syntax) is determined by the database driver used by your report. You must, however, manually add the quotes and other elements of the syntax as you create the command.
    Optionally, you can create a parameter for your command by clicking Create and entering information in the Command Parameter dialog box.
    For more information about creating parameters, see To create a parameter for a command object.
    Click OK.
    You are returned to the Report Designer. In the Field Explorer, under Database Fields, a Command table appears listing the database fields you specified.
    Note:
    To construct the virtual table from your Command, the command must be executed once. If the command has parameters, you will be prompted to enter values for each one.
    By default, your command is called Command. You can change its alias by selecting it and pressing F2.

  • Optimize query results(timing) returned from custom search query

    Casey can you send the following to Oracle Support as soon as you can, we need their input on optimizing returning search results.
    To Oracle:
    We have noticed in the IdocScript reference guide that there is a way to optimize the query results returning to the user.
    Here is the scenario: We have created a custom web query where we send a query to the UCM and return a result using a custom template via url like so
    http://dnrucm.dnr.state.la.us/ucm/idcplg?IdcService=GET_SEARCH_RESULTS&QueryText=dDocTitle <matches> `AGREEMENT` <AND> xStateLeaseNum<matches>`00340`&ResultCount=30&SortOrder=Desc&SortField=dInDate&urlTemplate=/ucm/groups/public/documents/oos/hcst-search.hcst
    This works fine. The problem is that when a query is broader like
    http://dnrucm.dnr.state.la.us/ucm/idcplg?IdcService=GET_SEARCH_RESULTS&QueryText= xStateLeaseNum<matches>`00340`&ResultCount=30&SortOrder=Desc&SortField=dInDate&urlTemplate=/ucm/groups/public/documents/oos/hcst-search.hcst
    The query takes an extremely long time to execute and the results template sometimes never comes back, which seems like a timeout.
    Is there something else that we can do to optimize the query results?

    Hi John,
    What version of xMII are you using?
    Some things I would try:
    1. Clear the Java Web Start Cache - see if that makes any difference.
    2. If not, what happens if you save the query under a different name, and then try using it in a new transaction?
    3. Please feel free to enter you case into xMII Support via the SAP Support Portal if you are unable to make this work.
    Kind Regards,
    Diana Hoppe

  • Custom counter not labeling clips in correct sequence

    Anyone know why my custom counter feature is no longer assigning numbers to my clips in the right order?  I have a series of clips -- say an interview -- I select them all in sequence, and then using custom name and counter I expect to see them numbered sequentially.  Instead what I get seems random.  It has the right range of numbers associated with the clips but the sequence is all screwy.  When I apply the original camera names to the clips, however, it puts them in the right sequence.  Could have started when I upgraded to 10.0.3.  SUggestions???

    Yeah, the problem is still there.  I did get a call into Apple last week and had a fairly lengthy and encouraging conversation.  They were apparently unaware of this problem but were again able to reproduce the problem on their end.  The dude was quite empathetic regarding my frustration that 2 updates later the problem still exists.  So... I'm keeping my fingers crossed for 10.0.6, or better yet 10.0.5b.

  • Parameter passing to custom SQL query using PL/SQL FUNCTION

    Hi
    In order to pass a parameter to the query in custom folder of a business area I created a function and mapped it to the Custome query using Discoverer Desktop. There is no error in mapping as the system does not throw any error. When I am inputting the Parameter for the input values everytime the query doesnot return any rows.
    Can anybody help in this regard

    Hi,
    I need to take the request Id as input from the user and then fetch only the data pertaining to that requet Id. As a lot of complex joins are involved I need to pass request id as parameter to the custome folder.
    The package i greated:
    CREATE OR REPLACE PACKAGE SETPARAM
    AS
    param1 varchar2(25);
    param2 varchar2(25);
    FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER ;
    FUNCTION GET_PARAM1 RETURN varchar2;
    END SETPARAM;
    CREATE OR REPLACE PACKAGE BODY SETPARAM AS
    FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER IS
    BEGIN
    fnd_client_info.set_org_context('138');
    param1 := p1;
    dbms_output.put_line(param1);
    RETURN 1;
    END;
    FUNCTION GET_PARAM1 RETURN varchar2 AS
    BEGIN
    RETURN param1;
    END;
    END SETPARAM;
    I registered the set_param1 function as a pl/sql function in discoverer admin.
    This function is called on the condition associated with the parameter in Discoverer Desktop when i run the report.
    In the custom folder query i have this piece in the where clause
    WHERE tnfo.request_id = NVL(APPS.SETPARAM.GET_PARAM1,7383588)
    And everytime i get the data pertaining to request id =7383588,
    Please suggest where i went wrong
    thanks
    Ashwini

  • Customer Ageing query

    Hi
    We have a standard query in BW for customer ageing query 0FIAR_C03_Q0002.
    In this query we have several dates
    1. Document date
    2. Posting date
    3. Base line date
    4. Net due date.
    Its very tough to understand what is the significance of these dates and how the query is calculated based on which date. I am finding it difficult to xplani to the client about this report.
    Can anyone explain me about these dates and how the query is calculated on which date.
    Regards
    Annie

    Hi
    When i execute the query, there is a variable called KEY DATE(*). What is that date. When i see in the query designer, there is no variable specified in filter, free characteristics or Rows. Then from where is this varialbe is getting popping up.
    and when i enter a date, how it is going to calculate. I am very much confused. need your inputs.
    Regards
    Annie

  • Possible to execute custom SQL query?

    Is it possible to execute a custom SQL query and get back a collection of
    objects with Kodo JDO? Query expression languages like JDOQL are all very
    well (I actually think JDOQL is pretty messy), but sometimes when you've
    got a complex query (and you know you're using a RDBMS) it is best
    accomplished in a SQL statement. I see Kodo has extended JDOQL, which is
    good, but developing custom extensions seems to be limited to implementing
    kodo.jdbc.query.JDBCFilterListener where you can customise the where
    clause. What I want to be able to do is to specify the entire SQL string.
    I am looking into using Kodo JDO for my organisation, and being able to
    use custom SQL is something i would expect (and something we can do with
    our current O/R mapping product (TopLink)).
    Regards,
    Alex

    Patrick Linskey wrote:
    On Tue, 30 Sep 2003 10:57:13 +0000, Alex wrote:
    being able to use custom SQL is something i would expect
    We absolutely agree. Take a look at the samples/customSQL example in the
    Kodo distribution.
    -Patrick
    Patrick Linskey
    SolarMetric Inc.Hi Patrick,
    I have downloaded kodo-jdo-3.0.0RC1 for windows for evaluation, but there
    is no samples/customSQL directory.
    Alex.

  • Execute custom SQL query in OIM11g

    Hi,
    Can you please provide me some java code snippet to execute a custom sql query and also to get db connection to execute this query in OIM 11g. I am going to run this query in an adapter.
    Thanks a lot for ur help.
    Mike

    Hey Mike,
    Use the below sample code to get db connection and then to execute a query in OIM11g.
    String query = "SELECT UD_ADUSER_EMAIL FROM UD_ADUSER WHERE upper(UD_ADUSER_UID) like '%TESTU%'";
    Connection con = Platform.getOperationalDS().getConnection();
    PreparedStatement preparedStatement = con.prepareStatement(query);
    ResultSet resultSet = preparedStatement.executeQuery();
    while(resultSet.next())
    System.out.println("Output:"+resultSet.getString(1));
    }

  • The requested Performance Counter is not a custom counter...

    Hello All,
    I'm very new to both Oracle & .NET/IIS, and I am having trouble configuring one of my five IIS6/Win2003 servers. I have successfully deployed the same code on three other servers, each with the same ODAC (11.1.0.5.10 Beta) installation. Using sqlplus, I've been able to validate the connection to my db. There is even code using an older Oracle driver in part of the codebase that connects and works fine with the db, but I can't get my ODAC-reliant code to work.
    When I try to access the code that uses ODAC, I get the error below.
    Thanks in advance for any clues at all!
    - Jason
    The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.InvalidOperationException: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
    Source Error:
    Line 7: // Code that runs on application startup
    Line 8:
    Line 9: DashboardBusiness.WorkflowHelper.Init();
    Line 10: }
    Line 11:
    Source File: d:\Inetpub\hhh.net\shared\iHHH\Dashboard\Global.asax Line: 9
    Stack Trace:
    [InvalidOperationException: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.]
    System.Diagnostics.PerformanceCounter.Initialize() +1232
    System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly) +110
    System.Workflow.Runtime.PerformanceCounterManager.CreateCounters(String name) +70
    System.Workflow.Runtime.Hosting.ManualWorkflowSchedulerService.OnStarted() +220
    System.Workflow.Runtime.Hosting.WorkflowRuntimeService.HandleStarted(Object source, WorkflowRuntimeEventArgs e) +11
    System.EventHandler`1.Invoke(Object sender, TEventArgs e) +0
    System.Workflow.Runtime.WorkflowRuntime.StartRuntime() +835
    DashboardBusiness.WorkflowHelper.Init() +95
    ASP.global_asax.Application_Start(Object sender, EventArgs e) in d:\Inetpub\hhh.net\shared\iHHH\Dashboard\Global.asax:9
    Version Information: Microsoft .NET Framework Version:2.0.50727.1378; ASP.NET Version:2.0.50727.1378

    I've never seen this error in the context of trying to connect via ODP.NET or ODT.
    If you have Oracle Dev Tools for Visual Studio installed, you can try to create a connection to the database using Server Explorer. If this works, that means your ODP.NET connection is just fine.
    If you don't have VS or the tools, another thing you can try is connecting through ODP.NET using a simple OracleConnection.Open. Make sure you have your client set up to connect to the DB server.
    Here's some info about connecting to the DB:
    http://download.oracle.com/docs/html/B28089_01/featConnecting.htm#sthref101

  • Incorrect count query

    I'm using CursoredStream to fetch a large result set. When doing a cursor.size() Toplink generates the wrong count query. I do have group value functions in the query as shown below.
    For e.g. this is the cursor query:
    --- Actual select query ---
    SELECT t0.AWARD_ID, t0.AWARD_NUMBER, t0.FINAL_AMOUNT, t2.NAME,
    SUM(t1.REPORT_AMOUNT), t4.FISCAL_YEAR, t5.DESCRIPTION
    FROM REF_ENTITY t6, T_CODE t5, SOL t4, APP t3, APP_VERSION t2, SUBG t1,
    AWARD t0
    WHERE ((((t4.FISCAL_YEAR = '1993') AND (t6.REF_ENTITY_ID = 5)) AND (t4.SUBG_
    REPORT = 'Y')) AND ((t5.T_CODE_ID = t0.T_CODE_ID_STATUS) AND ((t2.APP_ID = t3.A
    PP_ID) AND ((t6.REF_ENTITY_ID = t4.REF_ENTITY_ID) AND ((t4.SOL_ID = t3.SOL_ID)
    AND ((t3.APP_ID = t0.APP_ID) AND (t0.AWARD_ID = t1.AWARD_ID)))))))
    GROUP BY t0.FINAL_AMOUNT, t0.AWARD_ID, t0.AWARD_NUMBER, t4.FISCAL_YEAR, t5.D
    ESCRIPTION, t2.NAME ORDER BY t0.AWARD_NUMBER ASC
    The count query generated by Toplink is:
    SELECT COUNT(*)
    FROM REF_ENTITY t4, AWARD t3, APP t2, SOL t1, SUBG t0
    WHERE ((((t1.FISCAL_YEAR = ?) AND (t4.REF_ENTITY_ID = ?))
    AND (t1.SUBG_REPORT = 'Y')) AND ((t4.REF_ENTITY_ID = t1.REF_ENTITY_ID)
    AND ((t1.SOL_ID = t2.SOL_ID) AND ((t2.APP_ID = t3.GMS_APP_ID)
    AND (t3.AWARD_ID = t0.AWARD_ID)))))
    I have to provide my own ValueReadQuery to get the correct count in the above case. Are there any rules for determining when we have to explicitly provide our own count query?
    cheers
    p.s: Toplink version 9.0.3.4

    Abe,
    This sounds like a bug. I assume you are using a ReportQuery to generate the initial SQL. You should only have to provide a ValueReadQuery to a cursored query when using SQL, stored-procedure, or to optimize what is being generated.
    This looks like the group-by on your ReportQuery is being ignored on the size query. The best plan is to submit this to support with the TopLink code used and the information provided in this post.
    In the mean time the work-around of providing your own query is probably the best solution.
    Doug

  • Count Query Performance

    How can we improve the perfromace of a count query?
    Suppose I have a table A that holds more than 50 million rows.
    Now if i want to count the no of rows which is the best one
    1) Select count(*) from A.
    Definitely not as it is doing a full table scan
    2) Select count(primary_key) from A.
    3) Select count(row_id) from A.
    One more question whats the difference between select count(*) from table_name and select count(1) from table_a. Many people suggest count(1) and i dont see any reason though.
    Kindly guide me.

    > Please see my points 1,2 and 3.
    Can this change the execution plan (path) of the CBO in anyway?
    1. count rows
    2. count rows using primary key
    3. counting rows using physical row addresses
    The fact is that the rows, and all the rows, need to be counted. The CBO will choose the most "attractive" I/O path - i.e. the smallest one, the one with the least amount of I/O. It does not need tricks like COUNT(1) or COUNT(PK) or COUNT(ROWID) in order to make an appropriate decision.
    Example:
    SQL> create table tab1 nologging as select level as ID, LPAD('*',4000,'*') as STUFF from dual connect by level <= 10000;
    Table created.
    SQL> set autotrace on
    Running a SELECT COUNT(*) without any alternate I/O paths (no indexes exist)
    SQL> select count(*) from tab1;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 899213575
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 2306 (4)| 00:00:28 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | TABLE ACCESS FULL| TAB1 | 9982 | 2306 (4)| 00:00:28 |
    Note
    - dynamic sampling used for this statement
    Statistics
    28 recursive calls
    0 db block gets
    10087 consistent gets
    10000 physical reads
    0 redo size
    208 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    Creating an PK index
    SQL> alter table tab1 add constraint pk_tab1 primary key(id) using index;
    Table altered.
    Running the same SELECT COUNT(*) - but the CBO now sees that the PK index
    is smaller and cheaper to scan than scanning the table
    SQL> select count(*) from tab1;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 1796789124
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 9 (23)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | INDEX FAST FULL SCAN| PK_TAB1 | 9982 | 9 (23)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    194 recursive calls
    0 db block gets
    131 consistent gets
    20 physical reads
    0 redo size
    222 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    5 sorts (memory)
    0 sorts (disk)
    1 rows processed
    SQL>

Maybe you are looking for